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-using-javascript-effects-joomla-15
Packt
03 Jun 2010
7 min read
Save for later

Using Javascript effects with Joomla! 1.5

Packt
03 Jun 2010
7 min read
(Read more interesting articles on Joomla! 1.5 here.) Using JavaScript effects Joomla! includes mootools—a powerful compact JavaScript framework. Mootools enables us to do many things, but it is used extensively in Joomla! to create client-side effects. Some of these, such as the accordion, are accessible through Joomla! classes. Others require special attention. In some instances it may be necessary to manually add the mootools library to the document. We can do this using the JHTML behavior.mootools type: JHTML::_('behavior.mootools'); JPane A pane is an XHTML area that holds more than one set of information. There are two different types of panes: Tabs: Tabs provides a typical tabbed area with tabs to the top that are used to select different panes. Sliders: Sliders, based on the mootools accordion, are vertical selections of headings above panels that can be expanded and contracted. We use the JPane class to implement panes. This example demonstrates a basic tabular pane with two panels: $pane =& JPane::getInstance('Tabs');echo $pane->startPane('myPane');{ echo $pane->startPanel('Panel 1', 'panel1'); echo "This is Panel 1"; echo $pane->endPanel(); echo $pane->startPanel('Panel 2', 'panel2'); echo "This is Panel 2"; echo $pane->endPanel();}echo $pane->endPane(); There are essentially two elements to a pane: the pane itself and the panels within the pane. We use the methods startPane() and endPane() to signify the start and end of the pane. When we use startPane() we must provide one string parameter, which is a unique identifier used to identify the pane. Panels are always created internally to a pane and use the methods startPanel() and endPanel(). We must provide the startPanel() method with two parameters, the name, which appears on the tab, and the panel ID. The following is a screenshot of the pane created from the previous code: Had we wanted to create a slider pane instead of a tab pane when we used the getInstance() method, we would need to have supplied the parameter Sliders instead of Tabs. This is a screenshot of the same pane as a slider: Panes are used extensively in Joomla! As a general rule, tabs are used for settings and sliders are used for parameters. Tooltips Tool tips are small boxes with useful information in them that appear in response to onmouseover events. They are used extensively in forms to provide more information about fields and their contents. Tooltips can be extremely helpful to users by providing small helpful hints such as what value should be put into a field or what is the purpose of a field. It takes a small amount of code to implement but adds a lot of value for our users. So how do we add a tooltip? We use JHTML to render tips easily. There are two types that we use: behavior.tooltip is used to import the necessary JavaScript to enable tooltips to work and it does not return anything. We only ever need to call this type once in a page. tooltip is used to render a tooltip in relation to an image or a piece of text. There are six parameters associated with tooltip, of which five are optional. We will explore the more common uses of these parameters. The most basic usage of tooltip returns a small information icon that onmouseover displays as a tooltip; as this example demonstrates: echo JHTML::_('tooltip', $tooltip); The next parameter allows us to define a title that is displayed at the top of the tooltip: echo JHTML::_('tooltip', $tooltip, $title); The next parameter allows us to select an image from the includes/js/ThemeOffice directory. This example uses the warning.png image: echo JHTML::_('tooltip', $tooltip, $title, 'warning.png'); The next obvious leap is to use text instead of an image and that is just what the next parameter allows us to do: echo JHTML::_('tooltip', $tooltip, $title, null, $text); There are some additional parameters that relate to using hypertext links. A full description of these is available in Appendix E, Joomla! HTML Library. We can modify the appearance of tooltips using CSS. There are three style classes that we can use: .tool-tip, .tool-title, and .tool-text. The tooltip is encapsulated by the .tool-tip class, and the .tool-title and .tool-text styles relate to the title and the content. This code demonstrates how we can add some CSS to the document to override the default tooltip CSS: // prepare the cSS$css = '/* Tooltips */.tool-tip{ min-width: 100px; opacity: 0.8; filter: alpha(opacity=80); -moz-opacity: 0.8;}.tool-title{ text-align: center;}.tool-text { font-style: italic;}';// add the CSS to the document$doc =& JFactory::getDocument();$doc->addStyleDeclaration($css); Let's add tooltips to our com_boxoffice/views/revue/tmpl/default.php layout file. The first step is to enable tooltips by adding behavior.tooltip to the beginning of our layout file as follows: <?php // No direct access defined('_JEXEC') or die('Restricted access'); // Enable tooltips JHTML::_('behavior.tooltip');?> This should be placed at the beginning as illustrated. This adds the mootool JavaScript class Tips to our document and adds the following JavaScript code to the document heading: <script type="text/javascript"> window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });</script> Next, we identify those elements that we wish to have a tooltip enabled for. There are two documented ways to implement a tooltip. We will create both for the movie title to illustrate: <tr> <td width="100" align="right" class="key"> <span class="editlinktip hasTip" title="::<?php echo JText::_('TIP_001');?>"> <label for="title"> <?php echo JText::_('Movie Title'); ?>: </label> </span> </td> <td> <input class="inputbox" type="text" name="title" id="title" size="25" value="<?php echo $this->revue->title;?>" /> <?php echo JHTML::_('tooltip', JText::_('TIP_001')); ?> </td></tr> The first approach wraps the label with a <span> that has two CSS classes declared editlinktip and hasTip, and a title attribute. The title attribute is a two part string with the parts separated by double colons; the first part is the tooltip title and the second is the tooltip text. Both methods will produce similar results. There are a few differences that you should keep in mind. The first approach displays the tip when you hover over the spanned element (in this case the label field). The second approach will generate a small icon next to the input field; the tip will appear when you move your mouse over the icon. You can duplicate the results of the first approach using the tooltip method with the following code: <?php $label = '<label for ="title">' . JText::_('Movie Title') . '</label>'echo JHTML::_('tooltip', JText::_('TIP_001'), '', '', $label);?> Note that the tip text is passed through JText with a key from our translation file. Here are the entries for our tips: # Tip TextTIP_001=Enter the film title.TIP_002=Choose the MPAA film rating.TIP_003=Provide a brief impression of the film.TIP_004=Enter the name of the reviewer.TIP_005=Enter 1-5 asterisks (*) for overall quality of the film.TIP_006=Enter the date of the review (mm/dd/yyyy).TIP_007=Do you wish to publish this revue? In the end the method you choose to implement tooltips is largely a personal preference.
Read more
  • 0
  • 0
  • 1812

article-image-working-jrockit-runtime-analyzer-sequel
Packt
03 Jun 2010
7 min read
Save for later

Working with JRockit Runtime Analyzer- A Sequel

Packt
03 Jun 2010
7 min read
Code The Code tab group contains information from the code generator and the method sampler. It consists of three tabs —the Overview, Hot Methods, and Optimizations tab. Overview This tab aggregates information from the code generator with sample information from the code optimizer. This allows us to see which methods the Java program spends the most time executing. Again, this information is available virtually "for free", as the code generation system needs it anyway. For CPU-bound applications, this tab is a good place to start looking for opportunities to optimize your application code. By CPU-bound, we mean an application for which the CPU is the limiting factor; with a faster CPU, the application would have a higher throughput.   In the first section, the amount of exceptions thrown per second is shown. This number depends both on the hardware and on the application—faster hardware may execute an application more quickly, and consequently throw more exceptions. However, a higher value is always worse than a lower one on identical setups. Recall that exceptions are just that, rare corner cases. As we have explained, theJVM typically gambles that they aren't occurring too frequently. If an application throws hundreds of thousands exceptions per second, you should investigate why. Someone may be using exceptions for control flow, or there may be a configuration error. Either way, performance will suffer. In JRockit Mission Control 3.1, the recording will only provide information about how many exceptions were thrown. The only way to find out where the exceptions originated is unfortunately by changing the verbosity of the log. An overview of where the JVM spends most of the time executing Java code can be found in the Hot Packages and Hot Classes sections. The only difference between them is the way the sample data from the JVM code optimizer is aggregated. In Hot Packages, hot executing code is sorted on a per-package basis and in Hot Classes on a per-class basis. For more fine-grained information, use the Hot Methods tab. As shown in the example screenshot, most of the time is spent executing code in the weblogic.servlet.internal package. There is also a fair amount of exceptions being thrown. Hot Methods This tab provides a detailed view of the information provided by the JVM code optimizer. If the objective is to find a good candidate method for optimizing the application, this is the place to look. If a lot of the method samples are from one particular method, and a lot of the method traces through that method share the same origin, much can potentially be gained by either manually optimizing that method or by reducing the amount of calls along that call chain. In the following example, much of the time is spent in the method com.bea.wlrt.adapter.defaultprovider.internal.CSVPacketReceiver.parseL2Packet(). It seems likely that the best way to improve the performance of this particular application would be to optimize a method internal to the application container (WebLogic Event Server) and not the code in the application itself, running inside the container. This illustrates both the power of the JRockit Mission Control tools and a dilemma that the resulting analysis may reveal—the answers provided sometimes require solutions beyond your immediate control.   Sometimes, the information provided may cause us to reconsider the way we use data structures. In the next example, the program frequently checks if an object is in a java. util.LinkedList. This is a rather slow operation that is proportional to the size of the list (time complexity O(n)), as it potentially involves traversing the entire list, looking for the element. Changing to another data structure, such as a HashSet would most certainly speed up the check, making the time complexity constant (O(1)) on average, given that the hash function is good enough and the set large enough.   Optimizations This tab shows various statistics from the JIT-compiler. The information in this tab is mostly of interest when hunting down optimization-related bugs in JRockit. It shows how much time was spent doing optimizations as well as how much time was spent JIT-compiling code at the beginning and at the end of the recording. For each method optimized during the recording, native code size before and after optimization is shown, as well as how long it took to optimize the particular method.   Thread/Locks The Thread/Locks tab group contains tabs that visualize thread- and lock-related data. There are five such tabs in JRA—the Overview, Thread, Java Locks, JVM Locks, and Thread Dumps tab. Overview The Overview tab shows fundamental thread and hardware-related information, such as the number of hardware threads available on the system and the number of context switches per second.   A dual-core CPU has two hardware threads, and a hyperthreaded core also counts as two hardware threads. That is, a dual-core CPU with hyperthreading will be displayed as having four hardware threads. A high amount of context switches per second may not be a real problem, but better synchronization behavior may lead to better total throughput in the system. There is a CPU graph showing both the total CPU load on the system, as well as the CPU load generated by the JVM. A saturated CPU is usually a good thing — you are fully utilizing the hardware on which you spent a lot of money! As previously mentioned, in some CPU-bound applications, for example batch jobs, it is normally a good thing for the system to be completely saturated during the run. However, for a standard server-side application it is probably more beneficial if the system is able to handle some extra load in addition to the expected one. The hardware provisioning problem is not simple, but normally server-side systems should have some spare computational power for when things get hairy. This is usually referred to as overprovisioning, and has traditionally just involved buying faster hardware. Virtualization has given us exciting new ways to handle the provisioning problem. Threads This tab shows a table where each row corresponds to a thread. The tab has more to offer than first meets the eye. By default, only the start time, the thread duration, and the Java thread ID are shown for each thread. More columns can be made visible by changing the table properties. This can be done either by clicking on the Table Settings icon, or by using the context menu in the table. As can be seen in the example screenshot, information such as the thread group that the thread belongs to, allocation-related information, and the platform thread ID can also be displayed. The platform thread ID is the ID assigned to the thread by the operating system, in case we are working with native threads. This information can be useful if you are using operating system-specific tools together with JRA.   Java Locks This tab displays information on how Java locks have been used during the recording. The information is aggregated per type (class) of monitor object.   This tab is normally empty. You need to start JRockit with the system property jrockit.lockprofiling set to true, for the lock profiling information to be recorded. This is because lock profiling may cause anything from a small to a considerable overhead, especially if there is a lot of synchronization. With recent changes to the JRockit thread and locking model, it would be possible to dynamically enable lock profiling. This is unfortunately not the case yet, not even in JRockit Flight Recorder. For R28, the system property jrockit.lockprofiling has been deprecated and replaced with the flag -XX:UseLockProfiling. JVM Locks This tab contains information on JVM internal native locks. This is normally useful for the JRockit JVM developers and for JRockit support. An example of a native lock would be the code buffer lock that the JVM acquires in order to emit compiled methods into a native code buffer. This is done to ensure that no other code generation threads interfere with that particular code emission. Thread Dumps The JRA recordings normally contain thread dumps from the beginning and the end of the recording. By changing the Thread dump interval parameter in the JRA recording wizard, more thread dumps can be made available at regular intervals throughout the recording.  
Read more
  • 0
  • 0
  • 1914

article-image-easily-modifying-page-joomla-15
Packt
02 Jun 2010
17 min read
Save for later

Easily modifying a page with Joomla! 1.5

Packt
02 Jun 2010
17 min read
(Read more interesting articles on Joomla!1.5 here.) Application message queue You may have noticed that when we raise a notice or a warning, a bar appears across the top of the page containing the notice or warning message. These messages are part of the application message queue. The application message queue is a message stack that is displayed the next time the application renders an HTML view. This means that we can queue messages in one request but not show them until a later request. There are three core message types: message, notice, and error. The next screenshot depicts how each of the different types of application message is rendered: We use the application enqueueMessage() method to add a message to the queue. This example demonstrates how we would add all of the messages shown in the previous screenshot to the message queue: $mainframe->enqueueMessage('A message type message');$mainframe->enqueueMessage('A notice type message', 'notice');$mainframe->enqueueMessage('An error type message', 'error'); The first parameter is the message that we want to add and the second parameter is the message type; the default is message. It is uncommon to add notice or error messages this way; normally we will use JError::raiseNotice() and JError::raiseWarning() respectively. This means that we will, in most cases, use one parameter with the enqueueMessage() method. It is possible however, to add messages of our own custom types. This is an example of how we would add a message of type bespoke: $mainframe->enqueueMessage('A bespoke type message', 'bespoke'); Custom type messages will render in the same format as message type messages. Imagine we want to use the bespoke message type to render messages but not display them. This could be useful for debugging purposes. This example demonstrates how we can add a CSS Declaration to the document, using the methods described earlier to modify the way in which the bespoke messages are displayed: $css = '/* Bespoke Error Messages */#system-message dt.bespoke{display: none;}dl#system-message dd.bespoke ul{ color: #30A427; border-top: 3px solid #94CA8D; border-bottom: 3px solid #94CA8D; background: #C8DEC7 url(notice-bespoke.png) 4px 4px no-repeat;}';$doc =& JFactory::getDocument();$doc->addStyleDeclaration($css); Now when bespoke messages are rendered, they will appear like this: Redirecting the browser Redirection allows us to redirect the browser to a new location. Joomla! provides us with some easy ways in which to redirect the browser. Joomla! redirects are implemented using HTTP 301 redirect response codes. In the event that response headers have already been sent, JavaScript will be used to redirect the browser. The most common time to redirect a browser is after a form has been submitted. There are a number of reasons why we might want to do this, such as the following: Redirecting after form submission prevents forms from being submitted multiple times when the browser is refreshed We can redirect to different locations depending on the submitted data Redirecting to another view reduces the amount of development required for each task in the controller There are many scenarios where the use of a redirect is common. The following list identifies some of these: Canceling editing an existing item Copying items Creating new items and updating existing items Deleting items Publishing or unpublishing items Updating item ordering Imagine a user submits a form that is used to create a new record in a database table. The first thing we need to do when we receive a request of this type is to validate the form contents. This next data flow diagram describes the logic that we could implement: The No route passes the invalid input to the session. We do this so that when we redirect the user to the input form we can repopulate the form with the invalid input. If we do not do this the user will have to complete the entire form again. We may choose to omit the Pass invalid input to user session process as the core components do. It is normal to include JavaScript to validate forms before they are submitted, and since the majority of users will have JavaScript support enabled, this may be a good approach to use. Note that omitting this process is not the same as omitting form validation. We must never depend on JavaScript or other client-side mechanisms for data validation. A good approach is to initially develop forms without client-side validation while ensuring that we properly handle invalid data with server-side scripts. As a quick aside, a good way to validate form contents is to use a JTable subclass check() method. If we place failed input into the session, we might want to put it in its own namespace. This makes it easier to remove the data later and helps prevent naming conflicts. The next example demonstrates how we might add the field value of myField to the myForm session namespace: // get the session$session =& JFactory::getSession();// get the raw value of myField$myFieldValue = JRequest::getString('myField', '', 'POST', JREQUEST_ALLOWRAW);// add the value to the session namespace myForm$session->set('myField', $myFieldValue, 'myForm') When we come to display the form we can retrieve the data from the session using the get() method. Once we have retrieved the data we must remember to remove the data from the session, otherwise it will be displayed every time we view the form (unless we use another flag as an indicator). We can remove data items from the myForm namespace using the clear() method: // get the session$session =& JFactory::getSession();// Remove the myField$session->clear('myField', 'myForm'); The final thing we do in the No route is to redirect the user back to the input form. When we do this, we must add some messages to the application queue to explain to the user why the input has been rejected. The Yes route adds a new record to the database and then redirects the user to the newly created item. As with the No route, it is normal to queue a message that will say that the new item has been successfully saved, or something to that effect. There are essentially two ways to redirect. The first is to use the application redirect() method. It is unusual to use this mechanism unless we are developing a component without the use of the Joomla! MVC classes. This example demonstrates how we use the application method: $mainframe->redirect('index.php?option=com_boxoffice'); This will redirect the user's browser to index.php?option=com_boxoffice. There are two additional optional parameters that we can provide when using this method. These are used to queue a message. This example redirects us, as per the previous example, and queues a notice type message that will be displayed after the redirect has successfully completed: $mainframe->redirect('index.php?option=com_boxoffice','Some Message', 'notice'); The final parameter, the message type, defaults to message. The application redirect() method immediately queues the message, redirects the user's browser, and ends the application. The more common mechanism for implementing redirects is to use the JController setRedirect() method. We generally use this from within a controller method that handles a task, but because the method is public we can use it outside of the controller. This example, assuming we are within a JController subclass method, will set the controller redirect to index.php?option=com_boxoffice: $this->setRedirect('index.php?option=com_boxoffice'); As with the application redirect() method, there are two additional optional parameters that we can provide when using this method. These are used to queue a message. This example sets the controller redirect, as per the previous example, and queues a notice type message that will be displayed after the redirect has successfully completed: $this->setRedirect('index.php?option=com_boxoffice', 'Some Message','notice'); Unlike the application redirect() method, this method does not immediately queue the optional message, redirect the user's browser, and end the application.To do this we must use the JController redirect() method. It is normal, in components that use redirects, to execute the controller redirect() method after the controller has executed a given task. This is normally done in the root component file, as this example demonstrates: $controller = new BoxofficeController();$controller->execute(JRequest::getCmd('task'));$controller->redirect(); Component XML metadata files and menu parameters When we create menu items, if a component has a selection of views and layouts, we can choose which view and which layout we want to use. We can create an XML metadata file for each view and layout. In these files we can describe the view or layout and we can define extra parameters for the menu item specific to the specified layout. Our component frontend has a single view with two layouts: default.php and list.php. The next figure describes the folder structure we would expect to find in the views folder (for simplicity, only the files and folders that we are discussing are included in the figure): When an administrator creates a link to this view, the options displayed will not give any information beyond the names of the folders and files described above, as the next screenshot demonstrates: The first element of this list that we will customize is the view name, Revue. To do this we must create a file in the revue folder called metadata.xml. This example customizes the name and description of the revue view: ?xml version="1.0" encoding="utf-8"?><metadata> <view title="Movie Revues"> <message> <![CDATA[Movie Revues]]> </message> </view></metadata> Now if an administrator were to view the list of menu item types, Revue would be replaced with the text Movie Revues as defined in the view tag title attribute. The description, defined in the message tag, is displayed when the mouse cursor is over the view name. The next task is to customize the definitions of the layouts, default.php and list.php. Layout XML metadata files are located in the tmpl folder and are named the same as the corresponding layout template file. For example, the XML metadata file for default.php would be named default.xml. So we need to add the files default.xml and list.xml to the tmpl folder. Within a layout XML metadata file, there are two main tags in which we are interested: layout and state. Here is an example of a XML metadata file <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Individual Revue"> <message> <![CDATA[Individual movie revue.]]> </message> </layout> <state> <name>Individual Revue</name> <description>Individual movie revue.</description> </state></metadata> And here is the list.xml file: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> </state></metadata> At first glance it may seem odd that we appear to be duplicating information in the layout and state tags. However, the layout tag includes information that is displayed in the menu item type list (essentially an overview). The state tag includes information that is displayed during the creation of a menu item that uses the layout. There are occasions when a more detailed description is required when we come to define a menu item. For example, we may want to warn the user that they must fill in a specific menu parameter. We will discuss menu parameters in a moment. Assuming we created the default.xml and list.xml files as shown previously, our menu item type list would now appear as follows: Now that we know how to modify the names and descriptions of views and layouts, we can investigate how to define custom menu parameters. There are many different types of parameter that we can define. Before you continue, you might want to familiarize yourself with this list of parameter types because we will be using them in the examples. A complete description of these parameters is available in Appendix B, Parameters (Core Elements): category editors filelist folderlist helpsites hidden imagelist languages list menu menuitem password radio section spacer sql text textarea timezones Menu parameters can be considered as being grouped into several categories: System Component State URL Advanced The System parameters are predefined by Joomla! (held in the administrator/components/com_menus/models/metadata/component.xml file). These parameters are used to encourage standardization of some common component parameters. System parameters are shown under the heading Parameters (System); we cannot prevent these parameters from being displayed. The Component parameters are those parameters that are defined in the component's config.xml file. Note that changing these parameters when creating a new menu item only affects the menu item, not the entire component. In essence, this is a form of overriding. This form of overriding is not always desirable; it is possible to prevent the component parameters from being shown when creating or editing a menu item. To do this we add the attribute menu to the root tag (config) of the component config.xml file and set the value of the attribute to hide: The remaining parameter groups—State, URL, and Advanced—are defined on a per layout basis in the layout XML metadata files inside the state tag. These are the groups in which we are most interested. The State parameters are located in a tag called params. In this example, which builds on our list.xml file, we add two parameters: a text field named revue_heading and a radio option named show_heading: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> </state></metadata> When an administrator creates a new menu item for this layout, these two parameters will be displayed under the heading Parameters (Basic). The parameters are not presented under a State heading, because State and URL parameters are consolidated into one section. URL parameters always appear above State parameters. We define URL parameters in much the same way, only this time we place them in a tag named url. The URL parameters are automatically appended to the URI; this means that we can access these parameters using JRequest. These parameters are of particular use when we are creating a layout that is used to display a single item that is retrieved using a unique ID. If we use these parameters to define an ID that is retrieved from a table, we should consider using the often overlooked sql parameter type. The following example builds on the previous example, and adds the URL parameter id, which is extracted from the #__boxoffice_revues table: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <url> <param type="sql" name="id" label="Revue:" description="Revue to display" query="SELECT id AS value, title AS id FROM #__boxoffice_revues" /> </url> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> </state></metadata> The query might be slightly confusing if you are not familiar with the sql parameter type. The query must return two fields, value and id. value specifies the value of the parameter and id specifies the identifier displayed in the drop-down box that is displayed when the parameter is rendered. When using the sql parameter type, if applicable, remember to include a WHERE clause to display only published or equivalent items. The Advanced parameters are specifically for defining parameters that are more complex than the State parameters. These parameters are defined in the advanced tag. This example adds an advanced parameter called advanced_setting: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <url> <param type="sql" name="id" label="Revue:" description="Revue to display" query="SELECT id AS value, title AS id FROM #__boxoffice_revues" /> </url> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> <advanced> <param type="radio" name="list_by_cat" label="List by Genre" description="List revues by genre." default="0"> <option value="0">No</option> <option value="1">Yes</option> </param> </advanced> </state></metadata> Advanced parameters will appear under the Parameters Advanced heading. Component parameters, Component Design—will appear under the Parameters (Component) heading. The resultant parameters area for this layout will appear as follows: All name and description elements from the XML metadata files will be translated into the currently selected locale language. When we save a menu item, all of the parameters, except URL parameters, are saved to the params field in the menu item record. This means that we can end up with naming conflicts between our parameters. We must ensure that we do not name any two parameters the same. This includes not using the predefined System parameter names. This list details the System parameter names: page_title show_page_title pageclass_sfx menu_image secure Once we have successfully created the necessary XML, we will be able to access the parameters from within our component using a JParameter object. This is described in the next section.
Read more
  • 0
  • 0
  • 1879

article-image-ajax-implementation-apex
Packt
01 Jun 2010
8 min read
Save for later

AJAX Implementation in APEX

Packt
01 Jun 2010
8 min read
(For more resources on Oracle, see here.) APEX introduced AJAX supports in version 2.0 (the product was called HTML DB back then). The support includes a dedicated AJAX framework that allows us to use AJAX in our APEX applications, and it covers both the client and the server sides. AJAX support on the client side The APEX built-in JavaScript library includes a special JavaScript file with the implementation of the AJAX client-side components. In earlier versions this file was called htmldb_get.js, and in APEX 3.1, it was changed to apex_get_3_1.js. In version 3.1, APEX also started to implement JavaScript namespace in the apex_ns_3_1.js file. Within the file, there is a definition to an apex.ajax namespace. I'm not mentioning the names of these files just for the sake of it. As the AJAX framework is not officially documented within the APEX documentation, these files can be very important and a useful source of information. By default, these files are automatically loaded into every application page as part of the #HEAD# substitution string in the Header section of the page template. This means that, by default, AJAX functionality is available to us on every page of our application, without taking any extra measures. The htmldb_Get object The APEX implementation of AJAX is based on the htmldb_Get object and as we'll see, creating a new instance of htmldb_Get is always the first step in performing an AJAX request. The htmldb_Get constructor function has seven parameters: function htmldb_Get(obj,flow,req,page,instance,proc,queryString) 1—obj The first parameter is a String that can be set to null, a name of a page item (DOM element), or an element ID. Setting this parameter to null will cause the result of the AJAX request to be assigned in a JavaScript variable. We should use this value every time we need to process the AJAX returned result, like in the cases where we return XML or JSON formatted data, or when we are relaying on the returned result, further in our JavaScript code flow. The APEX built-in JavaScript library defines, in the apex_builder.js file, (which is also loaded into every application page, just like apex_ get_3_1.js), a JavaScript global variable called gReturn. You can use this variable and assign it the AJAX returned result. Setting this parameter to the name (ID) of a page item will set the item value property with the result of the AJAX call. You should make sure that the result of the AJAX call matches the nature of the item value property. For example, if you are returning a text string into a text item it will work just fine. However, if you are returning an HTML snippet of code into the same item, you'll most likely not get the result you wanted. Setting this parameter to a DOM element ID, which is not an input item on the page, will set its innerHTML property to the result of the AJAX call. Injecting HTML code, using the innerHTML property, is a cross-browser issue. Moreover, we can't always set innerHTML along the DOM tree. To avoid potential problems, I strongly recommend that you use this option with <div> elements only. 2—flow This parameter represents the application ID. If we are calling htmldb_Get() from an external JavaScript file, this parameter should be set to $v('pFlowId') or its equivalent in version 3.1 or before ($x('pFlowId').value or html_GetElement('pFlowId').value ). This is also the default value, in case this parameter is left null. If we are calling htmldb_Get() as part of an inline JavaScript code we can use the Substitution String notation &APP_ID. (just to remind you that the trailing period is part of the syntax). Less common, but if you are using Oracle Web Toolkit to generate dynamic code (for dynamic content) that includes AJAX, you can also use the bind variable notation :APP_ID. (In this case, the period is just a punctuation mark.) 3—req This String parameter stands for the REQUEST value. Using the keyword APPLICATION_PROCESS with this parameter allows us to name an application level On Demand—PL/SQL Anonymous Block process that will be fired as part of the AJAX server-side processing. For example: 'APPLICATION_PROCESS=demo_code'. This parameter is case sensitive, and as a String, should be enclosed with quotes. If, as part of the AJAX call, we are not invoking an on-demand process, this parameter should be set to null (which is its default value). 4—page This parameter represents an application page ID. The APEX AJAX process allows us to invoke any application page, to run it in the background, on the server side, and then clip portions of the generated HTML code for this page into the AJAX calling page. In these cases, we should set this parameter to the page ID that we want to pull from. The default value of this parameter is 0 (this stands for page 0). However, this value can be problematic at times, especially when page 0 has not been defined on the application, or when there are inconsistencies between the Authorization scheme, or the page Authentication (such as Public and Required Authentication) of page 0 and the AJAX calling page. These inconsistencies can fail the execution of the AJAX process. In cases where you are not pulling information from another page, the safe bet is to set this parameter to the page ID of the AJAX calling page, using $v('pFlowStepId') or its equivalent for versions earlier than 3.1. In the case of an inline code, the &APP_PAGE_ID. Substitution String can also be used. Using the calling page ID as the default value for this parameter can be considered a "good practice" even for upcoming APEX versions, where implementation of page level on-demand process will probably be introduced. I hope you remember that as of version 3.2, we can only define on-demand processes on the application level. 5—instance This parameter represents the APEX session ID, and should almost always be left null (personally, I never encountered the need to set it otherwise). In this case, it will be populated with the result of $v('pInstance') or its earliest versions. 6—proc This String parameter allows us to invoke a stored or packaged procedure on the database as part of the AJAX process. The common behavior of the APEX AJAX framework is to use the application level On Demand PL/SQL Anonymous Block process as the logic of the AJAX server-side component. In this case, the on-demand process is named through the third parameter—req—using the keyword APPLICATION_PROCESS, and this parameter—proc—should be left null. The parameter will be populated with its default value of 'wwv_flow.show'(the single quotes are part of the syntax, as this is a String parameter). However, the APEX AJAX framework also allows us to invoke an external (to APEX) stored (or packaged) procedure as the logic of the AJAX server side. In this case, we can utilize an already existing logic in the database. Moreover, we can benefit from the "regular" advantages of stored procedures, such as a pre-complied code, for better performance, or the option to use wrapped PL/SQL packages, which can protect our business logic better (the APEX on-demand PL/SQL process can be accessed on the database level as clear text). The parameter should be formatted as a URL and can be in the form of a relative URL. In this case, the system will complete the relative URL into a full path URL based on the current window.location.href property. As with all stored or packaged procedures that we wish to use in our APEX application, the user (and in the case of using DAD, the APEX public user) should have the proper privileges on the stored procedure. In case the stored procedure, or the packaged procedure, doesn't have a public synonym defined for it then the procedure name should be qualified with the owner schema. For example, with inline code we can use: '#OWNER#.my_package.my_proc' For external code, you should retrieve the owner and make it available on the page (e.g. assign it to a JavaScript global variable) or define a public synonym for the owner schema and package. 7—queryString This parameter allows us to add parameters to the stored (packaged) procedure that we named in the previous parameter—proc. As we are ultimately dealing with constructing a URL, that will be POSTed to the server, this parameter should take the form of POST parameters in a query string—pairs of name=value, delimited by ampersand (&). Let's assume that my_proc has two parameters: p_arg1 and p_arg2. In this case, the queryString parameter should be set similar to the following: 'p_arg1=Hello&p_arg2=World' As we are talking about components of a URL, the values should be escaped so their code will be a legal URL. You can use the APEX built-in JavaScript function htmldb_Get_escape() to do that. If you are using the req parameter to invoke an APEX on-demand process with your AJAX call, the proc and queryString parameters should be left null. In this case, you can close the htmldb_Get() syntax right after the page parameter. If, on the other hand, you are invoking a stored (packaged) procedure, the req parameter should be set to null.
Read more
  • 0
  • 0
  • 4164

article-image-designing-secure-java-ee-applications-glassfish
Packt
31 May 2010
2 min read
Save for later

Designing Secure Java EE Applications in GlassFish

Packt
31 May 2010
2 min read
Security is an orthogonal concern for an application and we should assess it right from the start by reviewing the analysis we receive from business and functional analysts. Assessing the security requirements results in understanding the functionalities we need to include in our architecture to deliver a secure application covering the necessary requirements. Security necessities can include a wide area of requirements, which may vary from a simple authentication to several sub-systems. A list of these sub-systems includes identity and access management system and transport security, which can include encrypting data as well. In this article series, we will develop a secure Java EE application based on Java EE and GlassFish capabilities. In course of the article, we will cover the following topics: Analyzing Java EE application security requirements Including security requirements in Java EE application design Developing secure Business layer using EJBs Developing secure Presentation layer using JSP and Servlets Configuring deployment descriptors of Java EE applications Specifying security realm for enterprise applications Developing secure application client module Configuring Application Client Container Developing Secure Java EE Applications in GlassFish is the second part of this article series. Understanding the sample application The sample application that we are going to develop, converts different length measurement units into each other. Our application converts meter to centimeter, millimeter, and inch. The application also stores usage statistics for later use cases. Guest users who prefer not to log in can only use meter to centimeter conversion, while any company employee can use meter to centimeter and meter to millimeter conversion, and finally any of company's managers can access meter to inch in addition to two other conversion functionalities. We should show a custom login page to comply with site-wide look and feel. No encryption is required for communication between clients and our application but we need to make sure that no one can intercept and steal the username and passwords provided by members. All members' identification information is stored in the company's wide directory server. The following diagram shows the high-level functionality of the sample application: We have login action and three conversion actions. Users can access some of them after logging in and some of them can be accessed without logging in.
Read more
  • 0
  • 0
  • 9689

article-image-developing-secure-java-ee-applications-glassfish
Packt
31 May 2010
14 min read
Save for later

Developing Secure Java EE Applications in GlassFish

Packt
31 May 2010
14 min read
In this article series, we will develop a secure Java EE application based on Java EE and GlassFish capabilities. In course of the article, we will cover following topics: Analyzing Java EE application security requirements Including security requirements in Java EE application design Developing secure Business layer using EJBs Developing secure Presentation layer using JSP and Servlets Configuring deployment descriptors of Java EE applications Specifying security realm for enterprise applications Developing secure application client module Configuring Application Client Container Read Designing Secure Java EE Applications in GlassFish here. Developing the Presentation layer The Presentation layer is the closest layer to end users when we are developing applications that are meant to be used by humans instead of other applications. In our application, the Presentation layer is a Java EE web application consisting of the elements listed in the following table. In the table you can see that different JSP files are categorized into different directories to make the security description easier. Element Name Element Description Index.jsp Application entry point. It has some links to functional JSP pages like toMilli.jsp and so on. auth/login.html This file presents a custom login page to user when they try to access a restricted resource. This file is placed inside auth directory of the web application. auth/logout.jsp Logging users out of the system after their work is finished. auth/loginError.html Unsuccessful login attempt redirect users to this page. This file is placed inside auth directory of the web application jsp/toInch.jsp Converts given length to inch, it is only available for managers. jsp/toMilli.jsp Converts given length to millimeter, this page is available to any employee. jsp/toCenti.jsp Converts given length to centimeter, this functionality is available for everyone. Converter Servlet Receives the request and invoke the session bean to perform the conversion and returns back the value to user. auth/accessRestricted.html An error page for error 401 which happens when authorization fails. Deployment Descriptors The deployment descriptors which we describe the security constraints over resources we want to protect. Now that our application building blocks are identified we can start implementing them to complete the application. Before anything else let's implement JSP files that provides the conversion GUI. The directory layout and content of the Web module is shown in the following figure: Implementing the Conversion GUI In our application we have an index.jsp file that acts as a gateway to the entire system and is shown in the following listing: <html> <head><title>Select A conversion</title></head> <body><h1>Select A conversion</h1> <a href="auth/login.html">Login</a> <br/> <a href="jsp/toCenti.jsp">Convert Meter to Centimeter</a> <br/> <a href="jsp/toInch.jsp">Convert Meter to Inch</a> <br/> <a href="jsp/toMilli.jsp">Convert to Millimeter</a><br/> <a href="auth/logout.jsp">Logout</a> </body> </html> Implementing the Converter servlet The Converter servlet receives the conversion value and method from JSP files and calls the corresponding method of a session bean to perform the actual conversion. The following listing shows the Converter servlet content: @WebServlet(name="Converter", urlPatterns={"/Converter"}) public class Converter extends HttpServlet { @EJB private ConversionLocal conversionBean; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("POST"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try{ int valueToconvert = Integer.parseInt(request.getParameter("meterValue")); String method = request.getParameter("method"); out.print("<hr/> <center><h2>Conversion Result is: "); if (method.equalsIgnoreCase("toMilli")) { out.print(conversionBean.toMilimeter(valueToconvert)); } else if (method.equalsIgnoreCase("toCenti")) { out.print(conversionBean.toCentimeter(valueToconvert)); } else if (method.equalsIgnoreCase("toInch")) { out.print(conversionBean.toInch(valueToconvert)); } out.print("</h2></center>"); }catch (AccessLocalException ale) { response.sendError(401); }finally { out.close(); } } } Starting from the beginning we are using annotation to configure the servlet mapping and servlet name instead of using the deployment descriptor for it. Then we use dependency injection to inject an instance of Conversion session bean into the servlet and decide which one of its methods we should invoke based on the conversion type that the caller JSP sends as a parameter. Finally, we catch javax.ejb.AccessLocalException and send an HTTP 401 error back to inform the client that it does not have the required privileges to perform the requested action. The following figure shows what the result of invocation could look like: Each servlet needs some description elements in the deployment descriptor or included as deployment descriptor elements. Implementing the conversion JSP files is the last step in implementing the functional pieces. In the following listing you can see content of the toMilli.jsp file. <html> <head><title>Convert To Millimeter</title></head> <body><h1>Convert To Millimeter</h1> <form method=POST action="../Converter">Enter Value to Convert: <input name=meterValue> <input type="hidden" name="method" value="toMilli"> <input type="submit" value="Submit" /> </form> </body> </html> The toCenti.jsp and toInch.jsp files look the same except for the descriptive content and the value of the hidden parameter which will be toCenti and toInch respectively for toCenti.jsp and toInch.jsp. Now we are finished with the functional parts of the Web layer; we just need to implement the required GUI for security measures. Implementing the authentication frontend For the authentication, we should use a custom login page to have a unified look and feel in the entire web frontend of our application. We can use a custom login page with the FORM authentication method. To implement the FORM authentication method we need to implement a login page and an error page to redirect the users to that page in case authentication fails. Implementing authentication requires us to go through the following steps: Implementing login.html and loginError.html Including security description in the web.xml and sun-web.xml or sun-application.xml Implementing a login page In FORM authentication we implement our own login form to collect username and password and we then pass them to the container for authentication. We should let the container know which field is username and which field is password by using standard names for these fields. The username field is j_username and the password field is j_password. To pass these fields to container for authentication we should use j_security_check as the form action. When we are posting to j_security_check the servlet container takes action and authenticates the included j_username and j_password against the configured realm. The listing below shows login.html content. <form method="POST" action="j_security_check"> Username: <input type="text" name="j_username"><br /> Password: <input type="password" name="j_password"><br /> <br /> <input type="submit" value="Login"> <input type="reset" value="Reset"> </form> The following figure shows the login page which is shown when an unauthenticated user tries to access a restricted resource: Implementing a logout page A user may need to log out of our system after they're finished using it. So we need to implement a logout page. The following listing shows the logout.jsp file: <% session.invalidate(); %> <body> <center> <h1>Logout</h1> You have successfully logged out. </center> </body> Implementing a login error page And now we should implement LoginError.html, an authentication error page to inform user about its authentication failure. <html> <body> <h2>A Login Error Occurred</h2> Please click <a href="login.html">here</a> for another try. </body> </html> Implementing an access restricted page When an authenticated user with no required privileges tries to invoke a session bean method, the EJB container throws a javax.ejb.AccessLocalException. To show a meaningful error page to our users we should either map this exception to an error page or we should catch the exception, log the event for audition purposes, and then use the sendError() method of the HttpServletResponse object to send out an error code. We will map the HTTP error code to our custom web pages with meaningful descriptions using the web.xml deployment descriptor. You will see which configuration elements we will use to do the mapping. The following snippet shows AccessRestricted.html file: <body> <center> <p>You need to login to access the requested resource. To login go to <a href="auth/login.html">Login Page</a></p></center> </body> Configuring deployment descriptors So far we have implemented required files for the FORM-based authentication and we only need to include required descriptions in the web.xml file. Looking back at the application requirement definitions, we see that anyone can use meter to centimeter conversion functionality and any other functionality that requires the user to login. We use three different HTML pages for different types of conversion. We do not need any constraint on toCentimeter.html therefore we do not need to include any definition for it. Per application description, any employee can access the toMilli.jsp page. Defining security constraint for this page is shown in the following listing: <security-constraint> <display-name>You should be an employee</display-name> <web-resource-collection> <web-resource-name>all</web-resource-name> <description/> <url-pattern>/jsp/toMillimeter.html</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> <http-method>DELETE</http-method> </web-resource-collection> <auth-constraint> <description/> <role-name>employee_role</role-name> </auth-constraint> </security-constraint> We should put enough constraints on the toInch.jsp page so that only managers can access the page. The listing included below shows the security constraint definition for this page. <security-constraint> <display-name>You should be a manager</display-name> <web-resource-collection> <web-resource-name>Inch</web-resource-name> <description/> <url-pattern>/jsp/toInch.html</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <description/> <role-name>manager_role</role-name> </auth-constraint> </security-constraint> Finally we need to define any role we used in the deployment descriptor. The following snippet shows how we define these roles in the web.xml page. <security-role> <description/> <role-name>manager_role</role-name> </security-role> <security-role> <description/> <role-name>employee_role</role-name> </security-role> Looking back at the application requirements, we need to define data constraint and ensure that username and passwords provided by our users are safe during transmission. The following listing shows how we can define the data constraint on the login.html page. <security-constraint> <display-name>Login page Protection</display-name> <web-resource-collection> <web-resource-name>Authentication</web-resource-name> <description/> <url-pattern>/auth/login.html</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <user-data-constraint> <description/> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> One more step and our web.xml file will be complete. In this step we define an error page for HTML 401 error code. This error code means that application server is unable to perform the requested action due to negative authorization result. The following snippet shows the required elements to define this error page. <error-page> <error-code>401</error-code> <location>AccessRestricted.html</location> </error-page> Now that we are finished with declaring the security we can create the conversion pages and after creating these pages we can start with Business layer and its security requirements. Specifying the security realm Up to this point we have defined all the constraints that our application requires but we still need to follow one more step to complete the application's security configuration. The last step is specifying the security realm and authentication. We should specify the FORM authentication and per-application description; authentication must happen against the company-wide LDAP server. Here we are going to use the LDAP security realm LDAPRealm. We need to import a new LDIF file into our LDAP server, which contains groups and users definition required for this article. To import the file we can use the following command, assuming that you downloaded the source code bundle from https://www.packtpub.com//sites/default/files/downloads/9386_Code.zip and you have it extracted. import-ldif --ldifFile path/to/chapter03/users.ldif --backendID userRoot --clearBackend --hostname 127.0.0.1 --port 4444 --bindDN cn=gf cn=admin --bindPassword admin --trustAll --noPropertiesFile The following table show users and groups that are defined inside the users.ldif file. Username and password Group membership james/james manager, employee meera/meera employee We used OpenDS for the realm data storage and it had two users, one in the employee group and the other one in the manager group. To configure the authentication realm we need to include the following snippet in the web.xml file. <login-config> <auth-method>FORM</auth-method> <realm-name>LDAPRealm</realm-name> <form-login-config> <form-login-page>/auth/login.html</form-login-page> <form-error-page>/auth/loginError.html</form-error-page> </form-login-config> </login-config> If we look at our Web and EJB modules as separate modules we must specify the role mappings for each module separately using the GlassFish deployment descriptors, which are sun-web.xml and sun-ejb.xml. But we are going to bundle our modules as an Enterprise Application Archive (EAR) file so we can use the GlassFish deployment descriptor for enterprise applications to define the role mapping in one place and let all modules use that definitions. The following listing shows roles and groups mapping in the sun-application.xml file. <sun-application> <security-role-mapping> <role-name>manager_role</role-name> <group-name>manager</group-name> </security-role-mapping> <security-role-mapping> <role-name>employee_role</role-name> <group-name>employee</group-name> </security-role-mapping> <realm>LDAPRealm</realm> </sun-application> The security-role-mapping element we used in sun-application.xml has the same schema as the security-role-mapping element of the sun-web.xml and sun-ejb-jar.xml files. You should have noticed that we have a realm element in addition to role mapping elements. We can use the realm element of the sun-application.xml to specify the default authentication realm for the entire application instead of specifying it for each module separately. Summary In this article series, we covered the following topics: Analyzing Java EE application security requirements Including security requirements in Java EE application design Developing secure Business layer using EJBs Developing secure Presentation layer using JSP and Servlets Configuring deployment descriptors of Java EE applications Specifying security realm for enterprise applications Developing secure application client module Configuring Application Client Container We learnt how to develop a secure Java EE application with all standard modules including Web, EJB, and application client modules.
Read more
  • 0
  • 0
  • 5734
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-metaprogramming-and-groovy-mop
Packt
31 May 2010
6 min read
Save for later

Metaprogramming and the Groovy MOP

Packt
31 May 2010
6 min read
(For more resources on Groovy DSL, see here.) In a nutshell, the term metaprogramming refers to writing code that can dynamically change its behavior at runtime. A Meta-Object Protocol (MOP) refers to the capabilities in a dynamic language that enable metaprogramming. In Groovy, the MOP consists of four distinct capabilities within the language: reflection, metaclasses, categories, and expandos. The MOP is at the core of what makes Groovy so useful for defining DSLs. The MOP is what allows us to bend the language in different ways in order to meet our needs, by changing the behavior of classes on the fly. This section will guide you through the capabilities of MOP. Reflection To use Java reflection, we first need to access the Class object for any Java object in which are interested through its getClass() method. Using the returned Class object, we can query everything from the list of methods or fields of the class to the modifiers that the class was declared with. Below, we see some of the ways that we can access a Class object in Java and the methods we can use to inspect the class at runtime. import java.lang.reflect.Field;import java.lang.reflect.Method;public class Reflection { public static void main(String[] args) { String s = new String(); Class sClazz = s.getClass(); Package _package = sClazz.getPackage(); System.out.println("Package for String class: "); System.out.println(" " + _package.getName()); Class oClazz = Object.class; System.out.println("All methods of Object class:"); Method[] methods = oClazz.getMethods(); for(int i = 0;i < methods.length;i++) System.out.println(" " + methods[i].getName()); try { Class iClazz = Class.forName("java.lang.Integer"); Field[] fields = iClazz.getDeclaredFields(); System.out.println("All fields of Integer class:"); for(int i = 0; i < fields.length;i++) System.out.println(" " + fields[i].getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } }} We can access the Class object from an instance by calling its Object.getClass() method. If we don't have an instance of the class to hand, we can get the Class object by using .class after the class name, for example, String.class. Alternatively, we can call the static Class.forName, passing to it a fully-qualified class name. Class has numerous methods, such as getPackage(), getMethods(), and getDeclaredFields() that allow us to interrogate the Class object for details about the Java class under inspection. The preceding example will output various details about String, Integer, and Double. Groovy Reflection shortcuts Groovy, as we would expect by now, provides shortcuts that let us reflect classes easily. In Groovy, we can shortcut the getClass() method as a property access .class, so we can access the class object in the same way whether we are using the class name or an instance. We can treat the .class as a String, and print it directly without calling Class.getName(), as follows: The variable greeting is declared with a dynamic type, but has the type java.lang.String after the "Hello" String is assigned to it. Classes are first class objects in Groovy so we can assign String to a variable. When we do this, the object that is assigned is of type java.lang.Class. However, it describes the String class itself, so printing will report java.lang.String. Groovy also provides shortcuts for accessing packages, methods, fields, and just about all other reflection details that we need from a class. We can access these straight off the class identifier, as follows: println "Package for String class"println " " + String.packageprintln "All methods of Object class:"Object.methods.each { println " " + it }println "All fields of Integer class:"Integer.fields.each { println " " + it } Incredibly, these six lines of code do all of the same work as the 30 lines in our Java example. If we look at the preceding code, it contains nothing that is more complicated than it needs to be. Referencing String.package to get the Java package of a class is as succinct as you can make it. As usual, String.methods and String.fields return Groovy collections, so we can apply a closure to each element with the each method. What's more, the Groovy version outputs a lot more useful detail about the package, methods, and fields. When using an instance of an object, we can use the same shortcuts through the class field of the instance. def greeting = "Hello"assert greeting.class.package == String.package Expandos An Expando is a dynamic representation of a typical Groovy bean. Expandos support typical get and set style bean access but in addition to this they will accept gets and sets to arbitrary properties. If we try to access, a non-existing property, the Expando does not mind and instead of causing an exception it will return null. If we set a non-existent property, the Expando will add that property and set the value. In order to create an Expando, we instantiate an object of class groovy.util.Expando. def customer = new Expando()assert customer.properties == [:]assert customer.id == nullassert customer.properties == [:]customer.id = 1001customer.firstName = "Fred"customer.surname = "Flintstone"customer.street = "1 Rock Road"assert customer.id == 1001assert customer.properties == [ id:1001, firstName:'Fred', surname:'Flintstone', street:'1 Rock Road']customer.properties.each { println it } The id field of customer is accessible on the Expando shown in the preceding example even when it does not exist as a property of the bean. Once a property has been set, it can be accessed by using the normal field getter: for example, customer.id. Expandos are a useful extension to normal beans where we need to be able to dump arbitrary properties into a bag and we don't want to write a custom class to do so. A neat trick with Expandos is what happens when we store a closure in a property. As we would expect, an Expando closure property is accessible in the same way as a normal property. However, because it is a closure we can apply function call syntax to it to invoke the closure. This has the effect of seeming to add a new method on the fly to the Expando. customer.prettyPrint = { println "Customer has following properties" customer.properties.each { if (it.key != 'prettyPrint') println " " + it.key + ": " + it.value }}customer.prettyPrint() Here we appear to be able to add a prettyPrint() method to the customer object, which outputs to the console: Customer has following properties surname: Flintstone street: 1 Rock Road firstName: Fred id: 1001
Read more
  • 0
  • 0
  • 5326

article-image-hands-tutorial-getting-started-amazon-simpledb
Packt
28 May 2010
5 min read
Save for later

Hands-on Tutorial for Getting Started with Amazon SimpleDB

Packt
28 May 2010
5 min read
(For more resources on SimpleDB, see here.) Creating an AWS account In order to start using SimpleDB, you will first need to sign up for an account with AWS. Visit http://aws.amazon.com/ and click on Create an AWS Account. You can sign up either by using your e-mail address for an existing Amazon account, or by creating a completely new account. You may wish to have multiple accounts to separate billing for projects. This could make it easier for you to track billing for separate accounts. After a successful signup, navigate to the main AWS page— http://aws.amazon.com/, and click on the Your Account link at any time to view your account information and make any changes to it if needed. Enabling SimpleDB service for AWS account Once you have successfully set up an AWS account, you must follow these steps to enable the SimpleDB service for your account: Log in to your AWS account. Navigate to the SimpleDB home page—http://aws.amazon.com/simpledb/. Click on the Sign Up For Amazon SimpleDB button on the right side of the page. Provide the requested credit card information and complete the signup process. You have now successfully set up your AWS account and enabled it for SimpleDB. All communication with SimpleDB or any of the Amazon web services must be through either the SOAP interface or the Query/ReST interface. The request messages sent through either of these interfaces is digitally signed by the sending user in order to ensure that the messages have not been tampered within transit, and that they really originate from the sending user. Requests that use the Query/ReST interface will use the access keys for signing the request, whereas requests to the SOAP interface will use the x.509 certificates. Your new AWS account is associated with the following items: A unique 12-digit AWS account number for identifying your account. AWS Access Credentials are used for the purpose of authenticating requests made by you through the ReST Request API to any of the web services provided by AWS. An initial set of keys is automatically generated for you by default. You can regenerate the Secret Access Key at any time if you like. Keep in mind that when you generate a new access key, all requests made using the old key will be rejected. An Access Key ID identifies you as the person making requests to a web service. A Secret Access Key is used to calculate the digital signature when you make requests to the web service. Be careful with your Secret Access Key, as it provides full access to the account, including the ability to delete all of your data. All requests made to any of the web services provided by AWS using the SOAP protocol use the X.509 security certificate for authentication. There are no default certificates generated automatically for you by AWS. You must generate the certificate by clicking on the Create a new Certificate link, then download them to your computer and make them available to the machine that will be making requests to AWS. Public and private key for the x.509 certificate. You can either upload your own x.509 certificate if you already have one, or you can just generate a new certificate and then download it to your computer. Query API and authentication There are two interfaces to SimpleDB. The SOAP interface uses the SOAP protocol for the messages, while the ReST Requests uses HTTP requests with request parameters to describe the various SimpleDB methods and operations. In this book, we will be focusing on using the ReST Requests for talking to SimpleDB, as it is a much simpler protocol and utilizes straightforward HTTP-based requests and responses for communication, and the requests are sent to SimpleDB using either a HTTP GET or POST method. The ReST Requests need to be authenticated in order to establish that they are originating from a valid SimpleDB user, and also for accounting and billing purposes. This authentication is performed using your access key identifiers. Every request to SimpleDB must contain a request signature calculated by constructing a string based on the Query API and then calculating an RFC 2104-compliant HMAC-SHA1 hash, using the Secret Access Key. The basic steps in the authentication of a request by SimpleDB are: You construct a request to SimpleDB. You use your Secret Access Key to calculate the request signature, a Keyed-Hashing for Message Authentication code (HMAC) with an SHA1 hash function. You send the request data, the request signature, timestamp, and your Access Key ID to AWS. AWS uses the Access Key ID in the request to look up the associated Secret Access Key. AWS generates a request signature from the request data using the retrieved Secret Access Key and the same algorithm you used to calculate the signature in the request. If the signature generated by AWS matches the one you sent in the request, the request is considered to be authentic. If the signatures are different, the request is discarded, and AWS returns an error response. If the timestamp is older than 15 minutes, the request is rejected. The procedure for constructing your requests is simple, but tedious and time consuming. This overview was intended to make you familiar with the entire process, but don't worry—you will not need to go through this laborious process every single time that you interact with SimpleDB. Instead, we will be leveraging one of the available libraries for communicating with SimpleDB, which encapsulates a lot of the repetitive stuff for us and makes it simple to dive straight into playing with and exploring SimpleDB!
Read more
  • 0
  • 0
  • 6003

article-image-blogs-and-forums-using-plone-3
Packt
28 May 2010
11 min read
Save for later

Blogs and Forums using Plone 3

Packt
28 May 2010
11 min read
Blogs and forums have much to offer in a school setting. They help faculty and students communicate despite large class sizes. They engage students in conversations with each other. And they provide an easy way for instructors and staff members to build their personal reputations—and, thereby, the reputation of your institution. In this article, we consider how best to build blogs and forums in Plone. Along the way, we cite education-domain examples and point out tips for keeping your site stable and your users smiling. Plone's blogging potential Though Plone wasn't conceived as a blogging platform, its role as a full-fledged content management system gives it all the functionality of a blog and more. With a few well-placed tweaks, it can present an interface that puts users of other blogging packages right at home while letting you easily maintain ties between your blogs and the rest of your site. Generally speaking, blog entries are… Prominently labeled by date and organized in reverse chronological order Tagged by subject Followed by reader comments Syndicated using RSS or other protocols Plone provides all of these, with varying degrees of polish, out of the box: News items make good blog entries, and the built-in News portlet lists the most recent few, in reverse chronological order and with publication dates prominently shown. A more comprehensive, paginated list can easily be made using collections. Categories are a basic implementation of tags. Plone's built-in commenting can work on any content type, News Items included. Every collection has its own RSS feed. Add-on products: free as in puppies In addition to Plone's built-in tools, this article will explore the capabilities of several third-party add-ons. Open-source software is often called "free as in beer" or "free as in freedom". As typical of Plone add-ons, the products we will consider are both. However, they are also "free as in puppies". Who can resist puppies? They are heart-meltingly cute and loads of fun, but it's easy to forget, when their wet little noses are in your face, that they come with responsibility. Likewise, add-ons are free to install and use, but they also bring hidden costs: Products can hold you back. If you depend on one that doesn't support a new version of Plone, you'll face a choice between the product and the Plone upgrade. This situation is most likely at major version boundaries: for example, upgrading from Plone 3.x to Plone 4. Minor upgrades, as from Plone 3.2 to 3.3, should be fairly uneventful. (This was not always true with Plone 2.x, but release numbering has since gotten a dose of sanity.) One place products often fall short is uninstallation. It takes care to craft a quality uninstallation routine; low-quality or prerelease products sometimes fail to uninstall cleanly, leaving bits of themselves scattered throughout your site. They can even prevent your site from displaying any pages at all (often due to leaving remnants in portal_actions), and you may have to repair things by hand through the ZMI or, failing that, through an afternoon of fun with the Python debugger. The moral: even trying a product can be a risk. Test installation and uninstallation on a copy of your site before committing to one, and back up your Data.fs file before installing or uninstalling on production servers. Pace of work varies widely. Reporting a bug against an actively developed product might get you a new release within the week. Hitting a bug in an abandoned one could leave you fixing it yourself or paying someone else to. (Fortunately, there are scads of Plone consultants for hire in the #plone IRC channel and on the plone-users mailing list.) In addition to the above, products that add new content types (like blog entries, for instance) bring a risk of lock-in proportional to the amount of content you create with them. If a product is abandoned by its maintainer or you decide to stop using it for some other reason, you will need to migrate its content into some other type, either by writing custom scripts or by copying and pasting. These considerations are major drivers of this article's recommendations. For each of the top three Plone blogging strategies, we'll outline its capabilities, tick off its pros and cons, and estimate how high-maintenance a puppy it will be. Remember, even though puppies can be some work, a well-chosen and well-trained one becomes a best friend for life. News Items: blogging for the hurried or risk-averse Using news items as blog entries is, in true Extreme Programming style, "the simplest thing that could possibly work". Nonetheless, it's a surprisingly flexible practice and will disappoint only if you need features like pings, trackbacks, and remote editor integration. Here is an example front page of a Plone blog built using only news items, collections, and the built-in portlets: Structure of a news-item blog A blog in Plone can be as simple as a folder full of News Items, further organized into subfolders if necessary. Add a collection showing the most recent News Items to the top-level folder, and set it as its default page. As illustrated below, use an Item Type criterion for the collection to pull in the News Items, and use a Location criterion to exclude those created outside the blog folder: To provide pagination—recommended once the length of listings starts to noticeably impact download or render timetime—use the Limit Search Results option on the collection. One inconsistency is that only the Summary and Tabular Views on collections support pagination; Standard View (which shows the same information) does not. This means that Summary View, which sports a Read more link and is a bit more familiar to most blog users, is typically a good choice. Go easy on the pagination More items displayed per page is better. User tests on prototypes of gap.com's online store have suggested that, at least when selling shirts, more get sold when all are on one big page. Perhaps it's because users are faced with a louder mental "Continue or leave?" when they reach the end of a page. Regardless, it's something to consider when setting page size using a collection's Number of Items setting; you may want to try several different numbers and see how it affects the frequency with which your listing pages show up as "exit pages" in a web analytics package like AWStats. As a starting point, 50 is a sane choice, assuming your listings show only the title and description of each entry (as the built-in views do). The ideal number will be a trade-off between tempting visitors to leave with page breaks and keeping load and render times tolerable.   Finally, make sure to sort the entries by publication date. Set this up on the front-page collection's Criteria tab by selecting Effective Date and reversing the display order: As with all solutions in this article, a blog built on raw News Items can easily handle either single- or multi-author scenarios; just assign rights appropriately on the Sharing tab of the blog folder. News Item pros and cons Unadorned News Items are a great way to get started fast and confer practically zero upgrade risk, since they are maintained as part of Plone itself. However, be aware of these pointy edges you might bang into when using them as blog entries: With the built-in views, logged-out users can't see the authors or the publication dates of entries. Even logged-in users see only the modification dates unless they go digging through the workflow history. Categories applied to a News Item appear on its page, but clicking them takes you to a search for all items (both blog-related and otherwise) having that category. This could be a bug or a feature, depending on your situation. However, the ordering of the search results is unpredictable, and that is definitely unhelpful. The great thing about plain News Items is that there's a forward migration path. QuillsEnabled, which we'll explore later, can be layered atop an existing news-item-based blog with no migrations necessary and removed again if you decide to go back. Thus, a good strategy may be to start simple, with plain news items, and go after more features (and risk) as the need presents itself. Scrawl: a blog with a view One step up from plain News Items is Scrawl, a minimalist blog product that adds only two things: A custom Blog Entry type, which is actually just a copy of News Item. A purpose-built Blog view that can be applied to folders or collections, which are otherwise used just as with raw News Items. Here are both additions in action: Scrawl's Blog Entry isn't quite a verbatim copy of News Item; Scrawl makes a few tweaks: Commenting is turned on for new Blog Entries, without which authors would have to enable it manually each time. The chances of that happening are slim, since it's buried on the Edit → Settings tab, and users seldom stray from the default tab when editing. Blog Entry's default view is a slightly modified version of News Item's: it shows the author's name and the posting date even to unauthenticated users—and in a friendly "Posted by Fred Finster" format. It also adds a Permalink link, lest you forfeit crosslinks from users who know no other way of finding an entry's address. Calm your ringing phone by cloning types Using a custom content type for blog entries—even if it's just a copy of an existing one—has considerable advantages. For one, you can match contributors' vocabulary: assuming contributors think of part of your site as a blog (which they probably will if the word "blog" appears anywhere onscreen), they won't find it obvious to add "news items" there. Adding a "blog entry," on the other hand, lines up naturally with their expectations. This little trick, combined with judicious use of the Add new… → Restrictions… feature to pare down their options, will save hours of your time in training and support calls. A second advantage of a custom type is that it shows separately in Plone's advanced search. Visitors, like contributors, will identify better with the "blog entry" nomenclature. Plus, sometimes it's just plain handy to limit searches to only blogs. This type-cloning technique isn't limited to blog entries; you can clone and rename any content type: just visit portal_types in the ZMI, copy and paste a type, rename it, and edit its Title and Description fields. One commonly cloned type is File. Many contributors, even experts in noncomputer domains, aren't familiar with the word file. Cloning it to create PDF File, Word Document, and so on can go a long way toward making them comfortable using Plone.   Pros and cons of scrawl Scrawl's biggest risk is lock-in: since it uses its own Blog Entry content type to store your entries, uninstalling it leaves them inaccessible. However, because the Blog Entry type is really just the News Item type, a migration script is easy to write: # Turn all Blog Entries in a Plone site into News Items. # # Run by adding a "Script (Python)" in the ZMI (it doesn't matter where) and pasting this in. from Products.CMFCore.utils import getToolByName portal_catalog = getToolByName(context, 'portal_catalog') for brain in portal_catalog(portal_type='Blog Entry'): blog_entry = brain.getObject() # Get the actual blog entry from # the catalog entry. blog_entry.portal_type = 'News Item' # Update the catalog so searches see the new info: blog_entry.reindexObject() The reverse is also true: if you begin by using raw News Items and decide to switch to Scrawl, you'll need the reverse of the above script—just swap 'News Item' and 'Blog Entry'. If you have news items that shouldn't be converted to blog entries, your catalog query will have to be more specific, perhaps adding a path keyword argument, as in portal_catalog(portal_type='News Item', path='/my-plonesite/ blog-folder'). Aside from that, Scrawl is pretty risk-free. Its simplicity makes it unlikely to accumulate showstopping bugs or to break in future versions of Plone, and, if it does, you can always migrate back to news items or, if you have some programming skill, maintain it yourself—it's only 1,000 lines of code.
Read more
  • 0
  • 0
  • 30256

article-image-individual-learning-plan-ilp-moodle-19
Packt
28 May 2010
10 min read
Save for later

Individual Learning Plan (ILP) with Moodle 1.9

Packt
28 May 2010
10 min read
(For more resources on Moodle 1.9, see here.) The ILP module, once installed and activated, allows you to set some quite detailed targets within courses and to fine tune reports to and about students in order to better motivate them in their learning. This type of power means that there are quite a few options associated with the module and you will need to use the ones that are best suited to your needs. There is also the capability to tie the system in with your institution's own Student Information System (SIS) or Management Information System (MIS)) through a database abstraction layer. If you require this level of integration, you will need to discuss this with your network team or the company that provides your Moodle hosting service. In the UK, at least you can discuss this functionality with a Moodle partner that specializes in system integration with MIS. You can find out more about this at http://moodle.com/integration/. The installation process will install two modules: targets and reports, as well as a number of ILP related blocks for your courses such as Personal Learning Plan and Student Information. The modules and blocks that are installed as part of this package have a number of related settings associated with them, which will need to be adjusted at the site administration level. If you are the site administrator, you can do this; if not, you will need to ask the site admin to make the necessary changes. Module settings: Targets and Reports The basic settings required are to be able to set targets and view reports, though there are numerous levels and complexities to this activity. Again, you will need to adjust these as required. The settings are in the site administration panel. You will see two new icons for the ILP modules, as shown in the following screenshot, namely, Report and Target: Each of these new modules has a corresponding settings link. Report options The settings for the report allow you to determine what reports are visible to staff and students, as well as what can be shared between students. Set the visibility and information as required by your particular course or institution. The first block of settings relate to how the reports are viewed and whether or not students are made aware of any interactions on the part of tutors, as shown in the following screenshot: In this case, we are choosing to be able to see the status of each individual student and to send them messages when comments or concerns are posted. However, we have chosen not to show reports just within a course, as we are likely to teach students across the faculty. Therefore, it is more useful to get an overview of how they are working. The concerns we might highlight could be that a student has been missing key practical classes or has not attended their work placement. The second block of settings determines what types of reports you would like to see. It may be that you are only responsible for a certain aspect of a student's learning, in which case you may not enable all of the reporting functions. In this case, we are choosing to see all reports, as shown in the following screenshot. This may be the case if you are a personal tutor for some students and wish to get a detailed overview of their progress and activities, as well as be able to talk to them about any concerns raised by other staff. For example, a student to whom you are a personal tutor might express an interest in Product Design and therefore you might consult with colleagues in this subject area to set key targets for the student to achieve. These targets and achievements can be discussed with the students or with the students and their parents, to make sure that they are working towards their desired goals in technology. We can now save these settings in order to use all of these features on courses that we teach. Target options The settings for the Target module are similar—again the default for course-specific targets is disabled, which makes it easier to see student information across subjects. The main settings here, as shown in the following screenshot, relate to how messages are relayed to students about their targets. For example, there may be a modification to an exam board specification that makes a student's established target not such a high priority. If you are teaching students at a distance and do not see them regularly, then this would be a useful way to notify them of the changes. ILP blocks: Personal Learning Plan (PLP) The block element of ILP has several more settings that allow some customization of the block once initiated on your course page. It is shown under the add blocks menu as the Personal Learning Plan (PLP), showing that it is something that students have more ownership of as they can add targets and concerns themselves. Main options The default settings would be "No", but in this case, we would like the students to be able to see a complete range of information in relation to themselves and their courses in design technology. If the user guide link is set to 1, then it will show a link to the online guide for the module. This might be something to set up once everyone is comfortable with the use of the ILP. Student information block The final settings on the blocks page are for Student Info. The settings here allow you to customize messages and instructions for students in relation to the information they put in the PLP, such as information about themselves that only they or their teacher can see, or shared information that all other students will be able to see. The student can then use this space to fill in information about themselves, which will tie in with their targets and concerns and give a full picture of them for staff and even potential employers. The student's view of this becomes available through the course, though it will also link in through their profile. We will look at this in detail now. The following screenshot shows the student's view of the above settings when initiated: Once these settings under modules and blocks have been saved, staff can now create targets and modify reports, and students can get an overview of their work and learning, as we will see now. Creating targets The first task is to add some targets to your course for your students. The block will link to the area that displays the students so that you can see the targets, but the targets are added as activities. Switch on the edit function and choose a target for a section of your course where it is appropriate. This will be under the activities drop-down menu. The target requires a basic name and a summary of what it is for, as with all other activities. Once it is set, you can then make more specific targets for each student in the group by clicking on the target link from the front of the course. The following screenshot shows the target named Research Skills that we have created: Clicking on this link will open up a menu for all of your students. For each student, there is a link for targets and here you can add or modify targets for the students. Here you can see that a target has been set with a deadline of one month after it is set. You can add comments as it progresses, and the drop-down menu allows you to modify it so that it is either achieved (in which case when, or withdrawn as not achievable). The targets themselves can be general targets that need to be achieved across the range of the student's learning, or they can be tied specifically to a course by checking the Course related option checkbox, as shown in the following screenshot: You can also see that we have the option to tie it to courses that the student is taking. If you are a personal tutor, you can work across the subject range and apply a number of targets. All of these can have a specified deadline. You now need to allow students to see their plans. Accessing personal plans As a teacher, you need to switch on editing for your course. This makes the block visible on the bottom-right margin of your course (assuming that is where you added the block). Choose the Personal Learning Plan block. This will then be added to your course and can be moved to where it is most suited to your layout. The preceding screenshot is the view that you will see as a teacher and will allow you to see and comment on a student's targets and reports as needed, as well as export those reports. The students will have a more restricted view, as shown in the following screenshot: When students will click on the link My PLP, it will open the interface showing them their personal settings as well as any targets, concerns, or reports related to them. The more settings you have enabled on the admin section, the more they will see, so it is down to decide what information they can access. In this case, the student will be able to add some details about themselves for you and their class, but also see how they are faring in terms of targets. This can be used for tutorial sessions so that they can work on improving areas of perceived strengths or weaknesses. In terms of the targets that are set, they can interact with staff through comments so that a clear dialog can be established and hopefully issues can be picked up on as soon as possible. Once you hav e added various targets and worked with students through their concerns and those of other staff, you can then pull it all together through a report. The report can then be used to show their skills and aptitudes in their individual design areas and may show that they have a preference and an aptitude in one area such as resistant materials but not in food. This information can be used to provide clearer information for the students in the courses you design and the examples you use. Summary This article introduced you to a Personal Learning module which allows you and your students to set and evaluate targets and personal goals. This module will help your students reflect on their work and allow you to better guide them in their ideas and practices. Further resources on this subject: Moodle 1.9 Teaching Techniques [book] Moodle 1.9 Math [book] Moodle 1.9: Exploring Design Portfolios [article] Testing Students' Knowledge using Moodle Modules [article] Managing Student Work using Moodle: Part 1 [article] Managing Student Work using Moodle: Part 2 [article] Managing Student Work using Moodle: Part 3 [article]
Read more
  • 0
  • 0
  • 1929
article-image-3rd-international-soa-symposium
Packt
28 May 2010
2 min read
Save for later

3rd International SOA Symposium

Packt
28 May 2010
2 min read
With 80 Speaking sessions across 16 tracks, the International SOA and Cloud Symposium will feature the top experts from around the world. The conference will take place on October 5-6, 2010. There will also be a series of SOACP post-conference certification workshops running from October  7-13, 2010, including (for the first time in Europe) the Certified Cloud Computing Specialist Workshop.   The Agenda for 2010 is now online and contains internationally recognized speakers from organizations such as Microsoft, HP, IBM, Oracle, SAP, Amazon, Red Hat, Vordel, Layer7, TIBCO, Logica, SOA Systems, US Department of Defense, and CGI. International experts including Thomas Erl, Dirk Krafzig, Stefan Tilkov, Mark Little, Brian Loesgen, John deVadoss, Nicolai Josuttis, Tony Shan, Toufic Boubez, Paul C. Brown, Clemens Utschig, Satadru Roy, David Chou and many more will provide new and exclusive coverage of the latest SOA and Cloud Computing topics and innovations. Themes and Topics Exploring Modern Service Technologies and Practices Scaling Your Business Into the Cloud •    Service Governance & Scalability •    Service Architecture & Service Engineering Innovation•    SOA Case Studies & Strategic Planning•    REST Service Design & RESTful SOA•    Service Security & Policies•    Semantic Services & Patterns•    Service Modelling & BPM •    The Latest Cloud Computing Technology •    Building and Working with Cloud-Based Services •    Cloud Computing Business Strategies •    Case Studies & Business Models •    Understanding SOA & Cloud Computing •    Cloud-based Infrastructure & Products •    Semantic Web and the Cloud For further information, see http://soasymposium.com/agenda2010.php. Aside from the opportunity to network with 500 practitioners and 80 experts, the Symposium will feature the exclusive Pattern Review Committee, multiple book launches and galleys. Following the success of previous years’ International SOA Symposia in Amsterdam and Rotterdam, this edition will be held in Berlin. Every SOA Symposium and Cloud Symposium event is dedicated to providing valuable contents specifically for IT practitioners. Register by August 31st, and receive an early bird discount.So get a 10 % discount and pay only €981 excl. VAT for two Conference Days. Register now at www.soasymposium.com or www.cloudsymposium.com
Read more
  • 0
  • 0
  • 1466

article-image-installing-and-configuring-joomla-local-and-remote-servers
Packt
27 May 2010
8 min read
Save for later

Installing and Configuring Joomla! on Local and Remote Servers

Packt
27 May 2010
8 min read
Like every other endeavor in life, there are two ways of installing Joomla!—the easy way and the difficult way. In order to do it the difficult way, you will need to set up your server by yourself before you proceed with the installation. You have the choice of environment to use for your new installation: you may install directly to a live server or you can set up a test environment on your local computer. Minimum system requirements A fully-operational web server (preferably Apache) is required to successfully install and use Joomla!. You also need a database (preferably MySQL) and the server-side scripting language PHP, together with specific modules for MySQL, XML, and Zlib functionality, which are activated within PHP amongst others. Following are the minimum versions of these server components that are required: Software Minimum requirement Recommended Latest options Website PHP 4.3.10 4.4.7 5.x.series http://php.net MySQL 3.23.x or above   5.x series http://dev.mysql.com/downloads/mysql/5.0.html Apache 1.3 or above   2.2 series http://httpd.apache.org Installation on a local computer There are a number of ways to set up a test environment on your own local computer. Most time-pressed developers will install and configure directly onto a live server, but there are good reasons for running your application first on a local development server: Developing your application locally allows you to work on it even if you are not connected to the Internet. The experience that you gain from getting your local server running on a simple installation like WampServer for a machine running Windows, or MAMP for a Mac, will make it easier for you to understand server processes and databases. This knowledge will certainly pay off as you get deeper into Joomla!. The Web is constantly scanned and archived by various search engines, and so will everything that you put on the Web. This information will be around for quite a bit of time and you certainly don't want Google to display your inevitable learning mistakes for the world to see. Installation on WampServer WampServer2 enables you to run Apache, MySQL, and PHP on Windows, and is available for free. You can download it from http://www.wampserver.com. The WampServer2 package comes with the following components already configured to work together: Apache 2.2.11 MySQL 5.1.30 PHP 5.2.8 There are similar packages that already include Joomla! (such as DeveloperSide and WDE). However, note that these may not always have the latest secure version of Joomla!. Therefore, it is better to use WampServer2 and load it with the Joomla! version of your choice. WampServer2 is self-installing. Just double-click on the icon after you've unpacked your zipped download and follow the installation instructions. This gets your development environment ready in just a few minutes. Now let the fun begin! Installing Joomla! 1.5 on localhost Installing Joomla! on localhost can be remarkably straightforward: Download the latest stable release of Joomla!, and unzip the discernible Joomla! 1.5 folder. You will need to use a tool such as WinZip for Windows (http://www.winzip.com) to perform this task. Another free alternative to WinZip is IZArc (http://www.izarc.org/). Locate the directory in which WampServer2 is installed on your computer. This will usually be the root of your computer's main directory (usually C:) and in a folder named wamp. Open it, locate the www folder, and copy your Joomla! 1.5 folder into it. Name the Joomla! folder as per your preference. In the unlikely scenario that you will be installing only one Joomla! test site on your local machine, you may—just for the sake of living to a ripe old age—name it Joomla. Navigate to your computer desktop taskbar tray, click on the WampServer icon, and select the Start All Services option (if this has not yet been selected). Then open your browser and navigate to http://localhost. This will display the main WampServer2 interface and you will see your project, Joomla, listed under Your Projects. However, because Joomla! needs a database to run, you must create the database for our project. Click on the phpMyAdmin link. This will display another interface, this time for phpMyAdmin. Enter the name of your new database in the Create new database field. For the simple reason that we shouldn't live a complicated life, we have given this database the same name (Joomla) as our project and our installation folder. We are now ready to install Joomla!. Joomla! has an automated installation script that automatically populates database tables. The installation script will set the base URL, connect Joomla! to the database, and create tables in the database. Navigate to http://localhost/Joomla and start your installation. You will be presented with a step-by-step guide to the installation in the later pages. Page 1: Choose Language This page asks what language you want to use for the installation. We select English as the language of choice. Click on the Next button to continue with your installation. Page 2: Pre-installation Check Checks are made by the installation script on server configuration. If any of these items are not supported (marked as No), then your system does not meet the minimum requirements for the installation of Joomla!, and you should take the appropriate actions in order to correct the errors. Failing to do so could lead to your Joomla! installation not functioning properly. You are not likely to face this problem on your local installation, and if you do, it can be quickly fixed. Page 3: License The License page is just a page of legalese that the developers of Joomla! really think you must read. It tells you the conditions for use of the free software and also spells out liabilities. Primarily, if the Joomla! installation makes your computer to explode or you start acting funny after you are done with the installation, the suppliers of Joomla! will accept no liability. After correcting any host-specific errors and reading the license, you will be directed to the Database Configuration page. Page 4: Database Configuration On the Database Configuration page, you specify the database where Joomla! will store and retrieve data. Select the type of database from the drop-down list. This will generally be mysql. Also, enter the hostname of the database server that Joomla! will be installed on. This may not necessarily be the same as your web server, so check with your hosting provider if you are not sure. In the present case, it will be localhost. Now enter the MySQL username, password, and database name that you wish to use with Joomla!. These must already exist for the database that you are going to use. We have already determined this when we created the data base. Here are the values for our present project: Host Name: localhost Username: root (unless you have changed it) Password: Leave blank (unless you added a password when you set up your database) Database Name: Joomla (or whatever you have called yours) Table Prefix: If you are installing more than one instance of Joomla! in a single database, then give one of them a prefix (such as jos2_), or else the second instance will not install. Otherwise, you may safely ignore this. Click on the Next button to continue. Page 5: FTP Configuration You can safely omit this step and go on to the next page. But if you do decide to carry out this step, do take notice of the following requirements: As explained on this Joomla! installation page, due to file system permission restrictions on Linux and other Unix systems (and PHP Safe Mode restrictions), an FTP layer is used to handle fi le system manipulation and to enable Joomla! installers. You may enter an FTP username and password with access to the Joomla! root directory. This will be the FTP account that handles all of the file system operations when Joomla! requires FTP access to complete a task. However, for security reasons, if the option is available, you are advised to create a separate FTP user account with access to the Joomla! installation only and not to the entire web server. Page 6: Main Configuration This is where you define your site's public identity. The descriptions of the fields are as follows: Site Name: Enter the name of your Joomla! site. Your E-mail: This will be the e-mail address of the website Super Administrator. Admin Password: Enter a new password and then confirm it, in the appropriate fields. Along with the username admin, this will be the password that you will use to login to the Administrator Control Panel at the end of the installation. Install Sample Data: It is strongly recommended that new Joomla! users install the default sample data. To do this, select this option and click on the button, before proceeding to the next stage. Page 7: Finish That's all! Your installation success screen will be displayed. Congratulations, you are now on your way to becoming a Joomla! Guru. Once the installation script has successfully been completed and you have removed the installation folder, you will be directed to the Joomla! Administration login page—if you want to immediately perform administrative functions on your new site. Otherwise, clicking on the Site icon will direct you to the front page of your site showing all of the sample data—if you have loaded it. That is the most of what you need to know about installing Joomla!.
Read more
  • 0
  • 0
  • 5294

article-image-opening-openid-spring-security
Packt
27 May 2010
7 min read
Save for later

Opening up to OpenID with Spring Security

Packt
27 May 2010
7 min read
(For more resources on Spring, see here.) The promising world of OpenID The promise of OpenID as a technology is to allow users on the web to centralize their personal data and information with a trusted provider, and then use the trusted provider as a delegate to establish trustworthiness with other sites with whom the user wants to interact. In concept, this type of login through a trusted third party has been in existence for a long time, in many different forms (Microsoft Passport, for example, became one of the more notable central login services on the web for some time). OpenID's distinct advantage is that the OpenID Provider needs to implement only the public OpenID protocol to be compatible with any site seeking to integrate login with OpenID. The OpenID specification itself is an open specification, which leads to the fact that there is currently a diverse population of public providers up and running the same protocol. This is an excellent recipe for healthy competition and it is good for consumer choice. The following diagram illustrates the high-level relationship between a site integrating OpenID during the login process and OpenID providers. We can see that the user presents his credentials in the form of a unique named identifier, typically a Uniform Resource Identifier (URI), which is assigned to the user by their OpenID provider, and is used to uniquely identify both the user and the OpenID provider. This is commonly done by either prepending a subdomain to the URI of the OpenID provider (for example, https://jamesgosling.myopenid.com/), or appending a unique identifier to the URI of the OpenID provider URI (for example, https://me.yahoo.com/jamesgosling). We can visually see from the presented URI that both methods clearly identify both the OpenID provider(via domain name) and the unique user identifier. Don't trust OpenID unequivocally! You can see here a fundamental assumption that can fool users of the system. It is possible for us to sign up for an OpenID, which would make it appear as though we were James Gosling, even though we obviously are not. Do not make the false assumption that just because a user has a convincing-sounding OpenID (or OpenID delegate provider) they are the authentic person, without requiring additional forms of identification. Thinking about it another way, if someone came to your door just claiming he was James Gosling, would you let him in without verifying his ID? The OpenID-enabled application then redirects the user to the OpenID provider, at which the user presents his credentials to the provider, which is then responsible for making an access decision. Once the access decision has been made by the provider, the provider redirects the user to the originating site, which is now assured of the user's authenticity. OpenID is much easier to understand once you have tried it. Let's add OpenID to the JBCP Pets login screen now! Signing up for an OpenID In order to get the full value of exercises in this section (and to be able to test login), you'll need your own OpenID from one of the many available providers, of which a partial listing is available at http://openid.net/get-an-openid/. Common OpenID providers with which you probably already have an account are Yahoo!, AOL, Flickr, or MySpace. Google's OpenID support is slightly different, as we'll see later in this article when we add Sign In with Google support to our login page. To get full value out of the exercises in this article, we recommend you have accounts with at least: myOpenID Google Enabling OpenID authentication with Spring Security Spring Security provides convenient wrappers around provider integrations that are actually developed outside the Spring ecosystem. In this vein, the openid4java project ( http://code.google.com/p/openid4java/) provides the underlying OpenID provider discovery and request/response negotiation for the Spring Security OpenID functionality. Writing an OpenID login form It's typically the case that a site will present both standard (username and password) and OpenID login options on a single login page, allowing the user to select from one or the other option, as we can see in the JBCP Pets target login page. The code for the OpenID-based form is as follows: <h1>Or, Log Into Your Account with OpenID</h1> <p> Please use the form below to log into your account with OpenID. </p> <form action="j_spring_openid_security_check" method="post"> <label for="openid_identifier">Login</label>: <input id="openid_identifier" name="openid_identifier" size="20" maxlength="100" type="text"/> <img src="images/openid.png" alt="OpenID"/> <br /> <input type="submit" value="Login"/> </form> The name of the form field, openid_identifier, is not a coincidence. The OpenID specification recommends that implementing websites use this name for their OpenID login field, so that user agents (browsers) have the semantic knowledge of the function of this field. There are even browser plug-ins such as Verisign's OpenID SeatBelt ( https://pip.verisignlabs.com/seatbelt.do), which take advantage of this knowledge to pre-populate your OpenID credentials into any recognizable OpenID field on a page. You'll note that we don't offer the remember me option with OpenID login. This is due to the fact that the redirection to and from the vendor causes the remember me checkbox value to be lost, such that when the user's successfully authenticated, they no longer have the remember me option indicated. This is unfortunate, but ultimately increases the security of OpenID as a login mechanism for our site, as OpenID forces the user to establish a trust relationship through the provider with each and every login. Configuring OpenID support in Spring Security Turning on basic OpenID support, via the inclusion of a servlet filter and authentication provider, is as simple as adding a directive to our <http> configuration element in dogstore-security.xml as follows:/   <http auto-config="true" ...> <!-- Omitting content... --> <openid-login/> </http> After adding this configuration element and restarting the application, you will be able to use the OpenID login form to present an OpenID and navigate through the OpenID authentication process. When you are returned to JBCP Pets, however, you will be denied access. This is because your credentials won’t have any roles assigned to them. We’ll take care of this next. Adding OpenID users As we do not yet have OpenID-enabled new user registration, we'll need to manually insert the user account (that we'll be testing) into the database, by adding them to test-users-groups-data.sql in our database bootstrap code. We recommend that you use myOpenID for this step (notably, you will have trouble with Yahoo!, for reasons we'll explain in a moment). If we assume that our OpenID is https://jamesgosling.myopenid.com/, then the SQL that we'd insert in this file is as follows: insert into users(username, password, enabled, salt) values ('https:// jamesgosling.myopenid.com/','unused',true,CAST(RAND()*1000000000 AS varchar)); insert into group_members(group_id, username) select id,'https:// jamesgosling.myopenid.com/' from groups where group_ name='Administrators'; You'll note that this is similar to the other data that we inserted for our traditional username-and password-based admin account, with the exception that we have the value unused for the password. We do this, of course, because OpenID-based login doesn't require that our site should store a password on behalf of the user! The observant reader will note, however, that this does not allow a user to create an arbitrary username and password, and associate it with an OpenID—we describe this process briefly later in this article, and you are welcome to explore how to do this as an advanced application of this technology. At this point, you should be able to complete a full login using OpenID. The sequence of redirects is illustrated with arrows in the following screenshot: We've now OpenID-enabled JBCP Pets login! Feel free to test using several OpenID providers. You'll notice that, although the overall functionality is the same, the experience that the provider offers when reviewing and accepting the OpenID request differs greatly from provider to provider.
Read more
  • 0
  • 2
  • 43643
article-image-moodle-19-exploring-design-portfolios
Packt
27 May 2010
9 min read
Save for later

Moodle 1.9: Exploring Design Portfolios

Packt
27 May 2010
9 min read
(For more resources on Moodle 1.9, see here.) Exploring the Exabis portfolio The Exabis portfolio is a third-party add-on that can be placed in your courses to allow students to store and organize their work and allow them to share it with others, for example, external verifiers. The code can be downloaded from the Modules and plugins section at the Moodle website (http://moodle.org/mod/data/view.php?d=13&rid=1142&filter=1). Once the code has been installed, the site administrator will need to check the settings of the block for all users. Site-wide settings The first job, for an administrator, is to make sure the settings meet the institution's needs. These settings are available on the administration panel. You may need your site administrator to adjust these for you if you do not have these permissions. The following screenshot shows the two options available: The settings will be determined by what version you have installed on your system, and in this case, the options relate to how the portfolio looks. The key feature of recent portfolios is the ability to create views that are customized web pages. Most students will be familiar with this activity through social networking sites. Installing the Exabis block into a course To use the Exabis block, you first need to enable editing within the course you are responsible for. To do this, you need to click on the Turn editing on button, as shown in the following screenshot: This will change the view of your course, and a block will now be visible on the right-hand column to add further blocks to your course. The Add button, as shown in the previous screenshot, is a drop-down list and will list all available blocks in alphabetical order. You need to scroll down until you find the Exabis E-Portfolio listing and then click to add this block. Once the block has been added to your course area, you can make some more localized adjustments. In the staff view, there are three options. However, the two lower options merely point to different tabs on the same menu as the MyPortfolio link. Once you open the portfolio, you can see the layout of the block and the functions that it supports, as shown in the following screenshot: The personal information tab The first tab allows students to build up some personal information so that they have a sort of limited resume or CV. Once students click on the Information tab, they will see one button (Edit), which will open an edit window to allow them to add some notes and details. The Categories tab After students have entered some basic information about themselves, they need to organize their material. This is achieved initially by establishing some categories under which the information they gather can be structured. In this example, using the Product Design course, the student may need to create categories for each section they are working with. In the UK, for example, this would be: Materials and Components, Design and Market Influence, and Process and Manufacture. By clicking on the Categories tab, there will, as with the Information tab, be an edit button visible. Clicking on this button will open a window to create the required categories, as shown in the following screenshot: By clicking on the New button, as shown in the previous screenshot, the category will be created and you will then have the choice to add sub-categories or new categories as required. The layout of this edit window is as shown in the following screenshot: These can be further broken down into sub-categories that match the course specification. The process is the same as creating categories, and with each new category created, an additional field appears to add sub-categories, as seen in the previous screenshot. The resulting structure could look similar to the following screenshot, where each part of the specification has a corresponding category and sub-category. These categories will now be available in drop-down menus for the students to add various resources, such as files and notes, as shown in the following screenshot: In the previous screenshot, you can see that students have a drop-down box under Categories, which lists categories and sub-categories for them to link their resources too. Building up the portfolio content Students can now build up their portfolio of evidence and can share this information, if they need to, with staff, other students, or external examiners. The information is organized through the main My Portfolio tab, as shown in the following screenshot: Under this tab, there are sub-tabs that allow the students to link to websites, upload files, and also make notes about some of the material they have gathered. Each of these can now be associated with a category or sub-category to give some clear definition to their research work. The following screenshot shows a student adding some files to a sub-category related to design: In the previous screenshot, students could attach a file which may be some notes they made on a factory visit that they have scanned. Gradually, they can start building up a detailed folder of information and links to other useful resources. The following screenshot shows the MyPortfolio view as a student builds up some of their reference material and notes. Each of the resources is clearly categorized and time stamped and the type of resources is easy to see. Creating views In the release under discussion here (version 3.2.3 release 168) there is a tab to create views. This is still under development and not fully functional, but may well be functional by the time you install it. Clicking on the Views tab will show a button to add a view. Clicking on the Add View button will open an edit window to allow the student to organize their views, as shown in the following screenshot: The views are quite basic at present, but will allow students to build up a portfolio of evidence in an easy and organized way. Sharing their work and thoughts If students would like to share some of their work with each other, then they can via the Views tab. This tab, on the latest version, has a link to allow sharing. Once students enable the sharing function by clicking on the Change link, they can then choose what type of sharing they require and with whom. In the case shown here, the student can elect to share his/her work externally by creating a link to his/her folder from an external or an internal link. The Internal Access option allows them to further specify who can see their portfolio. In this case, they can share it with all of the staff who teach them in the design and technology faculty, or just some of the staff. In this case, when the product design teacher logs in and checks for shared portfolios, they will see this student's work. Importing and exporting portfolios Increasingly with e-portfolios there is the need to be able to take the entire portfolio with the students to other places of study or work. With the Exabis system, there is the ability to export the student's work in a number of formats. The two formats, currently available are Shareable Content Object Reference Module (SCORM) and Extensible Markup Language (XML). Both of these are file structures used to import and export groups of files from web-based systems such as Moodle. The import facility in Exabis will import a SCORM file, which is usually in a zipped format. The options shown for Export/Import are shown in the following screenshot: In both cases shown here, the export will allow students to save their work as a ZIP file, and depending on how they have structured their portfolio, they will have a range of choices regarding what to include in the export. The following screenshot shows the options for a SCORM export. The student, as shown in the previous screenshot, has chosen to save his/her Product Development material in a SCORM file. Clicking on the Create SCORM-File button will open a download dialog window where the student can chose where on his/her computer to save the zipped file. An additional feature shown in the previous Export your portfolio screenshot is the ability to include Moodle assignments in the portfolio of evidence. This would be useful if students take the portfolio to a new job. Clicking on the Import from Moodle-Assignments link results in a screen where students can add their assignments, as shown in the following screenshot: Under the Action column shown in this screenshot, the student can click on the add this file link. Clicking this link will open the MyPortfolio:Add window and the student can link this assignment to a category. The resulting link will then appear in their MyPortfolio: Files view. The assignment itself will be a hyperlink, which will open the word-processed assignment when clicked. Opening the assignment link will create a full URL to where the assignment can be located so that external examiners or employers can also view the work. It allows additional notes to be added by the student, such as follow up comments, as shown in the following screenshot: The additional commentary shows how the student has used the portfolio to track their learning process and to reflect on their earlier work. The whole process is therefore contained in an organized structure that the student controls and can be modified as their greater understanding dictates. Future developments in Exabis As mentioned, the views in this portfolio are not yet fully developed, but the current version is very usable. In order to have more flexibility and functionality, it is necessary to install a more fully featured e-portfolio such as MyStuff, which we will investigate in the next section.
Read more
  • 0
  • 0
  • 3081

article-image-plone-3-themes
Packt
26 May 2010
9 min read
Save for later

Plone 3 Themes

Packt
26 May 2010
9 min read
(For more resources on Plone, see here.) Plone's stock configuration delivers a great deal of concrete functionality: workflow, security, tagging, and more. However, the people whom you need to win over—like your boss and the public—often form their first impressions of your site based solely on visual design. Replacing the out-of-the-box look of Plone with one tailored to your organization is thus a very important task. Changing the overall look of a Plone site requires more than just the web designer's usual toolkit of HTML and CSS. In this article, we provide an introduction to the additional Zope- and Plone-specific techniques you need. We give an overview of Plone's somewhat complicated theming situation, show how to theme a site in a portable, reusable way, and demonstrate practices that strike a balance among ease, speed, and compatibility with future versions of Plone. Theming is a complex topic, and there are entire books on that topic alone, so we also give plenty of outside references in case your needs extend beyond the basic. An overview of Plone theming Plone themes, also known as skins, are visual designs that can be applied to a site, independent of its content. There are two main ways to create a theme: through the web and via the filesystem. Through-the-web versus filesystem One of the great advantages of Zope (and thus Plone) has historically been the customization power available through its web-based interface. Though there are some holes in this functionality with Plone 3 and 4, you can, for the most part, still point and click your way to a working theme. The advantages of this approach are: Immediate feedback. Iterations are simple. As a result, you're encouraged to test often, bugs turn up early, and bugs caught early are bugs solved easily. Explorability. Though the Zope Management Interface, where most theme work takes place, isn't the best-organized or friendliest environment in the world, it at least offers some semblance of navigable structure. You can find a piece of HTML or CSS you want to customize, click a button, and begin editing. There's less need to think abstractly. Accessibility. Through-the-web theming requires no access to the server's filesystem, so it is usable by people without, for example, Unix command-line experience or the ability to restart Zope. The alternative is theming by developing add-on products, which live on the server's filesystem. The advantages of this are: Better tools. Expressing a theme as files and folders lets you use the entire ecosystem of filesystem-based development tools: proper text editors and version control systems, for example. Ease of re-use. Encapsulating a theme as a product means you can easily make use of it on more than one site, copy it from machine to machine, or share it with the world. Completeness. Some customizations can't yet be done through the Web: for example, moving the search box from the top of the page to the bottom by moving its viewlet into a different viewlet manager. In practice, a filesystem product is usually better, with through-the-web styling used to test changes and to make emergency in-production tweaks between Zope restarts. A load of languages Theming involves several special-purpose languages. Here's the rundown: Language Use in Theming HTML The old standby, Hypertext Markup Language defines the semantic structure of every page. Plone's markup sticks admirably to specifying meaning and avoids visual design. For example, its navigation bars are <ul>s, and its portlets (those omnipresent titled sidebars) are actually definition lists (<dl>s) with the title as the term and the content as the definition. Visual styling is applied almost wholly by CSS. CSS Cascading Stylesheets, another standard tool in the web designer's kit, apply a layer of visual design atop HTML. Because Plone's HTML so assiduously avoids visual design, we can change the look of a Plone site substantially without tampering with markup. TAL Most theming can be done with just CSS, but sometimes, like when adding new element to a page, only HTML changes will do. All HTML in Plone is produced by Template Attribute Language (TAL), a simple XML-based language so named because it nestles entirely within the attributes of XML tags. Like other templating languages, TAL is a more readable alternative to littering program code with bits of hard-coded markup. It is good for inserting content into a page skeleton, repeating portions of a page, and doing other simple presentation logic. More complicated logic is best done in Python modules, where you aren't limited to cramped one-liners. A good introduction to TAL is http://docs.zope.org/zope2/zope2book/ZPT.html. METAL The Macro Expansion for TAL (METAL) language helps combine bits of TAL from different templates to create a single page. http://docs.zope.org/zope2/zope2book/ZPT.html#macros is a good introduction. Python The general-purpose language Zope and Plone are written in. We will write almost no Python in this article, but it often does make an appearance in page templates. It has a much more prominent role in Zope 3-style theming than in Zope 2. ZCML Some parts of theming use the Zope 3 component architecture, a scheme for tying plugins and customizations into a large system like Plone. The Zope Component Markup Language (ZCML) is an XML-based language that specifies where to plug these in. For example, we will use ZCML to tie our theme product to a third-party package that drastically simplifies overriding some templates. GenericSetup XML A variety of XML mini-languages, which show up in your product's profiles folder. These are run by GenericSetup, Plone's installation framework, when your theme product is installed or uninstalled. Don't let theming hold you up Theming is complicated and can be time-consuming the first time through. Don't make the common mistake of letting it hold up work on the rest of your site. Indeed, most information-oriented work—audience analysis, the creation and input of content, information architecture decisions, and development of custom content types—can go on without much thought toward the coat of paint that will eventually go over it. (Likewise, you can change the look of your site later without having to redo all your navigation and content.) The few elements to decide on ahead of time are… Navigation. What is your navigation strategy? Should the theme provide space for main or contextual navigation or for a search field? It can help to have your graphic designer join you for the last few minutes of each information architecture discussion to synchronize expectations. Drawing wireframes is another fast way to get everybody on the same page. For an excellent primer on strategies for organizing your site's content, see Peter Morville's Information Architecture for the World Wide Web. CSS styles. The style menu in Plone's built-in editor is commonly customized to suit the semantic needs of the site at hand. Decide early in the design process what styles will be needed: for example, body text, warning messages, sidebars containing supplementary material, and various levels of headings. It's not necessary to settle on a look for these styles—just to enumerate them and establish their CSS class names. After that, theme and content work can progress in parallel. Prepare your development environment Before we get down the business of creating a theme, make sure you have all the tools and settings in place: Run Zope in foreground mode. When developing, always launch Zope using bin/instance fg rather than bin/instance start. At the cost of a little processor power, this greatly speeds development by… Puting Zope into debug mode. This means it will notice certain changes to the product we're developing without needing to be constantly restarted. In Plone 3.3 and above, this automatically turns on the CSS and JavaScript debug modes as well (explained below). Printing error messages, usually hidden in the event.log file, to the terminal. Plone typically makes a lot of noise when it starts up; that can be ignored. But watch for errors, hidden among the innocuous INFO and DEBUG messages, when you exercise the functionality of your product. Turn on CSS debug mode. With Plone 3.3 or above, you can skip this step, as it's implicitly done when you run Zope in foreground mode. In older versions of Plone, go into the ZMI, then to your Plone site, and finally to portal_css. There, turn on Debug/development mode. This will keep Plone from doing its clever caching, merging, and compression of stylesheets while you're developing them, helping ensure that you always see the latest version of your work. Without CSS debug mode, your CSS changes will take effect only when Zope is restarted. Get Firefox, Firebug, and the Web Developer add-on. Firefox is a nice browser, but what really makes it shine is its third-party plugins. Get the latest version, available from http://www.getfirefox.com/, then grab two vital plugins, Firebug (http://getfirebug.com/) and Web Developer (https://addons.mozilla.org/firefox/addon/60). Turn off caching. In Firefox, show the Web Developer Toolbar (View ? Toolbars ? Web Developer Toolbar), then pull down its Disable menu and select Disable Cache. Together with enabling CSS debug mode, this will ensure that you always see your latest CSS changes. Nothing is more frustrating than spending hours chasing a problem, only to track it down to a stale cache. If you use Firefox for casual browsing, you may not wish to disable caching globally and slow down your surfing. In that case, be sure to use Shift+Command+R (on the Mac) or Shift+Ctrl+R (on other platforms) to force your stylesheets to reload when doing theme work. Begin your theme On-disk theme products can be quite verbose, so we employ a program to generate the skeleton of ours. We'll then make a few clean-ups before moving on to making a visual impact. Install paster and ZopeSkel To generate the empty shell of a theme, we'll use a code generation tool called paster. A set of Zope- and Plone-specific code snippets, called ZopeSkel, extends paster to provide a sort of "madlibs for Plone", churning out skeletal products whose blanks we can fill in. Here's how to get a copy of paster up and running: Some installations of Plone come with paster and ZopeSkel; check the bin folder in your buildout. If paster is in there, you're done; skip to the next section. If not, read on. Install easy_install, a simple Python installer, which we can use to install paster and ZopeSkel. Follow the platform-specific instructions on the easy_install download page: http://pypi.python.org/ pypi/setuptools. Use easy_install to install ZopeSkel, which also automatically installs paster. For example: easy_install ZopeSkel
Read more
  • 0
  • 0
  • 2195
Modal Close icon
Modal Close icon