Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-drupal-7-fieldscck-using-image-field-modules
Packt
11 Jul 2011
6 min read
Save for later

Drupal 7 Fields/CCK: Using the Image Field Modules

Packt
11 Jul 2011
6 min read
Drupal 7 Fields/CCK Beginner's Guide Explore Drupal 7 fields/CCK and master their use Adding image fields to content types We have learned how to add file fields to content types. In this section, we will learn how to add image fields to content types so that we can attach images to our content. Time for action – adding an image field to the Recipe content type In this section, we will add an image field to the Recipe content type. Follow these steps: Click on the Structure link in the administration menu at the top of the page. Click on the Content types link to go to the content types administration page. Click on the manage fields link on the Recipe row as in the following screenshot, because we would like to add an image field to the recipe content type. (Move the mouse over the image to enlarge it.) Locate the Add new field section. In the Label field enter "Image", and in the Field name field enter "image". In the field type select list, select "image" as the field type; the field widget will be automatically switched to select Image as the field widget. After the values are entered, click on Save. (Move the mouse over the image to enlarge it.)   What just happened?   We added an image field to the Recipe content type. The process of adding an image field to the Recipe content type is similar to the process of adding a file field to the Recipe content type, except that we selected image field as the field type and we selected image as the field widget. We will configure the image field in the next section. Configuring image field settings We have already added the image field. In this section, we will configure the image field, learn how to configure the image field settings, and understand how they reflect to image outputs by using those settings. Time for action – configuring an image field for the Recipe content type In this section, we will configure image field settings in the Recipe content type. Follow these steps: After clicking on the Save button, Drupal will direct us to the next page, which provides the field settings for the image field. The Upload destination option is the same as the file field settings, which provide us an option to decide whether image files should be public or private. In our case, we select Public files. The last option is the Default image field. We will leave this option for now, and click on the Save field settings button to go to the next step. (Move the mouse over the image to enlarge it.) This page contains all the settings for the image field. The most common field settings are the Label field, the Required field, and the Help text field. We will leave these fields as default. (Move the mouse over the image to enlarge it.) The Allowed file extension section is similar to the file field we have already learned about. We will use the default value in this field, so we don't need to enter anything for this field. The File directory section is also the same as the settings in the file field. Enter "image_files" in this field. (Move the mouse over the image to enlarge it.) Enter "640" x "480" in the Maximum image resolution field and the Minimum image resolution field, and enter "2MB" in the maximum upload size field. (Move the mouse over the image to enlarge it.) Check the Enable Alt field and the Enable Title field checkboxes. (Move the mouse over the image to enlarge it.) Select thumbnail in the Preview image style select list, and select Throbber in the Progress indicator section. (Move the mouse over the image to enlarge it.) The bottom part of this page, the image field settings section, is the same as the previous page we just saved, so we don't need to re-enter the values. Click on the Save settings button at the bottom of the page to store all the values we entered on this page. (Move the mouse over the image to enlarge it.) After clicking on the Save settings button, Drupal sends us back to the Manage fields setting administration page. Now the image field is added to the Recipe content type. (Move the mouse over the image to enlarge it.)   What just happened?   We have added and configured an image field for the Recipe content type. We left the default values in the Label field, the Required field, and the Help text field. They are the most common settings in fields. The Allowed file extension section is similar to the file field that we have seen, which provides us with the ability to enter the file extension of the images which are allowed to be uploaded. The File directory field is the same as the one in the file field, which provides us with the option to save the uploaded files to a different directory to the default location of the file directory. The Maximum image resolution field allows us to specify the maximum width and height of image resolution that will be uploaded. If the uploaded image is bigger than the resolution we specified, it will resize images to the size we specified. If we did not specify the size, it will not have any restriction to images. The Minimum image resolution field is the opposite of the maximum image resolution. We specify the minimum width and height of image resolution that is allowed to be uploaded, not the maximum width and height of image resolution. If we upload image resolution less than the minimum size we specified, it will throw an error message and reject the image upload. The Enable Alt field and the Enable Title field can be enabled to allow site administrators to enter the ALT and Title attributes of the img tag in XHTML, which can improve the accessibility and usability of a website when using images. The Preview image style select list allows us to select which image style will be used to display while editing content. Currently it provides three image styles, thumbnail, medium, and large. The thumbnail image style will be used by default. We will learn how to create a custom image style in the next section. Have a go hero – adding an image field to the Cooking Tip content type It's time for another challenge. We have created an image field to the Recipe content type. We can use the same method we have learned here to add and configure an image field to the Cooking Tip content type. You can apply the same steps used to create image fields to the Recipe content type and try to understand the differences between the settings on the image field settings administration page.
Read more
  • 0
  • 0
  • 2480

article-image-drupal-7-fieldscck-using-file-field-modules
Packt
08 Jul 2011
4 min read
Save for later

Drupal 7 fields/CCK: Using the file field modules

Packt
08 Jul 2011
4 min read
Adding and configuring file fields to content types There are many cases where we need to attach files to website content. For instance, a restaurant owner might like to upload their latest menu in PDF format to their website, or a financial institution would like to upload a new product catalog so customers can download and print out the catalog if they need it. The File module is built into the Drupal 7 core, which provides us with the ability to attach files to content easily, to decide the attachment display format, and also to manage file locations. Furthermore, the File module is integrated with fields and provides a file field type, so we can easily attach files to content using the already discussed field system making the process of managing files much more streamlined. Time for action – adding and configuring a file field to the Recipe content type In this section, we will add a file field to the Recipe content type, which will allow files to be attached to Recipe content. Follow these steps: Click on the Structure link in the administration menu at the top of the page. The following page will display a list of options. Click on the Content types link to go to the Content types administration page. Since we want to add a file field to the Recipe content type, we will click on the manage fields link on the Recipe row as shown in the following screenshot: (Move the mouse over the image to enlarge it.) This page will display the existing fields of the Recipe content type. In the Label field enter "File", and in the Field name field enter "file". In the field type select list select File as the field type, the field widget will be automatically switched to File as the field widget. After the values are entered, click on Save. A new window will pop up which provides the field settings for the file field that we are creating. There are two checkboxes, and we will enable both these checkboxes. The last radio button option will be selected by default. Then click on the Save field settings button at the bottom of the page. We clicked on the Save field settings button to store the values for the file field settings that we selected. After that, it will direct us to the file field settings administration page, as in the following screenshot: We can leave the Label field as default as it will be filled automatically with the value we entered previously. We will also leave the Required field as default, because we do not want to force users to attach files to every recipe. In the Help text field, we can enter "Attach files to this recipe". In the Allowed file extensions section, we can enter the file extensions that are allowed to be uploaded. In this case, we will enter "txt, pdf, zip". In the File directory section, we can enter the name of a subdirectory that will store the uploaded files, and in this case, we will enter "recipe_files": In the Maximum upload size section, we can enter a value to limit the file size when uploading files. We will enter "2MB" in this field. The Enable Description field checkbox allows users to enter a description about the uploaded files. In this case, we will enable this option, because we would like users to enter a description of the uploaded files. (Move the mouse over the image to enlarge it.) In the Progress indicator section, we can select which indicator will be used when uploading files. We select Throbber as the progress indicator for this field. (Move the mouse over the image to enlarge it.) You will notice the bottom part of the page is exactly same as in the previous section. We can ignore the bottom part and click on the Save settings button to store all the values we have entered. Drupal will direct us back to the manage fields administration page with a message saying we have successfully saved the configuration for the file field. After creating the file field, the file field row will be added to the table. This table will display the details about the file field we just created. (Move the mouse over the image to enlarge it.)
Read more
  • 0
  • 0
  • 4352

article-image-core-http-module-nginx
Packt
08 Jul 2011
8 min read
Save for later

The Core HTTP Module in Nginx

Packt
08 Jul 2011
8 min read
Nginx 1 Web Server Implementation Cookbook Over 100 recipes to master using the Nginx HTTP server and reverse proxy   Setting up the number of worker processes correctly Nginx like any other UNIX-based server software, works by spawning multiple processes and allows the configuration of various parameters around them as well. One of the basic configurations is the number of worker processes spawned! It is by far one of the first things that one has to configure in Nginx. How to do it... This particular configuration can be found at the top of the sample configuration file nginx.conf: user www www; worker_processes 5; error_log logs/error.log; pid logs/nginx.pid; worker_rlimit_nofile 8192; events { worker_connections 4096; } In the preceding configuration, we can see how the various process configurations work. You first set the UNIX user under which the process runs, then you can set the number of worker processes that Nginx needs to spawn, after that we have some file locations where the errors are logged and the PIDs (process IDs) are saved. How it works... By default, worker_processes is set at 2. It is a crucial setting in a high performance environment as Nginx uses it for the following reasons: It uses SMP, which allows you to efficiently use multi-cores or multi-processors systems very efficiently and have a definite performance gain. It increases the number of processes decreases latency as workers get blocked on disk I/O. It limits the number of connections per process when any of the various supported event types are used. A worker process cannot have more connections than specified by the worker_connections directive. There's more... It is recommended that you set worker_processes as the number of cores available on your server. If you know the values of worker_processes and worker_connections, one can easily calculate the maximum number of connections that Nginx can handle in the current setup. Maximum clients = worker_processes * worker_connections   Increasing the size of uploaded files Usually when you are running a site where the user uploads a lot of files, you will see that when they upload a file which is more than 1MB in size you get an Nginx error stating, "Request entity too Large" (413), as shown in the following screenshot. We will look at how Nginx can be configured to handle larger uploads. How to do it... This is controlled by one simple part of the Nginx configuration. You can simply paste this in the server part of the Nginx configuration: client_max_body_size 100M; # M stands for megabytes This preceding configuration will allow you to upload a 100 megabyte file. Anything more than that, and you will receive a 413. You can set this to any value which is less than the available disk space to Nginx, which is primarily because Nginx downloads the file to a temporary location before forwarding it to the backend application. There's more... Nginx also lets us control other factors related to people uploading files on the web application, like timeouts in case the client has a slow connection. A slow client can keep one of your application threads busy and thus potentially slow down your application. This is a problem that is experienced on all the heavy multimedia user-driven sites, where the consumer uploads all kinds of rich data such as images, documents, videos, and so on. So it is sensible to set low timeouts. client_body_timeout 60; # parameter in seconds client_body_buffer_size 8k; client_header_timeout 60; # parameter in seconds client_header_buffer_size 1k; So, here the first two settings help you control the timeout when the body is not received at one read-step (basically, if the server is queried and no response comes back). Similarly, you can set the timeout for the HTTP header as well. The following table lists out the various directives and limits you can set around client uploading.   Using dynamic SSI for simple sites With the advent of modern feature-full web servers, most of them have Server-Side Includes (SSI) built in. Nginx provides easy SSI support which can let you do pretty much all basic web stuff. How to do it... Let's take a simple example and start understanding what one can achieve with it. Add the following code to the nginx.conf file: server { ..... location / { ssi on; root /var/www/www.example1.com; } } Add the following code to the index.html file: <html> <body> <!--# block name="header_default" --> the header testing <!--# endblock --> <!--# include file="header.html" stub="header_default" --> <!--# echo var="name" default="no" --> <!--# include file="footer.html"--> </body> </html> Add the following code to the header.html file: <h2>Simple header</h2> Add the following code to the footer.html file: <h2>Simple footer</h2> How it works... This is a simple example where we can see that you can simply include some partials in the larger page, and in addition to that you can create block as well within the page. So the <block> directive allows you to create silent blocks that can be included later, while the <include> directive can be used to include HTML partials from other files, or even URL end points. The <echo> directive is used to output certain variables from within the Nginx context. There's more... You can utilize this feature for all kinds of interesting setups where: You are serving different blocks of HTML for different browsers types You want to optimize and speed up certain common blocks of the sites You want to build a simple site with template inheritance without installing any other scripting language   Adding content before and after a particular page Today, in most of the sites that we visit, the webpage structure is formally divided into a set of boxes. Usually, all sites have a static header and a footer block. Here, in this following page you can see the YUI builder generating the basic framework of such a page. In such a scenario, Nginx has a really useful way of adding content before and after it serves a certain page. This will potentially allow you to separate the various blocks and optimize their performance individually, as well. Let's have a look at an example page: So here we want to insert the header block before the content, and then append the footer block: How to do it… The sample configuration for this particular page would look like this: server { listen 80; server_name www.example1.com; location / { add_before_body /red_block add_after_body /blue_block; ... } location /red_block/ { ... } location /blue_block/ { .... } } This can act as a performance enhancer by allowing you to load CSS based upon the browser only. There can be cases where you want to introduce something into the header or the footer on short notice, without modifying your backend application. This provides an easy fix for those situations. This module is not installed by default and it is necessary to enable it when building Nginx. ./configure –with-http_addition_module   Enabling auto indexing of a directory Nginx has an inbuilt auto-indexing module. Any request where the index file is not found will route to this module. This is similar to the directory listing that Apache displays. How to do it... Here is the example of one such Nginx directory listing. It is pretty useful when you want to share some files over your local network. To start auto index on any directory all you need to do is to carry out the following example and place it in the server section of the Nginx configuration file: server { location 80; server_name www.example1.com; location / { root /var/www/test; autoindex on; } } How it works... This will simply enable auto indexing when the user types in http://www.example1.com. You can also control some other things in the listings in this way: autoindex_exact_size off; This will turn off the exact file size listing and will only show the estimated sizes. This can be useful when you are worried about file privacy issues. autoindex_localtime on; This will represent the timestamps on the files as your local server time (it is GMT by default): This image displays a sample index auto-generated by Nginx using the preceding configuration. You can see the filenames, timestamp, and the file sizes as the three data columns.  
Read more
  • 0
  • 0
  • 9198

article-image-nginx-web-services-configuration-and-implementation
Packt
08 Jul 2011
6 min read
Save for later

Nginx Web Services: Configuration and Implementation

Packt
08 Jul 2011
6 min read
Nginx 1 Web Server Implementation Cookbook Installing new modules and compiling Nginx Today, most softwares are designed to be modular and extensible. Nginx, with its great community, has an amazing set of modules out there that lets it do some pretty interesting things. Although most operating system distributions have Nginx binaries in their repositories, it is a necessary skill to be able to compile new, bleeding edge modules, and try them out. Now we will outline how one can go about compiling and installing Nginx with its numerous third-party modules. How to do it... The first step is to get the latest Nginx distribution, so that you are in sync with the security and performance patches (http://sysoev.ru/nginx/nginx-0.7.67.tar.gz). Do note that you will require sudo or root access to do some of the installation steps going ahead. Un-tar the Nginx source code. This is simple, you will need to enter the following command: tar -xvzf nginx-0.7.67.tar.gz Go into the directory and configure it. This is essential, as here you can enable and disable the core modules that already come with Nginx. Following is a sample configure command: ./configure --with-debug --with-http_ssl_module --with-http_realip_module --with-http_ssl_module --with-http_perl_module --with-http_stub_status_module You can figure out more about what other modules and configuration flags use: ./configure --help If you get an error, then you will need to install the build dependencies, depending on your system. For example, if you are running a Debian based system, you can enter the following command: apt-get build-dep nginx This will install all the required build dependencies, like PCRE and TLS libraries. After this, you can simply go ahead and build it: sudo make install This was the plain vanilla installation! If you want to install some new modules, we take the example of the HTTP subscribe-publish module. Download your module (http://pushmodule.slact.net/downloads/nginx_http_push_module-0.692.tar.gz). Un-tar it at a certain location:/path/to/module. Reconfigure Nginx installation: ./configure ..... --add-module=/path/to/module The important part is to point the –add-module flag to the right module path. The rest is handled by the Nginx configuration script. You can continue to build and install Nginx as shown in step 5. sudo make install If you have followed steps 1 to 10, it will be really easy for you to install any Nginx module. There's more... If you want to check that the module is installed correctly, you can enter the following command: nginx -V A sample output is something as shown in the following screenshot: This basically gives you the compilation flags that were used to install this particular binary of Nginx, indirectly listing the various modules that were compiled into it. Running Nginx in debug mode Nginx is a fairly stable piece of software which has been running in production for over a decade and has built a very strong developer community around it. But, like all software there are issues and bugs which crop up under the most critical of situations. When that happens, it's usually best to reload Nginx with higher levels of error logging and if possible, in the debug mode. How to do it... If you want the debug mode, then you will need to compile Nginx with the debug flag (--with-debug). In most cases, most of the distributions have packages where Nginx is precompiled with debug flag. Here are the various levels of debugging that you can utilize: error_log LOGFILE [debug | info | notice | warn | error | crit | debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_imap]; Downloading the example code You can download the example code files here If you do not set the error log location, it will log to a compiled-in default log location. This logging is in addition to the normal error logging that you can do per site. Here is what the various specific debug flags do: There's more... Nginx allows us to log errors for specific IP addresses. Here is a sample configuration that will log errors from 192.168.1.1 and the IP range of 192.168.10.0/24: error_log logs/error.log; events { debug_connection 192.168.1.1; debug_connection 192.168.10.0/24; } This is extremely useful when you want to debug in the production environment, as logging for all cases has unnecessary performance overheads. This feature allows you to not set a global debug on the error_log, while being able to see the debug output for specific matched IP blocks based on the user's IP address. Easy reloading of Nginx using the CLI Depending on the system that you have, it will offer one clean way of reloading your Nginx setup Debian based: /etc/init.d/Nginx reload Fedora based: service Nginx reload FreeBSD/BSD: service Nginx reload Windows: Nginx -s reload All the preceding commands reload Nginx; they send a HUP signal to the main Nginx process. You can send quite a few control signals to the Nginx master process, as outlined in the following table. These let you manage some of the basic administrative tasks: How to do it... Let me run you through the simple steps of how you can reload Nginx from the command line. Open a terminal on your system. Most UNIX-based systems already have fairly powerful terminals, while you can use PuTTY on Windows systems. Type in ps auxww | grep nginx. This will output something as shown in the following screenshot: If nothing comes, then it means that Nginx is not running on your system. If you get the preceding output, then you can see the master process and the two worker processes (it may be more, depending on your worker_processes configuration). The important number is 3322, which is basically the PID of the master process. To reload Nginx, you can issue the command kill -HUP <PID of the nginx master process>. In this case, the PID of the master process is 3322. This will basically read the configurations again, gracefully close your current connections, and start new worker processes. You can issue another ps auxww | grep nginx to see new PIDs for the worker processes (4582,4583): If the worker PIDs do not change it means that you may have a problem while reloading the configuration files. Go ahead and check the Nginx error log. This is very useful while writing scripts, which control Nginx configuration. A good example is when you are deploying code on production; you will temporarily point the site to a static landing page.  
Read more
  • 0
  • 0
  • 8339

article-image-building-financial-functions-excel-2010
Packt
07 Jul 2011
5 min read
Save for later

Building Financial Functions into Excel 2010

Packt
07 Jul 2011
5 min read
Excel 2010 Financials Cookbook Powerful techniques for financial organization, analysis, and presentation in Microsoft Excel         Till now, in the previous articles, we have focused on manipulating data within and outside of Excel in order to prepare to make financial decisions. Now that the data has been prepared, re-arranged, or otherwise adjusted, we are able to leverage the functions within Excel to make actual decisions. Utilizing these functions and the individual scenarios, we will be able to effectively eliminate the uncertainty due to poor analysis. Since this article utilizes financial scenarios for demonstrating the use of the various functions, it is important to note that these scenarios take certain "unknowns" for granted, and makes a number of assumptions in order to minimize the complexity of the calculation. Real-world scenarios will require a greater focus on calculating and accounting for all variables. Determining standard deviation for assessing risk In the recipes mentioned so far, we have shown the importance of monitoring and analyzing frequency to determine the likelihood that an event will occur. Standard deviation will now allow for an analysis of the frequency in a different manner, or more specifically, through variance. With standard deviation, we will be able to determine the basic top and bottom thresholds of data, and plot general movement within that threshold to determine the variance within the data range. This variance will allow the calculation of risk within investments. As a financial manager, you must determine the risk associated with investing capital in order to gain a return. In this particular instance, you will invest in stock. In order to minimize loss of investment capital, you must determine the risk associated between investing between two different stocks, Stock A, and Stock B. In this recipe, we will utilize standard deviation to determine which stock, either A or B, presents a higher risk, and hence a greater risk of loss. How to do it... We will begin by entering the selling prices of Stock A and Stock B in columns A and B, respectively: Within this list of selling prices, at first glance we can see that Stock B has a higher selling price. The stock opening price and selling price over the course of 52 weeks almost always remains above that of Stock A. As an investor looking to gain a higher return, we may wish to choose Stock B based on this cursory review; however, high selling price does not negate the need for consistency. In cell C2, enter the formula =STDEV(A2:A53) and press Enter: In cell C3, enter the formula =STDEV(B2:B53) and press Enter: We can see from the calculation of standard deviation, that Stock B has a deviation range or variance of over $20, whereas Stock A's variance is just over $9: Given this information, we can determine that Stock A presents a lower risk than Stock B. If we invest in Stock A, at any given time, utilizing past performance, our average risk of loss is $9, whereas in Stock B we an average risk of $20. How it works... The function of STDEV or standard deviation in Excel utilizes the given numbers as a complete population. This means that it does not account for any other changes or unknowns. Excel will use this data set as a complete set and determine the greatest change from high to low within the numbers. This range of change is your standard deviation. Excel also includes the function STDEVP that treats the data as a selection of a larger population. This function should be sed if you are calculating standard deviation on a subset of data (for example, six months out of an entire year). If we translate these numbers into a line graph with standard deviation bars, as shown in the following screenshot for Stock A, you can see the selling prices of the stock, and how they travel within the deviation range: If we translate these numbers into a line graph with standard deviation bars, as shown in the following screenshot for Stock B, you can see the selling prices of the stock, and understand how they travel within the deviation range: The bars shown on the graphs represent the standard deviation as calculated by Excel. We can see visually that not only does Stock B represent a greater risk with the larger deviation, but also many of the stock prices fall below our deviation, representing further risk to the investor. With funds to invest as a finance manager, Stock A represents a lower risk investment. There's more... Standard deviation can be calculated for almost any data set. For this recipe, we calculated deviation over the course of one year; however, if we expand the data to include multiple years we can further determine long-term risk. While Stock B represents high short-term risk, in the long-term analysis, Stock B may present as a less risky investment. Combining standard deviation with a five-number summary analysis, we can further gain risk and performance information.
Read more
  • 0
  • 0
  • 4923

article-image-apache-cassandra-working-multiple-datacenter-environments
Packt
07 Jul 2011
5 min read
Save for later

Apache Cassandra: Working in Multiple Datacenter Environments

Packt
07 Jul 2011
5 min read
Cassandra High Performance Cookbook Over 150 recipes to design and optimize large scale Apache Cassandra deployments       Changing debugging to determine where read operations are being routed Cassandra replicates data to multiple nodes; because of this, a read operation can be served by multiple nodes. If a read at QUORUM or higher is submitted, a Read Repair is executed, and the read operation will involve more than a single server. In a simple flat network which nodes have chosen for digest reads, are not of much consequence. However, in multiple datacenter or multiple switch environments, having a read cross a switch or a slower WAN link between datacenters can add milliseconds of latency. This recipe shows how to debug the read path to see if reads are being routed as expected. How to do it... Edit <cassandra_home>/conf/log4j-server.properties and set the logger to debug, then restart the Cassandra process: log4j.rootLogger=DEBUG,stdout,R On one display, use the tail -f <cassandra_log_dir>/system.log to follow the Cassandra log: DEBUG 06:07:35,060 insert writing local RowMutation(keyspace='ks1', key='65', modifications=[cf1]) DEBUG 06:07:35,062 applying mutation of row 65 In another display, open an instance of the Cassandra CLI and use it to insert data. Remember, when using RandomPartitioner, try different keys until log events display on the node you are monitoring: [default@ks1] set cf1[‘e'][‘mycolumn']='value'; Value inserted. Fetch the column using the CLI: [default@ks1] get cf1[‘e'][‘mycolumn']; Debugging messages should be displayed in the log. DEBUG 06:08:35,917 weakread reading SliceByNamesReadComman d(table='ks1', key=65, columnParent='QueryPath(columnFami lyName='cf1', superColumnName='null', columnName='null')', columns=[6d79636f6c756d6e,]) locally ... DEBUG 06:08:35,919 weakreadlocal reading SliceByNamesReadCo mmand(table='ks1', key=65, columnParent='QueryPath(columnFa milyName='cf1', superColumnName='null', columnName='null')', columns=[6d79636f6c756d6e,]) How it works... Changing the logging property level to DEBUG causes Cassandra to print information as it is handling reads internally. This is helpful when troubleshooting a snitch or when using the consistency levels such as LOCAL_QUORUM or EACH_QUORUM, which route requests based on network topologies. Using IPTables to simulate complex network scenarios in a local environment While it is possible to simulate network failures by shutting down Cassandra instances, another failure you may wish to simulate is a failure that partitions your network. A failure in which multiple systems are UP but cannot communicate with each other is commonly referred to as a split brain scenario. This state could happen if the uplink between switches fails or the connectivity between two datacenters is lost. Getting ready When editing any firewall, it is important to have a backup copy. Testing on a remote machine is risky as an incorrect configuration could render your system unreachable. How to do it... Review your iptables configuration found in /etc/sysconfig/iptables. Typically, an IPTables configuration accepts loopback traffic: :RH-Firewall-1-INPUT - [0:0] -A INPUT -j RH-Firewall-1-INPUT -A FORWARD -j RH-Firewall-1-INPUT -A RH-Firewall-1-INPUT -i lo -j ACCEPT Remove the highlighted rule and restart IPTables. This should prevent instances of Cassandra on your machine from communicating with each other: #/etc/init.d/iptables restart Add a rule to allow a Cassandra instance running on 10.0.1.1 communicate to 10.0.1.2: -A RH-Firewall-1-INPUT -m state --state NEW -s 10.0.1.1 -d 10.0.1.2 -j ACCEPT How it works... IPTables is a complete firewall that is a standard part of current Linux kernel. It has extensible rules that can permit or deny traffic based on many attributes, including, but not limited to, source IP, destination IP, source port, and destination port. This recipe uses the traffic blocking features to simulate network failures, which can be used to test how Cassandra will operate with network failures. Choosing IP addresses to work with RackInferringSnitch A snitch is Cassandra's way of mapping a node to a physical location in the network. It helps determine the location of a node relative to another node in order to ensure efficient request routing. The RackInferringSnitch can only be used if your network IP allocation is divided along octets in your IP address. Getting ready The following network diagram demonstrates a network layout that would be ideal for RackInferringSnitch. How to do it... In the <cassandra_home>/conf/cassandra.yaml file: endpoint_snitch: org.apache.cassandra.locator.RackInferringSnitch Restart the Cassandra instance for this change to take effect. How it works... The RackInferringSnitch requires no extra configuration as long as your network adheres to a specific network subnetting scheme. In this scheme, the first octet, Y.X.X.X, is the private network number 10. The second octet, X.Y.X.X, represents the datacenter. The third octet, X.X.Y.X, represents the rack. The final octet represents the host, X.X.X.Y. Cassandra uses this information to determine which hosts are ‘closest'. It is assumed that ‘closer' nodes will have more bandwidth and less latency between them. Cassandra uses this information to send Digest Reads to the closest nodes and route requests efficiently. There's more... While it is ideal if the network conforms to what is required for RackInferringSnitch, it is not always practical or possible. It is also rigid in that if a single machine does not adhere to the convention, the snitch will fail to work properly.
Read more
  • 0
  • 0
  • 4625
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-ejb-31-working-interceptors
Packt
06 Jul 2011
3 min read
Save for later

EJB 3.1: Working with Interceptors

Packt
06 Jul 2011
3 min read
EJB 3.1 Cookbook Build real world EJB solutions with a collection of simple but incredibly effective recipes with this book and eBook        The recipes in this article are based largely around a conference registration application as developed in the first recipe of the previous article on Introduction to Interceptors. It will be necessary to create this application before the other recipes in this article can be demonstrated. Using interceptors to enforce security While security is an important aspect of many applications, the use of programmatic security can clutter up business logic. The use of declarative annotations has come a long way in making security easier to use and less intrusive. However, there are still times when programmatic security is necessary. When it is, then the use of interceptors can help remove the security code from the business logic. Getting ready The process for using an interceptor to enforce security involves: Configuring and enabling security for the application server Adding a @DeclareRoles to the target class and the interceptor class Creating a security interceptor How to do it... Configure the application to handle security as detailed in Configuring the server to handle security recipe. Add the @DeclareRoles("employee") to the RegistrationManager class. Add a SecurityInterceptor class to the packt package. Inject a SessionContext object into the class. We will use this object to perform programmatic security. Also use the @DeclareRoles annotation. Next, add an interceptor method, verifyAccess, to the class. Use the SessionContext object and its isCallerInRole method to determine if the user is in the "employee" role. If so, invoke the proceed method and display a message to that effect. Otherwise, throw an EJBAccessException. @DeclareRoles("employee") public class SecurityInterceptor { @Resource private SessionContext sessionContext; @AroundInvoke public Object verifyAccess(InvocationContext context) throws Exception { System.out.println("SecurityInterceptor: Invoking method: " + context.getMethod().getName()); if (sessionContext.isCallerInRole("employee")) { Object result = context.proceed(); System.out.println("SecurityInterceptor: Returned from method: " + context.getMethod().getName()); return result; } else { throw new EJBAccessException(); } } } Execute the application. The user should be prompted for a username and password as shown in the following screenshot. Provide a user in the employee role. The application should execute to completion. Depending on the interceptors in place, you will console output similar to the following: INFO: Default Interceptor: Invoking method: register INFO: SimpleInterceptor entered: register INFO: SecurityInterceptor: Invoking method: register INFO: InternalMethod: Invoking method: register INFO: register INFO: Default Interceptor: Invoking method: create INFO: Default Interceptor: Returned from method: create INFO: InternalMethod: Returned from method: register INFO: SecurityInterceptor: Returned from method: register INFO: SimpleInterceptor exited: register INFO: Default Interceptor: Returned from method: register How it works... The @DeclareRoles annotation was used to specify that users in the employee role are associated with the class. The isCallerInRole method checked to see if the current user is in the employee role. When the target method is called, if the user is authorized then the InterceptorContext's proceed method is executed. If the user is not authorized, then the target method is not invoked and an exception is thrown. See also EJB 3.1: Controlling Security Programmatically Using JAAS  
Read more
  • 0
  • 0
  • 3118

article-image-ejb-31-introduction-interceptors
Packt
06 Jul 2011
7 min read
Save for later

EJB 3.1: Introduction to Interceptors

Packt
06 Jul 2011
7 min read
EJB 3.1 Cookbook Build real world EJB solutions with a collection of simple but incredibly effective recipes with this book and eBook Introduction Most applications have cross-cutting functions which must be performed. These cross-cutting functions may include logging, managing transactions, security, and other aspects of an application. Interceptors provide a way to achieve these cross-cutting activities. The use of interceptors provides a way of adding functionality to a business method without modifying the business method itself. The added functionality is not intermeshed with the business logic resulting in a cleaner and easier to maintain application. Aspect Oriented Programming (AOP) is concerned with providing support for these cross-cutting functions in a transparent fashion. While interceptors do not provide as much support as other AOP languages, they do offer a good level of support. Interceptors can be: Used to keep business logic separate from non-business related activities Easily enabled/disabled Provide consistent behavior across an application Interceptors are specific methods invoked around a method or methods of a target EJB. We will use the term target, to refer to the class containing the method(s) an interceptor will be executing around. The interceptor's method will be executed before the EJB's method is executed. When the interceptor method executes, it is passed as an InvocationContext object. This object provides information relating to the state of the interceptor and the target. Within the interceptor method, the InvocationContext's method proceed can be issued that will result in the target's business method being executed or, as we will see shortly, the next interceptor in the chain. When the business method returns, the interceptor continues execution. This permits execution of code before and after the execution of a business method. Interceptors can be used with: Stateless session EJBs Stateful session EJBs Singleton session EJBs Message-driven beans The @Interceptors annotation defines which interceptors will be executed for all or individual methods of a class. Interceptor classes use the same lifecycle of the EJB they are applied to, in the case of stateful EJBs, which means the interceptor could be passivated and activated. In addition, they support the use of dependency injection. The injection is done using the EJB's naming context. More than one interceptor can be used at a time. The sequence of interceptor execution is referred to as an interceptor chain. For example, an application may need to start a transaction based on the privileges of a user. These actions should also be logged. An interceptor can be defined for each of these activities: validating the user, starting the transaction, and logging the event. The use of interceptor chaining is illustrated in the Using interceptors to handle application statistics recipe. Lifecycle callbacks such as @PreDestroy and @PostConstruct can also be used within interceptors. They can access interceptor state information as discussed in the Using lifecycle methods in interceptors recipe. Interceptors are useful for: Validating parameters and potentially changing them before they are sent to a method Performing security checks Performing logging Performing profiling Gathering statistics An example of parameter validation can be found in the Using the InvocationContext to verify parameters recipe. Security checks are illustrated in the Using interceptors to enforce security recipe. The use of interceptor chaining to record a method's hit count and the time spent in the method is discussed in the Using interceptors to handle application statistics recipe. Interceptors can also be used in conjunction with timer services. The recipes in this article are based largely around a conference registration application as developed in the first recipe. It will be necessary to create this application before the other recipes can be demonstrated. Creating the Registration Application A RegistrationApplication is developed in this recipe. It provides the ability of attendees to register for a conference. The application will record their personal information using an entity and other supporting EJBs. This recipe details how to create this application. Getting ready The RegistrationApplication consists of the following classes: Attendee – An entity representing a person attending the conference AbstractFacade – A facade-based class AttendeeFacade – The facade class for the Attendee class RegistrationManager – Used to control the registration process RegistrationServlet – The GUI interface for the application The steps used to create this application include: Creating the Attendee entity and its supporting classes Creating a RegistrationManager EJB to control the registration process Creating a RegistrationServlet to drive the application The RegistrationManager will be the primary vehicle for the demonstration of interceptors. How to do it... Create a Java EE application called RegistrationApplication. Add a packt package to the EJB module and a servlet package in the application's WAR module. Next, add an Attendee entity to the packt package. This entity possesses four fields: name, title, company, and id. The id field should be auto generated. Add getters and setters for the fields. Also add a default constructor and a three argument constructor for the first three fields. The major components of the class are shown below without the getters and setters. @Entity public class Attendee implements Serializable { private String name; private String title; private String company; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public Attendee() { } public Attendee(String name, String title, String company) { this.name = name; this.title = title; this.company = company; } } Next, add an AttendeeFacade stateless session bean which is derived from the AbstractFacade class. The AbstractFacade class is not shown here. @Stateless public class AttendeeFacade extends AbstractFacade<Attendee> { @PersistenceContext(unitName = "RegistrationApplication-ejbPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } public AttendeeFacade() { super(Attendee.class); } } Add a RegistrationManager stateful session bean to the packt package. Add a single method, register, to the class. The method should be passed three strings for the name, title, and company of the attendee. It should return an Attendee reference. Use dependency injection to add a reference to the AttendeeFacade. In the register method, create a new Attendee and then use the AttendeeFacade class to create it. Next, return a reference to the Attendee. @Stateful public class RegistrationManager { @EJB AttendeeFacade attendeeFacade; Attendee attendee; public Attendee register(String name, String title, String company) { attendee = new Attendee(name, title, company); attendeeFacade.create(attendee); return attendee; } } In the servlet package of the WAR module, add a servlet called RegistrationServlet. Use dependency injection to add a reference to the RegistrationManager. In the try block of the processRequest method, use the register method to register an attendee and then display the attendee's name. public class RegistrationServlet extends HttpServlet { @EJB RegistrationManager registrationManager; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet RegistrationServlet</title>"); out.println("</head>"); out.println("<body>"); Attendee attendee = registrationManager.register("Bill Schroder", "Manager", "Acme Software"); out.println("<h3>" + attendee.getName() + " has been registered</h3>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } ... } Execute the servlet. The output should appear as shown in the following screenshot: How it works... The Attendee entity holds the registration information for each participant. The RegistrationManager session bean only has a single method at this time. In later recipes we will augment this class to add other capabilities. The RegistrationServlet is the client for the EJBs.
Read more
  • 0
  • 0
  • 2412

article-image-overview-web-services-sakai
Packt
06 Jul 2011
16 min read
Save for later

An overview of web services in Sakai

Packt
06 Jul 2011
16 min read
Connecting to Sakai is straightforward, and simple tasks, such as automatic course creation, take only a few lines of programming effort. There are significant advantages to having web services in the enterprise. If a developer writes an application that calls a number of web services, then the application does not need to know the hidden details behind the services. It just needs to agree on what data to send. This loosely couples the application to the services. Later, if you can replace one web service with another, programmers do not need to change the code on the application side. SOAP works well with most organizations' firewalls, as SOAP uses the same protocol as web browsers. System administrators have a tendency to protect an organization's network by closing unused ports to the outside world. This means that most of the time there is no extra network configuration effort required to enable web services. Another simplifying factor is that a programmer does not need to know the details of SOAP or REST, as there are libraries and frameworks that hide the underlying magic. For the Sakai implementation of SOAP, to add a new service is as simple as writing a small amount of Java code within a text file, which is then compiled automatically and run the first time the service is called. This is great for rapid application development and deployment, as the system administrator does not need to restart Sakai for each change. Just as importantly, the Sakai services use the well-known libraries from the Apache Axis project. SOAP is an XML message passing protocol that, in the case of Sakai sites, sits on top of the Hyper Text Transfer Protocol (HTTP). HTTP is the protocol used by web browsers to obtain web pages from a server. The client sends messages in XML format to a service, including the information that the service needs. Then the service returns a message with the results or an error message. The architects introduced SOAP-based web services first to Sakai , adding RESTful services later. Unlike SOAP, instead of sending XML via HTTP posts to one URL that points to a service, REST sends to a URL that includes information about the entity, such as a user, with which the client wishes to interact. For example, a REST URL for viewing an address book item could look similar to http://host/direct/addressbook_item/15. Applying URLs in this way makes for understandable, human-readable address spaces. This more intuitive approach simplifies coding. Further, SOAP XML passing requires that the client and the server parse the XML and at times, the parsing effort is expensive in CPU cycles and response times. The Entity Broker is an internal service that makes life easier for programmers and helps them manipulate entities. Entities in Sakai are managed pieces of data such as representations of courses, users, grade books, and so on. In the newer versions of Sakai, the Entity Broker has the power to expose entities as RESTful services. In contrast, for SOAP services, if you wanted a new service, you would need to write it yourself. Over time, the Entity Broker exposes more and more entities RESTfully, delivering more hooks free to integrate with other enterprise systems. Both SOAP and REST services sit on top of the HTTP protocol. Protocols This section explains how web browsers talk to servers in order to gather web pages. It explains how to use the telnet command and a visual tool called TCPMON (http://ws.apache.org/commons/tcpmon/tcpmontutorial.html) to gain insight into how web services and Web 2.0 technologies work. Playing with Telnet It turns out that message passing occurs via text commands between the browser and the server. Web browsers use HTTP to get web pages and the embedded content from the server and to send form information to the server. HTTP talks between the client and server via text (7-bit ASCII) commands. When humans talk with each other, they have a wide vocabulary. However, HTTP uses fewer than twenty words. You can directly experiment with HTTP using a Telnet client to send your commands to a web server. For example, if your demonstration Sakai instance is running on port 8080, the following command will get you the login page: telnet localhost 8080 GET /portal/login The GET command does what it sounds like and gets a web page. Forms can use the GET verb to send data at the end of the URL. For example, GET /portal/login?name=alan&age=15 is sending the variables name=alan and age=15 to the server. Installing TCPMON You can use the TCPMON tool to view requests and responses from a web browser such as Firefox. One of TCPMON's abilities is that it can act as an invisible man in the middle, recording the messages between the web browser and the server. Once set up, the requests sent from the browser go to TCPMON and it passes the request on to the server. The server passes back a response and then TCPMON, a transparent proxy, returns the response to the web browser. This allows us to look at all requests and responses graphically. First, you can set up TCPMON to listenon a given port number—by convention, normally port 8888—and then you can configure your web browser to send its requests through the proxy. Then, you can type the address of a given page into the web browser, but instead of going directly to the relevant server, the browser sends the request to the proxy, which then passes it on and passes the response back. TCPMON displays both the request and the responses in a window. You can download TCPMON here. After downloading and unpacking, you can—from within the build directory—run either tcpmon.bat for the Windows environment or tcpmon.sh for the UNIX/Linux environment. To configure a proxy, you can click on the Admin tab and then set the Listen Port to 8888 and select the Proxy radio button. After that, clicking on Add will create a new tab, where the requests and responses will be displayed later. Your favorite web browser now has to recognize the newly-setup proxy. For Firefox 3, you can do this by selecting the menu option Edit/Preferences, and then choosing the Advanced tab and the Network tab, as shown in the next screenshot. You will need to set the proxy options, HTTP proxy to 127.0.0.1, and the port number to 8888. If you do this, you will need to ensure that the No proxies text input is blank. Clicking on the OK button enables the new settings. (Move the mouse over the image to enlarge.) To use the Proxy from within Internet Explorer 7 for a Local Area Network (LAN), you can edit the dialog box found under Tools | Internet Options | Connections | LAN settings. Once the proxy is working, typing http://localhost:8080/portal/login in the address bar will seamlessly return the login page of your local Sakai instance. Otherwise, you will see an error message similar to Proxy Server Refused Connection for Firefox or Internet Explorer cannot display the webpage. To turn off the proxy settings, simply select the No Proxies radio box and click on OK for Firefox 3, and for Internet Explorer 7, unselect the Use a proxy server for the LAN tick box and click on OK Requests and returned status codes When TCPMON is running a proxy on port 8888, it allows you to view the requests from the browser and the response in an extra tab, as shown in the following screenshot. Notice the extra information that the browser sends as part of the request. HTTP/1.1 defines the protocol and version level and the lines below GET are the header variables. The User-Agent defines which client sends the request. The Accept headers tell the server what the capabilities of the browser are, and the Cookie header defines the value stored in a cookie. HTTP is stateless, in principle; each response is based only on the current request. However, to get around this, persistent information can be stored in cookies. Web browsers normally store their representation of a cookie as a little text file or in a small database on the end users' computers. Sakai uses the supporting features of a servlet container, such as Tomcat, to maintain state in cookies. A cookie stores a session ID, and when the server sees the session ID, it can look up the request's server-side state. This state contains information such as whether the user is logged in, or what he or she has ordered. The web browser deletes the local representation of the cookie each time the browser closes. A cookie that is deleted when a web browser closes is known as a session cookie. The server response starts with the protocol followed by a status number. HTTP/1.1 200 OK tells the web browser that the server is using HTTP version 1.1 and was able to return the requested web page successfully. 2xx status codes imply success. 3xx status codes imply some form of redirection and tell the web browser where to try to pick up the requested resource. 4xx status codes are for client errors, such as malformed requests or lack of permission to obtain the resource. 4xx states are fertile grounds for security managers to look in log files for attempted hacking. 5xx status codes mostly have to do with a failure of the server itself and are mostly of interest to system administrators and programmers during the debugging cycle. In most cases, 5xx status numbers are about either high server load or a broken piece of code. Sakai is changing rapidly and even with the most vigorous testing, there are bound to be the occasional hiccups. You will find accurate details of the full range of status codes at: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. Another important part of the response is Content-Type, which tells the web browser which type of material the response is returning, so the browser knows how to handle it. For example, the web browser may want to run a plug-in for video types and display text natively. Content-Length in characters is normally also given. After the header information is finished, there is a newline followed by the content itself. Web browsers interpret any redirects that are returned by sending extra requests. Web browsers also interpret any HTML pages and make multiple requests for resources such as JavaScript files and images. Modern browsers do not wait until the server returns all the requests, but render the HTML page live as the server returns the parts. The GET verb is not very efficient for posting a large amount of data, as the URL has a length limit of around 2000 characters. Further, the end user can see the form data, and the browser may encode entities such as spaces to make the URL unreadable. There is also a security aspect: if you are typing passwords in forms using GET, others may see your password or other details. This is not a good idea, especially at Internet Cafés where the next user who logs on can see the password in the browsing history. The POST verb is a better choice. Let us take as an example the Sakai demonstration login page (http://localhost:8080/portal/login). The login page itself contains a form tag that points to the relogin page with the POST method. <form method="post" action="http://localhost:8080/portal/relogin" enctype="application/x-www-form-urlencoded"> Note that the HTML tag also defines the content type. Key features of the POST request compared to GET are: The form values are stored as content after the header values There is a newline between the end of the header and the data The request mentions data and the amount of data by the use of the Content-Length header value The essential POST values for a login form with user admin (eid=admin) and password admin (pw=admin) will look like: POST http://localhost:8080/portal/relogin HTTP/1.1 Content-Type: application/x-www-form-urlencoded Content-Length: 31 eid=admin&pw=admin&submit=Login POST requests can contain much more information than GET requests, and the requests hide the values from the address bar of the web browser. This is not secure. The header is just as visible as the URL, so POST values are also neither hidden nor secure. The only viable solution is for your web browser to encrypt your transactions using SSL/TLS (http://www.ietf.org/rfc/rfc2246.txt) for security, and this occurs every time you connect to a server using an HTTPS URL. SOAP Sakai uses the Apache Axis framework, which the developers have configured to accept SOAP calls via POST. SOAP sends messages in a specific XML format with the Content-Type, otherwise known as MIME type, application/soap+xml. A programmer does not need to know more than that, as the client libraries take care of the majority of the excruciating low-level details. An example SOAP message generated by the Perl module, SOAP::Lite (http://www.soaplite.com/), for creating a login session in Sakai will look like the following POST data: <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope soap_encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" > <c-gensym3 xsi_type="xsd:string">admin</c-gensym3> <c-gensym5 xsi_type="xsd:string">admin</c-gensym5> </login> </soap:Body> </soap:Envelope> There is an envelope with a body containing data for the service to consume. The important point to remember is that both the client and the server have to be able to parse the specific XML schema. SOAP messages can include extra security features, but Sakai does not require these. The architects expect organizations to encrypt web services using SSL/TSL. The last extra SOAP-related complexity is the Web Service Description Language (http://www.w3.org/TR/wsdl). Web services may change location or exist in multiple locations for redundancy. The service writer can define the location of the services and the data types involved with those services in another file, in XML format. JSON Also worth mentioning is JavaScript Object Notation (JSON), which is another popular format, passed using HTTP. When web developers realized that they could force browsers to load parts of a web page in at a time, it significantly improved the quality of the web browsing experience for the end user. This asynchronous loading enables all kinds of whiz-bang features, such as when you type in a search term and can choose from a set of search term completions before pressing on the Submit button. Asynchronous loading delivers more responsive and richer web pages that feel more like traditional desktop applications than a plain old web page. JSON is one of the formats of choice for passing asynchronous requests and responses. The asynchronous communication normally occurs through HTTP GET or POST, but with a specific content structure that is designed to be human readable and script language parser-friendly. JSON calls have the file extension .json as part of the URL. As mentioned in RFC 4627, an example image object communicated in JSON looks like: { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": "100" }, "IDs": [116, 943, 234, 38793] } } By confusing the boundaries between client and server, a lot of the presentation and business logic is locked on the client side in scripting languages such as JavaScript. The scripting language orchestrates the loading of parts of pages and the generation of widget sets. Frameworks such as jQuery (http://jquery.com/) and MyFaces (http://myfaces.apache.org/) significantly ease the client-side programming burden. REST To understand REST, you need to understand the other verbs in HTTP (http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html). The full HTTP set is OPTIONS, GET, HEAD, POST, PUT, DELETE, and TRACE. The HEAD verb returns from the server only the headers of the response without the content, and is useful for clients that want to see if the content has changed since the last request. PUT requests that the content in the request be stored at a particular location mentioned in the request. DELETE is for deleting the entity. REST uses the URL of the request to route to the resource, and the HTTP verb GET is used to get a resource, PUT to update, DELETE to delete, and POST to add a new resource. In general, POST request is for creating an item, PUT for updating an item, DELETE for deleting an item, and GET for returning information on the item. In SOAP, you are pointing directly towards the service the client calls or indirectly via the web service description. However, in REST, part of the URL describes the resource or resources you wish to work with. For example, a hypothetical address book application that lists all e-mail addresses in HTML format would look similar to the following: GET /email To list the addresses in XML format or JSON format: GET /email.xml GET /email.json To get the first e-mail address in the list: GET /email/1 To create a new e-mail address, of course remembering to add the rest of e-mail details to the end of the GET: POST /email In addition, to delete address 5 from the list use the following command: DELETE /email/5 To obtain address 5 in other formats such as JSON or XML, then use file extensions at the end of the URL, for example: GET /email/5.json GET /email/5.xml RESTful services are intuitively more descriptive than SOAP services, and they enable easy switching of the format from HTML to JSON to fuel the dynamic and asynchronous loading of websites. Due to the direct use of HTTP verbs by REST, this methodology also fits well with the most common application type: CRUD (Create, Read, Update, and Delete) applications, such as the site or user tools within Sakai. Now that we have discussed the theory, in the next section we shall discuss which Sakai-related SOAP services already exist.
Read more
  • 0
  • 0
  • 3366

article-image-drupal-7-themes-dynamic-theming
Packt
05 Jul 2011
11 min read
Save for later

Drupal 7 Themes: Dynamic Theming

Packt
05 Jul 2011
11 min read
  Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling Designating a separate Admin theme Let's start with one of the simplest techniques, that is, designating a separate theme for the use of your admin interface. The Drupal 7 system comes bundled with the Seven theme, which is purpose-built for use by the administration interface. Seven is assigned as your site's admin theme by default. You can, however, change to any theme you desire. Changing the admin theme is done directly from within the admin system's Theme Manager. To change the admin theme, follow these steps: Log in and access your site's admin system. Select the Appearance option from the Management menu. After the Theme Manager loads in your browser, scroll down to the bottom of the page. You can see at the bottom of that page a combo box labeled Administration theme, as shown in the following screenshot. Select the theme you desire from the combo box. Click Save configuration, and your selected theme should appear immediately. The Administration theme combo box will display all the enabled themes on your site. If you don't see what you want listed in the combo box, scroll back up, and make sure you have enabled the theme you desire. If the theme you desire is not listed in the Theme Manager, you will need to install it first! Additionally note the option listed below the Administration theme combo box: Use the administration theme when editing or creating content. Though this option is enabled by default, you may want to de-select this option. If you de-select the option, the system will use the frontend theme for content creation and editing. In some cases, this is more desirable as it allows you to see the page in context, instead of inside the admin theme. It provides, in other words, a more realistic view of the final content item. Using multiple page templates Apart from basic blog sites, most websites today employ different page layouts for different purposes. In some cases this is as simple as one layout for the home page and another for the internal pages. Other sites take this much further and deliver different layouts based on content, function, level of user access, or other criteria. There are various ways you can meet this need with Drupal. Some of the approaches are quite simple and can be executed directly from the administration interface; others require you to work with the files that make up your Drupal theme. Creative use of configuration and block assignments can address some needs. Most people, however, will need to investigate using multiple templates to achieve the variety they desire. The bad news is that there is no admin system shortcut for controlling multiple templates in Drupal—you must manually create the various templates and customize them to suit your needs. The good news is that creating and implementing additional templates is not terribly difficult and is it possible to attain a high degree of granularity with the techniques described next. Indeed should you be so inclined, you could literally define a distinct template for each individual page of your site! While there are many good reasons for running multiple page templates, you should not create additional templates solely for the purpose of disabling regions to hide blocks. While the approach will work, it will result in a performance hit for the site, as the system will still produce the blocks, only to then wind up not displaying them for the pages. The better practice is to control your block visibility through the Blocks Manager. Drupal employs an order of precedence, implemented using a naming convention. You can unlock the granularity of the system through proper application of the naming convention. It is possible, for example, to associate templates with every element on the path, or with specific users, or with a particular functionality or node type—all through the simple process of creating a copy of the existing template and then naming it appropriately. In Drupal terms, this is called creating template suggestions. When the system detects multiple templates, it prefers the specific to the general. If the system fails to find multiple templates, it will apply the relevant default template from the Drupal core. The fundamental methodology of the system is to use the most specific template file it finds and ignore other, more general templates. This basic principle, combined with proper naming of the templates, gives you control over the template that will be applied in various situations. The default suggestions provided by the Drupal system should be sufficient for the vast majority of theme developers. However, if you find that you need additional suggestions beyond those provided by the system, it is possible to extend your site and add new suggestions. See http://drupal.org/node/190815 for an example of this advanced Drupal theming technique. Let's take a series of four examples to show how this system feature can be employed to provide solutions to common problems: Use a unique template for your site's home page Use a different template for a group of pages Assign a specific template to a specific page Designate a specific template for a specific user Creating a unique home page template Let's assume that you wish to set up a unique look and feel for the home page of a site. The ability to employ different appearance for the home page and the interior pages is one of the most common requests web developers hear. There are several techniques you can employ to achieve the result; which is right for you depends on the extent and nature of the variation required, and to a lesser extent, upon the flexibility of the theme you presently employ. For many people a combination of the techniques will be used. Another factor to consider is the abilities of the people who will be managing and maintaining the site. There is often a conflict between what is easiest for the developers and what will be easiest for the site administrators. You need to keep this in mind and strive to create manageable structures. It is, for example, much easier for a client to manage a site that populates the home page dynamically, then to have to create content in multiple places and remember to assign things in the proper fashion. In this regard, using dedicated templates for the home page is generally preferable. One option to address this issue is the creative use of configuration and assignment. You can achieve a degree of variety within a theme—without creating dedicated templates—by controlling the visibility and positioning of the blocks on the home page. Another option you may want to consider is using a contributed module to assist with this task. The Panels and Views modules in particular are quite useful for assembling complex home page layouts. See Useful Extensions for Themers for more information on these extensions. If configuration and assignment alone do not give you enough flexibility, you will want to consider using a dedicated template that is purpose-built for your home page content. To create a dedicated template for your home page, follow these steps: Access the Drupal installation on your server. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system). Paste it back in the same directory as the original file and rename it page--front.tpl.php. Make any changes you desire to the new page--front.tpl.php. Save the file. Clear the Drupal theme cache. That's it—it's really that easy. The system will now automatically display your new template file for the site's home page, and use the default page.tpl.php for the rest of the site. Note that page--front.tpl.php will be applied to whatever page you specify as the site's front page using the site configuration settings. To override the default home page setting visit the Site Information page from the Configuration Manager. To change the default home page, enter the path of the page you desire to use as the home page into the field labeled Default home page. Next, let's use the same technique to associate a template with a group of pages. The file naming syntax has changed slightly in Drupal 7. In the past, multiple words contained in a file name were consistently separated with a single hyphen. In Drupal 7, a single hyphen is only used for compound words; a double hyphen is used for targeting a template. For example, page--front.tpl.php uses the double hyphen as it indicates that we are targeting the page template when displayed for the front page. In contrast, maintenance-page.tpl.php shows the single hyphen syntax, as it is a compound name. Remember, suggestions only work when placed in the same directory as the base template. In other words, to get page--front.tpl.php to work, you must place it in the same directory as page.tpl.php. Using a different template for a group of pages You can provide a template to be used by any distinct group of pages. The approach is the same as we saw in the previous section, but the name for the template file derives from the path for the pages in the group. For example, to theme the pages that relate to users, you would create the template page--user.tpl.php. A note on templates and URLs Drupal bases the template order of precedence on the default path generated by the system. If the site is using a module like Pathauto, that alters the path that appears to site visitors, remember that your templates will still be displayed based on the original paths. The exception here being page--front.tpl.php, which will be applied to whatever page you specify as the site's front page using the site's Configuration Manager. The following table presents a list of suggestions you can employ to theme various pages associated with the default page groupings in the Drupal system: The steps involved in creating a template-specific theme to a group of pages is the same as that used for the creation of a dedicated home page template: Access the Drupal installation on your server. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system). Paste it back in the same directory as the original file and rename it as shown in the table above, for example page--user.tpl.php. Make any changes you desire to the new template. Save the file. Clear the Drupal theme cache. Note that the names given in the table above will set the template for all the pages within the group. If you need a more granular solution—that is, to create a template for a sub-group or an individual page within the group, see the discussion in the following sections. Assigning a specific template to a specific page Taking this to its extreme, you can associate a specific template with a specific page. By way of example, assume we wish to provide a unique template for a specific content item. Let's assume the page you wish to style is located at http://www.demosite.com/node/2. The path of the page gives you the key to the naming of the template you need to style it. In this case, you would create a copy of the page.tpl.php file and rename it to page--node--2.tpl.php. Using template suggestion wildcards One of the most interesting changes in Drupal 7 is the introduction of template suggestion wildcards. In the past, you would have to specify the integer value for individual nodes, for example, page--user--1.tpl.php. If you wished to also style the pages for the entire group of users, you had the choice of either creating page--user.tpl.php, that affects all user pages, including the login forms, or you would be forced to create individual templates to cover each of the individual users. With Drupal 7 we can now simply use a wildcard in place of the integer values, for example, page--user--%.tpl.php. The new template page--user--%.tpl.php will now affect all the individual user pages without affecting the login pages. Designating a specific template for a specific user Assume that you want to add a personalized theme for the user with the ID of 1 (the first user in your Drupal system, and for many sites, the ID used by the super user). To do this, copy the existing page.tpl.php file, rename it to reflect its association with the specific user, and make any changes to the new file. To associate the new template file with the user, name the file: page—-user--1.tpl. Now, when the user with ID=1 logs into the site, they will be presented with this template. Only user 1 will see this template and only when he or she is logged in and visiting the user page.
Read more
  • 0
  • 0
  • 2888
article-image-drupal-7-themes-creating-dynamic-css-styling
Packt
05 Jul 2011
7 min read
Save for later

Drupal 7 Themes: Creating Dynamic CSS Styling

Packt
05 Jul 2011
7 min read
Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling The reader would benefit by referring the previous article on Dynamic Theming In addition to creating templates that are displayed conditionally, the Drupal system also enables you to apply CSS selectively. Drupal creates unique identifiers for various elements of the system and you can use those identifiers to create specific CSS selectors. As a result, you can provide styling that responds to the presence (or absence) of specific conditions on any given page. Employing $classes for conditional styling One of the most useful dynamic styling tools is $classes. This variable is intended specifically as an aid to dynamic CSS styling. It allows for the easy creation of CSS selectors that are responsive to either the layout of the page or to the status of the person viewing the page. This technique is typically used to control the styling where there may be one, two, or three columns displayed, or to trigger display for authenticated users. Prior to Drupal 6, $layout was used to detect the page layout. With Drupal 6 we got instead, $body_classes. Now, in Drupal 7, it's $classes. While each was intended to serve a similar purpose, do not try to implement the previous incarnations with Drupal 7, as they are no longer supported! By default $classes is included with the body tag in the system's html.tpl.php file; this means it is available to all themes without the necessity of any additional steps on your part. With the variable in place, the class associated with the body tag will change automatically in response to the conditions on the page at that time. All you need to do to take advantage of this and create the CSS selectors that you wish to see applied in the various situations. The following chart shows the dynamic classes available to you by default in Drupal 7: If you are not certain what this looks like and how it can be used, simply view the homepage of your site with the Bartik theme active. Use the view source option in your browser to then examine the body tag of the page. You will see something like this: <body class="html front not-logged-in one-sidebar sidebar-first page-node">. The class definition you see there is the result of $classes. By way of comparison, log in to your site and repeat this test. The body class will now look something like this: <body class="html front logged-in one-sidebar sidebar-first page-node">. In this example, we see that the class has changed to reflect that the user viewing the page is now logged in. Additional statements may appear, depending on the status of the person viewing the page and the additional modules installed. While the system implements this technique in relation to the body tag, its usage is not limited to just that scenario; you can use $classes with any template and in a variety of situations. If you'd like to see a variation of this technique in action (without having to create it from scratch), take a look at the Bartik theme. Open the node.tpl.php file and you can see the $classes variable added to the div at the top of the page; this allows this template to also employ the conditional classes tool. Note that the placement of $classes is not critical; it does not have to be at the top of the file. You can call this at any point where it is needed. You could, for example, add it to a specific ordered list by printing out $classes in conjunction with the li tag, like this: <li class="<?php print $classes; ?>"> $classes is, in short, a tremendously useful aid to creating dynamic theming. It becomes even more attractive if you master adding your own variables to the function, as discussed in the next section. Adding new variables to $classes To make things even more interesting (and useful), you can add new variables to $classes through use of the variable process functions. This is implemented in similar fashion to other preprocess function. Let's look at an example, in this case, taken from Drupal.org. The purpose here is to add a striping class keyed to the zebra variable and to make it available through $classes. To set this up, follow these steps: Access your theme's template.php file. If you don't have one, create it. Add the following to the file: <?php function mythemename_preprocess_node(&$vars) { // Add a striping class. $vars['classes_array'][] = 'node-' . $vars['zebra']; } ?> Save the file. The variable will now be available in any template in which you implement $classes. Creating dynamic selectors for nodes Another handy resource you can tap into for CSS styling purposes is Drupal's node ID system. By default, Drupal generates a unique ID for each node of the website. Node IDs are assigned at the time of node creation and remain stable for the life of the node. You can use the unique node identifier as a means of activating a unique selector. To make use of this resource, simply create a selector as follows: #node-[nid] { } For example, assume you wish to add a border to the node with the ID of 2. Simply create a new selector in your theme's stylesheet, as shown: #node-2 { border: 1px solid #336600 } As a result, the node with the ID of 2 will now be displayed with a 1-pixel wide solid border. The styling will only affect that specific node. Creating browser-specific stylesheets A common solution for managing some of the difficulties attendant to achieving true cross-browser compatibility is to offer stylesheets that target specific browsers. Internet Explorer tends to be the biggest culprit in this area, with IE6 being particularly cringe-worthy. Ironically, Internet Explorer also provides us with one of the best tools for addressing this issue. Internet Explorer implements a proprietary technology known as Conditional Comments. It is possible to easily add conditional stylesheets to your Drupal system through the use of this technology, but it requires the addition of a contributed module to your system, called Conditional Stylesheets. While it is possible to set up conditional stylesheets without the use of the module, it is more work, requiring you to add multiple lines of code to your template.php. With the module installed, you just add the stylesheet declarations to your .info file and then, using a simple syntax, set the conditions for their use. Note also that the Conditional Stylesheets module is in the queue for inclusion in Drupal 8, so it is certainly worth looking at now. To learn more, visit the project site at http://drupal.org/project/conditional_styles. If, in contrast, you would like to do things manually by creating a preprocess function to add the stylesheet and target it by browser key, please see http://drupal.org/node/744328. Summary This article covers the basics needed to make your Drupal theme responsive to the contents and the users. By applying the techniques discussed in this article, you can control the theming of pages based on content, state of the pages, or the users viewing them. Taking the principles one step further, you can also make the theming of elements within a page conditional. The ability to control the templates used and the styling of the page and its elements is what we call dynamic theming. Further resources on this subject: Drupal 7: Customizing an Existing Theme [Article] Drupal 7 Themes: Dynamic Theming [Article] 25 Useful Extensions for Drupal 7 Themers [Article] Drupal and Ubercart 2.x: Install a Ready-made Drupal Theme [Article] Building an Admin Interface in Drupal 7 Module Development [Article] Content in Drupal: Frequently Asked Questions (FAQ) [Article] Drupal Web Services: Twitter and Drupal [Article]
Read more
  • 0
  • 0
  • 2660

article-image-pfsense-configuring-nat-and-firewall-rules
Packt
05 Jul 2011
5 min read
Save for later

pfSense: Configuring NAT and Firewall Rules

Packt
05 Jul 2011
5 min read
  pfSense 2 Cookbook A practical, example-driven guide to configuring even the most advanced features of pfSense 2.0         Read more about this book       (For more resources related to this subject, see here.) Introduction The core functionality of any firewall involves creating port forward and firewall security rules, and pfSense is no different. These core features, plus others, can all be found on the main Firewall menu of the pfSense web interface. This article explains how to configure these rules and the features associated with them. Once you've done a few, you'll realize just how easy it is with pfSense. Creating an alias This recipe describes how to use, create, edit, and delete aliases. Aliases provide a degree of separation between our rules and values that may change in the future (for example, IP addresses, ports, and so on). It's best to use aliases whenever possible. How to do it... Browse to Firewall | Aliases. Click on the "plus" button to add a new alias. Add a Name for the alias. Add an optional Description. Select an alias Type and finish the configuration based on that selection. See the following There's more section for details on each alias type (Hosts, Networks, Ports, OpenVPN Users, URL, and URL Table). (Move the mouse over the image to enlarge it.) Save the changes. Apply changes, if necessary. How it works... An alias is a place-holder (that is a variable) for information that may change. A host alias is a good example; we can create a host alias called Computer1 and have it store an IP address of 192.168.1.200. We can then create firewall and NAT rules that use the Computer1 alias instead of explicitly specifying the IP address of Computer1, which may change. If the IP address of Computer1 does change, then we simply edit the alias instead of modifying numerous rules. Aliases allow for the flexibility and simplification of future changes. It's best to use aliases whenever possible. There's more... Adding aliases within aliases is a great way to manage and simplify rules. To illustrate the power of aliases, let's say our organization has a single VoIP phone that must be allowed to communicate with our VoIP server. An example of this rule without aliases is as follows: A better example, using aliases is as follows: (Move the mouse over the image to enlarge it.) An even better example, using sub-aliases is: (Move the mouse over the image to enlarge it.) Sub-aliases will allow us to easily add more phones by simply modifying an alias: (Move the mouse over the image to enlarge it.) Host alias Selecting Host(s) as an alias Type allows you to create an alias that holds one or more IP addresses: (Move the mouse over the image to enlarge it.) Network alias Selecting Network(s) as an alias Type allows you to create an alias that holds one or more networks (that is ranges of IP addresses): (Move the mouse over the image to enlarge it.) Port alias Selecting Port(s) as an alias Type allows you to create an alias that holds one or more ports: (Move the mouse over the image to enlarge it.) OpenVPN Users alias Selecting OpenVPN Users as an alias Type allows you to create an alias that holds one or more OpenVPN usernames: (Move the mouse over the image to enlarge it.) URL alias Selecting URL as an alias Type allows you to create an alias that holds one or more URLs: (Move the mouse over the image to enlarge it.) URL Table alias Selecting URL Table as an alias Type allows you to create an alias that holds a single URL pointing to a large list of addresses. This can be especially helpful when you need to import a large list of IPs and/or subnets. (Move the mouse over the image to enlarge it.) Using an alias Aliases can be used anywhere you see a red textbox. Simply begin typing and pfSense will display any available aliases that match the text you've entered: Alias auto-complete is context aware. For example, if the textbox requires a port number then pfSense will only display port alias matches. Editing an alias To modify an existing alias, follow these steps: Browse to Firewall | Aliases. Click on the edit button to edit an alias. Make the necessary changes. Save the changes. Apply the changes. Deleting an alias: To remove an existing alias, follow these steps: Browse to Firewall | Aliases. Click the delete button to delete an alias. Save the changes. Apply the changes. Bulk-importing aliases To import a list of multiple IP addresses, follow these steps: Browse to Firewall | Aliases. Click on the import button to bulk import aliases. Provide an Alias Name. Provide an optional Description. Paste a list of IP addresses, one per line, in the Aliases to Import textbox: (Move the mouse over the image to enlarge it.) Save the changes. Apply the changes.
Read more
  • 0
  • 0
  • 12323

article-image-designing-user-security-oracle-peoplesoft-applications
Packt
04 Jul 2011
12 min read
Save for later

Designing User Security for Oracle PeopleSoft Applications

Packt
04 Jul 2011
12 min read
Understanding User security Before we get into discussing the PeopleSoft security, let's spend some time trying to set the context for user security. Whenever we think of a complex system like PeopleSoft Financial applications with potentially hundreds of users, the following are but a few questions that face us: Should a user working in billing group have access to transactions, such as vouchers and payments, in Accounts Payable? Should a user who is a part of North America business unit have access to the data belonging to the Europe business unit? Should a user whose job involves entering vouchers be able to approve and pay them as well? Should a data entry clerk be able to view departmental budgets for the organization? These questions barely scratch the surface of the complex security considerations of an organization. Of course, there is no right or wrong answer for such questions, as every organization has its own unique security policies. What is more important is the fact that we need a mechanism that can segregate the access to system features. We need to enforce appropriate controls to ensure users can access only the features they need. Implementation challenge Global Vehicles' Accounts Payable department has three different types of users – Mary, who is the AP manager; Amy, who is the AP Supervisor; and Anton, who is the AP Clerk. These three types of users need to have the following access to PeopleSoft features: User typeAccess to featureDescriptionAP ClerkVoucher entryA clerk should be able to access system pages to enter vouchers from various vendors.AP SupervisorVoucher entry Voucher approval Voucher postingA supervisor also needs to have access to enter vouchers. He/she should review and approve each voucher entered by the clerk. Also, the supervisor should be able to execute the Voucher Post process that creates accounting entries for vouchers.AP ManagerPay cycle Voucher approvalAP manager should be the only one who can execute the Pay Cycle (a process that prints checks to issue payments to vendors). Manager (in addition to the Supervisor) should also have the authority to approve vouchers. Note that this is an extremely simplified scenario that does not really include all the required features in Accounts Payable. Solution We will design a security matrix that uses distinct security roles. We'll configure permission lists, roles, and user profiles to limit user access to required system features. PeopleSoft security matrix is a three-level structure consisting of Permission lists (at the bottom), Roles (in the middle) and User profiles (at the top). The following illustration shows how it is structured: We need to create a User Profile for each user of the system. This user profile can have as many Roles as needed. For example, a user can have roles of Billing Supervisor and Accounts Receivable Payment Processor, if he/she approves customer invoices as well as processes customer payments. Thus, the number of roles that a user should be granted depends entirely on his/her job responsibilities. Each role can have multiple permission lists. A Permission list determines which features can be accessed by a Role. We can specify which pages can be accessed, the mode in which they can be accessed (read only/add/update) in a permission list. In a nutshell, we can think of a Role as a grouping of system features that a user needs to access, while a Permission list defines the nature of access to those system features. Expert tip Deciding how many and which roles should be created needs quite a bit of thinking about. How easy will it be to maintain them in future? Think of the scenarios where a function needs to be removed from a role and added to another. How easy would it be to do so? As a rule of thumb, you should map system features to roles in such a way that they are non-overlapping. Similarly, map system pages to permission lists so that they are mutually exclusive. This simplifies user security maintenance to a large extent. Note that although it is advisable, it may not always be possible. Organizational requirements are sometimes too complicated to achieve this. However, a PeopleSoft professional should try to build a modular security design to the extent possible. Now, let's try to design our security matrix for the hypothetical scenario presented previously and test our thumb rule of mutually exclusive roles and permission lists. What do you observe as far as required system features for a role are concerned? You are absolutely right if you thought that some of system features (such as Voucher entry) are common across roles. Which roles should we design for this situation? Going by the principle of mutually exclusive roles, we can map system features to the permission lists (and in turn roles) without overlapping them. We'll denote our roles by the prefix 'RL' and permission lists by the prefix 'PL'. Thus, the mapping may look something like this: RolePermission listSystem featureRL_Voucher_EntryPL_Voucher_EntryVoucher EntryRL_Voucher_ApprovalPL_Voucher_ApprovalVoucher ApprovalRL_Voucher_PostingPL_Voucher_PostingVoucher PostingRL_Pay_CyclePL_Pay_CyclePay Cycle So, now we have created the required roles and permission lists, and attached appropriate permission lists to each of the roles. In this example, due to the simple scenario, each role has only a single permission list assigned to it. Now as the final step, we'll assign appropriate roles to each user's User profile. UserRoleSystem feature accessedMaryRL_Voucher_ApprovalVoucher ApprovalRL_Pay_CyclePay CycleAmyRL_Voucher_EntryVoucher EntryRL_Voucher_ApprovalVoucher ApprovalRL_Voucher_PostingVoucher PostingAntonRL_Voucher_EntryVoucher Entry Now, as you can see, each user has access to the appropriate system feature through the roles and in turn, permission lists attached to their user profiles. Can you think of the advantage of our approach? Let's say that a few months down the line, it is decided that Mary (AP Manager) should be the only one approving vouchers, while Amy (AP Supervisor) should also have the ability to execute pay cycles and issue payments to vendors. How can we accommodate this change? It's quite simple really – we'll remove the role RL_Voucher_Approval from Amy's user profile and add the role RL_Pay_Cycle to her profile. So now the security matrix will look like this: UserRoleSystem feature accessedMaryRL_Voucher_ApprovalVoucher ApprovalRL_Pay_CyclePay CycleAmyRL_Voucher_EntryVoucher EntryRL_Pay_CyclePay CycleRL_Voucher_PostingVoucher PostingAntonRL_Voucher_EntryVoucher Entry Thus, security maintenance becomes less cumbersome when we design roles and permission lists with non-overlapping system features. Of course, this comes with a downside as well. This approach results in a large number of roles and permission lists, thereby increasing the initial configuration effort. The solution that we actually design for an organization needs to balance these two objectives. Expert tip Having too many permission lists assigned to a User Profile can adversely affect the system performance. PeopleSoft recommends 10-20 permission lists per user. Configuring permission lists Follow this navigation to configure permission lists: PeopleTools | Security | Permissions & Roles | Permission Lists The following screenshot shows the General tab of the Permission List set up page. We can specify the permission list description on this tab. We'll go through some of the important configuration activities for the Voucher Entry permission list discussed previously. Can Start Application Server?: Selecting this field enables a user with this permission list to start PeopleSoft application servers (all batch processes are executed on this server). A typical system user does not need this option. Allow Password to be Emailed?: Selecting this field enables users to receive forgotten passwords through e-mail. Leave the field unchecked to prevent unencrypted passwords from being sent in e-mails. Time-out Minutes – Never Time-out and Specific Time-out: These fields determine the number of minutes of inactivity after which the system automatically logs out the user with this permission list. The following screenshot shows the Pages tab of the permission list page. This is the most important place where we specify the menus, components, and ultimately the pages that a user can access. In PeopleSoft parlance, a component means collection of pages that are related to each other. In the previous screenshot, you are looking at a page. You can also see other related pages used to configure permission lists – General, PeopleTools, Process, and so on. All these pages constitute a component. A menu is a collection of various components. It is typically related to a system feature, such as 'Enter Voucher Information' as you can see in the screenshot. Thus, to grant a page access, we need to enter its component and menu details. Expert tip In order to find out the component and menu for a page, press CTRL+J when it is open in the internet browser. Menu Name: This is where we need to specify all the menus to which a user needs to have access. Note that a permission list can grant access to multiple menus, but our simple example includes only one system feature (Voucher entry) and in turn, only one menu. Click the + button to add and select more menus. Edit Component hyperlink: Once we select a menu, we need to specify which components under it should be accessed by the permission list. Click the Edit Components hyperlink to proceed. The system opens the Component Permissions page, as shown in the following screenshot: In this page, the system shows all components under the selected menu. The previous screenshot shows only a part of the component list under the 'Enter Voucher Information' menu. Voucher entry pages for which we need to grant access exist under a component named VCHR_EXPRESS. Click the Edit Pages hyperlink to grant access to specific pages under a given component. The system opens the Page Permissions page, as shown in the following screenshot: The given screenshot shows the partial list of pages under the Voucher Entry component. Panel Item Name: This field shows the page name to which access is to be granted. Authorized?: In order to enable a user to access a page, select this checkbox. As you can see, we have authorized this permission list to access six pages in this component. Display Only: Clicking this checkbox allows the user to get read-only access for the given page. He/she cannot make any changes to the data on this page. Add: Selecting this checkbox enables the user to add a new transaction (in this case new vouchers). Update/Display: Selecting this checkbox enables the user to retrieve the current effective dated row. He/she can also add future effective dated rows in addition to modifying them. Update/Display All: This option gives the user all of the privileges of the Update/Display option. In addition he/she can retrieve past effective dated rows as well. Correction: This option enables the user to perform all the possible operations; that is, to retrieve, modify or add past, current, and future effective dated rows. Effective dates are usually relevant for master data set ups. It drives when a particular value comes into effect. A vendor may be set up with effective date of 1/1/2001, so thatit comes into effect from that date. Now assume that its name is slated to change on 1/1/2012. However, we can add a new vendor row with the new name and the appropriate effective date. The system automatically starts using the new name from 1/1/2012. Note that there can be multiple future effective dated rows, but only one current row. The next tab PeopleTools contains configuration options that are more relevant for technical developers. As we are concentrating on business users of the system, we'll not discuss them. Click the Process tab. As shown in the following screenshot, this tab is used to configure options for Process groups. A process group is a collection of batch processes belonging to a specific internal department or a business process. For example, PeopleSoft delivers a process group ARALL that includes all Accounts Receivable batch processes. PeopleSoft delivers various pre-configured process groups; however, we can create our own process groups depending on the organization's requirements. Click the Process Group Permissions hyperlink. The system opens a new page where we can select as many process groups as needed. When a process group is selected for a permission list, it enables the users to execute batch and online processes that are part of it. The following screenshot shows the Sign-on Times tab. This tab controls the time spans when a user with this permission list can sign-on to the system. We can enforce specific days or specific time spans for a particular day when users can sign-on. In the case of our permission list, there are no such limits and users with this permission list will be able to sign-on anytime on all days of the week. The next tab on this page is the Component Interface. The component interface is a PeopleSoft utility that automates bulk data entry into PeopleSoft pages. We can select component interface values on this tab, so that users with this permission list have access rights to use them. Due to the highly technical nature of the activities involved, we will not discuss the Web Libraries, Web Services, Mass change, Links, and Audit tabs. Oracle offers exhaustive documentation on PeopleSoft applications at the following here. The next important tab on the permission list page is Query. On this tab, the system shows two hyperlinks: Access Group Permissions and Query Profile. Click the Access Group Permissions hyperlink. The system opens the Permission List Access Groups page, as shown in the next screenshot. This page controls which database tables can be accessed by users to create database queries, using a PeopleSoft tool called Query Manager. Tree Name: A tree is a hierarchical structure of database tables. As shown in the screenshot, the tree QUERY_TREE_AP groups all AP tables. Access Group: Each tree has multiple nodes called access groups. These access groups are just logical groups of tables within a tree. In the screenshot, VOUCHERS is a group of voucher-related tables within the AP table tree. With this configuration, users will be able to create database queries on voucher tables in AP. Using the Query Profile hyperlink, we can set various options that control how users can create queries (such as if he/she can use joins, unions, and so on in queries, how many database rows can be fetched by the query, if the user can copy the query output to Microsoft Excel, and so on).
Read more
  • 0
  • 0
  • 7038
article-image-wordpress-3-security-overall-risk-site-and-server
Packt
04 Jul 2011
7 min read
Save for later

WordPress 3 Security: Overall Risk to Site and Server

Packt
04 Jul 2011
7 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) How proactive we can be depends on our hosting plan. Then again, harping back to my point about security’s best friend—awareness—even Automattic bloggers could do with a heads-up. Just as site and server security each rely on the other, this section mixes the two to outline the big picture of woe and general despair. The overall concern isn’t hard to grasp. The server, like any computer, is a filing cabinet. It has many drawers—or ports—that each contain the files upon which a service (or daemon) depends. Fortunately, most drawers can be sealed, welded shut, but are they? Then again, some administrative drawers, for instance containing control panels, must be accessible to us, only to us, using a super-secure key and with the service files themselves providing no frailty to assist forcing an entry. Others, generally in our case the web files drawer, cannot even be locked because, of course, were it so then no one could access our sites. To compound the concern, there’s a risk that someone rummaging about in one drawer can internally access the others and, from there, any networked cabinets. Let's break down our site and server vulnerabilities, vying them against some common attack scenarios which, it should be noted, merely tip the iceberg of malicious possibility. Just keep smiling.   Physical server vulnerabilities Just how secure is the filing cabinet? We’ve covered physical security and expanded on the black art of social engineering. Clearly, we have to trust our web hosts to maintain the data center and to screen their personnel and contractors. Off-server backup is vital.   Open ports with vulnerable services We manage ports, and hence differing types of network traffic, primarily with a firewall. That allows or denies data packets depending on the port to which they navigate. FTP packets, for example, navigate to the server’s port 21. The web service queues up for 80. Secure web traffic—https rather than http—heads for 443. And so on. Regardless of whether or not, say, an FTP server is installed, if 21 is closed then traffic is denied. So here’s the problem. Say you allow an FTP service with a known weakness. Along comes a hacker, exploits the deficiency and gains a foothold into the machine, via its port. Similarly, every service listening on every port is a potential shoo-in for a hacker. Attacking services with a (Distributed) Denial of Service attack Many in the blogging community will be aware of the Digg of death, a nice problem to have where a post’s popularity, duly Digged, leads to a sudden rush of traffic that, if the web host doesn’t intervene and suspend the site, can overwhelm server resources and even crash the box. What’s happened here is an unintentional denial of service, this time via the web service on port 80. As with most attacks, DoS attacks come in many forms but the malicious purpose, often concentrated at big sites or networks and sometimes to gain a commercial or political advantage, is generally to flood services and, ultimately, to disable HTTP. As we introduced earlier, the distributed variety are most powerful, synchronizing the combined processing power of a zombie network, or botnet, against the target.   Access and authentication issues In most cases, we simply deny access by disabling the service and closing its port. Many of us, after all, only ever need web and administration ports. Only? Blimey! Server ports, such as for direct server access or using a more user-friendly middleman such as cPanel, could be used to gain unwanted entry if the corresponding service can be exploited or if a hacker can glean your credentials. Have some typical scenarios. Buffer overflow attacks This highly prevalent kind of memory attack is assisted by poorly written software and utilizes a scrap of code that’s often introduced through a web form field or via a port-listening service, such as that dodgy FTP daemon mentioned previously. Take a simplistic example. You’ve got a slug of RAM in the box and, on submitting data to a form, that queues up in a memory space, a buffer, where it awaits processing. Now, imagine someone submits malicious code that's longer, containing more bits, than the programmer allowed for. Again, the data queues in its buffer but, being too long, it overflows, overwriting the form’s expected command and having itself executed instead. So what about the worry of swiped access credentials? Again, possibilities abound. Intercepting data with man-in-the-middle attacks The MITM is where someone sits between your keystrokes and the server, scouring the data. That could be, for example, a rootkit, a data logger, a network, or a wireless sniffer. If your data transits unencrypted, in plain text, as is the case with FTP or HTTP and commonly with e-mail, then everything is exposed. That includes login credentials. Cracking authentication with password attacks Brute force attacks, on the other hand, run through alphanumeric and special character combinations against a login function, such as for a control panel or the Dashboard, until the password is cracked. They’re helped immensely when the username is known, so there’s a hint not to use that regular old WordPress chestnut, admin. Brute forcing can be time-consuming, but can also be coordinated between multiple zombies, warp-speeding the process with the combined processing power. Dictionary attacks, meanwhile, throw A-Z word lists against the password and hybrid attacks morph brute force and dictionary techniques to crack naïve keys such as pa55worD. The many dangers of cross-site scripting (XSS) XSS crosses bad code—adds it—with an unsecured site. Site users become a secondary target here because when they visit a hacked page, and their browser properly downloads everything as it resolves, they retrieve the bad code to become infected locally. An in-vogue example is the iframe injection which adds a link that leads to, say, a malicious download on another server. When a visitor duly views the page, downloading it locally, malware and all, the attacker has control over that user’s PC. Lovely. There's more. Oh so much more. Books more in fact. There's too much to mention here, but another classic tactic is to use XSS for cookie stealing. ... All that’s involved here is a code injection to some poor page that reports to a log file on the hacker’s server. Page visitors have their cookies chalked up to the log and have their session hijacked, together with their session privileges. If the user’s logged into webmail, so can the hacker. If it’s online banking, goodbye to your funds. If the user’s a logged-in WordPress administrator, you get the picture. Assorted threats with cross-site request forgery (CSRF) This is not the same as XSS, but there are similarities, the main one being that, again, a blameless if poorly built site is crossed with malicious code to cause an effect. A user logs into your site and, in the regular way, is granted a session cookie. The user surfs some pages, one of them having been decorated with some imaginative code from an attacker which the user’s browser correctly downloads. Because that script said to do something to your site and because the unfortunate user hadn’t logged out of your site, relinquishing the cookie, the action is authorized by the user’s browser. What may happen to your site, for example, depends on the user’s privileges so could vary from a password change or data theft to a nice new theme effect called digital soup.  
Read more
  • 0
  • 0
  • 2020

article-image-wordpress-3-security-risks-and-threats
Packt
04 Jul 2011
11 min read
Save for later

WordPress 3 Security: Risks and Threats

Packt
04 Jul 2011
11 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) You may think that most of this is irrelevant to WordPress security. Sadly, you'd be wrong. Your site is only as safe as the weakest link: of the devices that assist in administering it or its server; of your physical security; or of your computing and online discipline. To sharpen the point with a simple example, whether you have an Automattic-managed wordpress.com blog or unmanaged dedicated site hosting, if a hacker grabs a password on your local PC, then all bets are off. If a hacker can borrow your phone, then all bets are off. If a hacker can coerce you to a malicious site, then all bets are off. And so on. Let's get one thing clear. There is no such thing as total security and anyone who says any different is selling something. Then again, what we can achieve, given ongoing attention, is to boost our understanding, to lock our locations, to harden our devices, to consolidate our networks, to screen our sites and, certainly not least of all, to discipline our computing practice. Even this carries no guarantee. Tell you what though, it's pretty darned tight. Let's jump in and, who knows, maybe even have a laugh here and there to keep us awake. Calculated risk So what is the risk? Here's one way to look at the problem: RISK = VULNERABILITY x THREAT A vulnerability is a weakness, a crack in your armour. That could be a dodgy wireless setup or a poorly coded plugin, a password-bearing sticky note, or an unencrypted e-mail. It could just be the tired security guy. It could be 1001 things, and then more besides. The bottom line vulnerability though, respectfully, is our ignorance. A threat, on the other hand, is an exploit, some means of hacking the flaw, in turn compromising an asset such as a PC, a router, a phone, your site. That's the sniffer tool that intercepts your wireless, the code that manipulates the plugin, a colleague that reads the sticky, whoever reads your mail, or the social engineer who tiptoes around security. The risk is the likelihood of getting hacked. If you update the flawed plugin, for instance, then the threat is redundant, reducing the risk. Some risk remains because, when a further vulnerability is found there will be someone, somewhere, who will tailor an exploit to threaten it. This ongoing struggle to minimize risk is the cat and mouse that is security. To minimize risk, we defend vulnerabilities against threats. You may be wondering, why bother calculating risk? After all, any vulnerability requires attention. You'd not be wrong but, such is the myriad complexity of securing multiple assets, any of which can add risk to our site, and given that budgets or our time are at issue, we need to prioritize. Risk factoring helps by initially flagging glaring concerns and, ideally assisted by a security policy, ensuring sensible ongoing maintenance. Securing a site isn't a one-time deal. Such is the threatscape, it's an ongoing discipline.   An overview of our risk Let's take a WordPress site, highlight potential vulnerabilities, and chew over the threats. WordPress is an interactive blogging application written in PHP and working in conjunction with a SQL database to store data and content. The size and complexity of this content manager is extended with third party code such as plugins and themes. The framework and WordPress sites are installed on a web server and that, the platform, and its file system are administered remotely. WordPress. Powering multi-millions of standalone sites plus another 20 million blogs at wordpress.com, Automattic's platform is an attack target coveted by hackers. According to wordpress.org 40% of self-hosted sites run the gauntlet with versions 2.3 to 2.9. Interactive. Just being online, let alone offering interaction, sites are targets. A website, after all, is effectively an open drawer in an otherwise lockable filing cabinet, the server. Now, we're inviting people server-side not just to read but to manipulate files and data. Application, size, and complexity. Not only do applications require security patching but, given the sheer size and complexity of WordPress, there are more holes to plug. Then again, being a mature beast, a non-custom, hardened WordPress site is in itself robust. PHP, third party code, plugins, and themes. Here's a whole new dynamic. The use of poorly written or badly maintained PHP and other code adds a slew of attack vectors. SQL database. Containing our most valuable assets, content and data, MySQL, and other database apps are directly available to users making them immediate targets for hackers. Data. User data from e-mails to banking information is craved by cybercriminals and its compromise, else that of our content, costs sites anything from reputation to a drop or ban in search results as well as carrying the remedial cost of time and money. Content and media. Content is regularly copied without permission. Likewise with media, which can also be linked to and displayed on other sites while you pay for its storage and bandwidth. Upload, FTP, and private areas provide further opportunities for mischief. Sites. Sites-plural adds risk because a compromise to one can be a compromise to all. Web server. Server technologies and wider networks may be hacked directly or via WordPress, jeopardizing sites and data, and being used as springboards for wider attacks. File system. Inadequately secured files provide a means of site and server penetration. Administered remotely. Casual or unsecured content, site, server, and network administration allows for multi-faceted attacks and, conversely, requires discipline, a secure local working environment, and impenetrable local-to-remote connectivity.   Meet the hackers This isn't some cunning ploy by yours-truly to see for how many readers I can attain visitor's rights, you understand. The fact is to catch a thief one has to think like one. Besides, not all hackers are such bad hats. Far from it. Overall there are three types-white hat, grey hat, and black hat-each with their sub-groups. White hat One important precedent sets white hats above and beyond other groups: permission. Also known as ethical hackers, these decent upstanding folks are motivated: To learn about security To test for vulnerabilities To find and monitor malicious activity To report issues To advise others To do nothing illegal To abide by a set of ethics to not harm anyone So when we're testing our security to the limit, that should include us. Keep that in mind. Black hat Out-and-out dodgy dealers. They have nefarious intent and are loosely sub-categorized: Botnets A botnet is a network of automated robots, or scripts, often involved in malicious activity such as spamming or data-mining. The network tends to be comprised of zombie machines, such as your server, which are called upon at will to cause general mayhem. Botnet operators, the actual black hats, have no interest in damaging most sites. Instead they want quiet control of the underlying server resources so their malbots can, by way of more examples, spread malware or Denial of Service (DoS) attacks, the latter using multiple zombies to shower queries to a server to saturate resources and drown out a site. Cybercriminals These are hackers and gangs whose activity ranges from writing and automating malware to data-mining, the extraction of sensitive information to extort or sell for profit. They tend not to make nice enemies, so I'll just add that they're awfully clever. Hacktivists Politically-minded and often inclined towards freedom of information, hacktivists may fit into one of the previous groups, but would argue that they have a justifiable cause. Scrapers While not technically hackers, scrapers steal content-often on an automated basis from site feeds-for the benefit of their generally charmless blog or blog farms. Script kiddies This broad group ranges anything from well-intentioned novices (white hat) to online graffiti artists who, when successfully evading community service, deface sites for kicks. Armed with tutorials galore and a share full of malicious warez, the hell-bent are a great threat because, seeking bragging rights, they spew as much damage as they possibly can. Spammers Again not technically hackers but this vast group leeches off blogs and mailing lists to promote their businesses which frequently seem to revolve around exotic pharmaceutical products. They may automate bomb marketing or embed hidden links but, however educational their comments may be, spammers are generally, but not always, just a nuisance and a benign threat. Misfits Not jargon this time, this miscellaneous group includes disgruntled employees, the generally unloved, and that guy over the road who never really liked you. Grey hat Grey hatters may have good intentions, but seem to have a knack for misplacing their moral compass, so there's a qualification for going into politics. One might argue, for that matter, that government intelligence departments provide a prime example. Hackers and crackers Strictly speaking, hackers are white hat folks who just like pulling things apart to see how they work. Most likely, as kids, they preferred Meccano to Lego. Crackers are black or grey hat. They probably borrowed someone else's Meccano, then built something explosive. Over the years, the lines between hacker and cracker have become blurred to the point that put-out hackers often classify themselves as ethical hackers. This author would argue the point but, largely in the spirit of living language, won't, instead referring to all those trying to break in, for good or bad, as hackers. Let your conscience guide you as to which is which instance and, failing that, find a good priest.   Physically hacked off So far, we have tentatively flagged the importance of a safe working environment and of a secure network from fingertips to page query. We'll begin to tuck in now, first looking at the physical risks to consider along our merry way. Risk falls into the broad categories of physical and technical, and this tome is mostly concerned with the latter. Then again, with physical weaknesses being so commonly exploited by hackers, often as an information-gathering preface to a technical attack, it would be lacking not to mention this security aspect and, moreover, not to sweet-talk the highly successful area of social engineering. Physical risk boils down to the loss or unauthorized use of (materials containing) data: Break-in or, more likely still, a cheeky walk-in Dumpster diving or collecting valuable information, literally from the trash Inside jobs because a disgruntled (ex-)employee can be a dangerous sort Lost property when you leave the laptop on the train Social engineering which is a topic we'll cover separately, so that's ominous Something just breaks ... such as the hard-drive Password-strewn sticky notes aside, here are some more specific red flags to consider when trying to curtail physical risk: Building security whether it's attended or not. By the way, who's got the keys? A cleaner, a doorman, the guy you sacked? Discarded media or paper clues that haven't been criss-cross shredded. Your rubbish is your competitor's profit. Logged on PCs left unlocked, unsecured, and unattended or with hard drives unencrypted and lacking strong admin and user passwords for the BIOS and OS. Media, devices, PCs and their internal/external hardware. Everything should be pocketed or locked away, perhaps in a safe. No Ethernet jack point protection and no idea about the accessibility of the cable beyond the building. No power-surge protection could be a false economy too. This list is not exhaustive. For mid-sized to larger enterprises, it barely scratches the surface and you, at least, do need to employ physical security consultants to advise on anything from office location to layout as well as to train staff to create a security culture. Otherwise, if you work in a team, at least, you need a policy detailing each and every one of these elements, whether they impact your work directly or indirectly. You may consider designating and sub-designating who is responsible for what and policing, for example, kit that leaves the office. Don't forget cell and smart phones and even diaries.  
Read more
  • 0
  • 0
  • 3105
Modal Close icon
Modal Close icon