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-installation-and-configuration-oracle-soa-suite-11g-r1-part-2
Packt
19 Nov 2009
6 min read
Save for later

Installation and Configuration of Oracle SOA Suite 11g R1: Part 2

Packt
19 Nov 2009
6 min read
Additional actions In the following section, you will be performing additional configuration that is optional but will greatly improve performance and usability in the context of the development work you are about to start. Setting memory limits Review the memory settings. This value is dependent on your machine resources and may need to be adjusted for your machine. Allocating less memory for startup will give you better performance on a machine with less memory available. This value is appropriate for a 3 GB memory machine or less. Edit the SOA domain environment file found here (make sure you have the SOA Domain environment file): C:OracleMiddlewarehome_11gR1user_projectsdomains domain1binsetSOADomainEnv.cmd Set memory values: set DEFAULT_MEM_ARGS=-Xms512m -Xmx512m Starting and stopping Now it's time to start your servers. You can start them using the provided script or you can start them separately. Instructions for both methods are included. Starting First set boot.properties and then start the servers. Before you start, set the boot properties so you are not prompted to log in during server startup. Copy C:pobinboot.properties to C:OracleMiddlewarehome_11gR1user_projectsdomainsdomain1. Edit the copied file to reflect the password for your configuration (entered during domain configuration). The first time the server is started this file is encrypted and copied to the server locations.You can start the servers one at a time or you can use the start_all script to start the admin and SOA managed servers (not BAM). To start them one at a time instead, skip to step 6. Copy the startup script to the Oracle directory: C:pobinstart_all.cmd toC:OracleMiddleware Edit the copied file to reflect your environment. Open a command window and start your servers as shown. You must specify how many seconds to wait after starting the admin server before starting the managed server. The admin server must be in the RUNNING state before the managed server starts (see the following screenshot). Try 180 seconds and adjust as necessary. You will need more time the first time you start after a machine reboot than for subsequent restarts: cd C:OracleMiddlewarestart_all.cmd 180 Your servers are now starting automatically so you can skip steps 6-10. Jump to step 12 to continue. To start the servers manually, continue with the following steps. Open three command windows, one for the WebLogic admin server, one for the SOA managed server, and one for the BAM managed server (only start BAM when you need it for a BAM lab). Start the Admin Server first: cd C:OracleMiddlewarehome_11gR1user_projectsdomainsdomain1startWebLogic.cmd Wait for the Admin Server to finish starting up. It takes a few minutes—watch for status RUNNING in the log console window: Start the SOA managed server in the second command window. This start script is in the bin directory. You can also run it directly from the bin directory: cd C:OracleMiddlewarehome_11gR1user_projectsdomainsdomain1binstartManagedWebLogic.cmd soa_server1 When prompted, enter the username weblogic and password welcome1. If you did step 1 and set boot.properties, you will not be prompted. The server is started when you see the message, INFO: FabricProviderServlet.stateChanged SOA Platform is running and accepting requests. Start the BAM managed server in the third command window—do this only when needed for the BAM lab: cd C:OracleMiddlewarehome_11gR1user_projectsdomainsdomain1binstartManagedWebLogic.cmd bam_server1 When prompted, enter the user name weblogic and password welcome1. If you did step 1 and set boot.properties, you will not be prompted. Watch for the RUNNING status. Console URLs Log in with weblogic/welcome1 for all consoles: Weblogic console: http://localhost:7001/console Enterprise Manager console: http://localhost:7001/em SOA worklist: http://localhost:8001/integration/worklistapp B2B console: http://localhost:8001/b2b BAM (must use IE browser): http://localhost:9001/OracleBAM Stopping servers Whenever you need to stop the servers complete the following: Stop the managed servers first by entering Ctrl+C in the command window. Wait until stopped. Stop the admin server by entering Ctrl+C in the command window. WebLogic Server console settings There are two suggested changes to make in the WebLogic Server console. First, you will be viewing application deployments often using the WebLogic server console. This is a lot more convenient if you change the settings not to show libraries as this makes the list a lot shorter and you can find what you need more quickly. Start the WebLogic Admin Server (WLS) if it is not already running. Log in to the WLS console http://localhost:7001/console. Click on Deployments in the left navigation bar. Click on Customize this table at the top of the Deployments table. Change the number of rows per page to 100 (there are only about 30). Select the checkbox to exclude libraries and click on Apply. Second, when the server is started, internal applications like the WLS console are not deployed completely and you see a slight delay when you first access the console. You saw this delay just now when you first accessed the console URL. You can change this behavior to deploy internal applications at startup instead and then you don't get the delay when you access the console. This is convenient for demos (if you want to show the console) and also if you tend to use the console each time you start up the server. Click on domain1 in the left navigation bar in the WLS console. Click on Configuration | General tab. Deselect Enable on-demand deployment of internal applications checkbox. Click on the Save button. EM settings for development The Enterprise Manager can provide different levels of information about composite runtime instances based on a property setting. During development, it is helpful to have a higher setting. These settings are not used on production machines except when specifically needed for debugging purposes as there is a performance cost. Start your servers if they are not already running. Log in to the EM console at http://localhost:7001/em. Right-click on the soa-infra (soa_server1) in the left navigation bar to open the SOA menu and select SOA Administration | Common Properties. Select Audit Level: Development and select the checkbox for Capture Composite Instance State. Click on Apply and click on Yes. If you need to uninstall JDeveloper and servers If you need to uninstall everything, complete the following: First save anything from C:OracleMiddlewarejdev_11gR1jdevelopermywork that you want to keep as this directory will be deleted. Run Uninstall from the program menu to completion for both JDeveloper and WLS. Delete C:OracleMiddlewarejdev_11gR1 and C:OracleMiddlewarehome_11gR1. If you get an error message about not being able to delete because a name or path is too long, change the names of the composite directories within home_ 11gR1user_projectsdomainsdomain1deployed-composites to abcd and try deleting again. Delete program groups from C:Documents and SettingsAll UsersStart MenuPrograms: Oracle Fusion Middleware 11.1.1.1.0 Oracle SOA 11g - Home1 Oracle WebLogic Complete the Dropping existing schema section earlier in this article to clean up the database.
Read more
  • 0
  • 0
  • 2652

article-image-listening-activities-moodle-19-part-2
Packt
19 Nov 2009
6 min read
Save for later

Listening Activities in Moodle 1.9: Part 2

Packt
19 Nov 2009
6 min read
Activity 3: Investigating texts using Quiz Aim: Using quiz to investigate texts Moodle modules: Quiz Extra programs: None Ease of setup: *** As noted elsewhere, Quiz can be a useful module for practicing different language skills. This is primarily because we can build in helpful feedback and because we can allow students to spend as much time as they want practicing. There are various ways that Quiz can help students listen. Here are some examples: Listening and matching: students listen for gist information and match answers to general questions about the text. Ordering task for arranging events in a sequence. Multiple-choice for information transfer, identifying speakers' attitudes, and identifying numbers. Gap-fill tasks: Students listen to a song, poem, or other text, and fill in the missing words. It's worth thinking carefully about what sorts of words you want to blank out. Do you want to focus on grammar words (prepositions, pronouns, and conjunctions, etc.), words that are difficult to spell, or keywords (words that convey the main meaning of the text)? To exemplify each of these examples, we'll make one quiz with four different question types. You could choose to have quizzes with any number of different question types. We'll take as our listening text a story which we recorded ourselves. We could record it in a recording program like Audacity. The story is about a rather special trip to the zoo. Here is a possible transcript abridged from http://www.onlyfunnystories.com/ZooJob.asp: One day an out of work mime artist is visiting the zoo and attempts to earn some money as a street performer monkey. As soon as he starts to draw a crowd, a zoo keeper grabs him and drags him into his office. The zoo keeper explains to the mime artist that the zoo's most popular attraction, a gorilla, has died suddenly and the keeper fears that attendance at the zoo will fall off. He offers the mime artist a job to dress up as the gorilla until they can get another one. The mime artist accepts. So the next morning the mime artist puts on the gorilla suit and enters the cage before the crowd comes. He discovers that it's a great job. He can sleep all he wants, play and make fun of people and he draws bigger crowds than he ever did as a mime. However, eventually the crowds tire of him and he tires of just swinging on trees. He begins to notice that the people are paying more attention to the lion in the cage next to his. Not wanting to lose the attention of his audience, he climbs to the top of his cage, crawls across a partition, and dangles from the top to the lion's cage. Of course, this makes the lion furious, but the crowd loves it. At the end of the day the zoo keeper comes and gives the mime artist a raise for being such a good attraction. Well, this goes on for some time, the mime keeps taunting the lion, the crowds grow larger, and his salary keeps going up. Then one terrible day when he is dangling over the furious lion he slips and falls. The mime artist is terrified. The lion gathers itself and prepares to pounce. The mime artist is so scared that he begins to run round and round the cage with the lion close behind. Finally, the mime artist starts screaming and yelling, "Help me, help me!", but the lion is quick and pounces. The mime artist soon finds himself flat on his back looking up at the angry lion and the lion says, "Shut up you idiot! Do you want to get us both fired?" The questions start with general gist questions (matching). Then comes an ordering question, which requires slightly more attention to detail. The last two are multiple-choice and gap-fill questions, which get students to focus on detailed aspects of the listening text. Here's how to do it The following sections refer you to the activities and point out any major differences. Setting up the quiz Listening and matching question Use NanoGong to create sound clips which replace pictures and texts. Here are some examples of the matching questions you could set up. These are general questions which help students get the gist of the story. Question Answer How many animals are there in the story?. Three Where does this take place? The zoo Where does the zoo keeper find the mime artist? On the street How many animals are there in the cages? Two This is what your matching question might look like: Here are a few more matching questions you could consider: Match recordings to pictures. Students could hear a description of an image (painting, photo) and identify the description. The easiest way to do this would be to take some photos of similar scenes. Match individual words to sounds. Students hear the recording and decide which words they are hearing. Recording Choice A. "I hear you're coming"   B."It's over here" hear/here   hear/here Ordering question In this variation students listen to a story and then order events in sequence. We need to make sure that the sequence is not guessable without hearing the story. Here are the stages from our story that you could include in the question: The zookeeper grabs the mime artist. The zookeeper offers the mime artist a job. The gorilla lies on top of the neighboring cage. The lion tries to attack the gorilla. The lion tells the gorilla off. This is what the ordering question would look like: Multiple-choice question Multiple-choice questions are a good way of getting students to investigate texts in more detail. Here are some possible questions we could include in this activity. Question 1 According to the story, why does the mime artist accept a job as a gorilla? Answer 1 His work on the street isn't going well. Answer 2 The zookeeper has an urgent need for a gorilla. Answer 3 He always wanted to work as a gorilla in a zoo. Answer 4 The last gorilla quit the job.
Read more
  • 0
  • 0
  • 1847

article-image-load-validate-and-submit-forms-using-ext-js-30-part-3
Packt
19 Nov 2009
4 min read
Save for later

Load, Validate, and Submit Forms using Ext JS 3.0: Part 3

Packt
19 Nov 2009
4 min read
Loading form data from the server An important part of working with forms is loading the data that a form will display. Here's how to create a sample contact form and populate it with data sent from the server. How to do it... Declare the name and company panel: var nameAndCompany = { columnWidth: .5, layout: 'form', items: [ { xtype: 'textfield', fieldLabel: 'First Name', name: 'firstName', anchor: '95%' }, { xtype: 'textfield', fieldLabel: 'Last Name', name: 'lastName', anchor: '95%' }, { xtype: 'textfield', fieldLabel: 'Company', name: 'company', anchor: '95%' }, { xtype: 'textfield', fieldLabel: 'Title', name: 'title', anchor: '95%' } ]} Declare the picture box panel: var picBox = { columnWidth: .5, bodyStyle: 'padding:0px 0px 0px 40px', items: [ { xtype: 'box', autoEl: { tag: 'div', style: 'padding-bottom:20px', html: '<img id="pic" src="' + Ext.BLANK_IMAGE_URL + '" class="img-contact" />' } }, { xtype: 'button', text: 'Change Picture' } ]} Define the Internet panel: var internet = { columnWidth: .5, layout: 'form', items: [ { xtype: 'fieldset', title: 'Internet', autoHeight: true, defaultType: 'textfield', items: [{ fieldLabel: 'Email', name: 'email', vtype: 'email', anchor: '95%' }, { fieldLabel: 'Web page', name: 'webPage', vtype: 'url', anchor: '95%' }, { fieldLabel: 'IM', name: 'imAddress', anchor: '95%' }] }]} Declare the phone panel: var phones = { columnWidth: .5, layout: 'form', items: [{ xtype: 'fieldset', title: 'Phone Numbers', autoHeight: true, defaultType: 'textfield', items: [{ fieldLabel: 'Home', name: 'homePhone', anchor: '95%' }, { fieldLabel: 'Business', name: 'busPhone', anchor: '95%' }, { fieldLabel: 'Mobile', name: 'mobPhone', anchor: '95%' }, { fieldLabel: 'Fax', name: 'fax', anchor: '95%' }] }]} Define the business address panel: var busAddress = { columnWidth: .5, layout: 'form', labelAlign: 'top', defaultType: 'textarea', items: [{ fieldLabel: 'Business', labelSeparator:'', name: 'bAddress', anchor: '95%' }, { xtype: 'radio', boxLabel: 'Mailing Address', hideLabel: true, name: 'mailingAddress', value:'bAddress', id:'mailToBAddress' }]} Define the home address panel: var homeAddress = { columnWidth: .5, layout: 'form', labelAlign: 'top', defaultType: 'textarea', items: [{ fieldLabel: 'Home', labelSeparator:'', name: 'hAddress', anchor: '95%' }, { xtype: 'radio', boxLabel: 'Mailing Address', hideLabel: true, name: 'mailingAddress', value:'hAddress', id:'mailToHAddress' }]} Create the contact form: var contactForm = new Ext.FormPanel({ frame: true, title: 'TODO: Load title dynamically', bodyStyle: 'padding:5px', width: 650, items: [{ bodyStyle: { margin: '0px 0px 15px 0px' }, items: [{ layout: 'column', items: [nameAndCompany, picBox] }] }, { items: [{ layout: 'column', items: [phones, internet] }] }, { xtype: 'fieldset', title: 'Addresses', autoHeight: true, hideBorders: true, layout: 'column', items: [busAddress, homeAddress] }], buttons: [{ text: 'Save' }, { text: 'Cancel' }]}); Handle the form's actioncomplete event: contactForm.on({ actioncomplete: function(form, action){ if(action.type == 'load'){ var contact = action.result.data; Ext.getCmp(contact.mailingAddress).setValue(true); contactForm.setTitle(contact.firstName + ' ' + contact.lastName); Ext.getDom('pic').src = contact.pic; } }}); Render the form: contactForm.render(document.body); Finally, load the form: contactForm.getForm().load({ url: 'contact.php', params:{id:'contact1'}, waitMsg: 'Loading'}); How it works... The contact form's building sequence consists of defining each of the contained panels, and then defining a form panel that will serve as a host. The following screenshot shows the resulting form, with the placement of each of the panels pinpointed: Moving on to how the form is populated, the JSON-encoded response to a request to provide form data has a structure similar to this: {success:true,data:{id:'1',firstName:'Jorge',lastName:'Ramon',company:'MiamiCoder',title:'Mr',pic:'img/jorger.jpg',email:'ramonj@miamicoder.net',webPage:'http://www.miamicoder.com',imAddress:'',homePhone:'',busPhone:'555 555-5555',mobPhone:'',fax:'',bAddress:'123 Acme Rd #001nMiami, FL 33133',hAddress:'',mailingAddress:'mailToBAddress'}} The success property indicates whether the request has succeeded or not. If the request succeeds, success is accompanied by a data property, which contains the contact's information. Although some fields are automatically populated after a call to load(), the form's title, the contact's picture, and the mailing address radio button require further processing. This can be done in the handler for the actioncomplete event: contactForm.on({ actioncomplete: function(form, action){ if(action.type == 'load'){} }}); As already mentioned, the contact's information arrives in the data property of the action's result: var contact = action.result.data; The default mailing address comes in the contact's mailingAddress property. Hence, the radio button for the default mailing address is set as shown in the following line of code: Ext.getCmp(contact.mailingAddress).setValue(true); The source for the contact's photo is the value of contact.pic: Ext.getDom('pic').src = contact.pic; And finally, the title of the form: contactForm.setTitle(contact.firstName + ' ' + contact.lastName); There's more... Although this recipe's focus is on loading form data, you should also pay attention to the layout techniques used—multiple rows, multiple columns, fieldsets—that allow you to achieve rich and flexible user interfaces for your forms. See Also... The next recipe, Serving the XML data to a form, explains how to use a form to load the XML data sent from the server.
Read more
  • 0
  • 0
  • 4250

article-image-creating-design-ez-publish-4-templating-system-part-2
Packt
19 Nov 2009
8 min read
Save for later

Creating a Design with eZ Publish 4 Templating System: Part 2

Packt
19 Nov 2009
8 min read
eZ Webin For this article it is assumed that the eZ Webin package is installed as a frontend for our site. This package is very flexible and is usually used as a starting point for developing a new site. By default, it includes: A flexible layout Some useful custom content classes (blog, event, forum, article, and so on) Web 2.0 features, such as a tag cloud and comment functions Custom template operators In our project, we will extend and override the eZ Webin template in order to create the Packtmedia Magazine site and add some features needed for the project. We will see this step-by-step as we understand better how eZ Publish works. Overriding the standard page layout The page layout is the main template and defines the style of the entire site. To create a page layout template, we need to create a file named pagelayout.tpl and place it inside the templates folder of our design extension. As we said, we will work with eZ Webin. This extension doesn't use the standard page layout but overrides the standard page layout with its own custom behavior. We need to do the same overriding from the eZ Webin pagelayout.tpl. To override the template, we have to copy it in our design's extension folder placed in extension/packtmedia/design/magazine/templates/. Now open a shell and execute this: # cd /var/www/packtmediaproject/extension# cp /ezwebin/design/ezwebin/templates/pagelayout.tpl /packtmedia/design/magazine/templates/ We will use this new pagelayout.tpl file to implement the wireframe that we developed in the previous sections. Section for our project eZ Publish includes features for creating a particular view in order to add content objects inside specified sections. For example, if we take a look at our wireframe, we need to assign a different layout for rendering the Issue archive folder and its subfolders. To do this, we have to create a new section in the administration panel and associate it to the entire Issue archive subtree. After that, we can use the fetch functions to select the correct view for that section. Creating a new section To create a new section, we have to open our browser and from the site's backend, select the Setup tab from the top menu. We then need to navigate to the Sections link in the left-hand menu, and then click on the New section button. Next, we will create a new section called Archive and select the default Content structure value in the select menu. Now, a new Archive link will appear in the Sections list. We have to click on the + button to the left of the Archive link, and then select the Issue archive node, by selecting the relevant checkbox. After we have saved, click on the Select button. All of the Issue archive subfolders will be placed inside the Archive section. We have to remember the ID of this section, which we'll use to create the override rules. In this case, the section ID number is 6, as seen in the first screenshot in the Creating a new section section. Setting up the section permission access By default, eZ Publish creates private sections that only an administrator can access. To make a section public, we need to give read permission to anonymous users. To set up the rules, we have to go back to Setup tab on the top menu, and then click on the Role and policies link on the left-hand menu. Here, we have to click on the Edit button on the right-hand side of the Anonymous link, and then click on the New policy button. Next, select the content option in the Module field, and then click on the Grant access to one function button. Select the read option in the Function field, and then click on the Grant limited access button. Next, select the Anonymous option for the Section field. Click on the OK button, and then click on the OK button on the Edit <Anonymous> Role page. Now, the anonymous user can access the Archive section. In the next paragraph, we will use this section to create custom override rules. Customizing the page layout After we copy the pagelayout.tpl template into the new path, we have to work on it in order to create the three columns inside the content layout of the eZ Webin template. To do this, first of all, we have to remove the leftmost sidebar, along with the secondary navigation menu, inside the Archive section that we have created. Open the pagelayout.tpl file that you have copied into your favorite IDE, and take a look at the code. At line 62 we will find the following code: {if and( is_set( $content_info.class_identifier ), ezini('MenuSettings', 'HideLeftMenuClasses', 'menu.ini' )|contains($content_info.class_identifier ) )}{set $pagestyle = 'nosidemenu noextrainfo'} Here, eZ Webin hides the side menu if the content class belongs to the array returned by the ezini operator. We now need to extend the IF sentence and add a control to the section ID, by using the following code: {if or(and( is_set( $content_info.class_identifier ), ezini('MenuSettings', 'HideLeftMenuClasses', 'menu.ini' )|contains($content_info.class_identifier ) ), $module_result.section_id|eq(6))}{set $pagestyle = 'nosidemenu noextrainfo'} As we can see, this code will now check to see if the browsed section has an ID equal to 6 (that is, the archive section ID that we previously created) and if it has, will hide the unnecessary sidebar. CSS editing Luckily, the entire template code of eZ Webin is strongly semantic and all of the elements have their own IDs and classes. Thanks to this, we can change a lot of things by simply working on the CSS. By default, the CMS uses six CSSes. These are: core.css: this is the global stylesheet where all of the standard tag styles for eZ Publish are defined; usually, this file is overridden by all of the others webstyletoolbar.css: this stylesheet is imported for the frontend web toolbar that is used for editing the content pagelayout.css: this is where all of the default styles of the global pagelayout are defined content.css: this is where all the default styles of the content classes are defined site-colors.css: this file is used to override the pagelayout.css to skin a site differently classes-colors.css: this file is used to override the default styles defined by the content.css file To edit the CSS, we have to copy the original eZ Webin stylesheet from the /var/www/packtmediaproject/extension/ezwebin/design/ezwebin/stylesheets folder to our design directory and then to execute the following commands: # cd /var/www/packtmediaproject/extension/# cp -rf ezwebin/design/ezwebin/stylesheets/* packtmedia/design/magazine/stylesheets/ Now, every time that we want to change the stylesheet, we have to remember to edit the CSS files in the design/magazine/stylesheets/ directory of our extension. Creating a new style package In eZ Publish, as we did for extension, it's possible to create a portable style package, so we can share and reuse our custom style in other sites. We can do this by navigating to the backend admin site and uploading the new stylesheet that we want to use. First, we have to create our CSS files by using our favorite CSS editor; we have to remember that they will override the default styles, so we only need to add the lines that we want to change. After we create the new stylesheet files, we have to open the browser, click on the Setup tab, and then click on the Package link in the left-hand sidebar. The system will ask us where we want to create our new package. We will select the local repository and click on the Create new package button. eZ Publish will then ask us which kind of package we want to create. We have to select the Site style wizard, and then click on the Create new package button. We can now choose a thumbnail for the style that we are uploading, or continue without it. After selecting the thumbnail, the wizard will ask us to choose the CSS file that we previously created. Select it, and then click on the Next button. With the wizard, we will also upload one or more images, for example a new logo file, or other images related to the CSS. To not upload files, we simply have to click on the Next button without selecting a file in the form. We have to remember that all of the images that we upload will be saved in a subfolder named images, which will be placed in the same directory as the stylesheet. This will be useful when we need to set the relative path of the images used inside the CSS. We can now add the package information and export it to our PC (if required). The new style package will automatically be installed in the eZ Publish package folder. It will be accessible from the Design tab, via the sidebar's Look and Feel link. If we select the package and clear the cache automatically, it will be applied to the frontend. Summary In this article, we learned the basics of the templating system of eZ Publish. We worked on template's function and operator, and also learned how to extend the default WYSIWYG editor of eZ Publish. Moreover, we created the site wireframe and learned how the design overriding feature works. We also created a new stylesheet package, and applied it to our extension.
Read more
  • 0
  • 0
  • 2451

article-image-plotting-data-using-matplotlib-part-2
Packt
19 Nov 2009
15 min read
Save for later

Plotting data using Matplotlib: Part 2

Packt
19 Nov 2009
15 min read
Plotting data from a CSV file A common format to export and distribute datasets is the Comma-Separated Values (CSV) format. For example, spreadsheet applications allow us to export a CSV from a working sheet, and some databases also allow for CSV data export. Additionally, it's a common format to distribute datasets on the Web. In this example, we'll be plotting the evolution of the world's population divided by continents, between 1950 and 2050 (of course they are predictions), using a new type of graph: bars stacked. Using the data available at http://www.xist.org/earth/pop_continent.aspx (that fetches data from the official UN data at http://esa.un.org/unpp/index.asp), we have prepared the following CSV file: Continent,1950,1975,2000,2010,2025,2050Africa,227270,418765,819462,1033043,1400184,1998466Asia,1402887,2379374,3698296,4166741,4772523,5231485Europe,547460,676207,726568,732759,729264,691048Latin America,167307,323323,521228,588649,669533,729184Northern America,171615,242360,318654,351659,397522,448464Oceania,12807,21286,31160,35838,42507,51338 In the first line, we can find the header with a description of what the data in the columns represent. The other lines contain the continent's name and its population (in thousands) for the given years. In the first line, we can find the header with a description of what the data in the columns represent. The other lines contain the continent's name and its population (in thousands) for the given years. There are several ways to parse a CSV file, for example: NumPy's loadtxt() (what we are going to use here) Matplotlib's mlab.csv2rec() The csv module (in the standard library) but we decided to go with loadtxt() because it's very powerful (and it's what Matplotlib is standardizing on). Let's look at how we can plot it then: # for file opening made easierfrom __future__ import with_statement We need this because we will use the with statement to read the file. # numpyimport numpy as np NumPy is used to load the CSV and for its useful array data type. # matplotlib plotting moduleimport matplotlib.pyplot as plt# matplotlib colormap moduleimport matplotlib.cm as cm# needed for formatting Y axisfrom matplotlib.ticker import FuncFormatter# Matplotlib font managerimport matplotlib.font_manager as font_manager In addition to the classic pyplot module, we need other Matplotlib submodules: cm (color map): Considering the way we're going to prepare the plot, we need to specify the color map of the graphical elements FuncFormatter: We will use this to change the way the Y-axis labels are displayed font_manager: We want to have a legend with a smaller font, and font_manager allows us to do that def billions(x, pos): """Formatter for Y axis, values are in billions""" return '%1.fbn' % (x*1e-6) This is the function that we will use to format the Y-axis labels. Our data is in thousands. Therefore, by dividing it by one million, we obtain values in the order of billions. The function is called at every label to draw, passing the label value and the position. # bar widthwidth = .8 As said earlier, we will plot bars, and here we defi ne their width. The following is the parsing code. We know that it's a bit hard to follow (the data preparation code is usually the hardest one) but we will show how powerful it is. # open CSV filewith open('population.csv') as f: The function we're going to use, NumPy loadtxt(), is able to receive either a filename or a file descriptor, as in this case. We have to open the file here because we have to strip the header line from the rest of the file and set up the data parsing structures. # read the first line, splitting the yearsyears = map(int, f.readline().split(',')[1:]) Here we read the first line, the header, and extract the years. We do that by calling the split() function and then mapping the int() function to the resulting list, from the second element onwards (as the first one is a string). # we prepare the dtype for exacting data; it's made of:# <1 string field> <len(years) integers fields>dtype = [('continents', 'S16')] + [('', np.int32)]*len(years) NumPy is flexible enough to allow us to define new data types. Here, we are creating one ad hoc for our data lines: a string (of maximum 16 characters) and as many integers as the length of years list. Also note how the fi rst element has a name, continents, while the last integers have none: we will need this in a bit. # we load the file, setting the delimiter and the dtype abovey = np.loadtxt(f, delimiter=',', dtype=dtype) With the new data type, we can actually call loadtxt(). Here is the description of the parameters: f: This is the file descriptor. Please note that it now contains all the lines except the first one (we've read above) which contains the headers, so no data is lost. delimiter: By default, loadtxt() expects the delimiter to be spaces, but since we are parsing a CSV file, the separator is comma. dtype: This is the data type that is used to apply to the text we read. By default, loadtxt() tries to match against float values # "map" the resulting structure to be easily accessible:# the first column (made of string) is called 'continents'# the remaining values are added to 'data' sub-matrix# where the real data arey = y.view(np.dtype([('continents', 'S16'), ('data', np.int32, len(years))])) Here we're using a trick: we view the resulting data structure as made up of two parts, continents and data. It's similar to the dtype that we defined earlier, but with an important difference. Now, the integer's values are mapped to a field name, data. This results in the column continents with all the continents names,and the matrix data that contains the year's values for each row of the file. data = y['data']continents = y['continents'] We can separate the data and the continents part into two variables for easier usage in the code. # prepare the bottom arraybottom = np.zeros(len(years)) We prepare an array of zeros of the same length as years. As said earlier, we plot stacked bars, so each dataset is plot over the previous ones, thus we need to know where the bars below finish. The bottom array keeps track of this, containing the height of bars already plotted. # for each line in datafor i in range(len(data)): Now that we have our information in data, we can loop over it. # create the bars for each element, on top of the previous barsbt = plt.bar(range(len(data[i])), data[i], width=width, color=cm.hsv(32*i), label=continents[i], bottom=bottom) and create the stacked bars. Some important notes: We select the the i-th row of data, and plot a bar according to its element's size (data[i]) with the chosen width. As the bars are generated in different loops, their colors would be all the same. To avoid this, we use a color map (in this case hsv), selecting a different color at each iteration, so the sub-bars will have different colors. We label each bar set with the relative continent's name (useful for the legend) As we have said, they are stacked bars. In fact, every iteration adds a piece of the global bars. To do so, we need to know where to start drawing the bar from (the lower limit) and bottom does this. It contains the value where to start drowing the current bar. # update the bottom arraybottom += data[i] We update the bottom array. By adding the current data line, we know what the bottom line will be to plot the next bars on top of it. # label the X ticks with yearsplt.xticks(np.arange(len(years))+width/2, [int(year) for year in years]) We then add the tick's labels, the years elements, right in the middle of the bar. # some information on the plotplt.xlabel('Years')plt.ylabel('Population (in billions)')plt.title('World Population: 1950 - 2050 (predictions)') Add some information to the graph. # draw a legend, with a smaller fontplt.legend(loc='upper left', prop=font_manager.FontProperties(size=7)) We now draw a legend in the upper-left position with a small font (to better fit the empty space). # apply the custom function as Y axis formatterplt.gca().yaxis.set_major_formatter(FuncFormatter(billions) Finally, we change the Y-axis label formatter, to use the custom formatting function that we defined earlier. The result is the next screenshot where we can see the composition of the world population divided by continents: In the preceding screenshot, the whole bar represents the total world population, and the sections in each bar tell us about how much a continent contributes to it. Also observe how the custom color map works: from bottom to top, we have represented Africa in red, Asia in orange, Europe in light green, Latin America in green, Northern America in light blue, and Oceania in blue (barely visible as the top of the bars). Plotting extrapolated data using curve fitting While plotting the CSV values, we have seen that there were some columns representing predictions of the world population in the coming years. We'd like to show how to obtain such predictions using the mathematical process of extrapolation with the help of curve fitting. Curve fitting is the process of constructing a curve (a mathematical function) that better fits to a series of data points. This process is related to other two concepts: interpolation: A method of constructing new data points within the range of a known set of points extrapolation: A method of constructing new data points outside a known set of points The results of extrapolation are subject to a greater degree of uncertainty and are influenced a lot by the fitting function that is used. So it works this way: First, a known set of measures is passed to the curve fitting procedure that computes a function to approximate these values With this function, we can compute additional values that are not present in the original dataset Let's first approach curve fitting with a simple example: # Numpy and Matplotlibimport numpy as npimport matplotlib.pyplot as plt These are the classic imports. # the known points setdata = [[2,2],[5,0],[9,5],[11,4],[12,7],[13,11],[17,12]] This is the data we will use for curve fitting. They are the points on a plane (so each has a X and a Y component) # we extract the X and Y components from previous pointsx, y = zip(*data) We aggregate the X and Y components in two distinct lists. # plot the data points with a black crossplt.plot(x, y, 'kx') Then plot the original dataset as a black cross on the Matplotlib image. # we want a bit more data and more fine grained for# the fitting functionsx2 = np.arange(min(x)-1, max(x)+1, .01) We prepare a new array for the X values because we wish to have a wider set of values (one unit on the right and one on to the left of the original list) and a fine grain to plot the fitting function nicely. # lines styles for the polynomialsstyles = [':', '-.', '--'] To differentiate better between the polynomial lines, we now define their styles list. # getting style and count one at timefor d, style in enumerate(styles): Then we loop over that list by also considering the item count. # degree of the polynomialdeg = d + 1 We define the actual polynomial degree. # calculate the coefficients of the fitting polynomialc = np.polyfit(x, y, deg) Then compute the coefficients of the fitting polynomial whose general format is: c[0]*x**deg + c[1]*x**(deg – 1) + ... + c[deg]# we evaluate the fitting function against x2y2 = np.polyval(c, x2) Here, we generate the new values by evaluating the fitting polynomial against the x2 array. # and then we plot itplt.plot(x2, y2, label="deg=%d" % deg, linestyle=style) Then we plot the resulting function, adding a label that indicates the degree of the polynomial and using a different style for each line. # show the legendplt.legend(loc='upper left') We then show the legend, and the final result is shown in the next screenshot: Here, the polynomial with degree=1 is drawn as a dotted blue line, the one with degree=2 is a dash-dot green line, and the one with degree=3 is a dashed red line. We can see that the higher the degree, the better is the fit of the function against the data. Let's now revert to our main intention, trying to provide an extrapolation for population data. First a note: we take the values for 2010 as real data and not predictions (well, we are quite near to that year) else we have very few values to create a realistic extrapolation. Let's see the code: # for file opening made easierfrom __future__ import with_statement# numpyimport numpy as np# matplotlib plotting moduleimport matplotlib.pyplot as plt# matplotlib colormap moduleimport matplotlib.cm as cm# Matplotlib font managerimport matplotlib.font_manager as font_manager# bar widthwidth = .8# open CSV filewith open('population.csv') as f: # read the first line, splitting the years years = map(int, f.readline().split(',')[1:]) # we prepare the dtype for exacting data; it's made of: # <1 string field> <6 integers fields> dtype = [('continents', 'S16')] + [('', np.int32)]*len(years) # we load the file, setting the delimiter and the dtype above y = np.loadtxt(f, delimiter=',', dtype=dtype) # "map" the resulting structure to be easily accessible: # the first column (made of string) is called 'continents' # the remaining values are added to 'data' sub-matrix # where the real data are y = y.view(np.dtype([('continents', 'S16'), ('data', np.int32, len(years))]))# extract fieldsdata = y['data']continents = y['continents'] This is the same code that is used for the CSV example (reported here for completeness). x = years[:-2]x2 = years[-2:] We are dividing the years into two groups: before and after 2010. This translates to split the last two elements of the years list. What we are going to do here is prepare the plot in two phases: First, we plot the data we consider certain values After this, we plot the data from the UN predictions next to our extrapolations # prepare the bottom arrayb1 = np.zeros(len(years)-2) We prepare the array (made of zeros) for the bottom argument of bar(). # for each line in datafor i in range(len(data)): # select all the data except the last 2 values d = data[i][:-2] For each data line, we extract the information we need, so we remove the last two values. # create bars for each element, on top of the previous barsbt = plt.bar(range(len(d)), d, width=width, color=cm.hsv(32*(i)), label=continents[i], bottom=b1)# update the bottom arrayb1 += d Then we plot the bar, and update the bottom array. # prepare the bottom arrayb2_1, b2_2 = np.zeros(2), np.zeros(2) We need two arrays because we will display two bars for the same year—one from the CSV and the other from our fitting function. # for each line in datafor i in range(len(data)): # extract the last 2 values d = data[i][-2:] Again, for each line in the data matrix, we extract the last two values that are needed to plot the bar for CSV. # select the data to compute the fitting functiony = data[i][:-2] Along with the other values needed to compute the fitting polynomial. # use a polynomial of degree 3c = np.polyfit(x, y, 3) Here, we set up a polynomial of degree 3; there is no need for higher degrees. # create a function out of those coefficientsp = np.poly1d(c) This method constructs a polynomial starting from the coefficients that we pass as parameter. # compute p on x2 values (we need integers, so the map)y2 = map(int, p(x2)) We use the polynomial that was defined earlier to compute its values for x2. We also map the resulting values to integer, as the bar() function expects them for height. # create bars for each element, on top of the previous barsbt = plt.bar(len(b1)+np.arange(len(d)), d, width=width/2, color=cm.hsv(32*(i)), bottom=b2_1) We draw a bar for the data from the CSV. Note how the width is half of that of the other bars. This is because in the same width we will draw the two sets of bars for a better visual comparison. # create the bars for the extrapolated valuesbt = plt.bar(len(b1)+np.arange(len(d))+width/2, y2, width=width/2, color=cm.bone(32*(i+2)), bottom=b2_2) Here, we plot the bars for the extrapolated values, using a dark color map so that we have an even better separation for the two datasets. # update the bottom arrayb2_1 += db2_2 += y2 We update both the bottom arrays. # label the X ticks with yearsplt.xticks(np.arange(len(years))+width/2, [int(year) for year in years]) We add the years as ticks for the X-axis. # draw a legend, with a smaller fontplt.legend(loc='upper left', prop=font_manager.FontProperties(size=7)) To avoid a very big legend, we used only the labels for the data from the CSV, skipping the interpolated values. We believe it's pretty clear what they're referring to. Here is the screenshot that is displayed on executing this example: The conclusion we can draw from this is that the United Nations uses a different function to prepare the predictions, especially because they have a continuous set of information, and they can also take into account other environmental circumstances while preparing such predictions. Tools using Matplotlib Given that it's has an easy and powerful API, Matplotlib is also used inside other programs and tools when plotting is needed. We are about to present a couple of these tools: NetworkX Mpmath
Read more
  • 0
  • 0
  • 6514

article-image-nav-2009-reports
Packt
19 Nov 2009
8 min read
Save for later

NAV 2009: Reports

Packt
19 Nov 2009
8 min read
What is a report? A report is a vehicle for organizing, processing, and displaying data in a format suitable for outputting. In the past, reports went to hardcopy devices (for example printers). Reporting technology is now more general purpose and flexible. Reports may be displayed on-screen in preview mode rather than being printed, or output to another device (for example, disk storage in PDF format), but with the same formatting as though they were printed. In fact, all of the report screenshots in this article were taken from reports generated in preview mode. Once generated, the data contents of a report are static. Part of the new flexibility of NAV 2009 is the capability to output reports in preview mode, which have interactive capabilities. However, those capabilities only affect the presentation of the data, not the data included in the report dataset. Examples include dynamic sorting and show or hide data (expand or collapse). Even so, all specification of the data selection criteria for a report must be done at the beginning, before the report is generated. NAV 2009 also allows dynamic functionality for drill down into the underlying data, drill through to a page, and even drill through into another report. In NAV, report objects can also be classified as processing only by setting the correct report property (that is, by setting the ProcessingOnly property to Yes). A ProcessingOnly report will display no data to the user in the traditional reporting manner, but will simply process and update data in the tables. A report can add, change, or delete data in tables, whether the report is ProcessingOnly or a normal printing report. In general, reports are associated with one or more tables. A report can be created without being externally associated with any table, but that is an exception, not a rule. Even if a report is associated with a particular table, it can freely access and display data from other referenced tables. Two NAV report designers NAV 2009 report design uses a pair of Report Designer tools. The first is the Report Designer that is part of the C/SIDE development environment. The second is the Visual Studio Report Designer. For simplicity, we will refer to these as C/SIDE RD and VS RD in this article. The C/SIDE RD is the only tool needed to create reports for the Classic Client. If a NAV 2009 system is using only the Classic Client, then only reports created using the C/SIDE RD can be run. However, when using the RoleTailored Client, both C/SIDE RD and VS RD reports can be run. The RTC runs C/SIDE RD reports by invoking a temporary instance of the Classic Client, running the report, and then closing down the Classic Client instance (no additional license slots are used). In this article, we will focus totally on the design of reports for the RoleTailored Client using the VS RD. The typical report development process for an RTC report begins by doing foundation work in the C/SIDE RD. That's where all the data structure, working data elements, data flow, and C/AL logic are defined. The only way to create or modify report objects is to start in the C/SIDE RD. Once all of the elements are in place, the development work proceeds to the VS RD where the layout and presentation work is done, including any desired dynamic options. The following flow chart provides a conceptual view of the creation of a new report using the two different Report Design approaches—one for the Classic Client and the other for the RoleTailored Client. The functions in the center and left chart paths are those done in the C/SIDE RD (steps 1 through 7). Those in the right set of the chart are the ones done in the VS RD (steps 4 and 6 through 10). Steps 1, 2, 3, and 5 are essentially the same (but not quite) regardless of the target client. Step 4 is done in the C/SIDE RD Sections Designer for both clients, but what you do is quite different in each case. As you can see, many of the functions are the same regardless of the target client. Most of those are done within the Classic Report Designer. Therefore, the accurate claim for NAV 2009 that, even though the layout function uses Visual Studio Report Designer, a large part of the report design is still done within the traditional NAV Report Designer. For the experienced NAV Classic Client developer who is moving to RTC projects, the biggest challenges will be to learn exactly which tasks are done using which development tool, and to learn the intricacies of the Visual Studio Report Designer layout tools. Those intricacies include understanding just how the VS RD features interact with the NAV data structures and the C/SIDE RD definitions. This chart shows the general flow of NAV report design in order to make it easier to understand which functions are done in which of the Report Design tools, and allows comparison of the Classic and RoleTailored design processes. In practice, the actual flow will depend on the specifics of a particular report. It's feasible for a simple C/SIDE report to be entirely generated by the Wizard, but that is generally not true for a VS RD report. It's important to note that some of the steps defined in the chart can be performed in a different sequence than that is shown, and some can be repeated in an iterative fashion. Nevertheless, the chart that follows is a good introductory guide to NAV Report Design. Terminology for the following chart: Working Data is all the non-database data needed to process the report; Report Data is what will be displayed in the report. A Hybrid Report Designer The Report Designer toolset in NAV 2009 represents a set of compromises tied back to some initial NAV 2009 product feature goals. One product feature goal was to retain the ability of developers of developers to do their to do their work within C/SIDE, thus avoiding scrapping more than a decade of knowledge and experience. A second product feature goal was to provide a much more fully featured set of reporting capabilities. After much thought and experimentation, the decision was made to create a toolset that would target report generation using the functionality of SQL Server Reporting Services (SSRS). The method of accomplishing that was to "glue together" the data and logic definition parts of the C/SIDE Report Designer to the layout parts of Visual Studio Report Designer, in order to create a hybrid. When a report is designed, VS RD builds a definition of the report layout in the XML-structured Report Definition Language Client-side (RDLC). When you exit VS RD, the latest copy of the RDLC code is stored in the current C/SIDE Report object. When you exit the Report Designer and save your Report object, the C/SIDE RD saves the combined set of report definition information, C/SIDE and RDLC, in the database. If you export a report object in text format, you will be able to see the two separate sets of report definition. The XML-structured RDLC is quite obvious (beginning with the heading RDLDATA). NAV report—look and feel NAV allows you to create reports of many different kinds with vastly different "look and feel" attributes. The consistency of report look and feel does not have the same level of design importance as the consistency of look and feel for pages does. The standard NAV application only uses a few of the possible report styles, most of which are in a relatively "plain-Jane" format. While good design practice dictates that enhancements should integrate seamlessly unless there is an overwhelming justification for being different, there are many opportunities for providing replacement or additional reporting capabilities. The tools that are available within NAV for accessing and manipulating data in textual format are very powerful. Unlike the previous versions of NAV, this new version includes a reasonable set of graphical reporting capabilities. And, of course, there is always the option to output report results to another processing/presentation tool such as Excel. NAV report types The following are the types of reports: List: This is a formatted list of data. A sample list report in the standard system is the Customer – Order Detail list shown in the following screenshot: Document: This is formatted along the lines of a pre-printed form, where a page (or several pages) represents a complete, self-contained report. Examples are Customer Invoice, Packing List (even though it's called a list, it's a document report), Purchase Order, and Accounts Payable check.The following screenshot is a Customer Sales-Invoice document report: The List and Document report types are defined based on their layout. The next three report types are defined based on their usage rather than their layout.
Read more
  • 0
  • 0
  • 7617
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-keeping-extensions-secure-joomla-15-part-2
Packt
18 Nov 2009
15 min read
Save for later

Keeping Extensions Secure with Joomla! 1.5: Part 2

Packt
18 Nov 2009
15 min read
Making a directory path safe When we poke around in the server filesystem, we want to make sure that we know what we are doing. If we are dealing with directories, Joomla! provides us with some easy ways to make sure that those directories are being safely referenced. Failure to properly sanitize directory paths can lead to major security vulnerabilities. For example, if we were attempting to remove a directory, a security vulnerability could allow the deletion of the completely wrong resource! For more information about external control of paths, refer to CWE-73. A directory path is a URL to a directory. A directory path does not include a file. To safely manage a path to a file, refer to the next recipe, Making a path safe. How to do it... The static JFolder class, which is a part of the joomla.filesystem library, provides us with all sorts of useful methods for working with folders. To use the class, we must import it. jimport('joomla.filesystem.folder'); This bit is nice and easy. We use the JFolder::makeSafe() method and pass the name of the folder we want to sanitize. This method returns a string that can be used to interact safely with a folder. // make the directory path safe$safeDirPath = JFolder::makeSafe($unsafeDirPath); The one downside of JFolder::makeSafe() is that it assumes that the directory separators are correctly defined in the original string. For example, while running on a *nix system, if the string contained Windows-style backslashes instead of *nix style forward slashes, those slashes would be stripped. We can use the static JPath class to overcome this, as follows: // import JPath and JFolderjimport('joomla.filesystem.path');jimport('joomla.filesystem.folder');// clean the path$cleanDirPath = JPath::clean($unsafeDirPath);// make the directory path safe$safeDirPath = JFolder::makeSafe($cleanDirPath); This time we have included the JPath::clean() method prior to making the path safe. For more information about JPath, refer to the next recipe, Making a path safe. Directory separators The correct way to add directory separators in Joomla! is to use the DS constant. For example, the path to bar from foo is expressed as 'foo' . DS . 'bar'. How it works... What exactly does the JFolder::makeSafe() method do to guarantee that the directory path is safe? It strips out any characters or character sequences that are seen as posing potential security risks. The following list describes the characters that are considered safe: Alphanumeric (a-z, A-Z, and 0-9) Colon Dash Directory separators—the exact character sequence will depend on the environment Space Underscore The following table shows some examples of input and output strings from the JFolder::makeSafe() and JPath::clean() methods running on a Windows system (DS == ''). This is intended to show why using the two together can be preferable. If we choose to use the two together, order of usage is important. We should always use the JPath::clean() method first and the JFolder::makeSafe() method next. Although, as the fourth example shows, sometimes it can be worth cleaning a second time, which means clean, make safe, and clean.   Original   Clean   Safe   Clean and safe   foobar   foobar   foobar   foobar   //foo/bar   foobar   foobar   foobar   foo bar   foo bar   foo20bar   foo20bar   foo bar/..   foo bar..   foo bar   foo bar   /foo"   foo"   foodel   foodel   del *.*   del *.*       See also For information about safely dealing with files, refer to the previous recipe, Making a filename safe. For information about dealing with paths, please refer to the next recipe, Making a path safe. Making a path safe This recipe is similar to the previous two recipes, Making a filename safe and Making a directory path safe. This recipe differs in that it is for a complete path, normally to a file. There is a whole raft of security issues associated with processing paths. The following list identifies some of the more common issues we need to be aware of: CWE-22: Path traversal CWE-73: External control of filename or path CWE-98: Insufficient control of filename for include/require statement in PHP program (aka 'PHP file inclusion') CWE-434: Unrestricted file upload All of these vulnerabilities can have serious consequences, which should not be overlooked. For example, a malicious user could upload a destructively tailored script file and then execute it. Luckily, Joomla! provides us with some easy ways to reduce the risks associated with these potential weaknesses. Getting ready Before we delve into some of the complex ways of safely dealing with paths, let's start small. If we browse a basic installation of Joomla!, we will discover a large number of empty index.html files. These files prevent directory listings. Most web servers automatically generate directory listings if we visit a directory in which there are no index files. We should always add a copy of the empty index.html file to every directory in our extension. The use of empty index.html files provides a form of security through obscurity. This is only intended to be a very basic safeguard and should never be relied on for complete protection. For more information, refer to CWE-656. The second thing we should do is ensure that all of our PHP files can only be executed if the _JEXEC constant has been defined. This is used to make sure that the file has been executed from within Joomla!, that is, make sure it is not being used as a standalone script or is included from a script other than Joomla! // Check file executed from within Joomla!defined('_JEXEC') or die('Restricted access'); How to do it... If we are retrieving a path value from a request variable, we can use the PATH type. This type is not entirely what it seems, as a PATH type cannot be an absolute path and cannot reference hidden files and folders. This means it cannot start with any form of directory separator, as it would in a *nix environment, or a drive identifier, as it would in a Windows environment. It also means that none of the folder names or the optional filename can start with a period (a *nix hidden file/folder). If a value does not reach these criteria, the return value will be null. Therefore, it is very important to consider the suitability of the PATH type before opting to use it. // get the value of myPath from the request$myPath = JRequest::getVar('myPath', 'default', 'REQUEST', 'PATH'); On its own, the PATH type does not really constitute a security measure. For example, it does not protect against the path traversal CWE-22. Once we have our path variable, it is time to clean it. Cleaning is done in Joomla! using the static JPath class. Cleaning resolves any issues with directory separators. The exact process depends on the filesystem directory separator, for example a back or forward slash. The point is that if the directory separators in the string are incorrect, they are corrected as necessary. // import the JPath classjimport('joomla.filesystem.path');// clean $myPath$myPath = JPath::clean($myPath); Like the PATH type, a cleaned path does not really constitute a security measure. For example, it too does not protect against path traversal CWE-22. OK, we've heard enough about not constituting a security measure. Now it's time to overcome that problem. The static JPath class includes the JPath::check() method, which checks for path traversal and also that the path is within the Joomla! installation. The only constraint is that the method can only deal with absolute paths. Remember the PATH type used in JRequest can only cope with relative paths. Therefore, if we use the PATH type, we must convert it to an absolute path before using the JPath::check() method. // check for path traversal and snoopingJPath::check($myPath); The odd thing about this method is that we don't really do anything with the result! There is a very good reason for this. If the check fails, Joomla! will exit and display a suitable error message. In some instances, this may not be appropriate. Unfortunately, there is nothing we can do to prevent this. Therefore, if we want to avoid this we will have to check the path ourselves. Generally speaking, if a path fails the check, it is likely that an attack has been attempted. For that reason, exiting Joomla! is probably the most suitable response. However, the JPath::check() method does have one serious limitation. It only checks for snooping outside of the Joomla! root directory. We can manually check that we are only looking in a specified area in the Joomla! installation. // create path which must be the root of the directory$safePath = JPATH_COMPONENT . DS . 'safeFolder' . DS;// check for snooping outside of $safePathif (strpos($myPath, $safePath) !== 0) { JError::raiseError(20, 'Snooping out of bounds'); jexit();}// check for file traversaljimport('joomla.filesystem.path');JPath::check($directory); Essentially, this only ensures that the start of the $myPath string is equivalent to $safePath. We deal with failures in the same way as the JPath::check() method. Notice that we still use the JPath::check() method because we can still effectively use this method to check for file traversal. See also The previous two recipes, Making a filename safe and Making a directory path safe, discuss how to work safely with filenames and paths. We can also use filesystem permissions to secure files and folders. Safely retrieving request data Almost 99% of the time, security vulnerabilities in PHP applications such as Joomla! are caused by inadequate input parsing and validation CWE-20. We access request data in Joomla! using the static JRequest class. Built into this class is the ability to cast values to specific types and to mask data. We cannot rely solely on JRequest to ensure that incoming data is safe. This is where validation comes into play. Input data always has definable constraints. For example, we might define an entity identifier as a positive integer no less than 1 and no greater than 4294967295 (the maximum value for an unsigned MySQL INT). If we can define the constraints, we can also check that the input adheres to the constraints. Validating strings tend to be more complex. This is because strings are highly versatile and can contain many different characters. One thing we should always bear in mind when dealing with string validation is the effect of different character encodings. Joomla! 1.5 is UTF-8 compliant. UTF-8 is a Unicode variable-size multibyte character encoding that enables the encoding of many different alphabets and symbols that would otherwise be unavailable. As PHP is not UTF-8 aware, we should always use the static JString methods instead of the PHP string functions when dealing with UTF-8 strings. Getting ready Prior to doing anything, it is worth defining and documenting the boundaries of all the input that we use in our extension. This may include value ranges and formats. This can be a lengthy task, but it will help to ensure that our extension is secure. How to do it... The most important thing we must do when accessing request data is to use JRequest. Even if we just want the raw values, JRequest forms an important part of the Joomla! framework. Even before we get a chance to execute any code in our extension, JRequest will have already performed vital security work in an attempt to prevent global variable injection, CWE-471. So where do we begin? We start with the simple JRequest::getVar() method. This method is used to safely get at the request data. There are five parameters, of which only the first is required. The following example shows how we use the first three of these parameters: // gets the value of name$value = JRequest::getVar('nameOfVar');// gets the value of name,// if name is not specified returns defaultValue$value = JRequest::getVar('nameOfVar', 'defaultValue');// gets the value of name,// if name is not specified returns defaultValue// name is retrieved from the GET request data$value = JRequest::getVar('nameOfVar', 'defaultValue', 'GET'); The third parameter can be any of the following values:   Value Description COOKIE HTTP Cookies ENV Environment variables FILES Uploaded file details GET HTTP GET variables POST HTTP POST variables REQUEST Combination of GET, POST, and COOKIE; this is the default SERVER Server and environment variables In most instances, REQUEST (the default) should be sufficient. The only time we need to use GET and POST explicitly is when we are expecting a request to use a specific HTTP method. For added security, we can restrict a request to a certain HTTP method using the static JRequest::getMethod() method, as shown in the following example: if (JRequest::getMethod() != 'GET') { jexit('UNEXPECTED REQUEST METHOD');} There's more... The following two subsections discuss the last two parameters, $type and $mask. It is in the last two parameters where the security benefits of JRequest become very apparent. Casting Strictly speaking, casting is not an accurate description of the fourth JRequest::getVar() parameter. The types that we can cast to are not the types that we would use to describe a variable. For example, WORD is not a PHP or Joomla! type, but it is an available option. The following example extracts an integer representation of the GET request value, nameOfVar: // gets the value of nameOfVar,// if nameOfVar is not specified returns 0// name is retrieved from the GET request data// casts the return value as an integer$int = JRequest::getVar('nameOfVar', 0, 'GET', 'INT'); Hey presto! We have a safe value that we know is an integer. Had we not included the parameter to cast the value, we would not have been able to guarantee that $int was in fact an integer. Of course, we could have used the PHP intval() function or cast the value ourselves using (int). Not all of the types we can cast to are as simple as an integer; for example, ALNUM is used to strip non-alphanumeric characters from a string value. JRequest also provides alias methods that allow us to achieve the same thing, but with less code. For example, we can quickly extract an integer. The following example is the same as the previous example: $int = JRequest::getInt('nameOfVar', 0); The following table describes all of the types we can cast to using JRequest. Note that only the most commonly used types have alias methods. Type   Description   Alias   DEFAULT   Aggressive cleaning occurs to remove all detected code elements     ALNUM   Alphanumeric string; strips all non-ASCII letters and numbers     ARRAY   Force array cast     BASE64   Base64 string; strips all non Base64 characters, which is useful for passing encoded data in a URL, for example a return URL     BOOL or BOOLEAN   Force Boolean cast   getBool()   CMD   Command; strips all non-alphanumeric, underscore, period, and dash characters, which is ideal for values such as task   getCmd()   FLOAT or DOUBLE   Floating point number   getFloat()   INT or INTEGER   Whole number   getInt()   PATH   Filesystem path; used to identify a resource in a filesystem, for example the path to an image to use as a logo (relative paths only)     STRING   String; often used with a mask to clean the data   getString()   USERNAME   Username; strips characters unsuitable for use in a username, including non-printing characters (for example a backspace), angled brackets, double and single quotation marks, percent signs, and ampersands     WORD   Word; strips all non-alpha and underscore characters   getWord()     By default, the most aggressive mask is applied. This will remove code, such as HTML and JavaScript, from the data. The next section describes how we use masks. Masking strings The fifth JRequest::getVar() parameter defines a mask. Masks are used in JRequest to define what is and isn't allowed in a string value. By default no masking is applied, which means that very aggressive security measures are taken to ensure that the incoming data is as safe as possible. While this is useful, it is not always appropriate. For example, the core component com_content allows users to enter HTML data in an article. Without a mask, this information would be stripped from the request data. There are three constants we can use to easily define the mask we want to apply. These are JREQUEST_NOTRIM, JREQUEST_ALLOWRAW, and JREQUEST_ALLOWHTML. The following example shows how we can use these: // using getVar$string = JRequest::getVar('nameOfVar', 'default', 'REQUEST', 'STRING', JREQUEST_ALLOWRAW);// using getString alias$string = JRequest::getString('nameOfVar', 'default', 'REQUEST', JREQUEST_ALLOWRAW); The following examples show how the output varies depending on the mask that we apply: # Original input value 1 <p>Paragraph <a onClick="alert('foobar');">link</a></p> 2 CSS <link type="text/css", href="http://somewhere/nasty.css" /> 3 space at front of input 4 &ltp&gtPara&lt/p&gt # Output value (No mask) 1 Paragraph link 2 CSS 3 space at front of input 4 &ltp&gtPara&lt/p&gt    
Read more
  • 0
  • 0
  • 1174

article-image-most-wanted-apache-myfaces-trinidad-12-tags-and-tag-attributes
Packt
18 Nov 2009
6 min read
Save for later

Most Wanted Apache MyFaces Trinidad 1.2 Tags and Tag Attributes

Packt
18 Nov 2009
6 min read
Component library structure Trinidad's approach to web technology is comprehensive: Aimed at full control of all the bits and pieces that make up a web application, little should be left that needs to be added. So based on such a closed world, Trinidad presents itself with a wealth of components and tags that even include very basic XHTML tags as replacements for the real XHTML originals. This is no radical replacement approach, rather it enables Trinidad to remain in full control of mechanisms such as partial-page rendering (PPR, also generally known as Ajax) that otherwise would need to deal with potentially incompatible libraries externally. The following image provides an outline of Trinidad's structural package design: Trinidad is divided into the following two namespaces: tr: It is the usual tag library id that references Trinidad's core library tags. It's a large library of over 100 components ranging from layout components and navigational components, to special viewer components that all implicitly support skinning, partial-page rendering, popup dialogs, error or info messaging, and so on. trh: It is the usual tag library id that references Trinidad's XHTML support library tags, a small companion that offers alternatives for those XHTML tags that are usually applied to build XHTML structures, for example, XHTML tables. Let us take a closer look at both namespaces. The upcoming image shows the core API's hierarchical structure. The tags are backed by two types of Trinidad classes—UIX* classes that deal with the JSF component requirements to implement specific JSF lifecycle processing methods, and Core* classes that deal with the specific properties (getters or setters). Trinidad’s XHTML tag library namespace (trh) Two groups can be distinguished from the trh namespace. The first one deals with the definition of an XHTML page and provides the developer with the following tags: <trh:html>: It is used to define the whole XHTML page, analogous to <html> <trh:head>: It is used to define the header, analogous to <head> <trh:body>: It is used to define the main contents, analogous to <body> <trh:script>: It is used to define a JavaScript to be executed, analogous to <script> <trh:tableLayout>: It is used to define an XHTML table. <trh:rowLayout>: It is used to define an XHTML table line, analogous to <tr>; note that it can also be used to display an arbitrary line, particularly when elements need to be kept in one and the same line. Alternatively, it is particularly interesting to look at the tr namespace as it provides some less heavy structures free from table constructions, for instance panelGroupLayout with a layout set to vertical or a panelBorderLayout, both generating div structures instead. <trh:cellFormat>: It is used to define an XHTML table cell as part of an XHTML table. The attributes of each tag are defined in a most consistent, and thus recognizable way. By the way, there are also tags for the construction of framesets such as trh:frame in case anyone still wants to make use of framesets. However, before we deal with the attributes let us conclude this structural overview by a look at the organization of the functionality of the core tag library. Trinidad’s core tag library namespace (tr) The following groups can be functionally distinguished which is also reflected in the packages structure of Trinidad's API (all beginning with org.apache.myfaces.trinidad.component; which has been left out here to avoid repetition). Note that, for completeness, we will also include information on the pure Java side as well as information on the few components that stem from the trh namespace: Basic document composition tags from the core API: document, stylesheet, form, subform. poll also appears here although it is not a composition tag. Form input and display tags, components from the core.input API: inputText, inputDate, inputListOfValues, and so on. Command or navigation tags from core.nav that includes two tag types: One that is focused on command tags that assumes a given form, presupposing the use of form and display tags from the foregoing group—commandButton, commandLink, goButton, goLink, and so on. The other deals exclusively with navigation: navigationTree, navigationPane, breadCrumbs, and so on. Large input and output component tags from core.data, for example, table, tree, and treeTable components. Layout component tags from core.layout, for example, all the swing-like panel tags, such as panelBorderLayout, panelHorizontalLayout, panelAccordion, showDetail, showDetailItem, and so on. Basic output components from core.output that are almost always used in a web application, for example, messages, outputText, outputLabel, spacer, statusIndicator, and so on. Model objects from core.model devised for various tags ; they provide the corresponding view models for their tag viewer counterparts, for example, SortableModel, CollectionModel and RowKeySet for tr:table, ChildPropertyTreeModel for tr:tree and ChartModel for tr:chart. A couple of converter components from trinidad.convert equip JSF and Trinidad input components with powerful JSF conversion, that is, convertNumber and convertDateTime. Validator components from trinidad.validator equip JSF and Trinidad input components with powerful JSF validation such as range validation (validateDateTimeRange) and validation by regular expression match (validateRegExp). Events and event listeners from trinidad.event add new event types and listeners specific for Trinidad components such as those that support Trinidad's dialog framework, for example, commandButton to launch a popup dialogue using LaunchEvent, ReturnEvent, and ReturnListener. It provides only a few tags, but these can be very utile, for example, fileDownloadActionListener, resetActionListener, returnActionListener, and setActionListener. There is a lot more to be found on the pure Java API side that either surfaces indirectly on the tag library as attributes, or is used implicitly by the tags themselves. Furthermore, there are utility classes and context support classes—RequestContext being probably the most prominent one because it offers a lot of functionality, for example, PPR from the server side. The following figure illustrates the Java side of things (it shows what the structure of some of the classes behind core.input look like): The preceding figure is an outline of the core.input API hierarchy. Again, we can see the typical UIX* and Core* structure. Finally, let us take a closer look at the tag attributes.
Read more
  • 0
  • 0
  • 1913

article-image-microsoft-chart-xml-data
Packt
18 Nov 2009
4 min read
Save for later

Microsoft Chart with XML Data

Packt
18 Nov 2009
4 min read
Introduction SQL 2000 Server provided T-SQL language extensions to operate bi-directionally with relational and XML sources. It also provided two system stored procedures, sp_XML_preparedocument and sp_XML_removedocument, that assist the XML to Relational transformation. This support for returning XML data from relational data using the For XML clause is continued in SQL Server 2005 and SQL Server 2008 although the support for XML is lot more extensive. The shape of the data returned by the For XML clause is further modified by choosing the following modes, raw, auto, explicit, or path. As a preparation for this article we will be creating an XML document starting from the PrincetonTemp table used in a previous article, Binding MS Chart Control to LINQ Data Source Control, on this site. Creating an XML document from an SQL Table Open the SQL Server Management and create a new query [SELECT * from PrincetonTemp for XML auto]. You can use the For XML Auto clause to create a XML document (actually what you create is a fragment - a root-less XML without a processing directive) as shown in Figure 01. Figure 01: For XML Auto clause of a SELECT statement The result shown in a table has essentially two columns with the second column containing the document fragment shown in the next listing. Listing 01: <PrincetonTemp Id="1" Month="Jan " Temperature="4.000000000000000e+001" RecordHigh="6.000000000000000e+001"/> <PrincetonTemp Id="2" Month="Feb " Temperature="3.200000000000000e+001" RecordHigh="5.000000000000000e+001"/> <PrincetonTemp Id="3"Month="Mar " Temperature="4.300000000000000e+001" RecordHigh="6.500000000000000e+001"/> <PrincetonTemp Id="4" Month="Apr " Temperature="5.000000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="5" Month="May " Temperature="5.300000000000000e+001" RecordHigh="7.400000000000000e+001"/> <PrincetonTemp Id="6" Month="Jun " Temperature="6.000000000000000e+001" RecordHigh="7.800000000000000e+001"/> <PrincetonTemp Id="7" Month="Jul " Temperature="6.800000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="8" Month="Aug " Temperature="7.100000000000000e+001" RecordHigh="7.000000000000000e+001"/> <PrincetonTemp Id="9" Month="Sep " Temperature="6.000000000000000e+001" RecordHigh="8.200000000000000e+001"/> <PrincetonTemp Id="10" Month="Oct " Temperature="5.500000000000000e+001" RecordHigh="6.700000000000000e+001"/> <PrincetonTemp Id="11" Month="Nov " Temperature="4.500000000000000e+001" RecordHigh="5.500000000000000e+001"/> <PrincetonTemp Id="12" Month="Dec " Temperature="4.000000000000000e+001" RecordHigh="6.200000000000000e+001"/> This result is attribute-centric as each row of data corresponds to a row in the relational table with each column represented as an XML attribute. The same data can be extracted in an element centric manner by using the directive elements in the SELECT statement as shown in the next figure. Figure 02: For XML auto, Elements clause of a Select statement This would still give us an XML fragment but now it is displayed with element nodes as shown in the next listing (only two nodes 1 and 12 are shown). Listing 02: <PrincetonTemp><Id>1</Id><Month>Jan </Month><Temperature>4.000000000000000e+001</Temperature> <RecordHigh>6.000000000000000e+001</RecordHigh> </PrincetonTemp> ... <PrincetonTemp><Id>12</Id><Month>Dec </Month><Temperature>4.000000000000000e+001</Temperature> <RecordHigh>6.200000000000000e+001 </RecordHigh></PrincetonTemp> To make a clear distinction between the results returned by the two select statements the first row of data is shown in blue. This has returned elements and not attributes. As you can see the returned XML still lacks a root element as well as the XML processing directive. To continue with displaying this data in MS Chart Save Listing 2 as PrincetonXMLDOC.xml to a location of your choice. Create a Framework 3.5 Web Site project Let us create a web site project and display the chart on the Default.aspx page. Open Visual Studio 2008 from its shortcut on the desktop. Click File  New | Web Site...|(or Shift+Alt+N) to open the New Web Site window. Change the default name of the site to a name of your choice (herein Chart_XMLWeb) as shown. Make sure you are creating a .NET Framework 3.5 web site as shown here. Figure 03: New Framework 3.5 Web Site Project Click on APP_Data folder in the solution explorer as shown in the next figure and click on Add Existing Item… menu item. Figure 04: Add an existing item to the web site folder In the interactive window that gets displayed browse to the location where you saved the PrincetonXMLDOC.xml file and click Add button. This will add the XML file to the ADD_Data folder of the web site project. Double click PrincetonXMLDOC.xml in the web site project folder to display and verify its contents as shown in the next figure. Only nodes 1 and 12 are shown expanded. As mentioned previously this is an XML fragment. Figure 05: Imported PrincetonXMLDOC.xml Modify this document by adding the <root/> as well as the XML processing instruction as shown in the next figure. Build the project. Figure 06: Modified PrincetonXMLDOX.xml (valid XML document)
Read more
  • 0
  • 0
  • 14701

article-image-unity-game-development-interactions-part-1
Packt
18 Nov 2009
8 min read
Save for later

Unity Game Development: Interactions (Part 1)

Packt
18 Nov 2009
8 min read
To detect physical interactions between game objects, the most common method is to use a Collider component—an invisible net that surrounds an object's shape and is in charge of detecting collisions with other objects. The act of detecting and retrieving information from these collisions is known as collision detection. Not only can we detect when two colliders interact, but we can also pre-empt a collision and perform many other useful tasks by utilizing a technique called Ray Casting, which draws a Ray—put simply, an invisible (non-rendered) vector line between two points in 3D space—which can also be used to detect an intersection with a game object's collider. Ray casting can also be used to retrieve lots of other useful information such as the length of the ray (therefore—distance), and the point of impact of the end of the line. In the given example, a ray facing the forward direction from our character is demonstrated. In addition to the direction, a ray can also be given a specific length, or allowed to cast until it finds an object. Over the course of the article, we will work with the outpost model. Because this asset has been animated for us, the animation of the outpost's door opening and closing is ready to be triggered—once the model is placed into our scene. This can be done with either collision detection or ray casting, and we will explore what you will need to do to implement either approach. Let's begin by looking at collision detection and when it may be appropriate to use ray casting instead of, or in complement to, collision detection. Exploring collisions When objects collide in any game engine, information about the collision event becomes available. By recording a variety of information upon the moment of impact, the game engine can respond in a realistic manner. For example, in a game involving physics, if an object falls to the ground from a height, then the engine needs to know which part of the object hit the ground first. With that information, it can correctly and realistically control the object's reaction to the impact. Of course, Unity handles these kinds of collisions and stores the information on your behalf, and you only have to retrieve it in order to do something with it. In the example of opening a door, we would need to detect collisions between the player character's collider and a collider on or near the door. It would make little sense to detect collisions elsewhere, as we would likely need to trigger the animation of the door when the player is near enough to walk through it, or to expect it to open for them. As a result, we would check for collisions between the player character's collider and the door's collider. However, we would need to extend the depth of the door's collider so that the player character's collider did not need to be pressed up against the door in order to trigger a collision, as shown in the following illustration. However, the problem with extending the depth of the collider is that the game interaction with it becomes unrealistic. In the example of our door, the extended collider protruding from the visual surface of the door would mean that we would bump into an invisible surface which would cause our character to stop in their tracks, and although we would use this collision to trigger the opening of the door through animation, the initial bump into the extended collider would seem unnatural to the player and thus detract from their immersion in the game. So while collision detection will work perfectly well between the player character collider and the door collider, there are drawbacks that call for us as creative game developers to look for a more intuitive approach, and this is where ray casting comes in. Ray casting While we can detect collisions between the player character's collider and a collider that fits the door object, a more appropriate method may be to check for when the player character is facing the door we are expecting to open and is within a certain distance of this door. This can be done by casting a ray forward from the player's forward direction and restricting its length. This means that when approaching the door, the player needn't walk right up to it—or bump into an extended collider—in order for it to be detected. It also ensures that the player cannot walk up to the door facing away from it and still open it—with ray casting they must be facing the door in order to use it, which makes sense. In common usage, ray casting is done where collision detection is simply too imprecise to respond correctly. For example, reactions that need to occur with a frame-by-frame level of detail may occur too quickly for a collision to take place. In this instance, we need to preemptively detect whether a collision is likely to occur rather than the collision itself. Let's look at a practical example of this problem. The frame miss In the example of a gun in a 3D shooter game, ray casting is used to predict the impact of a gunshot when a gun is fired. Because of the speed of an actual bullet, simulating the flight path of a bullet heading toward a target is very difficult to visually represent in a way that would satisfy and make sense to the player. This is down to the frame-based nature of the way in which games are rendered. If you consider that when a real gun is fired, it takes a tiny amount of time to reach its target—and as far as an observer is concerned it could be said to happen instantly—we can assume that even when rendering over 25 frames of our game per second, the bullet would need to have reached its target within only a few frames. In the example above, a bullet is fired from a gun. In order to make the bullet realistic, it will have to move at a speed of 500 feet per second. If the frame rate is 25 frames per second, then the bullet moves at 20 feet per frame. The problem with this is a person is about 2 feet in diameter, which means that the bullet will very likely miss the enemies shown at 5 and 25 feet away that would be hit. This is where prediction comes into play. Predictive collision detection Instead of checking for a collision with an actual bullet object, we find out whether a fired bullet will hit its target. By casting a ray forward from the gun object (thus using its forward direction) on the same frame that the player presses the fire button, we can immediately check which objects intersect the ray. We can do this because rays are drawn immediately. Think of them like a laser pointer—when you switch on the laser, we do not see the light moving forward because it travels at the speed of light—to us it simply appears. Rays work in the same way, so that whenever the player in a ray-based shooting game presses fire, they draw a ray in the direction that they are aiming. With this ray, they can retrieve information on the collider that is hit. Moreover, by identifying the collider, the game object itself can be addressed and scripted to behave accordingly. Even detailed information, such as the point of impact, can be returned and used to affect the resultant reaction, for example, causing the enemy to recoil in a particular direction. In our shooting game example, we would likely invoke scripting to kill or physically repel the enemy whose collider the ray hits, and as a result of the immediacy of rays, we can do this on the frame after the ray collides with, or intersects the enemy collider. This gives the effect of a real gunshot because the reaction is registered immediately. It is also worth noting that shooting games often use the otherwise invisible rays to render brief visible lines to help with aim and give the player visual feedback, but do not confuse these lines with ray casts because the rays are simply used as a path for line rendering. Adding the outpost Before we begin to use both collision detection and ray casting to open the door of our outpost, we'll need to introduce it to the scene. To begin, drag the outpost model from the Project panel to the Scene view and drop it anywhere—bear in mind you cannot position it when you drag-and-drop; this is done once you have dropped the model (that is, let go off the mouse). Once the outpost is in the Scene, you'll notice its name has also appeared in the Hierarchy panel and that it has automatically become selected. Now you're ready to position and scale it!  
Read more
  • 0
  • 0
  • 3522
article-image-restful-java-web-services-design
Packt
18 Nov 2009
5 min read
Save for later

RESTful Java Web Services Design

Packt
18 Nov 2009
5 min read
We'll leave the RESTful implementation for a later article. Our sample application is a micro-blogging web service (similar to Twitter), where users create accounts and then post entries. Finally, while designing our application, we'll define a set of steps that can be applied to designing any software system that needs to be deployed as a RESTful web service. Designing a RESTful web service Designing RESTful web services is not different from designing traditional web applications. We still have business requirements, we still have users who want to do things with data, and we still have hardware constraints and software architectures to deal with. The main difference, however, is that we look at the requirements to tease out resources and forget about specific actions to be taken on these resources. We can think of RESTful web service design as being similar to Object Oriented Design (OOD). In OOD, we try to identify objects from the data we want to represent together with the actions that an object can have. But the similarities end at the data structure definition, because with RESTful web services we already have specific calls that are part of the protocol itself. The underlying RESTful web service design principles can be summarized in the following four steps: Requirements gathering—this step is similar to traditional software requirement gathering practices. Resource identification—this step is similar to OOD where we identify objects, but we don't worry about messaging between objects. Resource representation definition—because we exchange representation between clients and servers, we should define what kind of representation we need to use. Typically, we use XML, but JSON has gained popularity. That's not to say that we can't use any other form of resource representation—on the contrary, we could use XHTML or any other form of binary representation, though we let the requirements guide our choices. URI definition—with resources in place, we need to define the API, which consists of URIs for clients and servers to exchange resources' representations. This design process is not static. These are iterative steps that gravitate around   resources. Let's say that during the URI definition step we discover that one of the URI's responses is not covered in one of the resources we have identified. Then we go back to define a suitable resource. In most cases, however, we find that the resources that we already have cover most of our needs, and we just have to combine existing resources into a meta-resource to take care of the new requirement. Requirements of sample web service The RESTful web service we design in this article is a social networking web application similar to Twitter. We follow an OOD process mixed with an agile philosophy for designing and coding our applications. This means that we create just enough documentation to be useful, but not so much that we spend an inordinate amount of time deciphering it during our implementation phase. As with any application, we begin by listing the main business requirements, for which we have the following use cases (these are the main functions of our application): A web user creates an account with a username and a password (creating an account means that the user is now registered). Registered users post blog entries to their accounts. We limit messages to 140 characters. Registered and non-registered users view all blog entries. Registered and non-registered users view user profiles. Registered users update their user profiles, for example, users update their password. Registered and non-registered users search for terms in all blog entries. However simple this example may be, social networking sites work on these same principles: users sign up for accounts to post personal updates or information. Our intention here, though, is not to fully replicate Twitter or to fully create a social networking application. What we are trying to outline is a set of requirements that will test our understanding of RESTful web services design and implementation. The core value of social networking sites lies in the ability to connect to multiple users who connect with us, and the value is derived from what the connections mean within the community, because of the tendency of users following people with similar interests. For example, the connections between users create targeted distribution networks.The connections between users create random graphs in the graph theory sense, where nodes are users and edges are connections between users. This is what is referred to as the social graph. Resource identification Out of the use cases listed above, we now need to define the service's resources. From reading the requirements we see that we need users and messages. Users appear in two ways: a single user and a list of users. Additionally, users have the ability to post blog entries in the form of messages of no more than 140 characters. This means that we need resources for a single message and a list of messages. In sum, we identify the following resources: User List of users Message List of messages
Read more
  • 0
  • 0
  • 11057

article-image-user-interaction-and-email-automation-symfony-13-part2
Packt
18 Nov 2009
8 min read
Save for later

User Interaction and Email Automation in Symfony 1.3: Part2

Packt
18 Nov 2009
8 min read
Automated email responses Symfony comes with a default mailer library that is based on Swift Mailer 4, the detailed documentation is available from their web site at http://swiftmailer.org. After a user has signed up to our mailing list, we would like an email verification to be sent to the user's email address. This will inform the user that he/she has signed up, and will also ask him or her to activate their subscription. To use the library, we have to complete the following three steps: Store the mailing settings in the application settings file. Add the application logic to the action. Create the email template. Adding the mailer settings to the application Just like all the previous settings, we should add all the settings for sending emails to the module.yml file for the signup module. This will make it easier to implement any modifications required later. Initially, we should set variables like the email subject, the from name, the from address, and whether we want to send out emails within the dev environment. I have added the following items to our signup module's setting file, apps/frontend/config/module.yml: dev: mailer_deliver: true all: mailer_deliver: true mailer_subject: Milkshake Newsletter mailer_from_name: Tim mailer_from_email: no-reply@milkshake All of the settings can be contained under the all label. However, you can see that I have introduced a new label called dev. These labels represent the environments, and we have just added a specific variable to the dev environment. This setting will allow us to eventually turn off the sending of emails while in the dev environment. Creating the application logic Triggering the email should occur after the user's details have been saved to the database. To demonstrate this, I have added the highlighted amends to the submit action in the apps/frontend/modules/signup/actions/actions.class.php file, as shown in the following code: public function executeSubmit(sfWebRequest $request) { $this->form = new NewsletterSignupForm(); if ($request->isMethod('post') && $this->form-> bindAndSave($request->getParameter($this->form-> getName()))) { //Include the swift lib require_once('lib/vendor/swift-mailer/lib/swift_init.php'); try{ //Sendmail $transport = Swift_SendmailTransport::newInstance(); $mailBody = $this->getPartial('activationEmail', array('name' => $this->form->getValue('first_name'))); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance(); $message->setSubject(sfConfig::get('app_mailer_subject')); $message->setFrom(array(sfConfig:: get('app_mailer_from_email') => sfConfig::get('app_mailer_from_name'))); $message->setTo(array($this->form->getValue('email')=> $this-> form->getValue('first_name'))); $message->setBody($mailBody, 'text/html'); if(sfConfig::get('app_mailer_deliver')) { $result = $mailer->send($message); } } catch(Exception $e) { var_dump($e); exit; } $this->redirect('@signup'); } //Use the index template as it contains the form $this->setTemplate('index'); } Symfony comes with a sfMailer class that extends Swift_Mailer. To send mails you could simply implement the following Symfony method: $this->getMailer()->composeAndSend('from@example.com', 'to@example.com', 'Subject', 'Body'); Let's walk through the process: Instantiate the Swift Mailer. Retrieve the email template (which we will create next) using the $this->getPartial('activationEmail', array('name' => $this->form->getValue('first_name'))) method. Breaking this down, the function itself retrieves a partial template. The first argument is the name of the template to retrieve (that is activationEmail in our example) which, if you remember, means that the template will be called _activationEmail.php. The next argument is an array that contains variables related to the partial template. Here, I have set a name variable. The value for the name is important. Notice how I have used the value within the form object to retrieve the first_name value. This is because we know that these values have been cleaned and are safe to use. Set the subject, from, to, and the body items. These functions are Swift Mailer specific: setSubject(): It takes a string as an argument for the subject setFrom(): It takes the name and the mailing address setTo(): It takes the name and the mailing address setBody(): It takes the email body and mime type. Here we passed in our template and set the email to text/html Finally we send the email. There are more methods in Swift Mailer. Check out the documentation on the Swift Mailer web site (http://swiftmailer.org/). The partial email template Lastly, we need to create a partial template that will be used in the email body. In the templates folder of the signup module, create a file called _activationEmail.php and add the following code to it: Hi <?php echo $name; ?>, <br /><br /> Thank you for signing up to our newsletter. <br /><br /> Thank you, <br /> <strong>The Team</strong> The partial is no different from a regular template. We could have opted to pass on the body as a string, but using the template keeps our code uniform. Our signup process now incorporates the functionality to send an email. The purpose of this example is to show you how to send an automated email using a third-party library. For a real application, you should most certainly implement a two-phase option wherein the user must verify his or her action. Flashing temporary values Sometimes it is necessary to set a temporary variable for one request, or make a variable available to another action after forwarding but before having to delete the variable. Symfony provides this level of functionality within the sfUser object known as a flash variable. Once a flash variable has been set, it lasts until the end of the overall request before it is automatically destroyed. Setting and getting a flash attribute is managed through two of the sfUser methods. Also, you can test for a flash variable's existence using the third method of the methods listed here: $this->getUser()->setFlash($name, $value, $persist = true) $this->getUser()->getFlash($name) $this->getUser()->hasFlash($name) Although a flash variable will be available by default when a request is forwarded to another action, setting the argument to false will delete the flash variable before it is forwarded. To demonstrate how useful flash variables can be, let's readdress the signup form. After a user submits the signup form, the form is redisplayed. I further mentioned that you could create another action to handle a 'thank you' template. However, by using a flash variable we will not have to do so. As a part of the application logic for the form submission, we can set a flash variable. Then after the action redirects the request, the template can test whether there is a flash variable set. If there is one, the template should show a message rather than the form. Let's add the $this->getUser()->setFlash() function to the submit action in the apps/frontend/modules/signup/actions/actions.class.php file: //Include the swift lib require_once('lib/vendor/swift-mailer/lib/swift_init.php'); //set Flash $this->getUser()->setFlash('Form', 'completed'); try{ I have added the flash variable just under the require_once() statement. After the user has submitted a valid form, this flash variable will be set with the name of the Form and have a value completed. Next, we need to address the template logic. The template needs to check whether a flash variable called Form is set. If it is not set, the template shows the form. Otherwise it shows a thank you message. This is implemented using the following code: <?php if(!$sf_user->hasFlash('Form')): ?> <form action="<?php echo url_for('@signup_submit') ?>" method="post" name="Newsletter"> <div style="height: 30px;"> <div style="width: 150px; float: left"> <?php echo $form['first_name']->renderLabel() ?></div> <?php echo $form['first_name']->render(($form['first_name']-> hasError())? array('class'=>'boxError'): array ('class'=>'box')) ?> <?php echo ($form['first_name']->hasError())? ' <span class="errorMessage">* '.$form['first_name']->getError(). '</span>': '' ?> <div style="clear: both"></div> </div> .... </form> <?php else: ?><h1>Thank you</h1>You are now signed up.<?php endif ?> The form is now wrapped inside an if/else block. Accessing the flash variables from a template is done through $sf_user. To test if the variable has been set, I have used the hasFlash() method, $sf_user->hasFlash('Form'). The else part of the statement contains the text rather than the form. Now if you submit your form, you will see the result as shown in the following screenshot: We have now implemented an entire module for a user to sign up for our newsletter. Wouldn't it be really good if we could add this module to another application without all the copying, pasting, and fixing?
Read more
  • 0
  • 0
  • 8654

article-image-build-advanced-contact-manager-using-jboss-richfaces-33-part-1
Packt
18 Nov 2009
11 min read
Save for later

Build an Advanced Contact Manager using JBoss RichFaces 3.3: Part 1

Packt
18 Nov 2009
11 min read
The main layout Let's start preparing the space for the core features of the application. We want a three-column layout for groups, contacts list, and contact detail. Let's open the home.xhtml file and add a three-column panel grid inside the body: <h:panelGrid columns="3" width="100%" columnClasses="main-group-column, main-contacts-list-column,  main-contact-detail-column"></h:panelGrid> We are using three new CSS classes (one for every column). Let's open the /view/stylesheet/theme.css file and add the following code: .main-group-column { width: 20%; vertical-align: top;}.main-contacts-list-column { width: 40%; vertical-align: top;}.main-contact-detail-column { width: 40%; vertical-align: top;} The main columns are ready; now we want to split the content of every column in a separate file (so we don't have a large and difficult file to read) by using the Facelets templating capabilities—let's create a new folder inside the/view folder called main, and let's create the following empty files inside it: contactsGroups.xhtml contactsList.xhtml contactEdit.xhtml contactView.xhtml Now let's open them and put the standard code for an empty (included) file: <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><ui:composition ><!-- my code here --></ui:composition> Now, we have all of the pieces ready to be included into the home.xhtml file, let's open it and start adding the first column inside h:panelGrid: <a:outputPanel id="contactsGroups"> <ui:include src="main/contactsGroups.xhtml"/></a:outputPanel> As you can see, we surrounded the include with an a:outputPanel that will be used as a placeholder for the re-rendering purpose. Include a Facelets tag (ui:include) into the a:outputPanel that we used in order to include the page at that point. Ajax placeholders A very important concept to keep in mind while developing is that the Ajax framework can't add or delete, but can only replace existing elements in the page.For this reason, if you want to append some code, you need to use a placeholder. RichFaces has a component that can be used as a placeholder—a4j:outputPanel. Inside a4j:outputPanel, you can put other components that use the "rendered" attribute in order to decide if they are visible or not. When you want to re-render all the included components, just re-render the outputPanel, and all will work without any problem. Here is a non-working code snippet: <h:form> <h:inputText value="#{aBean.myText}"> <a4j:support event="onkeyup" reRender="out1" /> </h:inputText></h:form><h:outputText id="out1" value="#{aBean.myText}" rendered="#{not empty aBean.myText}"/> This code seems the same as that of the a4j:support example, but it won't work. The problem is that we added the rendered attribute to outputText, so initially, out1 will not be rendered (because the text property is initially empty and rendered will be equal to false). After the Ajax response, the JavaScript Engine will not find the out1 element (it is not in the page because of rendered="false"), and it will not be able to update it (remember that you can't add or delete elements, only replace them). It is very simple to make the code work: <h:form> <h:inputText value="#{aBean.myText}"> <a4j:support event="onkeyup" reRender="out2" /> </h:inputText></h:form><a4j:outputPanel id="out2"> <h:outputText id="out1" rendered="#{not empty aBean.myText}" value="#{aBean.myText}" /></a4j:outputPanel> As you can see, you just have to put the out1 component inside a4j:outputPanel (called out2) and tell a4j:support to re-render out2 instead of out1. Initially, out2 will be rendered but empty (because out1 will not be rendered). After the Ajax response, the empty out2 will be replaced with markup elements that also contain the out1 component (that is now visible, because the myText property is not empty after the Ajax update and the rendered property is true). A very important concept to keep in mind while developing is that the Ajax framework can't add or delete, but can only replace existing elements of the page. For this reason, if you want to append some code, you need to use a placeholder. The groups box This box will contain all the contacts groups, so the user will be able to organize contacts in different groups in a better way. We will not implement the group box features in this article. Therefore, by now the group column is just a rich:panel with a link to refresh the contact list. Let's open the contactsGroups.xhtml file and insert the following code: <h:form> <rich:panel> <f:facet name="header"> <h:outputText value="#{messages['groups']}" /> </f:facet> <h:panelGrid columns="1"> <a:commandLink value="#{messages['allContacts']}" ajaxSingle="true" reRender="contactsList"> <f:setPropertyActionListener value="#{null}" target="#{homeContactsListHelper.contactsList}" /> </a:commandLink> </h:panelGrid> </rich:panel></h:form> As you can see, we've put a three-column h:panelGrid (to be used in the future) and a:commandLink, which just sets the contactsList property of the homeContactListHelper bean (that we will see in the next section) to null, in order to make the list be read again. At the end of the Ajax interaction, it will re-render the contactsList column in order to show the new data. Also, notice that we are still supporting i18n for every text using the messages property; the task to fill the messages_XX.properties file is left as an exercise for the user. The contacts list The second column inside h:panelGrid of home.xhtml looks like: <a:outputPanel id="contactsList"> <ui:include src="main/contactsList.xhtml"/></a:outputPanel> As for groups, we used a placeholder surrounding the ui:include tag. Now let's focus on creating the data table—open the /view/main/contactsList.xhtml file and add the first snippet of code for dataTable: <h:form> <rich:dataTable id="contactsTable" reRender="contactsTableDS" rows="20" value="#{homeContactsListHelper.contactsList}" var="contact"> <rich:column width="45%"> <h:outputText value="#{contact.name}"/> </rich:column> <rich:column width="45%"> <h:outputText value="#{contact.surname}"/> </rich:column> <f:facet name="footer"> <rich:datascroller id="contactsTableDS" for="contactsTable" renderIfSinglePage="false"/> </f:facet> </rich:dataTable> <h:outputText value="#{messages['noContactsInList']}" rendered="#{homeContactsListHelper.contactsList.size()==0}"/></h:form> We just added the rich:dataTable component with some columns and an Ajax data scroller at the end. Differences between h:dataTable and rich:dataTable RichFaces provides its own version of h:dataTable, which contains more features and is better integrated with the RichFaces framework. The first important additional feature, in fact, is the skinnability support following the RichFaces standards. Other features are row and column spans support (we will discuss it in the Columns and column groups section), out-of-the-box filter and sorting (discussed in the Filtering and sorting section), more JavaScript event handlers (such as onRowClick, onRowContextMenu, onRowDblClick, and so on) and the reRender attribute. Like other data iteration components of the RichFaces framework, it also supports the partial-row update. Data pagination Implementing Ajax data pagination using RichFaces is really simple—just decide how many rows must be shown in every page by setting the rows attribute of dataTable (in our case, we've chosen 20 rows per page), and then "attach" the rich:datascroller component to it by filling the for attribute with the dataTable id: <rich:datascroller id="contactsTableDS" for="contactsTable" renderIfSinglePage="false"/> Here you can see another very useful attribute (renderIfSinglePage) that makes the component hidden when there is just a single page in the list (it means the list contains a number of items that is less than or equal to the value of the rows attribute). A thing to keep in mind is that the rich:datascroller component must stay inside a form component (h:form or a:form) in order to work. Customizing rich:datascroller is possible not only by using CSS classes (as usual), but also by personalizing our own parts using the following facets: pages controlsSeparator first, first_disabled last, last_disabled next, next_disabled previous, previous_disabled fastforward, fastforward_disabled fastrewind, fastrewinf_disabled Here is an example with some customized facets (using strings): <rich:datascroller id="contactsTableDS" for="contactsTable" renderIfSinglePage="false"> <f:facet name="first"> <h:outputText value="First" /> </f:facet> <f:facet name="last"> <h:outputText value="Last" /> </f:facet></rich:datascroller> Here is the result: You can use an image (or another component) instead of text, in order to create your own customized scroller. Another interesting example is: <rich:datascroller id="contactsTableDS" for="contactsTable" renderIfSinglePage="false"> <f:facet name="first"> <h:outputText value="First"/> </f:facet> <f:facet name="last"> <h:outputText value="Last"/> </f:facet> <f:attribute name="pageIndexVar" value="pageIndexVar"/> <f:attribute name="pagesVar" value="pagesVar"/> <f:facet name="pages"> <h:panelGroup> <h:outputText value="Page #{pageIndexVar} / #{pagesVar}"/> </h:panelGroup> </f:facet></rich:datascroller> The result is: By setting the pageIndexVar and pagesVar attributes, we are able to use them in an outputText component, as we've done in the example. A useful attribute of the component is maxPages that sets the maximum number of page links (the numbers in the middle), which the scroller shows—therefore, we can control the size of it. The page attribute could be bound to a property of a bean, in order to switch to a page giving the number—a simple use-case could be using an inputText and a commandButton, in order to let the client insert the page number that he/she wants to go to. Here is the code that shows how to implement it: <rich:datascroller for="contactsList" maxPages="20" fastControls="hide" page="#{customDataScrollerExampleHelper.scrollerPage}" pagesVar="pages" id="ds"> <f:facet name="first"> <h:outputText value="First" /> </f:facet> <f:facet name="first_disabled"> <h:outputText value="First" /> </f:facet> <f:facet name="last"> <h:outputText value="Last" /> </f:facet> <f:facet name="last_disabled"> <h:outputText value="Last" /> </f:facet> <f:facet name="previous"> <h:outputText value="Previous" /> </f:facet> <f:facet name="previous_disabled"> <h:outputText value="Previous" /> </f:facet> <f:facet name="next"> <h:outputText value="Next" /> </f:facet> <f:facet name="next_disabled"> <h:outputText value="Next" /> </f:facet> <f:facet name="pages"> <h:panelGroup> <h:outputText value="Page "/> <h:inputText value="#{customDataScrollerExampleHelper. scrollerPage}" size="4"> <f:validateLongRange minimum="0" /> <a:support event="onkeyup" timeout="500" oncomplete="#{rich:component('ds')}. switchToPage(this.value)" /> </h:inputText> <h:outputText value=" of #{pages}"/> </h:panelGroup> </f:facet></rich:datascroller> As you can see, besides customizing the text of the First, Last, Previous, and Next sections, we defined a pages facet by inserting h:inputText connected with an integer value inside a backing bean. We also added the a:support tag, in order to trim the page change after the keyup event is completed. We've also set the timeout attribute, in order to call the server every 500 ms and not every time the user types. You can see a screenshot of the feature here:
Read more
  • 0
  • 0
  • 1601
article-image-event-delivery-network-oracle-soa-suite-11g-r1
Packt
18 Nov 2009
2 min read
Save for later

Event Delivery Network with Oracle SOA Suite 11g R1

Packt
18 Nov 2009
2 min read
Creating truly decoupled composite SOA applications requires a complete separation of the service consumer and the service provider.This is typically achieved through the use of asynchronous messaging.In an asynchronous messaging pattern, applications can perform in a"fire and forget" mode. This removes the need of an application to know details of the application on the other side. Additionally, it also improves resource utilization as applications are not holding onto resources until the interaction is complete. On the other hand, this introduces complexities of creating and managing message queues and topics. It requires that both the publisher of the message and the consumer use the same messaging technology. Each messaging system also has its own constraints on the types of programming languages and environments that can use the service. In a service-oriented world, this tight coupling to the implementation of the underlying messaging system is at odds with the fundamental requirement of implementation independence. What's needed is a level of abstraction that allows applications to generate an event using business terms and associate a business object in an implementation‑independent form. Oracle SOA Suite 11g addresses this with the introduction of anew feature in the form of the Event Delivery Network. Introducing events The Event Delivery Network (EDN) in Oracle SOA Suite 11g provides a declarative way to use a publish/subscribe model to generate and consume business events without worrying about the underlying message infrastructure. Developers only need to produce or consume events without having to deal with any particular messaging API like JMS, AQ, and MQ, and so on. Consuming an event means expressing an interest in the occurrence of a specific situation,while producing an event means advertising this occurrence. Using the same concepts that are used in Web Service Definition Language (WSDL), EDN uses an XML-based Event Definition Language, which allows you to define the event and its associated,strongly typed data. This definition is then registered with the SOA Infrastructure and is available to all composites to publish or subscribe.   SERVICES MESSAGING EDN WSDL:Standard service interface model JMS API:Application Programming Interface EDL:Event Definition Language XSD:Strong typing Handful of raw types XSD Business-oriented Developer-oriented Business-oriented Wealth of tools Mostly coding tools Fully declarative  
Read more
  • 0
  • 0
  • 2804

article-image-joomla-flash-flashy-templates-headers-banners-and-tickers-part-1
Packt
18 Nov 2009
4 min read
Save for later

Joomla! with Flash: Flashy Templates, Headers, Banners, and Tickers: Part 1

Packt
18 Nov 2009
4 min read
In this article, we will mainly focus on the visual design of our site. To acquire the information presented here, it is assumed that you have some basic understanding of Joomla!'s visual design including templates, components, module position, and so on. Adding Flash in templates If you are familiar with Joomla! templates, then you will understand that there are two ways to display Flash in a template: By hardcoded embedding of Flash items By dynamically loading Flash objects at module positions We have seen many modules that can display Flash objects. Therefore, in this section, we will be looking into the embedding of Flash objects within templates. It will also be helpful if we understand the structure of Joomla! templates. Generally templates for Joomla! include headers in Flash. Flash animations are included in the header area of a Joomla! template. Some templates include the mechanism to show images from a specific directory. For example, the template shown in the following screenshot, available for download at http://joomlatp.com/joomla-1.5-templates/Templates-has-flash-header.html, is designed to show a Flash header comprised of the images kept in a directory: The following sections briefly describe the structure of a Joomla! template and the ways to embed a Flash object in this template. Structure of a Joomla! template The look and feel of Joomla! is determined by templates. You can apply a template to the frontend as well as to the backend. Templates for the Joomla! frontend reside in the /templates directory of the Joomla! webroot, while those for the administration panel are found in the /administrator/templates directory. You can install multiple templates and apply one or more templates to the different sections. However, you must designate one default template for the site. To designate a default template, go to Extensions | Template Manager. Select the desired template and click on the Default button on the toolbar. For assigning a template to a specific section of the site, click on a template, except the default template, and then select the section or the menu item for which you want to assign the template from the Menu Assignment section. If you examine the directory structure of a Joomla! template, you will find at least the following subdirectories in the templates directory: Directory Description mx_joofree2 This is the main template directory. It contains some subdirectories and at least the following files under its root: index.php: This is the main file for a template. The basic structure of a Joomla! template is defined in this file. We will examine this file later. templateDetails.xml: This XML file defines the template by mentioning its designer, the different files bundled with it, the positions and parameters available, and so on. params.ini: This file contains the parameters and their default values. For example, a template may use several colors for theming, but users can select a preferred color as a parameter for this template, and that information is stored in this file. mx_joofree2/css This directory contains all the cascading stylesheets to be used for a Joomla! site. This directory will contain at least one stylesheet named template_css.css. It may also contain a stylesheet named template_ie6.css and other stylesheets. mx_joofree2/html This folder may contain some definitions for the custom rendering of certain parts of the site. For example, the mx_joofree2 template contains two files-module.php and pagination.php. These two files define custom module rendering and pagination for Joomla!. For more information on using HTML overrides, refer to http://docs.joomla.org/How_to_override_the_content_from_the_Joomla!_core. mx_joofree2/images This folder contains the images for the template. It may contain a logo image, a background image, and so on. It may also contain some subdirectories, for example, the mx_joofree2 template contains a subdirectory images/headers, where the header images for the template are stored.
Read more
  • 0
  • 0
  • 3098
Modal Close icon
Modal Close icon