refcard

  • submit to reddit

Getting Started with Drupal

By Matt Vance

14,178 Downloads · Refcard 59 of 151 (see them all)

Download
FREE PDF


The Essential Drupal Cheat Sheet

Drupal is an open source content management system and framework written in PHP. Drupal is used to power many of today’s high-profile sites, such as Popular Science, Ubuntu and the Electronic Frontier Foundation. This DZone Refcard will provide useful information to help you perform three of the most common roles associated with setting up a new Drupal site: site building, theming, and development. Youll also enjoy these other related Refcardz from our DZone Refcardz library: Essential MySQL and PHP.
HTML Preview
Getting Started with Drupal

Getting Started with Drupal

By Matt Vance

about drupal

Drupal is an open source content management system and content management framework written in PHP. Drupal is used to power a variety of high-profile web sites, including sites for Popular Science (http://www.popsci.com/), Ubuntu (http://www.ubuntu.com/), and the Electronic Frontier Foundation (http://www.eff.org/).

Drupal is designed to be modular, with a number of optional modules included in the default “core” Drupal package. These modules serve to extend and enhance the capabilities of Drupal core. In addition, thousands of contributed modules are available for download from the central Drupal community website, Drupal.org.

Drupal is most often run on a LAMP server stack (an acronym for Linux, Apache, MySQL, and PHP). However, Drupal is not limited to a single architecture and can be run under Apple’s OS X or Microsoft Windows. Alternative web servers supported by Drupal include Microsoft IIS and lighttpd. In addition to MySQL, Drupal can also be run using PostgreSQL for database storage.

Hot Tip

For a more thorough PHP reference, see the PHP Refcard (http://refcardz.dzone.com/refcardz/php). Drupal also includes the open source jQuery JavaScript library to simplify the creation of dynamic behavior within a user’s browser. For help using jQuery, check out the jQuery Selectors Refcard. (http://refcardz.dzone.com/refcardz/jquery-selectors).

This Drupal Refcard will provide useful information to help you perform three of the common roles associated with setting up a new Drupal site: site building, theming, and development. This Refcard focuses on Drupal 6, the latest major release available as of this writing.

Drupal site building

Drupal can be used to create just about any type of website, from simple single-author blogs to multi-user social networking communities. Along with Drupal’s flexibility comes a steep learning curve. First time site builders can quickly become overwhelmed by the thousands of available contributed modules.

While the Drupal community strives to work together to create user friendly modules that combine together well, not all modules are created equal. Since developers can’t be expected to test their modules in combination with every other available module, there are bound to be incompatibilities. It is important, especially for first time site builders, to evaluate modules on a test site before installing them on a production site.

Not all Drupal modules are ready for prime time, but some modules have been around long enough and are useful for enough applications to warrant being on a site builder’s short list.

Hot Tip

Sign up for an account on Drupal.org. Some areas and tools on the site are only available to logged in users, plus it is an important first step toward getting involved in the “community” that develops, supports, and steers the Drupal project. Get involved on the forums; both asking and answering questions can help you get up-to-speed more quickly.

CCK

The Content Construction Kit module, also known as CCK (http://drupal.org/project/cck), allows site builders to extend beyond the default content types that are included with Drupal. Not only can the default page and story content types (sometimes called “node” types) be rearranged or customized with additional fields, but completely new content types can also be created. CCK includes several sub-modules for adding a variety of custom field types such as select boxes, check boxes, text boxes, and more. In addition, other contributed modules, such as Date (http://drupal.org/project/date), FileField (http://drupal.org/project/filefield), and ImageField

refcardzad

(http://drupal.org/project/imagefield), can be downloaded separately to add more complex fields to your custom content types.

Views

The Views module (http://drupal.org/project/views) allows site builders a great deal of control and flexibility in presenting lists of content, also called “views”, on a site. The Views module provides a graphical user interface that can output nodes, users, comments, and more. Views can be presented as pages, as RSS feeds, or “blocks” (the often small pieces of content that are typically reused on various pages in sidebars, headers, and footers). The individual items that make up a view can be customized in terms of sort order, fields displayed, and the format of the list (such as unordered lists or tables).

Views Module

The Views module interface can take some time to master, but it is worth the investment. The flexibility of Views can be useful not just to site builders but also to developers, since views can be exported and bundled with modules.

Add on modules such as the Views Bonus Pack (http://drupal.org/project/view_bonus) can extend the Views module even more to present content as CSV files, Microsoft Word DOC files, or as XML.

Hot Tip

When installing new contributed modules and themes, resist the temptation to place the files in the default /modules or /themes directories. To make future upgrades of Drupal easier, create a /sites/all/ modules and /sites/all/themes directory instead. Contributed and custom modules and themes should then be placed in their own respective subdirectories.

Administration menu

The Administration Menu module (http://drupal.org/project/admin_menu) provides administrators with a small drop-down menu at the top of every page to allow easy access to the various administration pages that must be configured when building a new Drupal site.

Pathauto

The Pathauto module (http://drupal.org/project/pathauto) extends Drupal’s core Path module by automating the process of creating more user friendly and search engine friendly URL aliases for a site’s content. Pathauto requires and works in conjunction with the Token module (http://drupal.org/project/token).

Wysiwyg API

Drupal does not include a WYSIWIG editor by default; however, a wide variety of WYSIWYG and other client-side editors can be made to work with Drupal. The WYSIWYG API module (http://drupal.org/project/wysiwyg) provides Drupal integration for a variety of add-on editors, including: TinyMCE, FCKeditor, the YUI Rich Text Editor. Other modules provide support for individual editors, but it is likely that more will opt to integrate with the WYSIWYG API module going forward, in order to avoid duplicating development effort.

Hot Tip

With thousands of contributed modules, there is inevitably overlap in the functionality provided by some modules. Rather than installing each overlapping module to compare functionality, first check the “Comparisons of contributed modules” section of the Drupal handbooks (http://drupal.org/node/266179) to see if someone else has already documented their comparison. Example comparisons include WYSIWYG modules, node access modules, and content rotator modules.

Drupal theming

Drupal provides a flexible theming layer to allow a site’s design to be highly customized. While Drupal can be used in conjunction with a variety of “theme engines” such as Smarty or PHPTAL, most users will want to become familiar with Drupal’s default theme engine format, PHPTemplate.

Depending on the needs of your site, you may choose to create a completely custom theme or use one of Drupal’s “starter themes” as the basis for a new site design. Starter themes such as Zen, Blueprint, or Framework strive to provide a basic foundation that can be customized to provide the look and feel your site requires.

To create your own custom theme from scratch, start by creating a new directory for the theme under the /sites/all/ themes directory. For example, to create a new theme called “Beautiful”, start by creating a new /sites/all/themes/beautiful directory.

Hot Tip

Drupal’s default theme, Garland, was not designed to be a “starter theme.” When looking to transform an existing theme to match a specific design, avoid using Garland. Instead, start from scratch or look to themes such as Zen, Framework, or Basic. For a detailed comparison of starter themes, see http://adaptivethemes.com/starter-themecomparison. html

.info file

Typically a theme directory contains a number of files that work together to make up the theme. At the very least, a [themename] .info file is required in order for Drupal to recognize a theme. Building on the example above, a minimal beautiful.info file might start with the following:


name = Beautiful
description = A example theme created for educational purposes.
core = 6.x
engine = phptemplate

A number of optional keys such as regions, stylesheets, and scripts can also be defined in order to override the defaults Drupal provides. More details can be found in the Drupal handbooks(http://drupal.org/node/171205).

Drupal themes typically contain a number of template files such as page.tpl.php or node.tpl.php. Each template file specifies how a particular portion of the site is to be presented. The various core modules provide default template files that can be copied into your theme directory and edited to customize them to suit the needs of a particular site.

Template files (.tpl.php)

The base template file found in most themes is the page.tpl. php file which acts as a wrapper around most of the other template files. When building a new theme, the default page. tpl.php theme file found in the /modules/system directory can provide a good starting point. You can copy that file into your theme’s directory and customize it as needed.

Hot Tip

Drupal uses a theme registry to cache information about a theme. In order for Drupal to recognize changes to a theme such as adding files or changing the .info file, it is important to clear the theme registry. To clear the theme registry, go to the Performance page (Administer > Site configuration > Performance) and click on the “Clear cached data” button.

Additional template files can be used to customize the presentation of the various smaller elements of a Drupal site such as blocks, comments, polls, and more.

Template file Purpose
page.tpl.php the main container template file, which acts as a wrapper for the other template files below; see the following page for a list of available variables within the page.tpl.php file: http://api.drupal.org/api/file/modules/system/page.tpl.php
page-front.tpl.php can be used to specify a custom front page
node.tpl.php controls how the various content types or “nodes” are displayed; see the following page for a list of available variables within the node.tpl.php file: http://api.drupal.org/api/file/modules/node/node.tpl.php/6
node-[nodetype].tpl.php optional template files used to target and customize nodes of a specific content type
block.tpl.php contains the code used to display reuseable “block” content that may appear in multiple places within a site
block-[region].tpl.php optional template files to customize how blocks in specific block “regions” will appear; regions are the areas specified in the theme’s .info file where blocks can be designated to appear (such as headers, sidebars, etc)
comment.tpl.php controls the formatting of user comments

Template files can be targeted to customize specific content of a site by naming the files according to specific “suggestions.” For example, to customize the front page of a site, create a copy of the page.tpl.php file named page-front.tpl.php and customize the new front page template as needed. See the Drupal handbooks (http://drupal.org/node/190815) for more details about the various core template files and how to use and customize the suggestion options.

Hot Tip

When creating your own theme from scratch, be sure to output the $closure variable, just before the closing tag in the page.tpl.php file. The $closure variable is easy to overlook, but it is important because it outputs some final markup, which may cause some modules to fail, if it is missing.

template.php

The template.php file is an optional file used as a container for conditional processing and overriding of theme functions. In addition to overriding theme output using the template file method outlined above, Drupal also allows theme functions (any function beginning with “theme_”) to be overridden inside the template.php file. Those more familiar with programming in PHP may prefer to use template functions to override Drupal’s defaults in order to gain more flexibility and performance. A list of Drupal’s default theme functions can be found on the Drupal API site
(http://drupal.org/api/group/themeable).

Hot Tip

For help tracking down the particular function that controls the content you want to customize, install the Devel module (http://drupal.org/project/devel) and enable the Theme developer module that comes with it. The Theme developer module provides a graphical tool that can be used to select specific portions of a page and display the theme function or template file responsible for generating it.

style.css

Drupal will automatically recognize a style.css file as a theme’s primary cascading style sheet file. Additional CSS files can be specified in the .info file using the “stylesheets” key.

screenshot.png

The screenshot.png file is a thumbnail sized image of the theme presented on Drupal’s theme administration page to provide users with a preview of how a theme will look.

Drupal development

Drupal has a reputation as being created by developers for developers. While it has made great strides recently at becoming more user friendly, Drupal still has a lot to offer developers. Drupal has been designed with flexibility in mind. Developers can customize the vast majority of Drupal’s functionality through Drupal’s system of hook functions.

Novice users should not be dissuaded from creating their own custom modules. Even a simple single-function module can be useful for things such as customizing how Drupal presents a particular piece of content or form.

Hot Tip

Resist the temptation to modify the core of Drupal. “Hacking core” is discouraged, in favor of creating modules that modify Drupal’s behavior instead. Creating modules avoids having to maintain and apply patches to Drupal as updates get released
.

To develop a new custom module, start by creating a new directory for the module under the /sites/all/modules directory. For example, to create a new module called “Functional”, start by creating a new /sites/all/modules/functional directory.

Hot Tip

Before sitting down to develop a new custom module, take the time to browse or search the contributed modules available on Drupal.org. The thousands of modules available there are typically developed to be reusable in a variety of environments. You may not find a module that does exactly what you are looking for, you may find one that can be adapted to suit your needs. If you make improvements to an existing module, consider contributing your code back in the module’s issue queue, in the form of a patch. In addition to helping others, if the patch gets accepted, it will make future upgrades of the module on your own site easier.

.info file

As with themes, each Drupal module must include at least a .info file in order to be recognized. An example functional.info file might consist of the following:


; $Id$
name = Functional module
description = “A simple example module created for educational
purposes.”
core = 6.x

See the Drupal handbooks (http://drupal.org/node/231036) for details on the other keys that can be specified in the module’s .info file.

Once the .info file has been created, a module can be enabled on the Module administration page (Site building > Modules). However, until the .module file has been created, the module won’t provide any new functionality.

.module file

The .module file typically contains the majority of the code for a module. Modules interact with the core of Drupal by implementing various hook functions that get called as Drupal carries out various tasks. Certain specific hook functions will need to be implemented depending on what functionality or customization a particular module needs to provide. A list of available hook functions can be found on the Drupal API Reference site (http://api.drupal.org/api/group/hooks).

For our example functional.module file, we will implement the hook_nodeapi function. By implementing hook_nodeapi, a module can act on the node object used as a container for the majority of content within Drupal.

To implement a particular hook function within a module, replace the word hook within the functions name with the name of the module. For example, in a module called functional, the hook_nodeapi function is implemented as functional_nodeapi:


<?php
  function functional_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
   switch ($op) {
    case ‘view’:
     $node->content[‘body’][‘#value’] .= “<br><br>Brought to you
by RefCardz”;
     break;
  }
}

Once the “functional” module is enabled, all nodes within the site will appear with a “Brought to you by RefCardz” notice at the bottom.

Hot Tip

To quickly dump variables to the screen for debugging purposes, you can take advantage of the message area typically found at the top of the page in most themes, by using the following function: drupal_set_message(‘<pre>’ . print_r($variable, TRUE) . ‘</pre>’);
If you have the Devel module enabled, you can take advantage of more cleanly formatted output by using the following instead: dpm($variable);

By implementing hook_form_alter, modules can use Drupal’s Form API to add, remove, or change forms. For example, some sites use the Views module or Panels module to customize the site’s front page, so the “Promoted to front page” publishing option may need to be removed to avoid confusion. The following code will remove the checkbox used to promote content to the front page.


function functional_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == ‘page_node_form’) {
    unset($form[‘options’][‘promote’]);
  }
}

For a more detailed introduction to the Forms API, see the “Forms API Quickstart Guide” (http://api.drupal.org/api/file/ developer/topics/forums_api.html)

Useful Hook Functions (for a complete listing of hook functions, see
http://api.drupal.org/api/group/hooks/)
Description
hook_block
http://api.drupal.org/api/function/hook_block/
Declare a block or set of blocks
hook_cron
http://api.drupal.org/api/function/hook_cron/
Perform periodic actions
hook_db_rewrite_sql
http://api.drupal.org/api/function/hook_db_rewrite_sql/
Rewrite database queries, usually for access control
hook_enable
http://api.drupal.org/api/function/hook_enable/
Perform necessary actions after module is enabled
hook_form_alter
http://api.drupal.org/api/function/hook_form_alter/
Perform alterations before a form is rendered
hook_mail_alter
http://api.drupal.org/api/function/hook_mail_alter/
Alter any aspect of the emails sent by Drupal
hook_mail
http://api.drupal.org/api/function/hook_mail/
Prepare an email message based on parameters
hook_menu
http://api.drupal.org/api/function/hook_menu/
Define menu items and page callbacks
hook_perm
http://api.drupal.org/api/function/hook_perm/
Define user permissions
hook_user
http://api.drupal.org/api/function/hook_user/
Act on user account actions
hook_watchdog
http://api.drupal.org/api/function/hook_watchdog/
Log an event message

.install file

Another file commonly found in Drupal modules is the .install file. The .install file is used to store code that is run when a module is installed or uninstalled, such as the hook_schema and hook_install functions.

Common .install File Functions Description
hook_install
http://api.drupal.org/api/function/hook_install/
Install the current version of the database schema, and any other setup tasks.
hook_schema
http://api.drupal.org/api/function/hook_schema/
Define the current version of the atabase schema.
hook_uninstall
http://api.drupal.org/api/function/hook_uninstall
Remove any tables or variables that the module sets.

Modules for developers

Modules for Developers

Several of the contributed modules for Drupal provide tools useful to module developers.

Deadwood

As new versions of Drupal get released, it can take a while for existing modules to get upgraded. The Deadwood module (http://drupal.org/project/deadwood) helps speed up the process of upgrading Drupal modules by automating some of the code updates.

Devel module

The Devel module (http://drupal.org/project/devel) provides tools for clearing Drupal’s cache, for generating dummy content, for debugging access issues, for performance logging, and much more.

Devel Mode

The Devel module also includes an open source debugging tool called Krumo that can display a structured representation of any PHP variable. Devel adds “Dev load” and “Dev render” tabs to nodes which output the Node object through Krumo. With Devel enabled, you can output your own variables through Krumo using Devel’s print message function, dpm().

Coder module

Since the Deadwood module doesn’t completely automate the process of upgrading modules from one version of Drupal to the next, there is usually some manual coding to be performed after running Deadwood. That is where the Coder module (http://drupal.org/project/coder) comes in handy. The Coder module does not modify code, but it provides an automated code review that can pinpoint areas of code that need to be updated.

Coder Module

The Coder module can also help enforce coding standards by pinpointing sloppy coding and suggesting ways to clean it up. The Coder module can be especially helpful to run before contributing code back to the community at Drupal.org. Schema

The Schema module (http://drupal.org/project/schema)

provides tools for working with Drupal’s database Schema API. If you’ve already manually created the tables required by a module, the schema module can provide the corresponding schema data structure to be added to your module’s .install file, making it easier to replicate the same tables on another Drupal installation.

Cache Disable

Drupal’s caching system can be a source of confusion and productivity loss, if you are not careful. Rather than having to remember each of the various tasks that require the cache to be flushed, install and enable the Cache Disable module (http://drupal.org/project/cache_disable) when doing development on a new site. Just remember to turn the module off, once you have completed your development work.

API

The API module (http://drupal.org/project/api) is used to generate the hyperlinked documentation found at api.drupal. org. The same module can be used to provide a local version of Drupal’s API documentation. In addition to providing documentation on Drupal’s core modules, the API module can also generate documentation pages for installed modules that follow Drupal’s coding standards. If you prefer not to set up your own API site, you can still browse the documentation for many of the contributed modules, courtesy of Drupal consulting company Lullabot (http://api.lullabot.com/)

Other API Modules

Though Drupal does provide a full-fledged development framework, it doesn’t include everything one might need for every possible coding task. Thankfully, the repository of contibuted modules on drupal.org includes quite a few API modules. Many of the API modules provide no functionality on their own, but provide API code that other modules and module developers can build on. Example API modules include the Voting API (http://drupal.org/project/feedapi), Chart API (http://drupal.org/project/chart), and the Import/ Export API (http://drupal.org/project/importexportapi).

Resources

URL Reference
http://api.drupal.org/ Documentation of Drupal’s API
http://drupal.org/handbooks The Drupal community maintains several handbooks including documentation for beginners, themers, and developers
http://drupalcodesearch.com/ Drupal Code Search allows users to search much of Drupal’s contributed code, though the index may not reflect the latest up-to-the-minute changes
http://cvs.drupal.org/ A web interface to browse the code in the Drupal.org CVS repository, from the start of the project to the latest in contributed modules
http://drupalmodules.com/ Drupal Modules allows users to rate modules. Ratings can be handy when choosing modules to use on a site
http://drupal.org/planet Drupal Planet aggregates a number of blogs that post regularly about Drupal
http://groups.drupal.org/ Groups.Drupal is a gathering place for niche groups within the Drupal community. Try searching for a user group near you or a group focused on your specific area of interest
http://drupal.org/irc Learn how to connect to Drupals IRC channels and connect with a world-wide community of developers at all hours of the day
http://drupal.org/mailing-list Drupal.org provides a number of mailing lists to keep the community up-to-date. Anyone running a public Drupal site should subscribe to the security announcements mailing list
http://association.drupal.org/ The Drupal Association is a not-for-profit association charged with providing support to the Drupal project
http://drupal.org/getting-involved The Drupal project thrives largely due to a strong community of contributors. Read the “Getting Involved” handbook to learn how you too can contribute
http://ww.lullabot.com/podcast Several Drupal podcasts exist, both in audio and video formats, but the Lullabot podcasts are longest-running and arguably the most in-depth

About The Author

Photo of Matt Vance

Matt Vance

is a Web developer, technology consultant, and freelance writer living in Austin, Texas. He has written for Macworld magazine and Lifehacker.com. He can be contacted through his website, http://minezone.org/

Recommended Book

Drupal

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

JavaServer Faces 2.0

By Cay Horstmann

28,368 Downloads · Refcard 58 of 151 (see them all)

Download
FREE PDF


The Essential JavaServer Faces 2.0 Cheat Sheet

JavaServer Faces (JSF) is the “official” component-based view technology in the Java EE web tier. This JSF 2.0 DZone Refcard is perfect for both new and seasoned JSF developers. JSF 2.0, the long-awaited successor to JSF 1.x, brings exciting new features: less boilerplate code, better error handling, built-in Ajax, and more. This Refcard also provides updated summaries of the tags and attributes needed for JSF programming, along with a summary of the JSF expression language and a list of code snippets for common operations.
HTML Preview
JavaServer Faces 2.0

JavaServer Faces 2.0

By Cay Horstmann

JSF Overview

JavaServer Faces (JSF) is the “official” component-based view technology in the Java EE web tier. JSF includes a set of predefined UI components, an event-driven programming model, and the ability to add third-party components. JSF is designed to be extensible, easy to use, and toolable. This refcard describes JSF 2.0.

Development Process

A developer specifies JSF components in JSF pages, combining JSF component tags with HTML and CSS for styling. Components are linked with managed beans—Java classes that contain presentation logic and connect to business logic and persistence backends.

JSF framework

In JSF 2.0, it is recommended that you use the facelets format for your pages:


<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
  xmlns:f=”http://java.sun.com/jsf/core”
  xmlns:h=”http://java.sun.com/jsf/html”
  xmlns:ui=”http://java.sun.com/jsf/facelets”>
  <h:head>...</h:head>
  <h:body>
   <h:form>
       ...
   </h:form>
  </h:body>
</html>

These common tasks give you a crash course into using JSF.

Text Field

Code 1

page.xhtml


<h:inputText value=”#{bean1.luckyNumber}”>

WEB-INF/classes/com/corejsf/SampleBean.java


@ManagedBean(name=”bean1”)
@SessionScoped
public class SampleBean {
   public int getLuckyNumber() { ... }
   public void setLuckyNumber(int value) { ... }
   ...
}

Button

Press Button

page.xhtml


<h:commandButton value=”press me” action=”#{bean1.login}”/>

WEB-INF/classes/com/corejsf/SampleBean.java


@ManagedBean(name=”bean1”)
@SessionScoped
public class SampleBean {
   public String login() {
     if (...) return “success”; else return “error”;
   }
...
}


The outcomes success and error can be mapped to pages in faces-config.xml. if no mapping is specified, the page /success.xhtml or /error.xhtml is displayed.

Radio Buttons

Radio Button

page.xhtml


<h:selectOneRadio value=”#{form.condiment}>
<f:selectItems value=”#{form.items}”/>
</h:selectOneRadio>

WEB-INF/classes/com/corejsf/SampleBean.java


public class SampleBean {
  private static Map<String, Object> items;
  static {
    items = new LinkedHashMap<String, Object>();
    items.put(“Cheese”, 1); // label, value
    items.put(“Pickle”, 2);
    ...
  }
  public Map<String, Object> getItems() { return items; }
  public int getCondiment() { ... }
  public void setCondiment(int value) { ... }
  ...
}

JBoss Studio2.0_5.jpg

Validation and Conversion

Page-level validation and conversion:


<h:inputText value=”#{bean1.amount}” required=”true”>
  <f:validateDoubleRange maximum=”1000”/>
</h:inputText>
<h:outputText value=”#{bean1.amount}”>
  <f:convertNumber type=”currency”/>
</h:outputText>

The number is displayed with currency symbol and group separator: $1,000.00

Using the Bean Validation Framework (JSR 303) 2.0


public class SampleBean {
  @Max(1000) private BigDecimal amount;
}

Error Messages

Error Message


<h:outputText value=”Amount”/>
<h:inputText id=”amount” label=”Amount” value=”#{payment.amount}”/>
<h:message for=”amount”/>

Resources and Styles

page.xhtml


<h:outputStylesheet library=”css” name=”styles.css” target=”head”/>
...
<h:outputText value=”#{msgs.goodbye}!” styleClass=”greeting”>

faces-config.xml


<application>
  <resource-bundle>
    <base-name>com.corejsf.messages</base-name>
    <var>msgs</var>
  </resource-bundle>
</application>

WEB-INF/classes/com/corejsf/messages.properties


goodbye=Goodbye

WEB-INF/classes/com/corejsf/messages_de.properties


goodbye=Auf Wiedersehen

resources/css/styles.css


.greeting {
  font-style: italic;
  font-size: 1.5em;
  color: #eee;
}

Table with links

Table With Links


<h:dataTable value=”#{bean1.entries}” var=”row” styleClass=”table”
  rowClasses=”even,odd”>
  lt;h:column>
    <f:facet name=”header”>
      <h:outputText value=”Name”/>
    </f:facet>
    <h:outputText value=”#{row.name}”/>
  </h:column>
  <h:column>
    <h:commandLink value=”Delete” action=”#{bean1.deleteAction}”
      immediate=”true”>
      <f:setPropertyActionListener target=”#{bean1.idToDelete}”
        value=”#{row.id}”/>
    </h:commandLink>
  </h:column>
</h:dataTable>

WEB-INF/classes/com/corejsf/SampleBean.java


public class SampleBean {
  private int idToDelete;
  public void setIdToDelete(int value) { idToDelete = value; }
  public String deleteAction() {
    // delete the entry whose id is idToDelete
    return null;
  }
  public List<Entry> getEntries() { ... }
  ...
}

Ajax 2.0


<h:commandButton value=”Update”>
  <f:ajax execute=”
</h:commandButton>

lifecycle

lifecycle

The jsf expression language

An EL expression is a sequence of literal strings and expressions of the form base[expr1][expr2]... As in JavaScript, you can write base.identifier instead of base[‘identifier’] or base[“identifier”]. The base is one of the names in the table below or a bean name.

header A Map of HTTP header parameters, containing only the first value for each name
headerValues A Map of HTTP header parameters, yielding a String[] array of all values for a given name
param A Map of HTTP request parameters, containing only the first value for each name
paramValues A Map of HTTP request parameters, yielding a String[] array of all values for a given name
cookie A Map of the cookie names and values of the current request
initParam A Map of the initialization parameters of this web application
requestScope,
sessionScope,
applicationScope,
viewScope 2.0
A map of all attributes in the given scope
facesContext The FacesContext instance of this request
view The UIViewRoot instance of this request
component 2.0 The current component
cc 2.0
resource 2.0 Use resource[‘library:name’] to access a resource

Value expression: a reference to a bean property or an entry in a map, list or array. Examples:

userBean.name calls getName or setName on the userBean object pizza.choices[var] calls pizza.getChoices().get(var) or pizza.getChoices().put(var, ...)

Method expression: a reference to a method and the object on which it is to be invoked. Example:
userBean.login calls the login method on the userBean object when it is invoked. 2.0: Method expressions can contain parameters: userBean.login(‘order page’)

In JSF, EL expressions are enclosed in #{...} to indicate deferred evaluation. The expression is stored as a string and evaluated when needed. In contrast, JSP uses immediate evaluation, indicated by ${...} delimiters.

2.0: EL expressions can contain JSTL functions

fn:contains(str, substr),
fn:containsIgnoreCase(str, substr)
fn:startsWith(str, substr)
fn:endsWith(str, substr)
fn:length(str)
fn:indexOf(str)
fn:join(strArray, separator)
fn:split(str, separator)
fn:substring(str, start, pastEnd)
fn:substringAfter(str, separator)
fn:substringBefore(str, separator)
fn:replace(str, substr,
replacement)
fn:toLowerCase(str)
fn:toUpperCase(str)
fn:trim()
fn:escapeXml()

JSF Core Tags

Tag Description/Attributes
f:facet Adds a facet to a component - name: the name of this facet
f:attribute Adds an attribute to a component - name, value: the name and value of the attribute to set
f:param
Constructs a parameter child component
- name: An optional name for this parameter component.
- value:The value stored in this component.
f:actionListener f:valueChangeListener
Adds an action listener or value change listener to a component
- type: The name of the listener class
f:propertyAction Listener 1.2
Adds an action listener to a component that sets a bean property
to a given value
- target: The bean property to set when the action event occurs
- value: The value to set it to
f:phaseListener 1.2
Adds a phase listener to this page
- type: The name of the listener class
f:event 2.0
Adds a system event listener to a component
- name: One of preRenderComponent, postAddToView,
  preValidate, postValidate
- listenter: A method expression of the type
  void (ComponentSystemEvent) throws
  AbortProcessingException
f:converter
Adds an arbitrary converter to a component
- convertedId: The ID of the converter
f:convertDateTime
Adds a datetime converter to a component
- type: date (default), time, or both
- dateStyle, timeStyle: default, short, medium, long or full
- pattern: Formatting pattern, as defined in java.text.
  SimpleDateFormat
- locale: Locale whose preferences are to be used for parsing
  and formatting
- timeZone: Time zone to use for parsing and formatting
  (Default: UTC)
f:convertNumber
Adds a number converter to a component
- type: number (default), currency , or percent
- pattern: Formatting pattern, as defined in java.text.
  DecimalFormat
- minIntegerDigits, maxIntegerDigits,
  minFractionDigits, maxFractionDigits: Minimum,
  maximum number of digits in the integer and fractional part
- integerOnly: True if only the integer part is parsed (default:
  false)
- groupingUsed: True if grouping separators are used (default:
  true)
- locale: Locale whose preferences are to be used for parsing
  and formatting
- currencyCode: ISO 4217 currency code to use when
  converting currency values
- currencySymbol: Currency symbol to use when converting
  currency values
f:validator
Adds a validator to a component
- validatorID: The ID of the validator
f:validateDoubleRange,
f:validateLongRange,
f:validateLength
Validates a double or long value, or the length of a string
- minimum, maximum: the minimum and maximum of the valid
  range
f:validateRequired 2.0 Sets the required attribute of the enclosing component
f:validateBean 2.0
Specify validation groups for the Bean Validation Framework
(JSR 303)
f:loadBundle
Loads a resource bundle, stores properties as a Map
- basename: the resource bundle name
- value: The name of the variable that is bound to the bundle map
f:selectItem
Specifies an item for a select one or select many component
- binding, id: Basic attributes
- itemDescription: Description used by tools only
- itemDisabled: false (default) to show the value
- itemLabel: Text shown by the item
- itemValue: Item’s value, which is passed to the server as a
  request parameter
- value: Value expression that points to a SelectItem instance
- escape: true (default) if special characters should be converted
  to HTML entities
- noSelectionOption 2.0: true if this item is the “no selection
  option”
f:selectItems
Specifies items for a select one or select many component
- value: Value expression that points to a SelectItem, an array
  or Collection, or a Map mapping labels to values.
- var 2.0: Variable name used in value expressions when
  traversing an array or collection of non-SelectItem elements
- itemLabel 2.0, itemValue 2.0, itemDescription 2.0,
  itemDisabled 2.0, itemLabelEscaped 2.0: Item label,
  value, description, disabled and escaped flags for each item in
  an array or collection of non-SelectItem elements. Use the
  variable name defined in var.
- noSelectionOption 2.0: Value expression that yields the “no
  selection option” item or string that equals the value of the “no
  selection option” item
f:ajax 2.0
Enables Ajax behavior
- execute, render: Lists of component IDs for processing in the
  “execute” and “render” lifecycle phases
- event: JavaScript event that triggers behavior. Default: click
  for buttons and links, change for input components
- immediate: If true, generated events are broadcast during
  “Apply Request Values” phase instead of “Invoke Application”
- listener: Method binding of type void (AjaxBehaviorEvent)
- onevent, onerror: JavaScript handlers for events/errors
f:viewParam 2.0 Defines a “view parameter” that can be initialized with a request
parameter
-name, value: the name of the parameter to set
-binding, converter, id, required, value, validator,
valueChangeListener: basic attributes
f:metadata 2.0 Holds view parameters. May hold other metadata in the future

JSF HTML Tags

Tag Description
h:head 2.0,h:body 2.0,
h:form
HTML head, body, form
h:outputStylesheet 2.0,
h:outputScript 2.0
Produces a style sheet or script
h:inputText Single-line text input control.

code8.1

h:inputTextArea Multiline text input control.

code8.1

h:inputSecret Password input control. inputTextArea
h:inputHidden Hidden field
h:outputLabel Label for another
component for
accessibility
h:outputLink HTML anchor. code8.2
h:outputFormat Like outputText, but
formats compound
messages
h:outputText Single-line text output.
h:commandButton,
h:button 2.0
Button: submit, reset, or pushbutton. press me
h:commandLink, h:link 2.0 Link that acts like a
pushbutton.
register
h:message Displays the most recent
message for a component
Recent Message
h:messages Displays all messages
h:grapicImage Displays an image Image Display
h:selectOneListbox Single-select listbox Listbox
h:selectOneMenu Single-select menu Menu Select
h:selectOneRadio Set of radio buttons Radio Button Select
h:selectBooleanCheckbox Checkbox Checkbox
h:selectManyCheckbox Set of checkboxes Checkboxes
h:selectManyListbox Multiselect listbox Multiselect Listbox
h:selectManyMenu Multiselect menu Multiselect Menu
h:panelGrid HTML table
h:panelGroup Two or more components
that are laid out as one
h:dataTable A feature-rich table
component
h:column Column in a data table

Basic Attributes

id Identifier for a component
binding Reference to the component that can be used in a backing bean
rendered A boolean; false suppresses rendering
value A component’s value, typically a value binding
valueVhangeListener A method expression of the type void (ValueChangeEvent)
converter, validator Converter or validator class name
required A boolean; if true, requires a value to be entered in the associated field

Attributes for h:body and h:form

Attribute Description
binding, id, rendered Basic attributes
dir, lang, style, styleClass, target, title
h:form only: accept, acceptcharset, enctype
HTML 4.0 attributes
(acceptcharset corresponds
to HTML accept-charset,
styleClass corresponds to
HTML class)
onclick, ondblclick, onkeydown, onkeypress,
onkeyup, onmousedown, onmousemove, onmouseout,
onmouseover
h:body only: onload, onunload
h:form only: onblur, onchange, onfocus,
onreset, onsubmit
DHTML events

Attributes for h:inputText, h:inputSecret,
h:inputTextarea, and h:inputHidden

Code Attribute Description cols For h:inputTextarea only—number of columns immediate Process validation early in the life cycle redisplay For h:inputSecret only—when true, the input field’s value is redisplayed when the web page is reloaded required Require input in the component when the form is submitted rows For h:inputTextarea only—number of rows binding, converter, id, rendered, required, value, validator, valueChangeListener Basic attributes accesskey, alt, dir,
disabled, lang, maxlength,
readonly, size, style,
styleClasstabindex, title HTML 4.0 pass-through attributes—alt, maxlength, and size do not apply to h:inputTextarea. None apply to h:inputHidden onblur, onchange, onclick,
ondblclick, onfocus,
onkeydown, onkeypress,
onkeyup, onmousedown,
onmousemove, onmouseout,
onmouseover, onselect DHTML events. None apply to h:inputHidden

Attributes for h:outputText and h:outputFormat

Attribute Description
escape If set to true, escapes <, >, and & characters. Default value is true
Basic attributes
style, title HTML 4.0

Attributes for h:outputLabel

Attribute Description
for The ID of the component to be labeled.
binding, converter, id, rendered, value Basic attributes

Attributes for h:graphicImage

cloud Attribute Description library 2.0, name 2.0 The resource library (subdirectory of resources) and file name (in that subdirectory) binding, id, rendered, value Basic attributes alt, dir, height, ismap, lang,
longdesc, style, styleClass, title,
url, usemap, width HTML 4.0 onblur, onchange, onclick,
ondblclick, onfocus, onkeydown,
onkeypress, onkeyup, onmousedown,
onmousemove, onmouseout,
onmouseover, onmouseup DHTML events

Attributes for h:commandButton and h:commandLink

press me Attribute Description action (command tags) Navigation outcome string or method expression of type String () outcome 2.0 (non-command tags) Value expression yielding the navigation outcome fragment 2.0 (non-command tags) Fragment to be appended to URL. Don’t include the # separator actionListener Method expression of type void (ActionEvent) charset For h:commandLink only—The character encoding of the linked reference image (button tags) For h:commandButton only—A context-relative path to an image displayed in a button. If you specify this attribute, the HTML input’s type will be image immediate A boolean. If false (the default), actions and action listeners are invoked at the end of the request life cycle; if true, actions and action listeners are invoked at the beginning of the life cycle type For h:commandButton: The type of the generated input element: button, submit, or reset. The default, unless you specify the image attribute, is submit. For h:commandLink and h:link: The content type of the linked resource; for example, text/html, image/gif, or audio/basic value The label displayed by the button or link binding, id, rendered Basic attributes accesskey, dir, disabled (h:commandButton only), lang, readonly, style, styleClass, tabindex, title
link tags only: charset, coords, hreflang, rel, rev, shape, target HTML 4.0 onblur, onclick, ondblclick,
onfocus, onkeydown, onkeypress,
onkeyup, onmousedown, onmousemove,
onmouseout, onmouseover,
onmouseup DHTML events

Attributes for h:outputLink

Java Anchor Attribute Description accesskey, binding, converter, id, lang, rendered, value Basic attributes charset, coords, dir, hreflang, lang, rel, rev, shape, style, styleClass, tabindex, target, title, type HTML 4.0 onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Attributes for: h:selectBooleanCheckbox,
h:selectManyCheckbox, h:selectOneRadio,
h:selectOneListbox, h:selectManyListbox,
h:selectOneMenu, h:selectManyMenu

Boolean Checkbox Attribute Description enabledClass, disabledClass CSS class for enabled/disabled elements— h:selectOneRadio and h:selectManyCheckbox only selectedClass 2.0,
unselectedClass 2.0 CSS class for selected/unselected elements— h:selectManyCheckbox only layout Specification for how elements are laid out: lineDirection (horizontal) or pageDirection (vertical)—h:selectOneRadio and h:selectManyCheckbox only collectionType 2.0 selectMany tags only: the name of a collection class such as java.util.TreeSet hideNoSelectionOption 2.0 Hide item marked as “no selection option” binding, converter, id, immediate, required, rendered, validator, value, valueChangeListener Basic attributes accesskey, border, dir, disabled, lang, readonly, style, styleClass, size, tabindex, title HTML 4.0—border only for h:selectOneRadio and h:selectManyCheckbox, size only for h:selectOneListbox and h:selectManyListbox. onblur, onchange, onclick,
ondblclick, onfocus, onkeydown,
onkeypress, onkeyup, onmousedown,
onmousemove, onmouseout,
onmouseover, onmouseup, onselect DHTML events

Attributes for h:message and h:messages

Boolean Checkbox Attribute Description for The ID of the component whose message is displayed— applicable only to h:message errorClass, fatalClass, infoClass, warnClass CSS class applied to error/fatal/information/warning messages errorStyle, fatalStyle, infoStyle, warnStyle CSS style applied to error/fatal/information/warning messages globalOnly Instruction to display only global messages—h:messages only. Default: false layout Specification for message layout: table or list— h:messages only showDetail A boolean that determines whether message details are shown. Defaults are false for h:messages, true for h:message. showSummary A boolean that determines whether message summaries are shown. Defaults are true for h:messages, false for h:message. tooltip A boolean that determines whether message details are rendered in a tooltip; the tooltip is only rendered if showDetail and showSummary are true binding, id, rendered Basic attributes style, styleClass, title HTML 4.0

Attributes for h:panelGrid

Attribute Description
bgcolor Background color for the table
border Width of the table’s border
cellpadding Padding around table cells
cellspacing Spacing between table cells
columns Number of columns in the table
frame frame Specification for sides of the frame surrounding
the table that are to be drawn; valid values: none,
above, below, hsides, vsides, lhs, rhs, box, border
headerClass, footerClass CSS class for the table header/footer
rowClasses, columnClasses Comma-separated list of CSS classes for rows/columns
rules Specification for lines drawn between cells; valid values: groups, rows, columns, all
summary Summary of the table’s purpose and structure used for non-visual feedback such as speech
binding, id, rendered, value Basic attributes
dir, lang, style, styleClass, title, width HTML 4.0
onclick, ondblclick,
onkeydown, onkeypress,
onkeyup, onmousedown,
onmousemove, onmouseout,
onmouseover, onmouseup
DHTML events

Attributes for h:panelGroup

Attribute Description
binding, id, rendered Basic attributes
style, styleClass HTML 4.0

Attributes for h:dataTable

Attribute Description
bgcolor Background color for the table
border Width of the table’s border
cellpadding Padding around table cells
cellspacing Spacing between table cells
first index of the first row shown in the table
frame Specification for sides of the frame surrounding the table should be drawn; valid values: none, above, below, hsides, vsides, lhs, rhs, box, border
headerClass, footerClass CSS class for the table header/footer
rowClasses, columnClasses comma-separated list of CSS classes for rows/columns
rules Specification for lines drawn between cells; valid values: groups, rows, columns, all
summary summary of the table’s purpose and structure used for non-visual feedback such as speech
var The name of the variable created by the data table that represents the current item in the value
binding, id, rendered,
value
Basic attributes
dir, lang, style, styleClass, title, width HTML 4.0
onclick, ondblclick,
onkeydown, onkeypress,
onkeyup, onmousedown,
onmousemove, onmouseout,
onmouseover, onmouseup
DHTML events

Attributes for h:column

Attribute Description
headerClass 1.2,
footerClass 1.2
CSS class for the column’s header/footer
binding, id, rendered Basic attributes
Attribute Description
ui:define Give a name to content for use in a template
-name: the name of the content
ui:insert If a name is given, insert named content if defined or use the child elements otherwise. If no name is given, insert the content of the tag invoking the template -name: the name of the content
ui:composition Produces content from a template after processing child elements (typically ui:define tags) Everything outside the ui:composition tag is ignored -template: the template file, relative to the current page
ui:component Like ui:composition, but makes a JSF component -binding, id: basic attributes
ui:decorate, ui:fragment Like ui:composition, ui:
ui:include Include plain XHTML, or a file with a ui:composition or ui:component tag -src: the file to include, relative to the current page
ui:param Define a parameter to be used in an included file or template -name: parameter name -value: a value expression (can yield an arbitrary object)
ui:repeat Repeats the enclosed elements
  • value: a List, array, ResultSet, or object
  • offset, step, size: starting intex, step size, ending index of the iteration
  • var: variable name to access the current element
  • varStatus: variable name to access the iteration status, with integer properties begin, end, index, step and Boolean properties even, odd, first, last
ui:debug Shows debug info when CTRL+SHIFT+a key is pressed
  • hotkey: the key to press (default d)
  • rendered: true (default) to activate
ui:remove Do not include the contents (useful for comments or temporarily deactivating a part of a page)

About The Author

Photo of Cay S Horstmann

Cay S. Horstmann

has written many books on C++, Java and object-oriented development, is the series editor for Core Books at Prentice-Hall and a frequent speaker at computer industry conferences. For four years, Cay was VP and CTO of an Internet startup that went from 3 people in a tiny office to a public company. He is now a computer science professor at San Jose State University. He was elected Java Champion in 2005.

Cay Horstmann’s Java Blog

http://weblogs.java.net/blog/cayhorstmann/

Cay Horstmann’s Website-

http://www.horstmann.com/

Recommended Book

Maven

Core JavaServer Faces delves into all facets of JSF development, offering systematic best practices for building robust applications and maximizing developer productivity.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Getting Started with Spring-DM

By Craig Walls

16,699 Downloads · Refcard 57 of 151 (see them all)

Download
FREE PDF


The Essential Spring-DM Cheat Sheet

Spring is a framework that promotes development of loosely coupled/highly cohesive objects through dependency injection and interface-oriented design. Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This DZone Refcard shows you how to use Spring-DM to wire together OSGi services to build highly modular and dynamic applications. You may also enjoy the other Spring DZone Refcardz in our Collection: Spring Configuration and Spring Annotations.
HTML Preview
Getting Started with Spring-DM

Getting Started with Spring-DM

By Craig Walls

about spring-dm

Spring is a framework that promotes development of looselycoupled/ highly-cohesive objects through dependency injection and interface-oriented design. OSGi is a framework specification that promotes development of loosely-coupled/ highly-cohesive application modules through services and interface-oriented design. Seems like a match made in heaven! Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This reference card will be your resource for working with Spring- DM to wire together OSGi services and ultimately building modular applications.

You may be interested to know that Spring-DM is the basis for the SpringSource dm Server, a next-generation application server that embraces modularity through OSGi. What’s more, the upcoming OSGi R4.2 specification includes a component model known as the OSGi Blueprint Services that is heavily influenced by Spring-DM.

Introducing Spring-DM

The star player of Spring-DM is a bundle known as the Spring- DM extender. The Spring-DM extender watches for bundles to be installed and inspects them to see if they are Springenabled (that is, if they contain a Spring application context definition file). When it finds a Spring-enabled bundle, the extender will create a Spring application context for the bundle.

Spring Application Contexts

Spring-DM also provides a Spring configuration namespace that enables you to declare and publish Spring beans as OSGi services and to consume OSGi services as if they were just beans in a Spring application context. This declarative model effectively eliminates the need to work with the OSGi API directly.

Installing Spring-DM

One of the nice things about Spring-DM is that you do not need to include it in the classpath of your OSGi bundles or even reference it from those bundles. Installing Spring-DM involves two parts:

  1. Installing the Spring-DM and supporting bundles in your OSGi framework
  2. Adding the Spring-DM configuration namespace to your bundle’s Spring configuration XML files

You can download Spring-DM from
http://www.springframework.org/osgi. The distribution comes complete with everything you need to work with Spring- DM, including the Spring-DM extender bundle and all of its dependency bundles.

Installing the Spring-DM extender bundles

There are several means by which you can install bundles into an OSGi framework, depending on the OSGi framework and any add-ons or tools you may be using. But the most basic way is to use the “install” command that is available in most OSGi framework shells. For example, to install the Spring- DM extender bundle and the supporting Spring-DM bundles (assuming that you’ve unzipped the Spring-DM distribution in / spring-dm-1.2.0):


osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-core-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-extender-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-io-
   1.2.0.jar

Spring-DM depends on the Spring framework, so you’ll also need to install several other Spring bundles:

refcardzad


osgi> install file:///spring-dm-1.2.0/lib/spring-aop-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-context-
    2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-core-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-beans-2.5.6.A.jar

Finally, you’ll also need to install several other supporting bundles that Spring and Spring-DM depend on:


osgi> install file:///spring-dm-1.2.0/lib/com.springsource.net.
   sf.cglib-2.1.3.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.org.
   aopalliance-1.0.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   api-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   log4j-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   org.apache.commons.logging-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/log4j.osgi-1.2.15-
   SNAPSHOT.jar

Hot Tip

Use tools to help install bundles Installing bundles using the “install” command should work with almost any OSGi framework, but it is also quite a manual process. Pax Runner (http:// paxrunner.ops4j.org) is an OSGi framework launcher that takes a lot of the tedium out of installing bundles. Just use Pax Runner’s “spring dm” profile: % pax-run.sh --profiles=spring.dm

The Spring-DM configuration namespace

Schema URI:

http://www.springframework.org/schema/osgi

Schema XSD:

http://www.springframework.org/schema/osgi/spring-osgi.xsd

When it comes to declaring services and service consumers in Spring-DM, you’ll use Spring-DM’s core namespace. To do that, you’ll need to include the namespace in the XML file.


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xmlns:osgi=”http://www.springframework.org/schema/osgi”
	xsi:schemaLocation=”http://www.springframework.org/
schema/beans
	    http://www.springframework.org/schema/beans/
spring-beans.xsd
		   http://www.springframework.org/schema/osgi
		     http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
...
</beans>

Spring’s “beans” namespace is the default namespace, but if you know that most or all of the elements in the Spring configuration file will be from the Spring-DM namespace, you can make it the default namespace:

spring beans

Publishing Services

To demonstrate Spring-DM’s capabilities, we’re going to create a few OSGi services that translate English text into some other language. All of these services will implement the following Translator interface:


package com.habuma.translator;
public interface Translator
   {
String translate(String text);
}

The first service we’ll work with is one that translates English into Pig Latin. It’s implementation looks something like this:


package com.habuma.translator.piglatin;
import com.habuma.translator.Translator;
public class PigLatinTranslator implements Translator {
	private final String VOWELS = “AEIOUaeiou”;
	public String translate(String text) {
	  // actual implementation left out for brevity
	}
}

If we were working with basic OSGi (that is, without Spring- DM), we’d publish this service to the OSGi service registry using the OSGi API, perhaps in a bundle activator’s start() method:


public void start(BundleContext context) throws Exception {
	context.registerService(Translator.class.getName(),
				new PigLatinTranslator(), null);
}

Although the native OSGi approach will work fine, it requires us to work programmatically with the OSGi API. Instead, we’ll publish services declaratively using Spring-DM. The first step: Create a Spring context definition file that declares the PigLatinTranslator as a Spring bean:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
		  http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean id=”pigLatinTranslator”
    class=”com.habuma.translator.piglatin.PigLatinTranslator” />
</beans>

Hot Tip

Overriding the context configuration location By default, the Spring-DM extender looks for all XML files located in a bundle’s META-INF/spring folder and assumes that they’re all Spring context definition files that are to be used to create a Spring application context for the bundle; however, if you’d like to put your context definition files elsewhere in the bundle, use the Spring-Context: header in the META-INF/ MANIFEST.MF file.
For example, if you’d rather place your Spring configuration files in a directory called “spring-config” at the root of the bundle, add the following entry to your bundle’s manifest: Spring-Context: spring-config/*.xml

This Spring context file can be named anything, but it should be placed in the Pig Latin translator bundle’s META-INF/ spring directory. When the bundle is started in an OSGi framework, the Spring-DM extender will look for Spring context configuration files in that directory and use them to create a Spring application context for the bundle.

Publishing a simple OSGi service

By itself the Spring context we’ve created only creates a bean in the Spring application context. It’s not yet an OSGi service. To publish it as an OSGi service, we’ll create another Spring context definition file that uses the Spring-DM namespace:


<<?xml version=”1.0” encoding=”UTF-8”?>
<<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/
spring-beans.xsd
			  http://www.springframework.org/schema/osgi
				http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
   <<service ref=”pigLatinTranslator”
	  interface=”com.habuma.translator.Translator” />
<</beans:beans>

Hot Tip

Don’t mix your Spring and OSGi contexts Although you can certainly define all of your bundle’s Spring beans and OSGi services in a single Spring context definition file, it’s best to keep them in separate files (all in META-INF/spring). By keeping the OSGi-specific declarations out of the normal Spring context definition, you’ll be able to use the OSGi-free context to do non-OSGi integration tests of your beans.

This new Spring context file uses Spring-DM’s element to publish the bean whose ID is “pigLatinTranslator” in the OSGi service registry. The ref attribute refers to the Spring bean in the other context definition file. The interface attribute identifies the interface under which the service will be available in the OSGi service registry.

Publishing a service under multiple interfaces

Let’s suppose that the PigLatinTranslator class were to implement another interface, perhaps one called TextProcessor. And let’s say that we want to publish the service under both the Translator interface and the TextProcessor interface. In that case, you can use the element to identify the interfaces for the service:


<service ref=”pigLatinTranslator”>
  <interfaces>
    <beans:value>com.habuma.translator.Translator</beans:value>
    <beans:value>com.habuma.text.TextProcessor</beans:value>
  </interfaces>
</service>

Auto-selecting service interfaces

Instead of explicitly specifying the interfaces for a service, you can also let Spring-DM figure out which interfaces to use by specifying the auto-export attribute:


<service ref=”pigLatinTranslator”
       auto-export=”interfaces” />

By setting auto-export to “interfaces”, it tells Spring-DM to publish the service under all interfaces that the implementation class implements. You can also set auto-export to “all-classes” to publish the service under all interfaces and classes for the service or “class-hierarchy.”

Publishing a service with properties

It’s also possible to publish a service with properties to qualify that service. These properties can later be used to help refine the selection of services available to a consumer. For example, let’s say that we want to qualify Translator services by the language that they translate to:


<rvice ref=”pigLatinTranslator”
      interface=”com.habuma.translator.Translator”>
<service-properties>
   <beans:entry key=”translator.language” value=”Pig Latin” />
 </service-properties>
</service>

The <service-properties> element can contain one or more <entry> elements from the “beans” namespace. In this case, we’ve added a property named “translator.language” with a value of “Pig Latin”. Later, we’ll use this property to help select this particular service from among a selection of services that all implement Translator.

Consuming Services

Now that we’ve seen how to publish a service in the OSGi service registry, let’s look at how we can use Spring-DM to consume that service. To get started, we’ll create a simple client class:


package com.habuma.translator.client;
import java.util.List;
import com.habuma.translator.Translator;
public class TranslatorClient {
  private static String TEXT = “Be very very quiet. I’m hunting
rabbits!”;
  public void go() {
     System.out.println(“ TRANSLATED: “ +
        translator.translate(TEXT));
  }
  private Translator translator;
  public void setTranslator(Translator translator) {
    this.translator = translator;
  }
}

TranslatorClient is a simple POJO that is injected with a Translator and uses that Translator in its go() method to translate some text. We’ll declare it as a Spring bean like this:


<?xml version=”1.0” encoding=”UTF-8”?>
		<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean class=”com.habuma.translator.client.TranslatorClient”
     init-method=”go”>
   <property name=”translator” ref=”translator” />
  </bean>
</beans>

As with the service’s Spring context declaration, the name of this Spring context definition can be named anything, but it should be placed in the client bundle’s META-INF/spring folder so that the Spring-DM extender will find it.

The bean is declared with the init-method attribute set to call the go() method when the bean is created. And we use the <property> element to inject the bean’s translator property with a reference to a bean whose ID is “translator”.

The big question here is: Where does the “translator” bean come from?

Simple service consumption

Spring-DM’s <reference> element mirrors the <service> element. Rather than publishing a service, however, <reference> retrieves a service from the OSGi service registry. The simplest way to consume a Translator service is as follows:


<reference id=”translator”
interface=”com.habuma.translator.Translator” />

When the Spring-DM extender creates a Spring context for the client bundle, it will create a bean with an ID of “translator” that is a proxy to the service it finds in the service registry. With that id attribute and interface, it is quite suitable for wiring into the client bean’s translator property.

Setting a service timeout

In a dynamic environment like OSGi, services can come and go. When the client bundle starts up, there may not be a Translator service available for consumption. If it’s not available, then Spring-DM will wait up to 5 minutes for the service to become available before giving up and throwing an exception.

But it’s possible to override the default timeout using the <reference> element’s timeout attribute. For example, to set the timeout to 1 minute instead of 5 minutes:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	timeout=”60000” />

Notice that the timeout attribute is specified in milliseconds, so 60000 indicates 60 seconds or 1 minute.

Optional service references

Another way to deal with the dynamic nature of OSGi services is to specify that a service reference is optional. By default, the cardinality of a reference to a service is “1..1”, meaning that the service must be found within the timeout period or else an exception will be thrown. But you can specify an optional reference by setting the cardinality to “0..1”:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	cardinality=”0..1” />

Filtering services

Imagine that we have two or more Translator services published in the OSGi service registry. Let’s say that in addition to the Pig Latin translator there’s also another Translator service that translates text into Elmer Fudd speak. How can we ensure that our client gets the Pig Latin service when another implementations may be available?

Earlier, we saw how to set a property on a service when it’s published. Now we’ll use that property to filter the selection of services found on the consumer side:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	filter=”(translator.language=Pig Latin)” />

The filter attribute lets us specify properties that will help refine the selection of matching services. In this case, we’re only interested in a service that has its “translator.language” property set to “Pig Latin”.

Consuming multiple services

But why choose? What if we wanted to consume all matching services? Instead of pin-pointing a specific service, we can use Spring-DM’s <list> element to consume a collection of matching services:


<list id=”translators”
	interface=”com.habuma.translator.Translator” />

The Spring-DM extender will create a list of matching services that can be injected into a client bean collection property such as this one:


private List<Translator> translators;
public void setTranslators(List<Translator> translators) {
  this.translators = translators;
}

Optionally, you can use Spring-DM’s <set> element to create a set of matching services:


<set id=”translators”
   interface=”com.habuma.translator.Translator” />

The <list> and <set> elements share many of the same attributes with <reference>. For example, to consume a set of all Translator services filtered by a specific property:


<set id=”translators”
interface=”com.habuma.translator.Translator”
filter=”(translator.language=Elmer Fudd)” />

Testing Bundles

Hopefully, you’re in the habit of writing unit tests for your code. If so, that practice should extend to the code that is contained within your OSGi bundles. Because Spring-DM encourages POJO-based OSGi development, you can continue to write unit-tests for the classes that define and consume OSGi services just like you would for any other non-OSGi code.

But it’s also important to write tests that exercise your OSGi services as they’ll be used when deployed in an OSGi container. To accommodate in-OSGi integration testing of bundles, Spring-DM provides AbstractConfigurableBundleCreatorTests, a JUnit 3 base test class from which you can write your bundle tests.

What’s fascinating is how tests based on AbstractConfigurableBundleCreatorTests work. When the test is run, it starts up an OSGi framework implementation (Equinox by default) and installs one or more bundles into the framework. Finally, it wraps itself in an on-the-fly bundle and installs itself into the OSGi framework so that it can test bundles as an insider.

Writing a basic OSGi test

To illustrate, let’s write a simple test that loads our Translator interface bundle and the Pig Latin implementation bundle:


package com.habuma.translator.test;
import org.osgi.framework.ServiceReference;
import org.springframework.osgi.test.
AbstractConfigurableBundleCreatorTests;


import com.habuma.translator.Translator;
public class PigLatinTranslatorBundleTest
      extends AbstractConfigurableBundleCreatorTests {
  @Override
  protected String[] getTestBundlesNames() {
     return new String[] {
		“com.habuma.translator, interface, 1.0.0”,
		“com.habuma.translator, pig-latin, 1.0.0”
      };
  }
  public void testOsgiPlatformStarts() {
    assertNotNull(bundleContext);
  }
}

The getTestBundleNames() method returns an array of Strings where each entry represents a bundle that should be installed into the OSGi framework for the test. The format of each entry is a comma-separated set of values that identify the bundle by its Maven group ID, artifact ID, and version number.

So far, our test has a single test method, testOsgiPlatformStarts(). All this method does is test that the OSGi framework has started by asserting that bundleContext (inherited from AbstractConfigurableBundleCreatorTests) is not null.

Testing OSGi service references

A more interesting test we could write is one that uses the bundle context to lookup a reference to the Translator service and assert that it meets our expectations:


public void testServiceReferenceExists() {
  ServiceReference serviceReference =
    bundleContext.getServiceReference(Translator.class.
getName());
	assertNotNull(serviceReference);
	assertEquals(“Pig Latin”,
       serviceReference.getProperty(“translator.language”));
}

Here we retrieve a ServiceReference from the bundle context and assert that it isn’t null. This means that some implementation of the Translator service has been published in the OSGi service registry. Then, it examines the properties of the service reference and asserts that the “translator.language” property has been set to “Pig Latin”, as we’d expect from how we published the service earlier.

Testing OSGi services

One more thing we could test is that the Translator service does what we’d expect it to do. Certainly, this kind of test usually belongs in a unit test. But it’s still good to throw a smoke test its way to make sure that we’re getting the service we’re expecting.

We could use the ServiceReference to lookup the service. But, we can avoid any additional work with the OSGi API by having the Translator service wired directly into our test class. First, let’s add a Translator property and setter method to our test class


private Translator translator;
public void setTranslator(Translator translator) {
  this.translator = translator;
}

When the test is run, Spring will attempt to autowire the property with a bean from its own Spring application context. But we haven’t defined a Spring application context for the test yet. Let’s do that now:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
   xsi:schemaLocation=”http://www.springframework.org/schema/
beans
      http://www.springframework.org/schema/beans/spring-beans.
xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd”>
  <reference id=”translator”
    interface=”com.habuma.translator.Translator” />
</beans:beans>

You’ll recognize that this Spring context definition looks a lot like the one we created for the service consumer. In fact, our test class will ultimately be a consumer of the Translator service. We just have one more thing to do before we can test the service—we’ll need to override the getConfigLocations() method to tell the test where it can find the context definition file:


@Override
protected String[] getConfigLocations() {
   return new String[] { “bundle-test-context.xml” };
}

Now we can write our test method:


public void testTranslatorService() {
	assertNotNull(translator);
	assertEquals(“id-DAY is-thAY ork-wAY”,
       translator.translate(“Did this work”));
}

This method assumes that by the time it is invoked, the translator property has been set. It first asserts that it is not null and then throws a simple test String at it to test that the service does what we expect.

Changing the tested OSGi framework

By default, Spring-DM tests are run within Equinox. But you can change them to run within another OSGi framework implementation such as Apache Felix or Knopflerfish by overriding the getConfigLocations() method. For example, to run the test within Apache Felix:


@Override
  protected String getPlatformName() {
    return Platforms.FELIX;
}

Or for Knoplerfish:


@Override
protected String getPlatformName() {
  return Platforms.KNOPFLERFISH;
}

Providing a Custom Manifest

When a Spring-DM test gets wrapped up in an on-the-fly bundle, a manifest will be automatically generated for it. But if you’d like to provide a custom manifest. To provide a custom manifest for the on-the-fly bundle, all you need to do is override the getManifestLocation(). For example:


protected String getManifestLocation() {
  return “classpath:com.habuma.translator.Translator.MF”;
}

Be aware, however, that if you provide a custom manifest, you must include a few things in that manifest to make Spring-DM testing work. First, you’ll need to specify a bundle activator:


Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator

And you’ll need to import JUnit and Spring-DM packages:


Import-Package: junit.framework,
  org.osgi.framework,
  org.apache.commons.logging,
  org.springframework.util,
  org.springframework.osgi.service,
  org.springframework.osgi.util,
  org.springframework.osgi.test,
  org.springframework.context

References

Example Source Code:

http://www.habuma.com/refcard/spring-dm/translator.zip

Spring-DM Homepage:

http://www.springframework.org/osgi

OSGi Alliance:

http://www.osgi.org

Modular Java on Twitter:

http://twitter.com/modularjava

Craig’s Modular Java Blog:

http://www.modularjava.com

Craig’s Spring Blog:

http://www.springinaction.com

56 76

About The Author

Photo of Craig Walls

Craig Walls

is a Texas-based software developer with more than 15 years experience working the telecommunication, financial, retail, education, and software industries. He’s a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring and OSGi on his blog. When he’s not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, and two dogs.

Craig’s Publications:

  • Modular Java: Creating Flexible Applications with OSGi and Spring, 2009
  • Spring in Action, 2nd Edition, 2007
  • XDoclet in Action, 2003

Craig’s Blog: http://www.springinaction.com

Recommended Book

Spring in action

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Recommended Book

ModularJava

Modular Java is filled with tips and tricks that will make you a more proficient OSGi and Spring-DM developer. Equipped with the know-how gained from this book, you’ll be able to develop applications that are more robust and agile.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Agile Adoption

Reducing Cost

By Gemba Systems

17,905 Downloads · Refcard 54 of 151 (see them all)

Download
FREE PDF


The Essential Agile Adoption Cheat Sheet

Adopting Agile methods in your projects is easier than you think. This DZone Refcard series focuses on building software faster, better, and cheaper. This Refcard in particular teaches you four practical strategies for reducing the cost of software development. Learn how specific Agile methods like evolutionary design, refactoring and automated testing will help you reduce costs and eliminate risks. Other topics covered include how to adopt Agile practices successfully, as well as what’s next in Agile and a wealth of references. You’ll also enjoy Agile Adoption: Decreasing Time to Market, the first Refcard in this Agile Adoption series.
HTML Preview
JavaServer Faces 2.0

Agile Adoption: Reducing Cost

By Gemba Systems

About this agile adoption refcard

Faster, better, cheaper. That’s what we must do to survive. The Time to Market Refcard (a companion in this series) addresses faster, the Quality Refcard addresses better, and this Refcard addresses cheaper. This is about building the system for less.

Some of the costs of software development are associated with man hours needed to build the system, others with cost of maintenance over time, and yet others include hardware as well as software platform costs. Practices that educe any or all of these costs without sacrificing quality reduce the overall cost of the system.

Then there is the Pareto principle – a.k.a. the 80/20 rule. This rule suggests that roughly 20% of the software system is used 80% of the time. This is also backed up by research that is even more dramatic [figure with usage]. Practices that help the team build only what is needed in a prioritized manner reduce the cost and still deliver the most important business value to the customer (the part she uses).

Figure 1 Practices that help reduce the cost of building software.

reducecost

You will be able to use this Refcard to get 50,000 ft view of what will be involved to reduce the cost of developing your systems.

Four Strategies to reduce cost

Software development is complex and often very complicated. It is HARD. This is not some new revelation, in fact Fred Brooks in the well known paper, “No Silver Bullet.”, states:

The essence of a software entity is a construct of interlocking concepts ...

I believe the hard part of building software to be the specification, design, and testing of this conceptual construct, not the labor of representing it and testing the fidelity of the representation.

There are four major strategies that can help you reduce the cost of building and maintaining your software

Maintain the Theory of the Code

Brain

One way to look at software development is ‘theory building’. That is, programs are theories – models of the world mapped onto software – in the head of the individuals of the development team. Great teams have a shared understanding of how the software system represents the world. Therefore they know where to modify the code when a requirement change occurs, they know exactly where to go hunting for a bug that has been found, and they communicate well with each other about the world and the software.

Conversely, a team that does not have a shared ‘theory’ make communication mistakes all the time. The customer may say something that the business analyst misunderstands because she has a different world view. She may, in turn, have a different understanding than the developers, so the software ends up addressing a different problem or, after several trials, errors and frustrations, the right problem but very awkwardly. Software where the theory of the team does not match, or even worse, the theory is now lost because the original software team is long-gone, is very expensive to maintain.

Building a shared theory of the world-to-software-mapping is a human process that is best done face-to-face by trial and error and with significant time.

Build Less

It has been shown that we build many more features than are actually used. In fact, we can see in Figure 2, only about 20% of functionality we build is used often or always. More than 60% of all functionality built in software is rarely or never used!

Building

One way to reduce the cost of software is to find a way not to build the unused functionality. There are several Agile practices that help you get to that point.

Pie Chart

Functionality Usage

Figure 2: Most functionality built is never used.

Pay Less for Bug Fixes

Typically, anywhere between 60%-90% of software cost goes into the maintenance phase. That is, most of our money goes into keeping the software alive and useful for our clients after the initial build. Practices that help us reduce the cost of software maintenance will significantly affect the overall cost of the software product or system.

Figure 3

Figure 3: Maintain the theory of the code helps reducing the cost of making design changes and fixing bugs. Building less enables better understanding and helps to understand the theory of the code for a change because there is less to change

Pay Less for Changes

The only thing constant in today’s software market is change. If we can embrace change, plan for it, and reduce its cost

when it eventually happens we can make significant savings. One of the strongest points of Agile development is that its practices enable you to roll with the punches and change your software as the business world changes.

Hand with money

The four strategies above: maintain the theory of the code, build less, paying less for maintenance and being able to react to change are not independent.

The practices

Evolutionary Design

Four Icons

Evolutionary Design

Evolutionary Design

Book Evolutionary design is the simple design practice done continuously. Start off with a simple design and change that design only when a new requirement cannot be met by the existing design.
Dollar Evolutionary design reduces the cost by focusing on always building less. This, in turn, directly affects the cost of change drastically.
Cubes You are on a development team practicing automated developer tests, refactoring, and simple design. That’s it, because this is one of those things that is applicable to all types of development projects. The context is especially a match if the technology used technologies is new to a large part of the team.

Simple Design

Evolutionary Design

Book If a decision between coding a design for today’s requirements and a general design to accommodate for tomorrow’s requirements needs to be made, the former is a simple design. Simple design meets the requirements for the current iteration and no more.
Dollar Simple design reduces cost because you build less code to meet the requirements and you maintain less code afterwards. Simple designs are easier to build, understand, and maintain.
Cubes Simple design should only be used when your team also is writing automated developer tests and refactoring. A simple design is fine as long as you can change it to meet future requirements.

Refactoring

Diagram1

Book The practice of Refactoring code changes the structure (i.e., the design) of the code while maintaining its behavioe.
Dollar Costs are reduced because continuous refactoring keeps the design from degrading over time, ensuring that the code is easy to understand, maintain, and change.
Cubes You are on a development team that is practicing automated developer tests. You are currently working on a requirement that is not well-supported by the current design. Or you may have just completed a task (with its tests of course) and want to change the design for a cleaner solution before checking in your code to the source repository.

Automated Developer Tests

Icons

Book Automated developer tests are a set of tests that are written and maintained by developers to reduce the cost of finding and fixing defects—thereby improving code quality—and to enable the change of the design as requirements are addressed incrementally.
Dollar Automated developer tests reduce the cost of software development by creating a safety-net of tests that catch bugs early and enabling the incremental change of design. Beware, however, that automated developer tests take time to build and require discipline.
Cubes You are on a development team that has decided to adopt iterations and simple design and will need to evolve your design as new requirements are taken into consideration. Or you are on a distributed team. The lack of both face-to-face communication and constant feedback is causing an increase in bugs and a slowdown in development.

Evocative Document

Brain Small

Book Evocative documents are documents that evoke memories, conversations, and situations that are shared by those who wrote the document. They are more meaningful and representative of a team’s understanding of the system than traditional documents.
Dollar Evocative documents help by accurately representing the team’s internal model of the software and allowing that model to be handed down from master to apprentice. The better understanding of the system over time also reduces the maintenance cost of the system over time because appropriate changes reduce the deterioration of the software.
Cubes Current documentation isn’t working – as a document is passed from one person to another much of the context and value is lost, and as a result, the maintenance team’s understanding of the codebase constantly deteriorates. This is resulting in the calcification of your software system.

Automated Acceptance Tests

Diagram and icons

Book Automated acceptance tests are tests written at the beginning of the iteration that answer the question: “what will this requirement look like when it is done?”. This means that you start with failing tests at the beginning of each iteration and a requirement is only done when that test passes.
Dollar This practice builds a regression suite of tests in an incremental manner and catches errors, miscommunications, and ambiguities very early on. This, in turn, reduces the amount of work that is thrown away and therefore enables building less. The tests also catch bugs and act as a safety-net during change.
Cubes You are on a development project with an onsite customer who is willing and able to participate more fully as part of the development team. Your team is also willing to make difficult changes to any existing code. You are willing to pay the price of a steep learning curve.

The remaining practices also help reduce the cost of software development. Because of the limited size of the refcard, we will only summarize them below.

img1 A backlog is a prioritized list of requirements that enable a team to build less by making sure they always work on the most important items first and help the team understand the theory of the code when used as an evocative document that shows a larger picture of the system.
img2 An iteration is a time-box where the team builds what is on the backlog and is a potential release and therefore enables building less.
img3 The done state is a definition agreed upon by the entire team of what constitutes the completion of a requirement. The closer the done state is to deployable software, the better it is because it forces the team to resolve all hidden issues early and thus reduces cost.
img4 The cross-functional team is one that has the necessary expertise among its members to take a requirement from its initial concept to a fully deployed and tested piece of software within one iteration. A requirement can be taken off of the backlog, elaborated and developed, tested, deployed.
img5 A self-organizing team is in charge of its own fate. Management gives the team goals to achieve and the team members are responsible for driving towards those goals and achieving them. A self-organizing team recognizes and responds to changes in their environment and in their knowledge as they learn. A self-organizing team is frequently a cross functional team as well.
img6 The Retrospective is a meeting held at the end of a major cycle - iteration or release - to gather and analyze data about that cycle and decide on future actions to improve the team’s environment and process. A retrospective is about evaluating the people, their interactions, and the tools they use.
img7 Continuous integration reduces the total time it takes to build a software system by catching errors early and often. Errors caught early cost significantly less to fix when caught later. It leverages both automated acceptance tests and automated developer tests to give frequent feedback to the team and to pay a much smaller price for fixing a defect.
img8 A user story is an evocative document for requirements. A user story is a very high level description of the requirement to be built –it usually fits on a 3 x 5 index card – and is a “promise for a conversation” later between the person carrying out the Customer Part of Team practice and the implementers.

How to adopt Agile practices successfully

To successfully adopt Agile practices let’s start by answering the question “which ones first?” Once we have a general idea of how to choose the first practices there are other considerations.

Become “Well-Oiled” First

One way to look at software development is to see it as problem solving for business. When considering a problem to solve there are two fundamental actions that must be taken:

  • Solving the right problem. This is IT/Business alignment.
  • Solving the problem right. This is technical expertise.

Intuitively it would seem that we must focus on solving the right problem first because, no matter how well we execute our solution to the problem, if it is the wrong problem then our solution is worthless. This, unfortunately, is the wrong way to go. Research shows in Figure 3, that focusing on alignment first is actually more costly and less effective than doing nothing. It also shows that being “well-oiled”, that is focusing on technical ability first, is much more effective and a good stepping-stone to reaching the state where both issues are addressed.

Figure 3.2

Figure 4: The Alignment Trap (from Avoiding the Alignment Trap in Information Technology, Shpilberg, D. et al, MIT Sloan Management Review, Fall 20078.)

This is supported anecdotally by increasing reports of failed Agile projects that do not deliver on promised results. They adopt many of the soft practices such as Iteration, but steer away from the technically difficult practices such as Automated Developer Tests, Refactoring, and Done State. They never reach the “well-oiled” state.

So the lesson here is make sure that on your journey to adopt Agile practices that improve time to market (or any other business value for that matter), your team will need to become “well-oiled” to see significant, sustained improvement. And that means you should plan on adopting the difficult technical practices for sustainability.

Know What You Don’t Know

The Dreyfus Model of Skill Acquisition, is a useful way to look at how we learn skills – such as learning Agile practices necessary to reduce cost. It is not the only model of learning, but it is consistent, has been effective, and works well for our purposes. This model states that there are levels that one goes through as they learn a skill and that your level for different skills can and will be different. Depending on the level you are at, you have different needs and abilities. An understanding of this model is not crucial to learning a skill; after all, we’ve been learning long before this model existed. However, being aware of this model can help us and our team(s) learn effectively.

So let’s take a closer look at the different skill levels in the Dreyfus Model:

Pyramid

Figure 5: The Dreyfus Model for skill acquisition. One starts as a novice and through ecperience and learning advances towards expertise.

How can the Dreyfus Model help in an organization that is adopting agile methods? First, we must realize that this model is per skill, so we are not competent in everything. Secondly, if agile is new to us, which it probably is, then we are novices or advanced beginners; we need to search for rules and not break them until we have enough experience under our belts. Moreover, since everything really does depend on context, and we are not qualified to deal with context as novices and advanced beginners, we had better get access to some people who are experts or at least proficient to help guide us in choosing the right agile practices for our particular context. Finally, we’d better find it in ourselves to be humble and know what we don’t know to keep from derailing the possible benefits of this new method. And we need to be patient with ourselves and with our colleagues. Learning new skills will take time, and that is OK.

Choosing a Practice to Adopt

Choosing a practice comes down to finding the highest value practice that will fit into your context. Figure 1 will guide you in determining which practices are most effective in decreasing your time to market and will also give you an understanding of the dependencies. The other parts in this section, How to Adopt Agile Practices Successfully?, discuss other ideas that can help you refine your choices. Armed with this information:

figure 5

Figure 5: Steps for choosing and implementing practices.

What Next?

This Refcard is a quick introduction to Agile practices that can help you reduce the cost of building and maintaining your software and an introduction of how you to choose the practices for your organizational context. It is only a starting point. If you choose to embark on an Agile adoption initiative, your next step is to educate yourself and get as much help as you can afford. Books and user groups are a beginning. If you can, find an expert to join your team(s). Remember, if you are new to Agile, then you are a novice or advanced beginner and are not capable of making an informed decision about tailoring practices to your context.

References

Column 1

Column 2

Column 3

Column 4

Column 5

Column 6

Column 7

Column 8

Column 9

Column 10

Column 11

Column 12

Column 13

Column 14

Astels, David. 2003. Test-driven development: a practical guide. Upper Saddle River, NJ: Prentice Hall. x x
Avery, Christopher, Teamwork is an Individual Skill, San Francisco: Berrett-Koehler Publishers, Inc., 2001 x
Bain, Scott L., 2008, Emergent Design, Boston, MA: Pearson Education x x x x
Beck, Kent. 2003. Test-driven development by example. Boston, MA: Pearson Education. x x
Beck, K. and Andres, C., Extreme Programming Explained: Embrace Change (second edition), Boston: Addison-Wesley, 2005 x x x x x x x x
Cockburn, A., Agile Software Development: The Cooperative Game (2nd Edition), Addison-Wesley Professional, 2006. x
Cohn, M., Agile Estimating and Planning, Prentice Hall, 2005. x x
Crispin, L. and Gregory, J., Agile Testing: A Practical Guide for Testers and Agile Teams x
Derby, E., and Larson, D., Agile Retrospectives: Making Good Teams Great, Raliegh: Pragmatic Bookshelf, 2006. x x
Duvall, Paul, Matyas, Steve, and Glover, Andrew. (2006). Continuous Integration: Improving Software Quality and Reducing Risk. Boston: Addison-Wesley. x
Elssamadisy, A., Agile Adoption Patterns: A Roadmap to Organizational Success, Boston: Pearson Education, 2008 x x x x x x x x x x x x x x
Feathers, Michael. 2005. Working effectively with legacy code. Upper Saddle River, NJ: Prentice Hall. x x
Jeffries, Ron. “Running Tested Features.” http://www.xprogramming.com/xpmag/jatRtsMetric.htm x
Jeffries, Ron. 2004. Extreme programming adventures in C#. Redmond, WA: Microsoft Press. x x
Kerth, N., Project Retropsectives: A Handbook for Team Reviews, NY: Dorset House Publishing Company, 2001. x
Kerievsky, Joshua. “Don’t Just Break Software, Make Software.” http://www.industriallogic.com/papers/storytest.pdf x
Larman, C., Agile and Iterative Development: A Manager’s Guide, Boston: Addison-Wesley, 2004 x x
Larman, C., and Vodde, B., Scaling Lean and Agile Development, Boston: Addison-Wesley, 2009 x x x
Massol, Vincent. 2004. Junit in action. Greenwich, CT: Manning Publications. x x
Meszaros, XUnit Test Patterns: Refactoring Test Code, Boston: Addison-Wesley, 2007 x x
Mugridge, R., and W. Cunningham. 2005. Fit for Developing Software: Framework for Integrated Tests. Upper Saddle River, NJ: Pearson Education. x
Poppendieck, M., and Poppendieck, T., Implementing Lean Software Development, Addison-Wesley Professional, 2006. x
Rainsberger, J.B. 2004. Junit recipes: Practical methods for programmer testing. Greenwich, CT: Manning Publications. x x
Schwaber, K., and Beedle, M., Agile Software Development with Scrum, Upper Saddle River, New Jersey: Prentice Hall, 2001. x x x x
Senge, P., The Fifth Discipline: The Art and Practice of The Learning Organization, NY: Currency 2006. x
Surowiecki, J., The Wisdom of Crowds, NY: Anchor, 2005. x

About Gemba Systems

Gemba Systems is comprised of a group of seasoned practitioners who are experts at Lean & Agile Development as well as crafting effective learning experiences. Whether the method is Scrum, Extreme Programming, Lean Development or others - Gemba Systems helps individuals and teams to learn and adopt better product development practices. Gemba Systems has taught better development techniques - including lean thinking, Scrum and Agile Methods - to thousands of developers in dozens of companies around the globe. To learn more visit http://us.gembasystems.com/

Recommended Book

Maven

Agile Adoption Patterns will help you whether you’re planning your first agile project, trying to improve your next project, or evangelizing agility throughout your organization. This actionable advice is designed to work with any agile method, from XP and Scrum to Crystal Clear and Lean. The practical insights will make you more effective in any agile project role: as leader, developer, architect, or customer.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Getting Started with BIRT

By Virgil Dodson

12,391 Downloads · Refcard 49 of 151 (see them all)

Download
FREE PDF


The Essential BIRT Cheat Sheet

Eclipse Business Intelligence and Reporting Tools (BIRT) is an open source, Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT is the only top-level Eclipse project focused on business intelligence.This DZone Refcard provides an overview of the BIRT components focusing on a few key capabilities of the BIRT Designer, BIRT Runtime APIs, and BIRT Web Viewer. This Refcard should be interesting to report designers as well as developers or architects involved in integrating BIRT reports into applications.
HTML Preview
BIRT

Getting Started with BIRT

By Virgil Dodson

What Is Birt?

Eclipse Business Intelligence and Reporting Tools (BIRT) is an open source, Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT is the only top-level Eclipse project focused on business intelligence. BIRT provides core reporting features such as report layout, data access and scripting. This Refcard provides an overview of the BIRT components focusing on a few key capabilities of the BIRT Designer, BIRT Runtime APIs, and BIRT Web Viewer. This Refcard should be interesting to report designers as well as developers or architects involved in integrating BIRT reports into applications.

Design and Runtime components

BIRT has two main components: a report designer based on Eclipse, and a runtime component that you can add to your application. The charting engine within BIRT can also be used by itself, allowing you to add charts to your application.

Birt Components

Getting birt

Open Source BIRT can be downloaded from http://download. eclipse.org/birt/downloads/ or http://www.birt-exchange. com. There are several different packages containing BIRT depending on your needs.

BIRT All-In-One
Download
The fastest way to get started designing BIRT reports on Windows.
Includes everything you need to start designing BIRT Reports,
including the full Eclipse SDK.
BIRT Framework This download allows you to add the BIRT plug-in to your existing
Eclipse environment. (Make sure you check the dependencies and
update those too.)
RCP Designer Simple to use rich client version of the BIRT Report Designer
dedicated to creating reports without the rest of the Eclipse
development environment.
BIRT Runtime Deployment components of the BIRT project including a command
line example, API examples, and example web viewer.
BIRT Web Tools Integration Contains the plug-ins required to use the BIRT Web Project Wizard
and the BIRT Viewer JSP tag library.

Hot Tip

You can also get BIRT into your existing Eclipse environment through the Eclipse Update Manager. Be sure to also select the Data Tools Project when using this approach.

BIRT report designers

BirtReport

The BIRT report designers are easy-to-use, visual report development tools that meet a comprehensive range of reporting requirements. The report designers include taskspecific editors, builders, and wizards that make it easy to create reports that can be integrated into web applications. All BIRT report designers support:

  • Component-based model for reuse
  • Ease of use features
  • Support for a wide range of reports, layouts and formatting
  • Programmatic control
  • Data access across multiple data sources

BIRT FILE TYPES

Design File
(*.rptdesign)
An XML file that contains the data connection infromation, report layout and instructions. Created when making a report in the BIRT Designer.
Template File
(*.rpttemplate)
Ensures all reports you create start with some common elements such as a company header or predefined syles. The starting point for a BIRT report.
Library File
(*.rtplibrary)
Stores commonly used report elements, such as a company logo, so they are managed in one place for all reports.
Report Document
(*.rtpdocument)
The completed report including layout instructions and data. Can be transformed into final report output, such as HTML, PDF, and XLS.

BIRT Data Sources

BIRT supports a variety of data sources and can be extended to support any data to which you have access. In addition to the list below, BIRT also ships with a connection to the ClassicModels sample database and can be easily extended to connect to your custom data source. BIRT also includes a Joint Data Set which allows you to join data across data sources.

Flat File Data Source Supports tab, comma, semicolon, and pipe delimited data
JDBC Data Source Supports connections to relational databases
Scripted Data Source Allows you to communicate with Java objects or to any data you can get from you application.
Web Services Data
Source
Supports connections to a web service. A wizard helps you point at a service through a WSDL and select the data
XML Data Source Supports data from XML

Palette of report items

label Use to include static (or localized) text within a report. Typically for report titles, column headers or any other report text.
text Use to include richly formatted text to your report, including the ability to integrate HTML formatting with your dynamic data.
DynamicText Use to integrate your static text with dynamic or conditional data.
data Use to include data from your connection in the report.
image Use to include images from various embedded sources or dynamic locations.
grid Use to define the layout of a report. Can be nested within other grids to support complex layouts.
list Use to display Data elements from your data source that repeat and creates a new report row for each daata set row. Can contain multiple levels of grouping.
table Use to display repeating data elements within your report and has support for multiple columns and multiple levels of grouping.
chart Use to add rich, interactive charting to your BIRT report.
Cross Tab Use to display grouped and dynamic data by both the row and column level.
aggregation Use to build totals for tables and groups. Includes over 30 built-in functions like COUNT, SUM, MAX, MIN, AVE, RUNNINGSUM, COUNTDISTINCT, and RANK.

Chart types

Bar Chart1 Side-by-Side Bar Charts show bars from each series
one beside the other. These bars are arranged so that
they each have the same width. The width of the bars
depends on the number of series being plotted.
Stacked Bar Charts show bars stacked one above the
other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Bar Charts show bars stacked one
over the other in such a way that the total height of the
stacked bar (from its lowest to its highest) is 100%
Line Chart2 Overlay Line Charts show lines from each series
independent of the others. The lines are shown joining
the values for the series.
Stacked Line Charts show lines stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Line Charts show lines stacked one
over the other in such a way that the total height of the
stacked lines (from the lowest point to the highest in
each unit) is 100%
Area Chart3 Overlay Area Charts show areas from each series
independent of the others. The areas are shown
joining the values for the series.
Stacked Area Charts show areas stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Area Charts show areas stacked one
over the other in such a way that the total height of the
stacked areas (from the lowest point to the highest in
each unit) is 100%
Pie Chart4 Pie Charts show values as slices of a pie. The size of
each slice is proportional to the value it represents. Pie
charts for multiple series are plotted as multiple pies,
one for each series.
Meter Chart5 Standard Meter Charts contain a single dial with
region(s). The background of the dial can be divided
into regions with different colors.
Superimposed Meter Charts contain multiple dials
with identical regions. The dials overlap together so
that it can represent multiple needles within a single
region.
Scatter Chart6 Scatter Charts show the values arranged on the plot
using the category and value data as coordinates. Each
data value is indicated by a marker.
Stock Chart7 A Candlestick Stock Chart contains a box with lines
extending up and down from the ends. The upper and
lower edges of the box are the stock open and close
values. The upper and lower points of the line are the
high and low values.
A Bar-Stick Stock Chart contains a vertical line with
two horizontal lines sticking to it. The upper and lower
points of the vertical line are the stock open and close
values. The two horizontal lines are the high and low
values.
Bubble Chart8 Bubble Charts show the values arranged on the plot
using the category and value data as coordinates. Each
data value is indicated by a marker.
Difference Chart9 Difference Charts use two fills to represent the
positive and negative areas
Gantt Chart10 Standard Gantt Charts contain a connection line with
start and end markers.
Tube Chart1 Side-by-Side Tube Charts show tubes from each
series one beside the other. These tubes are arranged
so that they each have the same width. The width of
the tubes depends on the number of series being
plotted.
Stacked Tube Charts show tubes stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Tube Charts show tubes stacked
one over the other in such a way that the total height
of the stacked tube (from its lowest point to its highest)
is 100%
Cone Chart11 Side-by-Side Cone Charts show cones from each
series one beside the other. These cones are arranged
so that they each have the same width. The width of
the cones depends on the number of series being
plotted.
Stacked Cone Charts show cones stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Cone Charts show cones stacked
one over the other in such a way that the total height
of the stacked cone (from its lowest point to its highest)
is 100%
Pyramid Chart12 Side-by-Side Pyramid Charts show pyramids from
each series one beside the other. These pyramids are
arranged so that they each have the same width. The
width of the pyramids depends on the number of
series being plotted.
Stacked Pyramid Charts show pyramids stacked one
above the other. The positive and negative values are
stacked separately above and below the origin.
Percent Stacked Pyramid Charts show pyramids
stacked one over the other in such a way that the total
height of the stacked pyramid (from its lowest point to
its highest) is 100%

Hot Tip

Creating your first report:
  • Create a new Report Project from the category of Business Intelligence of Reporting Tools. Change to the Report Design perspective.
  • File -> New ->Report. Select the template called “My First Report” which launches a cheat sheet containing a step-by-step tutorial assisting you with connecting to data sources, creating data sets, and laying out your report.

Localization

BIRT supports internationalization of report data including support for bidirectional text. BIRT also supports the localization of static report elements within a report allowing you to replace report labels, table headers, and chart titles with localized text. BIRT uses resources files with name/value pairs and a *.properties file extension. For example, a file called MyLocalizedText_de.properties can include a line that says “welcomeMessage=Willkommen”. To use these files within a BIRT report:

Assign Resource File to entire report Report -> Properties -> Resources -> Resource File
Assign individual keys to a label Label -> Properties -> Localization -> Text key

Styles

Reports designed with the BIRT report designer can be richly formatted with styles that match your existing web application

Built-in Styles Built-in styles can be shared in a report library for managing style across multiple reports.
CSS Style Sheet BIRT can import CSS files at design time or reference existing CSS files at run time.

Report Parameters

A BIRT report can contain parameters that effect the report. Parameters can be supplied by the user or passed in programmatically from the application. Parameters can be bound to a data set query effectively filtering the report data. Parameters can also be used in expressions and scripting. For example, a parameter can be used with a visibility expression to hide a column or entire table. Available report parameter values can be supplied from a static list, dynamically created from a data set, or even cascading dynamic parameters. For example, selecting a Country presents the available States, and selecting a State presents the available Cities. Related parameters can be grouped for easier user navigation.

Parameter collection from the user can be in several forms:

Text Box Empty text area where the user can type the values desired
Combo/List Box A list of values is presented to the user. This list can be provided as a
static list or dynamically generated based on a data set query. multiple
values can be accepted.
Radio Button Provides boolean Yes/No, True/False, On/Off of parameters
Custom Parameters can be passed in programmatically so you can creae your
own web front end to collect the parameters from the user.

Customization wi th expressions, scripting and Events

BIRT includes out-of-the-box functionality that is available through drag-and-drop or by setting some properties, but also supports more advanced customizations through expressions, scripting, and events. The expression builder in BIRT allows you to do conditional report processing just about anywhere you need to instead of hard coding values. For example, the expression below will display the shipped date for orders that have already shipped, otherwise, it will display the order date.


if (dataSetRow[“STATUS”] == “Shipped”) {
  dataSetRow[“SHIPPEDDATE”];
} else {
  dataSetRow[“ORDERDATE”];
}

Scripting of a BIRT report can be done in either JavaScript or Java depending on your skill set and needs. Scripting allows you to circumvent the traditional event processing of the BIRT report. You can add scripting to report object, data source, and data element event types. Each of these event types has several events that you can overwrite.

For example, you can use scripting to navigate your Java objects and add them to a BIRT Data Set.


favoritesClass = new Packages.SimpleClass();
favorites = favoritesClass.readData();
…
var favrow = favorites.get(currentrow);
var Customer = favrow[0];
var Favorite = favrow[1];
var Color = favrow[2];
row[“Customer”]=Customer;
row[“Favorite”]=Favorite;
row[“Color”]=Color;

Use scripting to change bar colors on a chart based on plotted data.


if (dph.getOrthogonalValue() < 1000) {
  fill.set(255,0,0); //red
} else if (dph.getOrthogonalValue() < 5000) {
  fill.set(255,255,0); //yellow
} else {
  fill.set(0,255,0); //green
}

Use scripting to add or drop a report table based on a user parameter.


if (params[“showOrders”] == false){
  reportContext.getReportRunnable().designHandle.getDesignHandle()
    .findElement(“table1”).drop();
}

Or use scripting to include dynamic images that are based on the report data.


if (row[“CREDITLIMIT”] <= 0) {
“down.jpg”
} else {
“up.jpg”
}

Report deployment options

Once you create your report designs, there are several different ways to generate the report output. Obviously, you can run these reports directly from the BIRT Designer, but you can also run BIRT reports from the command line, generate BIRT reports from you Java application using the BIRT APIs, integrate and customize the example web viewer, or deploy your reports with third-party components and report servers.

APIs

BIRT supplies several APIs and an example J2EE application for generating and viewing reports. The major APIs are the Design Engine API(DE API), Report Engine API(RE API) and the Chart Engine API (CE API). In addition to the APIs, BIRT supports scripting using either Java or JavaScript within report designs.

Design Engine API(DE API) Use the Design Engine API (DE API) to create a custom report designer tool, or to explore or modify BIRT report designs. The BIRT Designer uses this API. You can call this API within a BIRT script to modify the currently running report design.
Report Engine API(RE API) Use the Report Engine API to run BIRT reports directly from Java code or to create a custom web application front end for BIRT.
Chart Engine API(CE API) Use the Chart Engine API to create and render charts apart from BIRT.

Birt report engine tasks

There are several tasks supplied by the Report Engine API that can be used to generate report output. A few key tasks are listed below.

IRunAndRenderTask Use this task to run a report and create the output directly to one of the supported output formats. This task does not create a report document.
IRunTask Use this task to run a report and generate a report document, which is saved to disk.
IGetParameterDefinitionTask Use this task to obtain information about parameters and their default values.
IDataExtractionTask Use this task to extract data from a report document. The BIRT viewer uses this class to extract report data into CSV format.

World ’s Simplest birt engine example


static void executeReport() throws EngineException
{
  IReportEngine engine=null;
  EngineConfig config = null;
try{
  // start up Platform
  config = new EngineConfig( );
  config.setBIRTHome(“C:\\BIRT_231\\birt-runtime-2_3_1\\
  ReportEngine”);
  config.setLogConfig(“C:\\BIRT_231\\logs”, java.util.logging.Level.
  FINEST);
  Platform.startup( config );
  // create new Report Engine
  IReportEngineFactory factory = (IReportEngineFactory) Platform
  .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_
  ENGINE_FACTORY );
  engine = factory.createReportEngine( config );
  // open the report design
  IReportRunnable design = null;
  design = engine.openReportDesign(“C:\\BIRT_231\\designs\\param
  .rptdesign”);
  // create RunandRender Task
  IRunAndRenderTask task = engine.createRunAndRenderTask(design);
  // pass necessary parameters
  task.setParameterValue(“ordParam”, (new Integer(10101)));
  task.validateParameters();
  // set render options including output type
  PDFRenderOption options = new PDFRenderOption();
  options.setOutputFileName(“my_report.pdf”);
  options.setOutputFormat(“pdf”);
  task.setRenderOption(options);
  // run task
  task.run();
  task.close();
  engine.destroy();
}catch( Exception ex){
	ex.printStackTrace();
}
finally
{
  Platform.shutdown( );
}


Hot Tip

If you are deploying the BIRT Engine within an RCP application you should NOT set the BIRT Home variable or execute the Platform.startup() method.

WEb Viewer

Web Viewer

The BIRT WebViewer is an example application that illustrates generating and rendering BIRT report output in a web application. This viewer demonstrates report pagination, an integrated table of contents, report export to several formats, and printing to local and server side printers.

The BIRT Web Viewer can be used in a variety of ways:

Stand-alone Use as a pre-built web application for running and viewing reports.
Modify Viewer Source Use as a starter web application that you can customize to your needs.
RCP Application Use as a plug-in for your existing RCP application.
Integrated with existing web application The viewer can be integrated with URLs or BIRT JSP tag library.

The BIRT Web Viewer consists of two main Servlets, the ViewerServlet and the BirtEngineServlet. These Servlets handle three mappings: (/frameset, /run, and /preview).

/frameset Renders the report in the full AJAX viewer, complete with toolbar, navigation bar
and table of contents features. This mapping also generates an intermediate
report document from the report design file to support the AJAX based features.
For example.
http://localhost:8080viewer/frameset?_report=myreport .rptdesign&parm1=value
/run Runs and renders the report but does not create a report document. This
mapping does not supply HTML pagination, TOC or toolbar features, but does
use the AJAX framework to collect parameters, support report cancelling and
retrieve the report output in HTML format. For example.
http://localhost:8080/viewer/run?_report=myreport.rptdesign&parm1=value)
/preview Runs and renders the report but does not generate a report document, although
an existing report document can be used; in this case, just the render operation
occurs. The output from the run and render operation is sent directly to the
browser. For example
http://localhost:8080/viewer/prevew?_report=myreport.rptdesign&parm1=value)

Viewer URL Parameters

Below are a few of the key URL parameters available for the viewer. These parameters can be used along with the Servlet mappings, such as, run, frameset, and preview, listed in the Web Viewer section.

Attribute Description
__id Unique identifier for the viewer.
__title Sets the report file.
__showtitle Determines if the report title is shown in the frameset viewer. Defaults to true. Valid values are true and false.
__toolbar Determines if the report toolbar is shown in the frameset viewer. Defaults to true. Valid values are true and false.
__navigationbar Determines if the navigation bar is shown in the framset viewer. Defaults to true. Valid values are true and false.
__parameterpage Determines if the parameter page is displayed. By default, the frameset, run, and preview mappings automatically determine if the parameter page is required. This setting overrides this behavior. Valid values are true and false.
__report Sets the name of the report design to process. This setting can be absolute path or relative to the working folder.
__document Sets the name for the rptdocument. The document is created when the report engine separates run and render tasks, and is used to support features like table of contents and pagination. This setting can be an absolute path or relative to the working folder.
__format Specifies the desired output format, such as pdf, html, doc, ppt, or xls.
__Locale Specifies the locale for the specific operation. Note that this setting overrides the default locale.
__page Specifies page to render.
__pagerange Specifies page range to render such as, 1-4, 7.
__bookmark Specifies a bookmark in the report to load. The viewer automatically loads the appropriate page.

Viewer Web.xml settings

The BIRT Web Viewer has several configuration options. These settings can be configured by modifying the web.xml file located in the WebViewerExample/WEB-INF folder. Below are a few of the key settings available for the viewer.

Attribute Description
BIRT_VIEWER
_LOCALE
This setting sets the default locale for the Web Viewer.
BIRT_VIEWER
_WORKING
_FOLDER
This is the default location for report designs. If the report design specified
in a URL parameter is relative, this path is pre-pended to the report name.
BIRT_VIEWER
_DOCUMENT
_FOLDER
If the __document parameter is not used, a report document is generated
in this location. If this setting is left blank, the default value, webapp/
documents, is used. If the__document URL parameter is used and the value
is relative, the report document is created in the working folder.
BIRT_VIEWER
_IMAGE_DIR
Specifies the default location to store temporary images generated by the
report engine. If this setting is left blank, the default location of webapp/
report/images is used.
BIRT_VIEWER
_LOG_DIR
Specifies the default location to store report engine log files. If this setting
is left blank, the default location of webapp/logs is used.
BIRT_VIEWER
_LOG_LEVEL
Sets the report engine log level. Valid values are:
OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, and FINEST.
BIRT_VIEWER
_SCRIPTLIB_DIR
Specifies the default location to place JAR files used by the script engine
or JARs containing Java event handlers. These JARs are appended to the
classpath. If this setting is left blank the default value of webapp/scriptlib
will be used.
BIRT_
RESOURCE_
PATH
This setting specifies the resource path used by report engine. The
resource path is used to search for libraries, images, and properties files
used by a report. If this setting is left blank, resources are searched for in
BIRT_VIEWER
_MAX_ROWS
Specifies the maximum number of rows to retrieve from a dataset
BIRT_VIEWER
_PRINT
_SERVERSIDE
This setting specifies whether server side printing is supported. If
set to OFF the toolbar icon used for server side printing is removed
automatically. Valid values are ON and OFF.

Viewer JSP Tag library

The BIRT Web Viewer includes a set of tags to make it easy to integrate BIRT reports into browser pages. These tags are available from the BIRT Web Tools Integration download. Below are a few the key JSP tags and a description of their usage.

Tag Description
viewer Displays the complete Viewer inside an IFRAME. This tag allows you to use frameset and run Servlet mappings. The AJAX Framework is used.
report Displays the report inside an IFRAME or DIV tag without the Viewer. This tag allows you to use preview mapping and does not create an rptdocument. The AJAX Framework is not used.
param Used to set parameter values when using the viewer or report tags. This tag must be nested within the viewer or report tag.
value Used to specify multiple values for a given param tag.
parameterPage Used to launch the BIRT parameter dialog or to create a customized parameter entry page. This tag can be used with the frameset, run, or preview mappings to launch the viewer after the parameters are entered.
paramDef Used within a parameterPage tag to retrieve pre-generated HTML for specific parameter control types such as radio, checkbox, dynamic or cascaded parameters

Simple viewer jsp tag example


<%@ taglib uri=”/birt.tld” prefix=”birt” %>
…
<birt:viewer
id=”birtViewer” pattern=”preview”
reportDesign=”TopNPercent.rptdesign”
height=”600” width=”800”
format=”html”
title=”My Viewer Tag”
isHostPage=”false”
showTitle=”true” showToolBar=”true”
showNavigationBar=”true”
showParameterPage=”true”>
</birt:viewer> 

BIRT REPORT OUTPUT FORMATS

In addition to delivering paginated report content to a web browser, BIRT also supports several other output formats. These formats listed below are support by both the Report Engine API as well as the BIRT Web Viewer.

Paginated web output An example web viewer is included with BIRT allowing for on demand paginated web output.
DOC Microsoft Word Document.
HTML Suitable for creating HTML pages of report data deployable to any server.
PDF Adobe PDF output suitable for emailing or printing.
Postscript Output can be directed to a printer that supports postscript.
PPT Powerpoint output.
XLS Excel file output.

Birt extension points

The APIs in BIRT define extension points that let the developer add custom functionality to the BIRT framework. These extensions can be in the form of custom data sources, report items, chart types, output formats, and functions. Once implemented, these custom extensions will show along with the built-in types. For example, you can create a custom report item, like a rotated text label, that will show up in the BIRT Palette along with the existing items.

Data Sources BIRT supports the Open Data Access (ODA) architecture, which means it can be extended to support custom data sources.
Functions BIRT allows you to create custom functions that extend those available in BIRT Expressions.
Report Items Report Items can be extended, allowing you to create your own custom report item.
Chart Types Additional chart types can be added to BIRT as plug-ins.
Output Emitters BIRT can be extended to include your own custom output type. For example, a simple CSV emitter exists and can be added to BIRT.

Additional Birt resources

Eclipse BIRT Project Site http://www.eclipse.org/birt
BIRT Exchange Community Site http://www.birt-exchange.com
Submitting/Searching BIRT Bugs http://bugs.eclipse.org/bugs/enter_bug.cgi?product=BIRT
Online BIRT Documentation http://www.birt-exchange.com/modules/documentation/

About The Author

Photo of author Virgil Dodson

Virgil Dodson

Virgil Dodson is a Developer Evangelist at Actuate Corporation and blogger/forum moderator at the BIRT Exchange community site. Virgil has over 13 years experience as a software developer. For the past 6 years he has helped Java developers get started with Actuate’s embedded reporting products. He holds a Bachelor of Science degree in Computer Information Systems from DeVry.

Recommended Book

Birt

Topics Discussed Include: Installing and deploying BIRT Deploying a BIRT report to an application server Understanding BIRT architecture Scripting in a BIRT report design Integrating BIRT functionality in applications Working with the BIRT extension framework


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Flex & Spring Integration

By Jon Rose and James Ward

14,378 Downloads · Refcard 48 of 151 (see them all)

Download
FREE PDF


The Essential Flex & Spring Integration Cheat Sheet

Adobe Flex Software is a popular framework for building Rich Internet Applications (RIAs). The Flex framework is used to create SWF files that run inside Flash Player. This DZone Refcard shows you how to integrate Flex and Spring to create a powerful platform for building robust RIAs. It starts off by showing you how to set up a server-side Java project with BlazeDS and the Spring Framework. After configuring your project with a basic Spring bean for use in BlazeDS, you’ll write your Flex application to use the Spring/BlazeDS service.
HTML Preview
Flex & Spring Integration

Flex & Spring Integration

By Jon Rose and James Ward

ABOUT Adobe Flex

Adobe Flex Software is a popular framework for building Rich Internet Applications (RIAs). The Flex framework is used to create SWF files that run inside Flash® Player. The framework was built for use by developers and follows traditional application development paradigms rather than the timelinebased development found in the Flash Professional authoring tools. Applications are built using the Flex Builder IDE™ - an Eclipse-based development environment. ActionScript® 3 is used to access data and build user interface components for web and desktop applications that run inside Flash Player or Adobe AIR® Software. The Flex Framework also uses a declarative XML language called MXML to simplify Flex development and layout.

ABOUT Spring

The Spring Framework is one of the most popular ways to build enterprise Java applications. Unlike traditional Java EE development, Spring provides developers a full featured “lightweight container,” that makes applications easy to test and develop. Although Spring is best known for its dependency injection features, it also provides features for implementing typical server-side enterprise applications, such as declarative security and transaction management.

WHy Flex and Spring?

Adobe Flex has strong ties to Java, which include an Eclipsebased IDE and BlazeDS, its open source server-based Java remoting and web messaging technology. In addition, most enterprise projects that use Flex build on a Java back end. With Flex and Java so often married together, it is only natural to want to integrate Flex with Spring-based Java back ends. Beyond greenfield development, many organizations want to revamp or replace the user interface of existing enterprise Spring applications using Flex. In late 2008, the Spring community recognized these cases and began working on the Spring BlazeDS Integration project to add support for Flex development with Java and Spring.

By default BlazeDS creates instances of server-side Java objects and uses them to fulfill remote object requests. This approach doesn’t work with Spring, as the framework is built around injecting the service beans through the Spring container. The Spring integration with BlazeDS allows you to configure Spring beans as BlazeDS destinations for use as remote objects in Flex.

Integrating Flex and spring

This Refcard assumes that you are already familiar with Spring and Flex. If you need an introduction or refresher to either, check out the Very First Steps in Flex and/or Spring Configuration DZone Refcardz.

To use BlazeDS, the server-side application could be any Java application that deploys as a WAR file. This Refcard uses the Eclipse IDE to create and edit the Java project. This Refcard walks you through the following steps:

  • Set up a server-side Java project with BlazeDS and the Spring Framework
  • Configure the Java project with a basic Spring bean for use in BlazeDS
  • Write Flex application to use the Spring/BlazeDS service

Hot Tip

BlazeDS provides simple two-way communication with Java back-ends. Adobe Flash Player supports a serialization protocol called AMF that alleviates the bottlenecks of text-based protocols and provides a simpler way to communicate with servers. AMF is a binary protocol for exchanging data that can be used over HTTP in place of text-based protocols that transmit XML. Applications using AMF can eliminate an unnecessary data abstraction layer and communicate more efficiently with servers. To see a demonstration of the performance advantages of AMF, see the Census RIA Benchmark at: http://www.jamesward.org/census.The specification for AMF is publicly available, and numerous implementations of AMF exist in a variety of technologies including Java, .Net, PHP, Python, and Ruby.

Hot Tip

The open source BlazeDS project includes a Java implementation of AMF that is used for remotely communicating with server-side Java objects as well as for a publish/subscribe messaging system. The BlazeDS remoting technology allows developers to easily call methods on Plain Old Java Objects (POJOs), Spring services, or EJBs. Developers can use the messaging system to send messages from the client to the server, or from the server to the client. BlazeDS can also be linked to other messaging systems such as JMS or ActiveMQ. Because the remoting and messaging technologies use AMF over HTTP, they gain the performance benefits of AMF as well as the simplicity of fewer data abstraction layers. BlazeDS works with a wide range of Javabased application servers, including Tomcat, WebSphere, WebLogic, JBoss, and ColdFusion.

To follow along with this tutorial you will need:

First, set up the server-side Java web project in Eclipse by creating a web application from the blazeds.war file (found inside the blazeds zip file).

  • Import the Blazeds.war file to create the project:
    • Choose File > Import
    • Select the WAR file option. Specify the location of the blazeds.war file. For the name of the web project, type dzone-server
    • Click Finish

Now you can create a server that will run the application:

  • Select File > New > Other
  • Select Server > Server
  • Click Next
  • Select Apache > Tomcat v6.0Server
  • Click Next
  • Specify the location where Tomcat is installed and select the JRE (version 5 or higher) to use
  • Click Next
  • Select dzone-server in the Available Projects list
  • Click Add to add it to the Configured Projects list
  • Click Finish

Next, in the dzone-server project create the basic Java classes to be used by BlazeDS and Spring:


public class MyEntity {
  private String firstName;
  private String lastName;
  private String emailAddress;
  public String getFirstName() {
   return firstName;
  }
public void setFirstName(String firstName) {
  this.firstName = firstName;
  }
public String getLastName() {
  return lastName;
  }
public void setLastName(String lastName) {
  this.lastName = lastName;
  }
public String getEmailAddress() {
  return emailAddress;
  }
public void setEmailAddress(String emailAddress) {
  this.emailAddress = emailAddress;
  }
}

Listing 1: Java entity to be passed between Java and Flex


import java.util.List;
public interface MyService {
  public List<MyEntity> getMyEntities();
}

Listing 2: Java Service Interface


import java.util.ArrayList;
import java.util.List;
public class MyServiceImpl implements MyService {
  public List<MyEntity> getMyEntities() {
   List<MyEntity> list = new ArrayList<MyEntity>();
   MyEntity entity = new MyEntity();
   entity.setFirstName(“Hello”);
   entity.setLastName(“World”);
   entity.setEmailAddress(“hello@world.com”);
   list.add(entity);
   MyEntity entity2 = new MyEntity();
   entity2.setFirstName(“Hello”);
   entity2.setLastName(“Space”);
   entity2.setEmailAddress(“hello@space.com”);
   list.add(entity2);
   MyEntity entity3 = new MyEntity();
   entity3.setFirstName(“Hello”);
   entity3.setLastName(“Neighbor”);
   entity3.setEmailAddress(“hello@neighbor.com”);
   list.add(entity3);
   return list;
  }
}

Listing 3: Java Example Service Implementation

Listings 1, 2, and 3 are very basic Java classes that you’ll use as examples for this tutorial. In a real-world application, the service implementation would likely connect to one or more enterprise services for data, such as a relational database. In this case, it simply returns a hard-coded set of entities as an ArrayList.

The basic Java web project with the BlazeDS dependencies is now complete.

Next, configure the Java project with a basic Spring bean for the MyService interface:

  • Copy the Spring libraries, the Spring BlazeDS Integration Library, and the ANTLR library to the project dzoneserver/ WebContent/WEB-INF/lib directory
  • Create a basic Spring Configuration File:
    • Right Click WebContent/WEB-INF and then choose New > File
    • For the file name, type application-config.xml
    • Click Finish
    • Copy and paste the text from Listing 4 into the file

<?xml version=”1.0” encoding=”UTF-8”?>
 <beans xmlns=”http://www.springframework.org/schema/beans”
 xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
 xsi:schemaLocation=”
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”>
 <!-- Spring Beans’s -->
 <bean id=”myService” class=”MyServiceImpl” />
</beans>

Listing 4: Basic Spring Configuration

Those familiar with Spring should recognize this as a basic Spring configuration for creating a simple bean from the MyServiceImpl class. Later in this tutorial you will be using this bean through BlazeDS.

At this point, you have a basic Java web project with a default BlazeDS configuration. Now, you’ll change the default BlazeDS configuration to use the newly created Spring bean.

To begin configuring Spring BlazeDS Integration, update the web.xml file by removing the default BlazeDS configuration and replacing it with the code from Listing 5.


<>?xml version=”1.0” encoding=”UTF-8”?>
<>web-app>
 <>display-name>dzone-server<>/display-name>
 <>servlet>
   <>servlet-name>Spring MVC Dispatcher Servlet<>/servlet-name>
   <>servlet-class>
   org.springframework.web.servlet.DispatcherServlet
   <>/servlet-class>
   <>init-param>
    <>param-name>contextConfigLocation<>/param-name>
    <>param-value>/WEB-INF/application-config.xml<>/param-value>
   <>/init-param>
   <>load-on-startup>1<>/load-on-startup>
  <>/servlet>
  <>!-- Map /spring/* requests to the DispatcherServlet -->
  <>servlet-mapping>
   <>servlet-name>Spring MVC Dispatcher Servlet<>/servlet-name>
   <>url-pattern>/spring/*<>/url-pattern>
  <>/servlet-mapping>
<>/web-app>

Listing 5: web.xml

The web.xml contents in Listing 5 create a servlet filter from Spring that will process all BlazeDS requests at: http://localhost:8080/dzone-server/spring This will be the base URL for accessing the BlazeDS endpoint. Also, you should notice that this is a standard DispatcherServlet for Spring.

Now that you have Spring wired into the Java web application, you will update the basic Spring configuration from Listing 4 so that it will work with BlazeDS. Add the highlighted section from Listing 6 to your application-config.xml file.


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
 xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
 xmlns:flex=”http://www.springframework.org/schema/flex”
 xsi:schemaLocation=”
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/flex
 http://www.springframework.org/schema/flex/spring-flex-1.0.xsd”>
 <!-- Spring Beans’s -->
 <bean id=”myService” class=”MyServiceImpl” />
 <!-- Simplest possible message broker -->
 <flex:message-broker />


 <!-- exposes myService as BlazeDS destination -->
 <flex:remote-service ref=”myService” />
</beans>

Listing 6: Advanced Spring Configuration for BlazeDS

Listing 6 exposes the MyServiceImpl class as a BlazeDS destination. First, the Flex® namespace is added to the configuration. Note that the XSD will not be published from Spring until the final 1.0 release, and until then you will have to add it manually to your XML catalog. With the Flex namespace added, the configuration uses the messagebroker tag to create the MessageBrokerFactoryBean. Since there is no additional configuration information provided, the MessageBroker will be created with “sensible defaults,” assuming that the service-config.xml is in WEB-INF/flex/ services-config.xml. The remote-service tag creates a destination from existing Spring beans.

Hot Tip

In Spring BlazeDS Integration release 1.0.0M2, the standard BlazeDS configuration file (servicesconfig. xml) is still used for configuration of the communication channels.

Next, update the default BlazeDS services-config.xml file (found in the WebContent/WEB-INF/flex folder) to reflect the Spring URL defined in the web.xml file. Replace the contents of the file with the code in Listing 7.


<?xml version=”1.0” encoding=”UTF-8”?>
  <services-config>
   <services>
    <default-channels>
     <channel ref=”my-amf”/>
   </default-channels>
  </services>
 <channels>
<channel-definition id=”my-amf”
class=”mx.messaging.channels.AMFChannel”>
  <endpoint
   url=”http://{server.name}:{server.port}/{context.root}/spring/
    messagebroker/amf”
   class=”flex.messaging.endpoints.AMFEndpoint”/>
  </channel-definition>
 <channel-definition id=”my-polling-amf”
class=”mx.messaging.channels.AMFChannel”>
<endpoint
  url=”http://{server.name}:{server.port}/{context.root}/spring/
   messagebroker/amfpolling”
    class=”flex.messaging.endpoints.AMFEndpoint”/>
     <properties>
    <polling-enabled>true</polling-enabled>
  <polling-interval-seconds>4</polling-interval-seconds>
 </properties>
</channel-definition>
</channels>
</services-config>

Listing 7: Update channel definition in services-config.xml

Note that the endpoint URL for the my-amf and my-polling-amf channels in Listing 7 include “spring” after the context.root parameter. This is the only configuration change you need to make in the BlazeDS default configuration files. All the remote destinations are configured in the Spring application-config. xml file.

You are now done configuring the server-side Spring / BlazeDS Java application. You may want to start up the Tomcat server to verify that your configuration is correct.

Now you can build the Flex application to use the Spring service remotely. Follow these steps to create the Flex project:

  • Select File > New > Other
  • In the Select A Wizard dialog box, select Flex Project
  • In the New Flex Project box, type in a project name: dzone-flex
  • Use the default location (which will already be checked)
  • Select Web Application (Runs In Flash Player)
  • Select None as the Application Server Type
  • Click Next
  • Specify the Output folder to be the location of the dzoneserver’s WebContent directory such as: C:\workspace\dzone-server\WebContent\
  • Click Finish

Your project will open in the MXML code editor and you’ll see a file titled main.mxml. Open the file and add the Flex® application code from Listing 8. This code accesses the MyServiceImpl class in Java and returns the results to Flex.


<?xml version=”1.0” encoding=”utf-8”?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”
   creationComplete=”srv.getMyEntities()”>
  <mx:AMFChannel id=”myamf”
uri=”/dzone-server/spring/messagebroker/amf”/>
  <mx:ChannelSet id=”channelSet” channels=”{[myamf]}”/>
 <mx:RemoteObject id=”srv”
  destination=”myService” channelSet=”{channelSet}”/>
 <mx:DataGrid dataProvider=”{srv.getMyEntities.lastResult}”/>
</mx:Application>

Listing 8: Final main.mxml source file for accessing the Spring service

The code in Listing 8 sets up the AMFChannel for accessing the Spring service. Note that the destination “flexMyService” is the same as the bean you defined in the application-config. xml Spring configuration file. Also, you might have noticed that none of the Flex code contains anything specific to Spring. The Flex code doesn’t have to change, as the client code has no knowledge of the fact that Spring is being used on the server.

To get the dzone-server to update the deployed web application you may need to right-click the dzone-server project and select Refresh.

With all steps of the tutorial completed, you can start the Tomcat server in Eclipse and access the application at the following URL: http://localhost:8080/dzone-server/main.html

Running Application

Figure 1: The running application

To allow the Flex application to be launched in Run or Debug mode from Eclipse:

  • Right-click the dzone-flex project
  • Select Properties, then Flex Build Path
  • For the Output Folder URL, type http://localhost:8080/dzone-server/
  • Click OK to update the project properties

Now you can right-click the main.mxml file and select Run As > Flex Application or Debug As > Flex Application.

The running application displays the data that was hard coded in the MyServiceImpl Java class, as seen in Figure 1. Now you have a complete sample application using Spring, BlazeDS, and Flex

User Authentication

One of the benefits of using Spring is that it provides support for many common enterprise requirements, including security. In this section, you’ll expand on the basic application by using Spring Security to protect the service channel with role-based authentication.

To add security to the application you will need to download the following dependencies:

Then add the following files to the WEB-INF/lib directory in the dzone-server project:

  • cglib-2.2.jar
  • aspectjrt.jar (located in the aspectj.jar file)
  • asm-3.1.jar
  • asm-commons-3.1.jar
  • spring-security-acl-2.0.4.jar
  • spring-security-core-2.0.4.jar
  • spring-security-core-tiger-2.0.4.jar

<beans:beans xmlns=”http://www.springframework.org/schema/security”
 xmlns:beans=”http://www.springframework.org/schema/beans”
 xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
 xsi:schemaLocation=”
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-
 2.0.4.xsd”>
<http auto-config=”true” session-fixation-protection=”none”/>
 <authentication-provider>
  <user-service>
   <user name=”jeremy” password=”atlanta”
  authorities=”ROLE_USER, ROLE_ADMIN” />
 <user name=”keith” password=”melbourne”
authorities=”ROLE_USER” />
</user-service>
</authentication-provider>
</beans:beans>

Listing 9: application-Context-security.xml Spring Security Configuration File

The first step is to create a very basic Spring Security configuration file. This example will use hard-coded credentials, however in a real application a database or LDAP server will likely be the source of the credentials. These methods of authentication can be easily configured with Spring Security. To learn more about Spring Security and how to add more advanced configurations, see the project home page at: http://static.springframework.org/spring-security/site/

To create a basic Spring Security Configuration File:

  • Right-click WebContent/WEB-INF and then choose New > File
  • For the file name, type applicationContext-security.xml
  • Click Finish
  • Copy the code from Listing 9 to the file

This configuration allows the user to authenticate through the Blaze DZ channel. Add the security configuration to the Spring configuration in the web.xml by updating the contextConfigLocation param-value as shown in Listing 10.


<servlet>
 <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</
  servlet-class>
 <init-param>
  <param-name>contextConfigLocation
  <param-value>
     /WEB-INF/application-config.xml
     /WEB-INF/applicationContext-security.xml
   </param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

Listing 10: web.xml File with Security Configuration Added

At this point, you need to update the Spring configuration file to secure the getMyEntities method on myService. To do this update the application-config.xml file with the code in Listing 11.


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
  xmlns:flex=”http://www.springframework.org/schema/flex”
  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  xmlns:security=”http://www.springframework.org/schema/security”
  xsi:schemaLocation=”
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/flex
  http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
  http://www.springframework.org/schema/security
  http://www.springframework.org/schema/security/spring-security-
2.0.4.xsd
  “>
  <flex:message-broker>
   <flex:secured />
  </flex:message-broker>
  <bean id=”myService” class=”MyServiceImpl”>
   <flex:remote-service/>
   <security:intercept-methods>
   <security:protect method=”getMyEntities” access=”ROLE_USER” />
  </security:intercept-methods>
 </bean>
</beans>

Listing 11: Updated application-config.xml Spring configuration file

If you run the Flex® application at this point, the getMyEntities service call will fail because the user is not authenticated.

Now that the server is configured to protect the service, you will update the Flex application to require the user to authenticate before loading data from the getMyEntities service method. The updated code shown in Listing 12 presents users with a login form (See Figure 2) until they are successfully authenticated. Once the user is authenticated, the view state is updated showing the DataGrid bound to the service results, and the service method is called.

Update the main.mxml page with the code in Listing 12. You can then run the application and login with one of the hard-coded username and password combinations from the applicationContext-security.xml configuration file.


<?xml version=”1.0” encoding=”utf-8”?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
  import mx.rpc.events.ResultEvent;
  import mx.rpc.events.FaultEvent;
  import mx.rpc.AsyncToken;
  import mx.rpc.AsyncResponder;
private function login():void {
var token:AsyncToken = channelSet.login(username.text, password.
text);
token.addResponder(new AsyncResponder(loginResult, loginFault));
}
private function loginResult(event:ResultEvent,
token:AsyncToken):void {
   //get data
   srv.getMyEntities();
   //change state
   currentState = “userAuthenticated”;
 }
 private function loginFault(event:FaultEvent, token:AsyncToken):void
{
invalidLogin = true;
}
</mx:Script>
<mx:AMFChannel id=”myamf”
uri=”/dzone-server/spring/messagebroker/amf”/>
<mx:ChannelSet id=”channelSet” channels=”{[myamf]}”/>
<mx:RemoteObject id=”srv”
destination=”myService” channelSet=”{channelSet}”/>
<mx:Boolean id=”invalidLogin”>false
<!-- Login Form -->
<mx:Panel id=”loginPanel” title=”Login Form”>
<mx:Label text=”Invalid username or password”
includeInLayout=”{invalidLogin}” visible=”{invalidLogin}” />
  <mx:Form defaultButton=”{loginButton}”>
   <mx:FormItem width=”100%” label=”Username”>
    <mx:TextInput id=”username”/>
   </mx:FormItem>
  <mx:FormItem width=”100%” label=”Password”>
 <mx:TextInput id=”password” displayAsPassword=”true” />
  </mx:FormItem>
    </mx:Form>
     <mx:ControlBar>
    <mx:Button id=”loginButton” label=”Login” click=”login()”/>
   </mx:ControlBar>
  </mx:Panel>
<mx:states>
 <mx:State name=”userAuthenticated”>
   <mx:RemoveChild target=”{loginPanel}” />
    <mx:AddChild>
   <mx:DataGrid dataProvider=”{srv.getMyEntities.lastResult}” />
  </mx:AddChild>
</mx:State>
</mx:states>
</mx:Application>

Listing 12: Update Flex Application

The Flex code in Listing 12 is very basic. It presents the user with the loginPanel until loginResult() is invoked by a successful login. The username and password parameters come from a login form and are passed to the channelSet’s login() method. On a successful login, the loginResult() handler function is called, and the post-login logic is invoked. In this case, the currentState is updated to userAuthenticated, which removes the login form and adds the DataGrid bound to the service call’s results. In addition, the getMyEntities service method is called to load the data.

Login Form

Now, you have a basic Flex®, Spring, and BlazeDS application protected with authentication.

Conclusion

In this Refcard, you first created a Spring bean that was exposed to the Flex client through BlazeDS using Spring BlazeDS Integration. Next, you secured your service by adding Spring Security, and basic Flex authentication. As you can see, the new Spring BlazeDS Integration project makes integrating Flex and Spring easy and straightforward. The combination of the two technologies creates a powerful platform for building robust RIAs. You can learn more about integrating Flex and Spring on the Spring BlazeDS Integration project site: http://www.adobe.com/devnet/flex/flex_java.html

About The Author

Photo of author Jon Rose

Jon Rose

Jon Rose is the Flex Practice Director for Gorilla Logic, an enterprise software consulting company located in Boulder, Colorado. He is an editor and contributor to InfoQ.com, an enterprise software community. Visit his website at: www.ectropic.com

Gorilla Logic, Inc. provides enterprise Flex and Java consulting services tailored to businesses in all industries. www.gorillalogic.com

Photo of author James Ward

James Ward

James Ward is a Technical Evangelist for Flex at Adobe. He travels the globe speaking at conferences and teaching developers how to build better software with Flex. Visit his websit at: www.jamesward.com

First Steps in Flex, co-authored by James, will give you just enough information, and just the right information, to get you started learning Flex--enough so that you feel confident in taking you own steps once you finish the book. For more information visit: http://www.firststepsinflex.com

Recommended Book

First Steps in Flex

First Steps in Flex will take you through your first steps on your way to becoming a powerful user interface programmer.

We’ve gone to great lengths to show you the world of Flex without burying you in information you don’t need right now. At the same time, we give pointers to places where you can go to explore more.

First Steps in Flex is the ideal starting point for any programmer who wants to quickly become proficient in Flex 3.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Core ASP.NET

By Holger Schwichtenberg

16,352 Downloads · Refcard 46 of 151 (see them all)

Download
FREE PDF


The Essential ASP.NET Cheat Sheet

ASP.NET stands for “Active Server Pages .NET”, which is a framework for the development of dynamic websites and web services. This DZone Refcard summarizes the most commonly used core functions and controls in ASP.NET. Author Holger Schwichtenberg shows you how to set up your ASP.NET development environment, explains the Webform model, and showcases common WebControls for Lists and Validation. He also explores ASP.NET state management features, configuration file management and shows the typical content of an .aspx page. This Refcard is useful for some of the most common tasks with ASP.NET, regardless of version number.
HTML Preview
Core ASP.NET

Core ASP.NET

By Holger Schwichtenberg

ABOUT ASP.NEt

ASP.NET stands for “Active Server Pages .NET”, however the full name is rarely used. ASP.NET is a framework for the development of dynamic websites and web services. It is based on the Microsoft .NET Framework and has been part of .NET since Version 1.0 was released in January 2002. The current version named 3.5 Service Pack 1 was released in August 2008. The next version, 4.0, is expected to be released at the end of the year 2009.

This Refcard summarizes the most commonly used core functions of ASP.NET. You will find this Refcard useful for some of the most common tasks with ASP.NET, regardless of the version you are using

Instalation

The best development environment for ASP.NET is Microsoft’s Visual Studio. You can either use the free Visual Web Developer Express Edition (http://www.microsoft.com/express/ vwd/) or any of the commercial editions of Visual Studio (e.g. Visual Studio Professional). The latest version that supports ASP.NET 2.0 and ASP.NET 3.5 is “2008” (internal version: 9.0). The .NET Framework and ASP.NET are part of the setup of Visual Web Developer Express Edition and Visual Studio. However, make sure you install Service Pack 1 for Visual Studio 2008, as this will not only fix some bugs but also add a lot of new features.

ASP.NET needs a server with the HTTP protocol (web server) to run. Visual Web Developer Express 2005/2008 and Visual Studio 2005/2008 contain a webserver for local use on your development machine. The “ASP.NET Development Server” (ADS) will be used when specifying a “File System” location when creating your project. Thus, “HTTP” would mean you address a local or remote instance of Internet Information Server (IIS) or any other ASP.NET enabled web server. ADS is a lightweight server that cannot be reached from other systems. However, there are differences between ADS and IIS, especially in the security model that makes it sometimes hard for beginners to deploy a website to the IIS that was developed with ADS. On the production system you will use IIS and only install the .NET Framework, because Visual Studio is not required here.

Hot Tip

If you choose to use Internet Information Server (IIS), install the IIS on your machine before installing the .NET Framework or Visual Studio. If you did not follow this installation order, you may use aspnet_regiis. exe to properly register ASP.NET within the IIS.

ASP.NEt Web Applications

An ASP.NET application consists of several .aspx files. An .aspx file can contain HTML markup and special ASP.NET markup (called Web Controls) as well as the code (Single Page Model). However, the Code Behind Model which comes with a separate code file called, the “Code Behind File” (.aspx. cs or .aspx.vb), provides a cleaner architecture and better collaboration between Web designers and Web developers. ASP.NET applications may contain several other elements such as configuration files (maximum one per folder), a global application file (only one per web application), web services, data files, media files and additional code files.

There are two types of Web projects: “Website Projects” (File/ New/Web Site) and “Web Application Projects” (File/New/ Project/Web Application). “Website” is the newer model, while Web Application Projects mainly exist for compatibility with Visual Studio .NET 2002 and 2003. This Refcard will only cover Web Site Projects. Most of this content is also valid for Web Applications.

Hot Tip

A well designed ASP.NET application distinguishes itself by having as little code in the Code Behind files and other code files as possible. The large majority of your code should be in referenced Assemblies (DLLs) as they are reusable in other Web applications. If you don’t want to put your code into a separate assembly, you at least should use separate classes in the “App_Code” folder within your web project.
Figure 1

Figure 1: The Content of an ASP.NET Web Application

The ASP.NET Web form Model

ASP.NET uses an object- and event-oriented model for web pages. The ASP.NET Page Framework analyzes all incoming requests as well as the .aspx page that the request is aimed at. The Page Framework creates an object model (alias control tree) based on this information and also fires a series of events. Event handlers in your code can access data, call external code in referenced .NET assemblies and manipulate the object model (e.g. fill a listbox or change the color of a textbox). After all event handlers have executed, the Page Framework renders the current state of the object model into HTML tags with optional CSS formatting, JavaScript code and state information (e.g. hidden fields or cookies). After interacting with the page, the user can issue a new request by clicking a button or a link that will restart the whole process.

Figure 2

Figure 2: The ASP.NET request/response life cycle

Web Controls

An ASP.NET page can contain common HTML markup. However, only ASP.NET web controls provide full objectand event-based functionality. Web controls have two representations: In the .aspx files they are tags with the prefix “asp:”, e.g. . In the code they are .NET classes, e.g. System.Web.UI.WebControls.TextBox.

Table 1 lists the core members of all web controls that are implemented in the base class “System.Web.UI.WebControls. WebControl”.

Name of Member Description
Id Unique identifier for a control within a page
ClientID Gets the unique identifier that ASP.NET generates if more than one control on the page has the same (String) ID.
Page Pointer to the page where the control lives
Parent Pointer to the parent control, may be the same as “Page”
HasControls() True, if the control has sub-controls
Controls Collection of sub-controls
FindControl(“NAME”) Finds a sub-control within the Controls collection by its ID
BackColor, BorderColor,
Borderstyle, BorderWidth,
Font, ForeColor, Height,
Width, ToolTip, TabIndex
Self-explaining properties for the formatting of the control.
CssClas The name of CSS class that is used for formatting the control
Style A collection of single CSS styles, if you don’t want to use a CSS class or override behavior in a CSS class
EnableViewState Disables page-scoped state management for this control
Visible Disables rendering of the control
Enabled Set to false if you want the control to be disabled in the browser
Focus() Set the focus to this control
DataBind() Gets the data (if the control is bound to a data source)
Init() Fires during initializtion of the page. Last chance to change basic setting e.g. the culture of the current thread that determines the behavior used for rendering the page.
Load() Fires during the loading of the page. Last to change to do any preparations./td>
PreRender() Fires after all user defined event handlers have completed
and right before rendering of the page starts. Your last
chance to make any changes to the controls on the page!
UnLoad() Event fires during the unloading of a page.

Table 1: Core Members in the base class system. Web.UI.WebControls.WebControl.

Tables 2, 3 and 4 list the most commonly used controls for ASP. NET web pages. However, there are more controls included in the .NET platform and many more from third parties not mentioned here.

Control Purpose/strong> Important specific members in
addition to the members inheritedn
from WebControl
<asp:Label> Static Text Text
<asp:TextBox> Edit Text (single line,
multiline or password)
TextMode, Text, TextChanged()
<asp:FileUpload> Choose a file for upload FileName, FileContent, FileBytes,SaveAs()
<asp:Button> Display a clasic button Click(), CommdName, Command()
<asp:ImageButton> Display a clickable image Click(), CommdName, Command()
<asp:LinkButton> Display a hyperlink that works like a button ImageUrl, ImageAlign, Click(),
CommdName, Command()
<asp:CheckBox> Choose an option Text, Checked, CheckedChanged()
<asp:RadioButton> Choose an option Text, Checked, CheckedChanged()
<asp:HyperLink> Display a hyperlink NavigateURL, Target, Text
<asp:Image> Display an image ImageURL, ImageAlign
<asp:ImageMap> Display a clickable
image with different
regions
ImageURL, ImageAlign,

Table 2: Core controls for ASP.NET web pages.

List controls display several items that the user can choose from. The selectable items are declared static in the .aspx file or created manually using the Items collection or created automatically by using data binding. For data binding you can fill DataSource with any enumerable collection of .NET objects. DataTextField and DataValueField specify which properties of the objects in the collection are used for the list control.

Hot Tip

If you bind a collection of primitive types such as strings or numbers, just leave DataTextField and DataValueField empty.

Hot Tip

Setting AppendDataBoundItems to true will add the databound items to the static items declared in the .aspx file. This will allow the user to select values that don’t exist in the data source such as the values “All” or “None”
Control Purpose Important specific members in
addition to the members inherited
from WebControl
<asp:Drop DownList> Allows the user to select
a single item from a
drop-down list
Items.Add(), Items.
Remove(), DataSource,,
DataTextField, DataValueField,
AppendDataBoundItems,
SelectedIndez, SelectedItem,
SelectedValue, SelectedIndexChanged()
<asp:ListBox> Single or multiple selection box Items.Add(), Items.
Remove(), DataSource,,
DataTextField, DataValueField,
AppendDataBoundItems,
SelectedIndez, SelectedItem,
SelectedValue, SelectedIndexChanged(),
Rows, SelectionMode
<asp:Check BoxList> Multi selection check box group Items.Add(), Items.
Remove(), DataSource,,
DataTextField, DataValueField,
AppendDataBoundItems,
SelectedIndez, SelectedItem,
SelectedValue, SelectedIndexChanged(),
RepeatLayout, RepeatDirection
<asp:Radio ButtonList> Single selection radio button group Items.Add(), Items.
Remove(), DataSource,,
DataTextField, DataValueField,
AppendDataBoundItems,
SelectedIndez, SelectedItem,
SelectedValue, SelectedIndexChanged(),
RepeatLayout, RepeatDirection
<asp:Bulleted List> List of items in a bulleted format Items.Add(), Items.
Remove(), DataSource,,
DataTextField, DataValueField,
AppendDataBoundItems,
SelectedIndez, SelectedItem,
SelectedValue, SelectedIndexChanged(),
BulletImageUrl, BulletStyle

Table 3: List Controls for ASP.NET web pages

Validation Controls check user input. They always refer to one input control ControlToValidate and display a text ErrorMessage if the validation fails. They perform the checks in the browser using JavaScript and also on the server. The client side validation can be disabled by setting EnableClientScript to false. However, the server side validation cannot be disabled for security reasons.

Control Purpose Important specific members
in addition to the members
inherited from WebControl
<asp:Required
FieldValidator>
Checks if a user changed the
initial value of an input control
ControlToValidate, ErrorMessage,
Display, EnableClientScript,
IsValid, InitialValue
<asp:Compare
Validator>
Compares the value entered by
the user in an input control with
the value entered in another
input control, or with a constant
value
ControlToValidate, ErrorMessage,
Display, EnablesClientScript,
IsValid, ValueToCompare, Type,
ControlToCompare
<asp:Range
Validator>
Checks whether the value of
an input control is within a
specified range of values
ControlToValidate, ErrorMessage,
Display, EnableClientScript,
IsValid, MinimumValue,
MaximumValue, Type
<asp:Regular
Expression Validator>
Checks if the user input
matches a given regular
ControlToValidate, ErrorMessage,
Display, EnavleClientScript,
IsValid, ValidationExpression
<asp:Custom
Validator>
Performs custom checks on the
server and optional also on the
client using JavaScript
ControlTValidate, ErrorMessage,
Display, EnableClientScript,
IsValid, ValidateEmptyText,
Client ValidationFunction,
ServerValidate()

Hot Tip

For the CustomValidator you can optionally write a JavaScript function that performs client side validation. The function has to look like this: <script type=”text/javascript”> function ClientValidate(source, args) { if (x > 0) // Any condition { args.IsValid=true; } else { args.IsValid=false; } } </script>

The Page Class

All web pages in ASP.NET are .NET classes that inherit from the base class “System.Web.UI.Page”. The class Page has associations to several other objects such as Server, Request, Response, Application, Session and ViewState (see figure 3). Therefore, developers have access to a wide array of properties, methods and events within their code. Table 5 lists the most important members of a Page and its dependent classes. Please note that the Page class has the class Control in its inheritance hierarchy and therefore shares a lot of members with the WebControl class (e.g. Init(), Load(), Controls, FindControl). However, these members are not repeated here.

Figure 3

Figure 3: Object Model of “System.Web.UI.Page”

Member Description
Page Title Title string of the Page
Page.IsPostBack True, if page is being loaded in response to a client postback. False if it is being loaded for the first time.
Page.IsAsync True, if the page is loaded in an asynchronous request (i.e. AJAX request)
Page.IsValid True, if all validation server controls in the current validation group validated successfully
Page.Master Returns the MasterPage object associated with this page
Page.PreviousPage Gets the page that transferred control to the current page (only available if using Server.Transfer, not available with Response. Redirect)
Page.SetFocus(Control ControlID) Sets the browser focus to the specified control (using JavaScript)
Trace.Write Writes trace information to the trace log.
User.Identity.IsAuthenticated True, if the user has been authenticated.
User.Identity.AuthenticationType Type of Authentication used (Basic, NTLM, Kerberos, etc)
User.Identity.Name Name of the current user
Server.MachineName Name of the computer the web server is running on
Server.GetLastError() Gets the Exception object for the last exception
Server.HtmlEncode(Text) Applies HTML encoding to a string
Server.UrlEncode(Pah) Applies URL encoding to a string
Server.MapPath(Path) Maps the given relative path to an absolute path on the web server
Server.Transfer(Path) Stops the execution of the current page and starts executing the given page as part of the current HTTP request
Request.AcceptTypes String array of cliet-supported MIME accept types.
Request.Browser Provides information about the browser
Request.ClientCertificate Provides the certificate of the client, if SSL client authentication is used
Request.Cookies The list of cookies that the browser sent to the web server
Request.Form The name and value of the input fields the browser sent to the web server
Request.Headers Data from the HTTP header the browser sent to the web server
Request.IsAuthenticated True, if the user is authenticated
Request.IsSecureConnection True, if SSL is used
Request.Path Virtual path of the HTTP request (without server name)
Request.QueryString Name/Value pairs the browser sent as part of the URL
Request.ServerVariables Complete list of name/value pairs with information about the server and the current request
Request.Url Complete URL of the request
Request.UrlReferrer Refering URL of the request (Previous page, the browser visited)
Request.UserAgent Browser identification
Request.UserHostAddress IP address of the client
Request.UserLanguages Preferred languages of the user (determined by browser settings)
Response.BinaryWrite(bytes) Writes information to an HTTP response output stream.
Response.Write(string) Writes information to an HTTP response output stream.
Response.WriteFile(string) Writes the specified file directly to an HTTP response output stream.
Response.BufferOutput True if the output to client is buffered
Response.Cookies Collection of cookies that shall be sent to the browser
Response.Redirect(Path) Redirects a client to a new URL using the HTTP status code 302
Response.StatusCode HTTP status code (integer) of the output returned to the client
Response.StatusDescription HTTP status string of the output returned to the client
Session.SessionID Unique identifier for the current session (a session is user specific)
Session.Item Gets or sets individual session values.
Session.IsCookieless True, if the ID for the current sessions are embedded in the URL. False, if its stored in an HTTP cookie
ViewState.Item Gets or sets the value of an item stored in the ViewState, which is a hidden field used for state management witin a page
Application.Item Gets or sets the value of an item stored in the application state, which is an applicationscope state management facility

Table 5: Most important members of the Page class and its associated classes

A Typical Page

Figure 4 shows the typical content of an .aspx page and Figure 5 the content of a typical code behind class. The sample used is a registration form with three fields: Name, Job Title and Email Address.


<%@ Page Language=”C#” AutoEventWireup=”true”
  CodeFile=”PageName.aspx.cs” Inherits=”PageName” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//en”
  “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
  <title>Registration Page</title>
  <link href=”MyStyles.css” rel=”stylesheet” type=”text/css”/>
  <style type=”text/css”>
   .Headline
   {
    font-size: large; font-weight: bold;
   }
  </style>
 </head>
 <body>
  <form id=”c_Form” ruanat=”server”>
  <div>
   <asp:Label runat=”server” ID=”C_Headline” Text=”Please register:”
     class=”Headline”></asp:label>
    <p>Name:
   <asp:TextBox ID=”C_Name” runat=”server”></asp:TextBox>
   <asp:RequiredFieldValidator ID=”C_NameVal” ControlToValidate=”C_
   Name” ruanat=”server” ErrorMessage=”Name required”></
   asp:RequiredFieldValidator>
 </p>
    <p>Job Title:
   <asp:DropDownList ID=”C_JobTitle” runat=”server”>
  <asp:ListItem Text=”Software Developer” Value=”SD”></
 asp:ListItem>
  <asp:ListItem Text=”Software Architect” Value=”SA”></
   asp:ListItem>
  </asp:DropDownList>
 </p>
<p>EMail:
  <asp:TextBox ID=”C_EMail” runat=”server”></asp:TextBox>
   <asp:RequiredFieldValidator Id=”C_EMailVal1” ControlToValidate=”C_
  EMail” runat=”server” ErrorMessage=”EMail required”></
  asp:RequiredFieldValidator>
  <asp:RegularExpressionValidator ID=”C_EMailVal2”
 ControlToValidate=”C_EMail” runat=”server” ErrorMessage=”Email
   not valid” ValidationExpression=”\w+([-+.’]\w+)*@\w+([-.]\
     w+)*\.\w+([-.]\w+)*”>
   </asp:RegularExpressionValidator>
   </p>
   <p>
  <asp:Button ID=”C_register” runat=”server” Text=”Register”
 onclick=”C_Register_Click”/>
   </p>
   </div>
 </form>
</body>
</html>

Figure 4: Typical content of an ASPX file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class PageName : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
   {
    // If an authenticated users starts using this page,
    // use his login name in the name textbox
    if (!Page.IsPostBack && Page.User.Identity.IsAuthenticated)
    {
     this.C_Name.Text = Page.User.Identity.Name;
     this.C_Name.Enabled = false;
    }
   }
 protected void C_Register_Click(object sender, EventArgs e)
  {
   if (Page.IsValid) // if all validation controls succedded
   { // call business logic and
    if (BL.Register(this.C_Name.Text, this.C_EMail.Text, this.C_
     JobTitle.SelectedValue))
    { // redirect to confirmation page
     Response.Redirect(“RegistrationConfirmation.aspx”);
    }
    else
    { // change the headline
     this.C_Headline. = “You are already registered!”;
    }
   }
  }
}    

Figure 5: Typical content of a Code Behind file

State Management

State management is a big issue in web applications as the HTTP protocol itself is stateless. There are three standard options for state management: hidden files, URL parameters and cookies. However, ASP.NET has some integrated abstractions from these base mechanisms know as View State, Session State, and Application State. Also, the direct use of cookies is supported in ASP.NET.

Hot Tip

Disabling the View State (EnableViewState=false in a control) will significantly reduce the size of the page sent to the browser. However, you will have to take care of the state management of the controls with disabled View State on your own. Some complex controls will suffer the loss of functionality without View State.

The following code snippet shows how to set values for a counter stored in each of these mechanisms:


ViewState[“Counter”] = CurrentCounter_Page + 1;
Session[“Counter”] = CurrentCounter_Session + 1;
Application[“Counter”] = CurrentCounter_Application + 1;
Response.Cookies[“Counter”].Value = (CurrentCounter_User +
  1).ToString();
Response.Cookies[“Counter”].Expires = DateTime.MaxValue; // no
  expiration

Figure 6: Setting Values

Hot Tip

When reading value from these objects, you have to check first if they already exist. Otherwise you will recieve the exception “NullReferenceExeception: Object reference not set to an instance of an object.”

The following code snippet shows how to read the current counter value from each of these mechanisms: Next Column ---->

Mechanism Scope Lifetime Base Mechanism Data Type Storing Value Reading Value
View State Single user on a single page Leaving the current page Hidden FIeld “ViewState” Object (any serializable.NET data type) Page.ViewState Page.ViewState
Session State Latest interaction of a single
user with the web page
Limited number of minutes after the last request from
the user
Cookie (“ASPSessionJD...”)or URL Parameter “(S(...))”
plus server side store (local RAM, RAM on dedicated
server or database)
Object. Object must be serializable
if the store is not the local RAM
Page.Session Page.Session
Cookies A single User Closing of the browser or dedicated point in time Cookie String Page.Response.Cookies/td> Page.Response.Cookies
Application State All users Shutting down the web application Local RAM Object Page.Application Page.Application

long CurrentCounter_Application, CurrentCounter_ApplicationLimited,
CurrentCounter_Session, CurrentCounter_Page, CurrentCounter_User;
 if (Application[“Counter”] == null) { CurrentCounter_Application =
  0; }
  else { CurrentCounter_Application = Convert.ToInt64(Application[“C
   ounter”]); }
 if (Session[“Counter”] == null) { CurrentCounter_Session = 0; }
  else { CurrentCounter_Session = Convert.
   ToInt64(Session[“Counter”]);}
 if (ViewState[“Counter”] == null) { CurrentCounter_Page = 0; }
  else { CurrentCounter_Page = Convert.
ToInt64(ViewState[“Counter”]); }
 if (Request.Cookies[“Counter”] == null) { CurrentCounter_User = 0; }
  else { CurrentCounter_User = Convert.ToInt64(Request.
   Cookies[“Counter”].Value); }

Figure 7: Reading Values

Configuration

All configurations for ASP.NET applications are stored in XMLbased configuration files with the fixed name “web.config”. In addition to the configuration files in the application root folder, subfolders may also contain a web.config that overrides parent settings. Also, there are the global configuration files machine. config and web.config in the folder \Windows\Microsoft.NET\ Framework\v2.0.50727\CONFIG that provide some default settings for all web applications. (Note: v2.0.50727 is still correct for ASP.NET 3.5!).

Visual Studio and Visual Web Developer create a default root configuration file in your web project that contains a lot of internal setting for ASP.NET 3.5 to work properly. Figure 6 shows a fragment from a web.config file with settings that are often used.


<!-- Connection strings -->
<connectionStrings>
  <add name=”RegistrationDatabase” connectionString=”Data
Source=EO2;Initial Catalog= RegistrationDatabase;Integrated
Security=True” providerName=”System.Data.SqlClient” />
</connectionStrings>
<!-- User defined settings -->
<AppSettings>
  <and key=”WebmasterEMail” value=”hs@IT-Visions.de” />
</appSettings>
<system.web>
  <!-- Specify a login page -->
  <!-- Use the URL for storing the authentication ID if cookies are
not allowed -->
  <!-- Set the authentication timeout to 30 minutes -->
<authentication mode=”Forms”>
  <forms loginUrl=”Login.aspx” cookieless=”AutoDetect” timeout=”30”>
  </forms>
  </authentication>
   <!-- Deny all unauthorizd access to this application -->
  <authorization>
   <deny users=”?” />
  </authorization>
 <!-- Use the URL for storing the session ID if cookies are not
allowed -->
 <!-- Set the session timeout to 30 minutes -->
 <sessionState cookieless=”AutoDetect” timeout=”30”></sessionState>
<!-- Display custom error pages for remote users -->
<customErrors mode=”RemoteOnly” defaultRedirect=”GenericErrorPage.
  htm”>
  <error statusCode=”403” redirect=”NoAccess.htm” />
  <error statusCode=”404” redirect=”FileNotFound.htm” />
</customErrors>
<!-- Turn on debugging -->
<compilation debug=”false”>

Figure 8: Typical setting in the web.config file.

Hot Tip

Please make sure you turn debugging off again before deploying your application as this decreases execution performance.

Deployment

ASP.NET applications can be deployed as source code via the so called “XCopy deployment”. This means you copy the whole content of the web project folder to the production system and configure the target folder on the production system as an IIS web application (e.g. using the IIS Manager). The production web server will automatically compile the application during the first request and recompile automatically if any of the source files changed.

However, you can precompile the application into .NET assemblies to improve protection of your intellectual property and increase execution speed for the first user. Precompilation can be performed through Visual Studio/Visual Web developer (Menu “Build/Publish Website”) or the command line tool aspnet_compiler.exe.

Hot Tip

Download the “Visual Studio 2008 Web Deployment Projects” from microsoft.com. This is an Add-In that provides better control over the precompilation process.

About The Author

Photo of author Holger Schwichtenberg

Holger Schwichtenberg

Holger Schwichtenberg is one of Europe’s best-known experts on .NET and Windows PowerShell. He holds both a Master’s degree and a Ph.D. in business informatics. Microsoft recognizes him as a Most Valuable Professional (MVP) since 2003. He is a .NET Code Wise Member, an MSDN Online Expert and an INETA speaker. He regularly gives high-level talks at conferences such as TechEd, Microsoft Summit, BASTA and IT Forum. He is the CEO of the German based company www.IT-Visions.de that provides consulting and training for many companies throughout Europe.

Publicaitions

Holger Schwichtenberg has published more than twenty books for Addison Wesley and Microsoft Press in Germany, as well as about 400 journal articles. His recent book “Essential PowerShell” has also been published by Addison Wesley in English.

Blog: www.dotnet-doktor.de (German)

Website: www.IT-Visions.de/en

Recommended Book

ASP.NET

An in-depth guide to the core features of Web development with ASP.NET, this book goes beyond the fundamentals. It expertly illustrates the intricacies and uses of ASP.NET 3.5 in a single volume. Complete with extensive code samples and code snippets in Microsoft Visual C# 2008, this is the ideal reference for developers who want to learn what s new in ASP.NET 3.5, or for those building professional-level Web development skills.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Agile Adoption

Decreasing Time to Market

By Gemba Systems

16,177 Downloads · Refcard 45 of 151 (see them all)

Download
FREE PDF


The Essential Agile Adoption Cheat Sheet

Agile methods are everywhere, but which one is the right fit for you and your business? What are the business values you want out of adopting Agile? This Dzone Refcard focuses on choosing the right Agile practices for your team or organization when getting to market faster is of prime importance. You’ll learn about the practices that are the building blocks of these methods- such as iterations, continuous integration, refactoring, automated developer tests, and many more.
HTML Preview
Agile Adoption:

Agile Adoption: Decreasing time to market

By Gemba Systems

About Agile Adoption

There are a myriad of Agile practices out there. Which ones are right for you and your team? What are the business values you want out of adopting Agile and what is your organization’s context? This Refcard is focused on helping you evaluate and choose the practices for your team or organization when getting to market faster is of prime importance. Instead of focusing on entire methods such as Scrum and XP, we will talk about the practices that are the building blocks of these methods such as iterations and automated developer tests. We will answer two basic questions:

  • What Agile practices should you consider to improve Time to Market?
  • How should you go about choosing from those practices given your organization and context?

What Agile Practices improve time to market?

Figure 1

Figure 1-These are the Agile practices that improve time to market. The most effective practices are near the top of the diagram. Therefore iteration is more effective than Onsite Customer for improving time to market. The arrows indicate dependencies. Continuous Integration depends on Automated Developer Tests for it to be effective.

Iteration

Figure 2

*Practices in pink are ones that don’t directly address time to market but are needed to support practices that do (hence a dependency). They are not described in this Refcard but can be found in the external references.

Table 1.1 An iteration is a time-boxed event that is anywhere between 1 to 4 weeks long. The development staff works throughout this period – without interruption – to build an agreed upon set of requirements that are accepted by the customer and meet an agreed upon “done state”.
Table 1.2 To get the most of an iteration and reduce your time to market, an iteration needs to work from an iteration backlog and reach a solid done state at its completion. Such an iteration reduces time to market because every time-boxed iteration is a potential release. There is little “work in progress” between iterations and defects are found early and often for cheaper and faster removal.
Table 1.3 Any software team that is building software where they are not 100% sure of their outcome is a candidate for performing iterations. Without iterations the majority of learning (from mistakes) only happens at the end and coursecorrections are difficult if not impossible.

Continuous Integration

Figure3

Figure 2-The cost of fixing a defect increases over time because of context switching, communication, and bugs being built on existing bugs.

Release Often

Diagram 1
Table 1.1 Release your software to your end customers as often as you can without inconveniencing them.
Table 1.2 Releasing often streamlines your development process and makes you deal with the pains of getting software good enough to go live. A team that releases often faces the pains and addresses the problems that make deployment difficult so that releasing is just another development task.
Table 1.3 You are on a project where releasing often will enable you to produce revenue earlier. Having new features available frequently will not inconvenience your customer base. The quality of your releases is superb and your customers eagerly await your next release (instead of religiously keeping away from your 1.0 releases).

Done State

Table 1.1 The done state is a definition agreed upon by the entire team of what constitutes the completion of a requirement. The closer the done state is to deployable software, the better it is because it forces the team to resolve all hidden issues.
Table 1.2 A done state that is close to deployment enables the team to be confident in its work. The psychological effect of this confidence is a development team that gives good estimates, delivers regularly, and is confident in releasing its software. An executive decision can be made to release what has been built at anytime.
Table 1.3 A team that should consider using a done state is one that has the necessary expertise and resources to build a requirement from end-to-end and perform all of the necessary build and deployment tasks.

Iteration Backlog

Backlog
Table 1.1 A backlog is a prioritized list of requirements. There are two common flavors of backlogs, one for the current iteration and one for the product. The product backlog contains all of the requirements prioritized by value to the customer. The iteration backlog is a list of requirements that a team has committed to building for an iteration.
Table 1.2 Properly prioritized backlogs that are used to set the goals for every iteration ensure that the team is always working on the most important requirements. When paired with iterations that produce working, tested software, backlogs give a development team the option to release at the end of any iteration having always worked on the most important issues.
Table 1.3 An expert on business value is needed to be part of the team to prioritize the backlog. If your team has such a person or someone that can coordinate with the business stakeholders to do so then use a product backlog. If you are using iterations then use an iteration backlog to set clear goals for the iterations and a release backlog to maintain long-term goals.

Automated Developer Tests

Table 1.1 Automated developer tests are a set of tests that are written and maintained by developers to reduce the cost of finding and fixing defects—thereby improving code quality—and to enable the change of the design as requirements are addressed incrementally.
Table 1.2 Automated developer tests reduce the time to market by actually reducing the development time. This is accomplished by reducing a developer’s time in debugging loops by catching errors in the safety-net of tests.
Table 1.3 You are on a development team that has decided to adopt iterations and simple design and will need to evolve your design as new requirements are taken into consideration. Or you are on a distributed team. The lack of both face-to-face communication and constant feedback is causing an increase in bugs and a slowdown in development.

Automated Acceptance Tests

Diagram 2
Table 1.1 Automated acceptance tests are tests written at the beginning of the iteration that answer the question: “what will this requirement look like when it is done?”. This means that you start with failing tests at the beginning of each iteration and a requirement is only done when that test passes.
Table 1.2 This practice builds a regression suite of tests in an incremental manner and catches errors, miscommunications, and ambiguities very early on. This, in turn, reduces the amount of work that is thrown away and enables faster development as you receive early feedback when a requirement is no longer satisfied.
Table 1.3 You are on a development project with an onsite customer who is willing and able to participate more fully as part of the development team. Your team is also willing to make difficult changes to any existing code. You are willing to pay the price of a steep learning curve.

Onsite Customer

Table 1.1 The onsite customer role in an Agile development team is a representative of the users of the system who understands the business domain of the software. The customer owns the backlog, is responsible for writing and clarifying requirements, and responsible for checking that the software meets the requirements specified.
Table 1.2 The role of customer helps improve time to market by supporting the developers by giving them clear requirements, providing clarifications and verifying that the software does really meet the needs of the user base. The customer provides early feedback to the development team so they never spend more than an iteration down a blind alley. Finally, having a customer who correctly prioritizes a backlog allows the team to deliver the most important items first when time is of the essence.
Table 1.3 The practice of onsite customer works best when the development team can be co-located with one or more domain experts. The person fulfilling the customer role is crucial to the success of the team and therefore will need sufficient time and resources to do the job.

Simple Design

Figure4

*Practices in pink are ones that don’t directly address time to market but are needed to support practices that do (hence a dependency). They are not described in this Refcard but can be found in the external references.

Table 1.1 If a decision between coding a design for today’s requirements and a general design to accommodate for tomorrow’s requirements needs to be made, the former is a simple design. Simple design meets the requirements for the current iteration and no more.
Table 1.2 Simple design improves time to market because you build less code to meet the requirements and you maintain less code afterwards. Simple designs are easier to build, understand, and maintain.
Table 1.3 Simple design should only be used when your team also is writing automated developer tests and refactoring. A simple design is fine as long as you can change it to meet future requirements.

Refactoring

Figure5

*Practices in pink are ones that don’t directly address time to market but are needed to support practices that do (hence a dependency). They are not described in this Refcard but can be found in the external references.

Table 1.1 The practice of Refactoring code changes the structure (i.e., the design) of the code while maintaining its behavior. Collective code ownership is needed because a refactoring frequently affects other parts of the system. Automated developer tests are needed to verify that the behavior of the system has not changed after the design change introduced by the refactoring.
Table 1.2 Refactoring improves time to market by supporting practices like Simple Design which, in turn, allow you to only write the software for the features that are needed now.
Table 1.3 You are on a development team that is practicing automated developer tests. You are currently working on a requirement that is not well-supported by the current design.

Cross-Functional Team

Table 1.1 The team that utilizes the Cross Functional Team practice is one that has the necessary expertise among its members to take a requirement from its initial concept to a fully deployed and tested piece of software within one iteration. A requirement can be taken off of the backlog, elaborated and developed, tested, deployed.
Table 1.2 Cross-functional teams primarily affect time to market by enabling true iterative and incremental development. Resource bottlenecks are resolved and teams can build features end-to-end.
Table 1.3 There is a hardening cycle at the end of each release indicating unresolved integration issues. Building a slice of functionality end-to-end in your system finds errors early and requires diverse expertise of many different people.

How to adopt agile practices successfully

To successfully adopt Agile practices let’s start by answering the question “which ones first?” Once we have a general idea of how to choose the first practices there are other considerations.

Become “Well-Oiled” First

One way to look at software development is to see it as problem solving for business. When considering a problem to solve there are two fundamental actions that must be taken:

  • Solving the right problem. This is IT/Business alignment.
  • Solving the problem right. This is technical expertise.

Intuitively it would seem that we must focus on solving the right problem first because, no matter how well we execute our solution to the problem, if it is the wrong problem then our solution is worthless. This, unfortunately, is the wrong way to go. Research shows in Figure 3, that focusing on alignment first is actually more costly and less effective than doing nothing. It also shows that being “well-oiled”, that is focusing on technical ability first, is much more effective and a good stepping-stone to reaching the state where both issues are addressed.

This is supported anecdotally by increasing reports of failed Agile projects that do not deliver on promised results. They adopt many of the soft practices such as Iteration, but steer away from the technically difficult practices such as Automated Developer Tests, Refactoring, and Done State. They never reach the “well-oiled” state.

So the lesson here is make sure that on your journey to adopt Agile practices that improve time to market (or any other business value for that matter), your team will need to become “well-oiled” to see significant, sustained improvement. And that means you should plan on adopting the difficult technical practices for sustainability.

Figure 3

Figure 3-The Alignment Trap (from Avoiding the Alignment Trap in Information Technology, Shpilberg, D. et al, MIT Sloan Management Review, Fall 2007.)

Minimize What You Build

Statistics show that most of what software development teams build is not used. In Figure 4 we see that only 7% of functionality is always used. And 45% is never used. This is a sad state of affairs, and an excellent opportunity. One of the easiest ways to speed up is to do less. If you have less to build, then not only do you spend less time writing and testing software, but you also reduce the complexity of the entire application. And by reducing the complexity of the application it takes less time to maintain because you have a simpler design, fewer dependencies, and fewer physical lines of code that your developers must understand and maintain.

Figure 4.1

Figure 4- Most functionality built is not used

Cross-Functional Team

Cartoon

Figure 5- Context matters. Choose Agile practices that fit your context.

The practices are all described within context. So, for example,the context for the Release Often practice indicates that your customers should be willing to install and run frequent releases and that the quality of your current builds are exceptional. If this is not the case, if your current releases go through a ‘stabilization phase’ and your customers have learned never to take a 1.0 release, then do not adopt Release Often, you will end up hurting your relationship with your customers.

Learning is the Bottleneck

Here is a hypothetical situation that we have presented to many experienced software development teams:

Suppose I was your client and I asked you and your team to build a software system for me. Your team proceeds to build the software system. It takes you a full year – 12 months – to deliver working, tested software.

I then thank the team and take the software and throw it out. I then ask you and your team to rebuild the system. You have the same team. The same requirements. The same tools and software. Basically – nothing has changed – it is exactly the same environment.

How long will it take you and your team to rebuild the system again?

When we present this hypothetical situation to development practitioners – many of them with 20+ years experience in building software – they typically respond with anywhere between 20% to 70% of the time. That is, rebuilding a system that originally takes one year to build takes only 2.5 to 8.5 months to build. It is a huge difference!

So, what is the problem? What was different? The team has learned. They learned about each other as a team and have gelled over the year. They learned about the true requirements – not just those written down. They also learned to use the toolset, they experienced the idiosyncrasies that come up during all software development, and basically they worked through all the unknowns until they built and delivered a successful software solution. Learning is THE bottleneck of software engineering.

The learning that occurs makes up a significant percentage of the time spent on the work. That’s the main reason that Agile practices work so well – they are all about recognizing and responding to change. Agile practices, from continuous integration to iterations, all consist of cycles that help the team learn fast. By cycling in every possible practice, Agile teams accelerate learning, addressing the bottleneck of software engineering. Call it “scientific method,” “continuous improvement” or “inspect and adapt”, to truly benefit from these practices you and your team(s) must learn well and learn often.

Know What You Don’t Know

Since learning is the bottleneck, it makes sense to talk a bit about how we actually learn. The Dreyfus Model of Skill Acquisition, is a useful model of learning. It is not the only model of learning, but it is consistent, has been effective, and works well for our purposes. This model states that there are levels that one goes through as they learn a skill and that your level for different skills can and will be different. Depending on the level you are at, you have different needs and abilities. An understanding of this model is not crucial to learning a skill; after all, we’ve been learning long before this model existed. However, being aware of this model can help us and our team(s) learn effectively.

So let’s take a closer look at the different skill levels in the Dreyfus Model:

Pyramid Diagram

Figure 6-The Drefyus Model for skill acquisition. One starts as a novice and through experience and learning advances towards expertise.

How can the Dreyfus Model help in an organization that is adopting agile methods? First, we must realize that this model is per skill, so we are not competent in everything. Secondly, if agile is new to us, which it probably is, then we are novices or advanced beginners; we need to search for rules and not break them until we have enough experience under our belts. Moreover, since everything really does depend on context,and we are not qualified to deal with context as novices and advanced beginners, we had better get access to some people who are experts or at least proficient to help guide us in choosing the right agile practices for our particular context. Finally, we’d better find it in ourselves to be humble and know what we don’t know to keep from derailing the possible benefits of this new method. And we need to be patient with ourselves and with our colleagues. Learning new skills will take time, and that is OK.

Choosing a Practice to Adopt

Choosing a practice comes down to finding the highest value practice that will fit into your context. Figure 1 will guide you in determining which practices are most effective in decreasing your time to market and will also give you an understanding of the dependencies. The other parts in this section discuss other ideas that can help you refine your choices. Armed with this information:

Figure7

Figure 7- Steps for Choosing and Implementing Practices

Small steps and failing fast are the most effective methods to release quickly. Weed out defects early because the earlier you find them, the less they will cost to fix as shown in Figure 2 and you won’t be building on a crumbling foundation. This is why Continuous Integration and Iteration lead the practices that most positively affect time to market. They are both, however, dependent on several practices to be effective, so consider starting with Automated Developer Tests and the Iteration trio – Iteration, Iteration Backlog, and Done State.

Next Steps

This refcard is a quick introduction to Agile practices that can help you improve your time to market and an introduction of how you to choose the practices for your organizational context. It is only a starting point. If you choose to embark on an Agile adoption initiative, your next step is to educate yourself and get as much help as you can afford. Books and user groups are a beginning. If you can, find an expert to join your team(s). Remember, if you are new to Agile, then you are a novice or advanced beginner and are not capable of making an informed decision about tailoring practices to your context.

Reference table

Collumn 2 Collumn 3 Collumn 4 Collumn 5 Collumn 6 Collumn 7 Collumn 8 Collumn 9 Collumn 10 Collumn 11
Astels, David. 2003. Test-driven development: a practical guide.
Upper Saddle River, NJ: Prentice Hall.
Pink Cross
Beck, Kent. 2003. Test-driven development by example. Boston, MA:
Pearson Education.
Blue Cross
Beck, K. and Andres, C., Extreme Programming Explained: Embrace
Change (second edition), Boston: Addison-Wesley, 2005
Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross
Cockburn, A., Agile Software Development: The Cooperative Game
(2nd Edition), Addison-Wesley Professional, 2006.
Blue Cross
Cohn, M., Agile Estimating and Planning, Prentice Hall, 2005. Pink Cross
Duvall, Paul, Matyas, Steve, and Glover, Andrew. (2006). Continuous
integration: Improving Software Quality and Reducing Risk. Boston: Addison-Wesley.
Blue Cross
Elssamadisy, A., Agile Adoption Patterns: A Roadmap to
Organizational Success, Boston: Pearson Education, 2008
Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross Pink Cross
Feathers, Michael. 2005. Working effectively with legacy code. Upper
Saddle River, NJ: Prentice Hall.
Blue Cross
Jeffries, Ron. “Running Tested Features.”
http://www.xprogramming.com/xpmag/jatRtsMetric.htm
Pink Cross
Jeffries, Ron. 2004. Extreme programming adventures in c#.
Redmond, WA: Microsoft Press.
Blue Cross
Kerievsky, Joshua. “Don’t Just Break Software, Make Software.”
http://www.industriallogic.com/papers/storytest.pdf
Pink Cross

ABOUT Gemba Systems

Gemba Systems

Gemba Systems is comprised of a group of seasoned practitioners who are experts at Lean & Agile Development as well as crafting effective learning experiences. Whether the method is Scrum, Extreme Programming, Lean Development or others - Gemba Systems helps individuals and teams to learn and adopt better product development practices. Gemba Systems has taught better development techniques - including lean thinking, Scrum and Agile Methods - to thousands of developers in dozens of companies around the globe. To learn more visit http://us.gembasystems.com/

Recommended Book

Agile Adoption Patterns

Agile Adoption Patterns will help you whether you’re planning your first agile project, trying to improve your next project, or evangelizing agility throughout your organization. This actionable advice is designed to work with any agile method, from XP and Scrum to Crystal Clear and Lean. The practical insights will make you more effective in any agile project role: as leader, developer, architect, or customer.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

JBoss RichFaces

By Nick Belaevski, Ilya Shaikovsky, Jay Balunas and Max Katz

18,103 Downloads · Refcard 44 of 151 (see them all)

Download
FREE PDF


The Essential JBoss RichFaces Cheat Sheet

JBoss RichFaces is a JSF component library that consists of two main parts: Ajax enabled JSF components and the CDK (Component Development Kit). It allows easy integration of Ajax capabilities into enterprise application development. This DZone Refcard is a great start for any developer looking to learn more about JBoss RichFaces. You will find plenty of examples and code samples that will help with your Rich Internet Applications. This Refcard also covers the following topics: What is RichFaces?, Basic Concepts, Controlling Traffic, Tags, Hot Tips and more.
HTML Preview
JBoss RichFaces

JBoss RichFaces

By Nick Belaevski, Ilya Shaikovsky Jay Balunas, and Max Katz

What is Richfaces?

RichFaces is a JSF component library that consists of two main parts: AJAX enabled JSF components and the CDK (Component Development Kit). RichFaces UI components are divided into two tag libraries a4j: and rich:. Both tag libraries offer out-of-the-box AJAX enabled JSF components. The CDK is a facility for creating, generating and testing you own rich JSF components (not covered in this card).

Installing Richfaces

See the RichFaces Project page for the latest version- http:// www.jboss.org/jbossrichfaces/.

Add these jar files to your WEB-INF/lib directory: richfacesapi. jar, richfaces-impl.jar, richfaces-ui.jar, commons-beanutils.jar, commons-collections.jar, commons-digester.jar, commons-logging.jar

RichFaces Filter

Update the web.xml file with the RichFaces filter:


<filter>
  <display-name>RichFaces Filter</display-name>
  <filter-name>richfaces</filter-name>
  <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
  <filter-name>richfaces</filter-name>
  <servlet-name>Faces Servlet</servlet-name>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
  <dispatcher>ERROR</dispatcher>
</filter-mapping>

Hot Tip

The RichFaces Filter is not needed for applications that use Seam (http://seamframework.org)

Page setup

Configure RichFaces namespaces and taglibs in your XHTML and JSP pages.

Facelets
xmlns:a4j=”http://richfaces.org/a4j”
xmlns:rich=”http://richfaces.org/rich”
JSP
<%@ taglib uri=”http://richfaces.org/a4j” prefix=”a4j”%>
<%@ taglib uri=”http://richfaces.org/rich” prefix=”rich”%>

Hot Tip

Use JBoss Tools for rapid project setup - http://www.jboss.org/tools

Basic Concepts

Sending an AJAX request

a4j:support

Sends an AJAX request based on a DHTML event supported by the parent component. In this example, the AJAX request will be triggered after the user types a character in the text box:

a4j:support

<h:inputText value=”#{echoBean.text}”>
  <a4j:support event=”onkeyup” action=”#{echoBean.count}”
	              reRender=”echo, cnt”/>
</h:inputText>
<h:outputText id=”echo” value=”Echo: #{echoBean.text}”/>
<h:outputText id=”cnt” value=”Count: #{echoBean.textCount}”/></td>

a4j:support can be attached to any html tag that supports DHTML events, such as:

</table>

a4j:commandButton, a4j:commandLink

Similar to h:commandButton and h:commandLink but with two major differences. They trigger an AJAX request and allow partial JSF component tree rendering.

The request goes through the standard JSF life cyle. During the Render Response, only components whose client ids are listed in the reRender attribute (echo, count) are rendered back the the browser.
a4j:support

<h:selectOneRadio value=”#{colorBean.color}”>
  <f:selectItems value=”#{colorBean.colorList}” />
  <a4j:support event=”onclick” reRender=”id” />
</h:selectOneRadio></td>
	
a4j:commandButton, a4j:commandLink

<h:inputText value=”#{echoBean.text}”/>
  <h:outputText id=“echo” value=“Echo: #{echoBean.text}”/>
  <h:outputText id=“cnt” value=“Count: #{echoBean.textCount}”/>
  <a4j:commandButton value=“Submit” action=“#{echoBean.count}”
     reRender=“echo, cnt”/>

Basic Concepts, continued

When the response is received, the browser DOM is updated with the new data i.e ‘RichFaces is neat’ and ‘17’.

New Data

a4j:commandLink works exactly the same but renders a link instead of a button.

a4j:poll

Enables independent periodic polling of the server via an AJAX request. Polling interval is defined by the interval attribute and enable/disable polling is configured via enabled attribute (true|fase).

a4j:poll

<a4j:poll id=”poll” interval=”500” enabled=”#{pollBean.enabled}”
reRender=”now” />
  <a4j:commandButton value=”Start” reRender=”poll”
	 action=”#{pollBean.start}” />
  <a4j:commandButton value=”Stop” reRender=”poll”
	 action=”#{pollBean.stop}” />
  <h:outputText id=”now” value=”#{pollBean.now}” />

a4j:poll

public class PollBean {
	private Boolean enabled=false; // setter and getter
	public void start () {enabled = true;}
	public void stop () {enabled = false;}
	public Date getNow () {return new Date();}
}

a4j:jsFunction

Allows sending an AJAX request directly from any JavaScript function (built-in or custom).

a4j:jsFunction

<td onmouseover=”setdrink(‘Espresso’)”
    onmouseout=”setdrink(‘’)”>Espresso</td>
...
<h:outputText id=”drink” value=”I like #{bean.drink}” />
<a4j:jsFunction name=”setdrink” reRender=”drink”>
<a4j:actionparam name=”param1” assignTo=”#{bean.drink}”/>
</a4j:jsFunction>

When the mouse hovers or leaves a drink, the setdrink() JavaScript function is called. The function is defined by an a4j:jsFunction tag which sets up the AJAX call. It can call listeners and perform partial page rendering. The drink parameter is passed to the server via a4j:actionparam tag.

a4j:push

a4j:push works similarly to a4j:poll; however, in order to check the presence of a message in a queue, it only makes a minimal HEAD request(ping-like) to the server without invoking the JSF life cycle. If a message exists, a sandard JSF request is sent to the server.

Partial view (page) rendering

There are two ways to perform partial view rendering when AJAX requests return.

ReRender attribute

Most RichFaces components support the reRender attribute to define the set of client ids to reRender.

Attribute Can bind to
reRender/td> Set, Collection, Array, comma-delimited String

ReRender can be set statically as in the examples above or with EL:


<a4j:commandLink reRender=”#{bean.renderControls}”/>

Basic Concepts, continued

It’s also possible to point to parent components to rerender all child components:


<a4j:commandLink value=”Submit” reRender=”panel” />
<h:panelGrid id=”panel”>
   <h:outputText />
   <h:dataTable>...</h:dataTable>
</h:panelGrid>

In the example above the child components of the outputPanel will be rerendered when the commandLink is submitted.

a4j:outputPanel

All child components of an a4j:outputPanel will be rerendered automatically for any AJAX request.


<a4j:commandLink value=”Submit” />
<a4j:outputPanel ajaxRendered=”true”>
   <h:outputText/>
   <h:dataTable></h:dataTable>
</a4j:outputPanel>

In the example above the child components of the outputPanel will be rerendered when the commandLink is submitted.

Hot Tip

If ajaxRendered=”false” (default) the a4j:outputPanel behaves just like h:panelGroup.

To limit rendering to only components set in the reRender attribute, set limitToList=”true”. In this example, only h:panelGrid will be rendered:


<a4j:commandLink reRender=”panel” limitToList=”true”/>
<h:panelGrid id=”panel”>
<h:dataTable>...</h:dataTable>
   </h:panelGrid>
<a4j:outputPanel ajaxRendered=”true”>
   lt;h:dataTable>...</h:dataTable>
</a4j:outputPanel>

Deciding what to process on the server

When an AJAX request is sent to the server, the full HTML form is always submitted. However, once on the server we can decide what components to decode or process during the Apply Request, Process Validations and Update Model phases. Selecting which components to process is important in validation. For example, when validating a component (field) via AJAX, we don’t want to process other components in the form (in order not to display error messages for components where input hasn’t been entered yet). Controlling what is processed will help us with that.

The simplest way to control what is processed on the server is to define an AJAX region using the a4j:region tag (by default the whole page is an AJAX region).


<h:inputText>
  <a4j:support event=”onblur” />
</h:inputText>
<a4j:region>
  <h:inputText>
    <a4j:support event=”onblur” />
  </h:inputText>
</a4j:region>

When the user leaves the 2nd input component (onblur event), an AJAX request will be sent where only this input field will be processed on the server. All other components outside this region will not be processed (no conversion/validation, update model, etc). It’s also possible to nest regions:


<a4j:region>
  ...
  <a4j:region>
    ...
  </a4j:region>
</a4j:region>

Basic Concepts, continued

When the request is invoked from the inner region, only components in the inner region will be processed. When invoked from outer region, all components (including inner region) will be processed.

When sending a request from a region, processing is limited to components inside this region. To limit rendering to a region, the renderRegionOnly attribute can be used:


<a4j:region renderRegionOnly=”true”>
   <h:inputText />
   <a4j:commandButton reRender=”panel”/>
   <h:panelGrid id=”panel”>
</a4j:region>
<a4j:outputPanel ajaxRendered=”true”>
   <h:dataTable></h:dataTable>
</a4j:outputPanel>

When the AJAX request is sent from the region, rendering will be limited to components inside that region only because renderRegionOnly=”true”. Otherwise, components inside a4j:outputPanel would be rendered as well.

To process a single input or action component, instead of wrapping inside a4j:region, it’s possible to use the ajaxSingle attribute:

<h:inputText> <a4j:support event=”onblur” ajaxSingle=”true”/> <<

When using ajaxSingle=”true” and a need arises to process additional components on a page, the process attribute is used to include id’s of components to be processed.


<h:inputText>
   <a4j:support event=”onblur” ajaxSingle=”true” process=”mobile”/>
</h:inputText>
<h:inputText id=”mobile”/>


The process can also point to an EL expression or container
component id in which case all components inside the
container will be processed.


When just validating form fields, it is usually not necessary
to go through the Update Model and Invoke Application
phases. Setting bypassUpdates=”true”, will skip these phases,
improving response time, and allowing you to perform
validation without changing the model’s state.


<h:inputText>
  <a4j:support event=”onblur” ajaxSingle=”true”
bypassUpdates=”true”/>
</h:inputText>

JavaScript interactions

RichFaces components send an AJAX request and do partial page rendering without writing any direct JavaScript code. If you need to use custom JavaScript functions, the following attributes can be used to trigger them.

Tag Attributte Description
a4j:commandButton,
a4j:commandLink,
a4j:support,
a4j:poll,
a4j:jsFunction
onbeforedomupdate: JavaScript code to be invoked after
response is received but before browser DOM update
oncomplete: JavaScript code to be invoked after browser DOM
updatedata. Allows to get the additional data from the server
during an AJAX call. Value is serialized in JSON format.
a4j:commandButton,
a4j:commandLink
onclick: JavaScript code to be invoked before AJAX request is sent.
a4j:support,
a4j:poll
onsubmit: JavaScript code to be invoked before AJAX request is sent.

Controlling Traffic

Flooding a server with small requests can cripple a web application, and any dependent services like databases.

Controlling Traffic, continued
Richfaces 3.3.0.GA and Higher

Queues can be defined using the<a4j:queue .../> component and are referred to as Named or Unnamed queues. Unnamed queues are also referred to as Default queues because components within a specified scope will use an unnamed queue by default.

Notable Attributes

Attribute Description
name Optional Attribute that determines if this is a named or unnamed queue
sizeExceededBehavior When the size limit reached: dropNext, DropNew, fireNext, fireNew
ignoreDupResponses If true then responses from the server will be ignored if there are queued evens of the same type waiting.
requestDelay Time in ms. events should wait in the queue incase more events of the same type are fired
Event Triggers onRequestDequeue, onRequestQueue, onSizeExeeded, onSubmit

Other notable attributes include: disabled, id, binding, status, size, timeout.

Named Queues

Named queues will only be used by components that reference them by name as below:


<a4j:queue name=”fooQueue” ... />
	<h:inputText … >
<a4j:support eventsQueue=”fooQueue” .../>
</h:inputText>

Unnamed Queues

Unnamed queues are used to avoid having to specifically reference named queues for every component.

Queue Scope Description
Global All views of the application will have a view scoped queue that does not need to be defined and that all components will use.
View Components within the parent will use this queue
Form Component within the parent or will use this queue

Global Queue

To enable the global queue for an application you must add this to the web.xml file.


<context-param>
<param-name>org.richfaces.queue.global.enabled</param-name>
  <param-value>true</param-value>
</context-param>

It is possible to disable or adjust the global queue’s settings in a particular view by referencing it by its name.


<a4j:queue name=”org.richfaces.global_queue” disabled=”true”... />

View Scoped Default Queues

Defined the <a4j:queue> as a child to the <f:view>.


<f:view>
  ...
  <a4j:queue ... />

Hot Tip

Performance Tips:

  • Control the number of requests sent to the server.
  • Limit the size of regions that are updated per request using <a4j:region/>
  • Cache or optimize database access for AJAX requests
  • Don’t forget to refresh the page when needed

Controlling Traffic, continued

Form Scoped Default Queue

This can be useful for separating behavior and grouping requests in templates.


<h:form>
   ...
<a4j:queue ... />
      ...


A4j:* Tags

The a4j:* tags provide core AJAX components that allow developers to augment existing components and provide plumbing for custom AJAX behavior.

a4j:repeat

This component is just like ui:repeat from Facelets, but also allows AJAX updates for particular rows. In the example below the component is used to output a list of numbers together with controls to change (the value is updated for the clicked row only):


<a4j:repeat value=”#{items}” var=”item”>
	<h:outputText value=”#{item.value} “ id=”value”/>
	<a4j:commandLink action=”#{item.inc}” value=” +1 “
reRender=”value”/>
  </a4j:repeat>

#{items} could be any of the supported JSF data models. var identifies a request-scoped variable where the data for each iteration step is exposed. No markup is rendered by the component itself so a4j:repeat cannot serve as a target for reRender.

The component can be updated fully (by usual means) or partially. In order to get full control over partial updates you should use the ajaxKeys attribute. This attribute points to a set of model keys identifying the element sequence in iteration. The first element has Integer(0) key, the second – Integer(1) key, etc. Updates of nested components will be limited to these elements.

a4j:include

Defines page areas that can be updated by AJAX according to application navigation rules. It has a viewId attribute defining the identifier of the view to include:


<a4j:include viewId=”/first.xhtml” /> 

One handy usage of a4j:include is for building multi-page wizards. Ajax4jsf command components put inside the included page (e.g. first.xhtml for our case) will navigate users to another wizard page via AJAX:


<a4j:commandButton action=”next” value=”To next page” />

(The “next” action should be defined in the faces-config.xml navigation rules for this to work). Setting ajaxRendered true will cause a4j:include content to be updated on every AJAX request, not only by navigation. Currently, a4j:include cannot be created dynamically using Java code.

a4j:keepAlive

Allows you to keep bean state (e.g. for request scoped beans) between requests:


<a4j:keepAlive beanName=”searchBean” />

Standard JSF state saving is used so in order to be portable

a4j:* Components, continued

it is recommended that bean class implements either java. io.Serializable or javax.faces.component.StateHolder.

a4j:keepAlive cannot be created programmatically using Java. Mark managed bean classes using the org.ajax4jsf. model.KeepAlive annotation in order to keep their states.JBoss Seam’s page scope provides a more powerful analog to ths behavior.

a4j:loadXXX
RichFaces provides several ways to load bundles, scripts, and styles into your application.

Tag Description
a4j:loadBundle a4j:loadBundle loads a resource bundle localized for the locale of the current view
a4j:loadScript loads an external JavaScript file into the current view
a4j:loadStyle loads an external .css file into the current view

a4j:status
Used to display the current status of AJAX requests such as “loading...” text and images. The component uses “start” and “stop” facets to define behavior. It is also possible to invoke Javascript or set styles based on status mode changes.

a4j:actionparam
Adds additional request parameters and behavior to command components (like a4j:commandLink or h:commandLink). This component can also add actionListeners that will be fired after the model has been updated.

rich:* tags

The rich: tags are ready-made or self-contained components. They don’t require any additional wiring or page control components to function.

Input Tags

Tag Description
rich:calendar Advanced Date and Time input with many options such as
inline/popup, locale, and custom date and time patterns.
rich:editor A complete WYSIWYG editor component that supports
HTML and Seam Text
rich:inplaceInput Inline inconspicuous input fields
rich:inputNumberSlider min/max values slider

Components include: comboBox, fileUpload, inplaceSelect, inputNumberSpinner

Output Tags

Tag Description
rich:modalPanel Blocks interactions with the rest of the page while active
rich:panelMenu Collapsable grouped panels with subgroup support
rich:progressBar AJAX polling of server state
rich:tabPanel Tabbed panel with client, server, or ajax switching
rich:toolBar Complex content and settings

Components include: paint2D, panel, panelBar,simpleTogglePanel, togglePanel, toolTip

Data Grids, Lists, and Tables

RichFaces has support for AJAX-based data scrolling, complex cell content, grid/list/table formats, filtering, sorting, etc....

rich:* Tags, continued

Tag Description
rich:dataTable Supports complex content, AJAX updates, sortable, and filterable columns
rich:extendedDataTable Adds scrollable data, row selection options, adjustable column locations, and row/column grouping
rich:dataGrid Complex grid rendering of grouped data from a model

Complex Content Sample

Tags Table

Menus

Hierarchical menus available in RichFaces include:

Tag Description Menus
rich:contextMenu Based on page location
and can be attached to
most components link
images, labels, etc...
rich:dropDownMenu Classic application style
menu that supports
icons and submenus.

Components include: rich:menItem, rich:menuGroup,rich:menuSeparator

Trees

RichFaces has tree displays that support many options such as switching (AJAX client or server), drag-drop and are dynamically generated from data models.

Tag Description Menus2
rich:tree Core parent component for a tree
rich:treeNode Creates sets of tree elements
rich:treeNodeAdaptor Defines data model sources for trees
rich:recursiveTree NodeAdaptor Adds recursive node definition from models

Selects

Provides visually appealing list manipulation options for the UI.

Tag Description Menus3
rich:listShuttle Advanced data list manipulation (figure x)
rich:orderingList Visually manipulate a lists order

Validation Tags

AJAX endabled validation including hibernate validation.

Tag Description
rich:ajaxValidator Event triggered validation without updating the model- this skips all JSF phases except validation.
rich:beanValidator Validate individual input fields using hibernate validators in your bean/model classes
rich:graphValidator Validate whole subtree of components using hibernate validators. can also validate the whole bean after model updates.

Drag-Drop

Allows many component types to support drag and drop features.

Tag Description
rich:dragSupport Add as a child to components you want to drag.
righ:dropSupport Define components that support dropped items.
rich:dragIndicator Allows for custom visualizations while dragging an item.
rich:dndParam To pass parameters during a drag-n-drop action.

Miscellaneous

Tag Description
rich:componentControl Attach triggers to call JS API functions on the components after defined events.
rich:effect Scriptaculous visual effect support
rich:gmap Embed GoogleMaps with custom controls
rich:hotKey Define events triggered by hot key (example: alt-z)
rich:insert Display and format files from the file system
rich:virtualEarth Embed Virtual Earth images and controls

Components include: rich:message, rich:messages, rich:jQuery

Skinning

Using out-of-the-box skins

RichFaces ships with a number of built-in skins.

Out-of-the-box Skins
default, classic, emeraldTown, blueSky, ruby, wine, deepMarine, sakura, plain, default, laguna*, glassx*, darkx*
* Require a separate jar file to function

Add the org.richfaces.SKIN context parameter to web.xml and set the skin name.


<context-param>
  <param-name>org.richfaces.SKIN</param-name>
  <param-value>blueSky</param-value>
</context-param>

Sample blueSky skin Sample ruby skin
sample 1 sample 2

Using skin property values on the page

You can use skinBean implicit object to use any value from the skin file on your page.


<h:commandButton value=”Next”
  style=”backgroundcolor:#{
skinBean.
  tabBackgroundColor}”/>

sample 3

The button color is set according to the current skin[Ruby].s

Loading different skins at runtime

You can define an applications skin with EL expression like this:


<context-param>
  <param-name>org.richfaces.SKIN</param-name>
  <param-value>#(skinBean.currentSkin)</param-value>
</context-param>

Define a session scoped skinBean and manage its currentSkin property at runtime with your skin names values. Every time a page is rendered, RichFaces will resolve the value in #{skinBean.currentSkin} to get the current skin. Changing Skins should not be done via AJAX but with a full page refresh. A full page refresh will ensure that all CSS links are correctly updated based on the new skin

Hot Tip

Advanced Skinning Features

  • Create custom skins, or extend the default skins
  • Override or extend styles per page as needed
  • Automatically skin the standard JSF components
  • Plug'n'Skin feature used to generate whole new skins using Maven archetypes

Customizing redefined CSS classes

Under the hood all RichFaces components are equipped with a set of predefined rich-* CSS classes that can be extended to allow customization of a components style (see documentation for details). By modifying these CSS classes you can update all components that use them such as:


.rich-input-text {
   color: red;
}

Project links for more information or questions:

Project page (http://www.jboss.org/jbossrichfaces)
Documentation (http://jboss.org/jbossrichfaces/docs)

About The Author

Photo of author Nick Belaevski

NickBelaevski

Nick Belaevski Nick Belaevski is the team leader of the RichFaces project working for Exadel Inc. He has more than four years of experience in development of middleware products including JBoss Tools and RichFaces.

Projects: RichFaces

Photo of author Ilya Shaikovski

Ilya Shaikovski

Ilya Shaikovsky is the Exadel product manager working on the RichFaces project since Exadel began ajax4jsf. He’s responsible for requirements gathering, specification development, JSF related product analysis and supporting RichFaces and JSF related technologies for business applications. Prior to this he worked on the Exadel Studio Pro product.

Projects: RichFaces

Photo of author Jay Balunas

Jay Balunas

Jay Balunas works as the RichFaces Project Lead and core developer at JBoss, a division of Red Hat. He has been architecting and developing enterprise applications for over ten years specializing in web tier frameworks, UI design, and integration. Jay blogs about Seam, RichFaces, and other technologies at http://in.relation.to/Bloggers/Jay

Projects: RichFaces, Seam Framework, and JBoss Tattletale

Photo of author Max Katz

Max Katz

Max Katz is a senior system engineer at Exadel. He is the author of “Practical Rich- Faces” (Apress). He has been involved with RichFaces since its inception. He has written numerous articles, provided training, and presented at many conferences and webinars about RichFaces. Max blogs about RichFaces and RIA technologies at http://mkblog.exadel.com.

Projects: RichFaces

Recommended Book

PracticalRichFaces

JBoss RichFaces is a rich JSF component library that helps developers quickly develop next–generation web applications. Practical RichFaces describes how to best take advantage of RichFaces, the integration of the Ajax4jsf and RichFaces libraries, to create a flexible and powerful programs. Assuming some JSF background, it shows you how you can radically reduce programming time and effort to create rich AJAX based applications.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Scalability & High Availability

By Eugene Ciurana

20,862 Downloads · Refcard 43 of 151 (see them all)

Download
FREE PDF


The Essential Scalability & High Availability Cheat Sheet

Scalability and Availability are mentioned so often that often it is difficult to know what they actually mean in each case. They are often interchanged and create confusion that results in poorly managed expectations and unrealistic metrics. This DZone Refcard provides you with the tools to define these terms so that your team can implement mission-critical systems with well-understood performance goals. This Refcard also covers: An Overview of Scalability and High Availability, Implementing Scalable Systems, Caching Strategies, Clustering, Redundancy and Fault Tolerance, Hot Tips, and More.
HTML Preview
Scalability & High Availability

Scalability & High Availability

By Eugene Ciurana

OVERVIEW

Scalability, High Availability, and Performance

The terms scalability, high availability, performance, and mission-critical can mean different things to different organizations, or to different departments within an organization. They are often interchanged and create confusion that results in poorly managed expectations, implementation delays, or unrealistic metrics. This Refcard provides you with the tools to define these terms so that your team can implement mission-critical systems with wellunderstood performance goals.

Scalability

It's the property of a system or application to handle bigger amounts of work, or to be easily expanded, in response to increased demand for network, processing, database access or file system resources.

Horizontal scalability
A system scales horizontally, or out, when it's expanded by adding new nodes with identical functionality to existing ones, redistributing the load among all of them. SOA systems and web servers scale out by adding more servers to a load-balanced network so that incoming requests may be distributed among all of them. Cluster is a common term for describing a scaled out processing system.

Clustering

Figure 1:Clustering

Vertical scalability
A system scales vertically, or up, when it's expanded by adding processing, main memory, storage, or network interfaces to a node to satisfy more requests per system. Hosting services companies scale up by increasing the number of processors or

Scalability, continued

the amount of main memory to host more virtual servers in the same hardware.

Virtualization

Figure 2:Virtualization

High Availability

Availability describes how well a system provides useful resources over a set period of time. High availability guarantees an absolute degree of functional continuity within a time window expressed as the relationship between uptime and downtime.

A = 100 – (100*D/U), D ::= unplanned downtime, U ::= uptime; D, U expressed in minutes

Uptime and availability don't mean the same thing. A system may be up for a complete measuring period, but may be unavailable due to network outages or downtime in related support systems. Downtime and unavailability are synonymous.

High Availability, continued

Measuring Availability
Vendors define availability as a given number of "nines" like in Table 1, which also describes the number of minutes or seconds of estimated downtime in relation to the number of minutes in a 365-day year, or 525,600, making U a constant for their marketing purposes.

Availability % Downtime in Minutes Downtime per Year Vendor Jargon
90 52,560.00 36.5 days one nine
99 5,256.00 4 days two nines
99.9 525.60 8.8 hours three nines
99.99 52.56 53 minutes four nines
99.999 5.26 5.3 minutes five nines
99.9999 0.53 32 seconds six nines

Table 1:Availability as a Percentage of Total Yearly Uptime

Analysis
High availability depends on the expected uptime defined for system requirements; don't be misled by vendor figures. The meaning of having a highly available system and its measurable uptime are a direct function of a Service Level Agreement. Availability goes up when factoring planned downtime, such as a monthly 8-hour maintenance window. The cost of each additional nine of availability can grow exponentially. Availability is a function of scaling the systems up or out and implementing system, network, and storage redundancy.

Service Level Agreement (SLA)

SLAs are the negotiated terms that outline the obligations of the two parties involved in delivering and using a system, like:

  • System type (virtual or dedicated servers, shared hosting)
  • Levels of availability
    • Minimum
    • Target
  • Uptime
    • Network
    • Power
    • Maintenance windows
  • Serviceability
  • Performance and Metrics
  • Billing

SLAs can bind obligations between two internal organizations (e.g. the IT and e-commerce departments), or between the organization and an outsourced services provider. The SLA establishes the metrics for evaluating the system performance, and provides the definitions for availability and the scalability targets. It makes no sense to talk about any of these topics unless an SLA is being drawn or one already exists.

IMPLEMENTING SCALABLE SYSTEMS

SLAs determine whether systems must scale up or out. They also drive the growth timeline. A stock trading system must scale in real-time within minimum and maximum availability levels. An e-commerce system, in contrast, may scale in during the "slow" months of the year, and scale out during the retail holiday season to satisfy much larger demand.

Implementing Scalable Systems, continued

Load Balancing

Load balancing is a technique for minimizing response time and maximizing throughput by spreading requests among two or more resources. Load balancers may be implemented in dedicated hardware devices, or in software. Figure 3 shows how load-balanced systems appear to the resource consumers as a single resource exposed through a well-known address. The load balancer is responsible for routing requests to available systems based on a scheduling rule.

Load Balancer

Figure 3: Availability as percentage of Total Yearly Uptime

Scheduling rules are algorithms for determining which server must service a request. Web applications and services are balanced by following round robin scheduling rules. Caching pools are balanced by applying frequency rules and expiration algorithms. Applications where stateless requests arrive with a uniform probability for any number of servers may use a pseudo-random scheduler. Applications like music stores, where some content is statistically more popular, may use asymmetric load balancers to shift the larger number popular requests to higher performance systems, serving the rest of the requests from less powerful systems or clusters.

Persistent Load Balancers
Stateful applications require persistent or sticky load balancing, where a consumer is guaranteed to maintain a session with a specific server from the pool. Figure 4 shows a sticky balancer that maintains sessions from multiple clients. Figure 5 shows how the cluster maintains sessions by sharing data using a database.

Sticky Load Balancer

Figure 4:Sticky Load Balancer

Common Features of a Load Balancer
Asymmetric load distribution – assigns some servers to handle a bigger load than others

  • Content filtering - inbound or outbound
  • Distributed Denial of Services (DDoS) attack protection
  • Firewall
  • Payload switching - send requests to different servers based on URI, port and/or protocol
  • Priority activation - adds standing by servers to the pool

Load Balancing, continued

  • Rate shaping - ability to give different priority to different traffic
  • Scripting - reduces human interaction by implementing programming rules or actions
  • SSL offloading - hardware assisted encryption frees web server resources
  • TCP buffering and offloading - throttle requests to servers in the pool
DatabaseSessions

Figure 5: Database Sessions

CACHING STRATEGIES

Stateful load balancing techniques require data sharing among the service providers. Caching is a technique for sharing data among multiple consumers or servers that are expensive to either compute or fetch. Data are stored and retrieved in a subsystem that provides quick access to a copy of the frequently accessed data.

Caches are implemented as an indexed table where a unique key is used for referencing some datum. Consumers access data by checking (hitting) the cache first and retrieving the datum from it. If it's not there (cache miss), then the costlier retrieval operation takes place and the consumer or a subsystem inserts the datum to the cache.

Write Policy

The cache may become stale if the backing store changes without updating the cache. A write policy for the cache defines how cached data are refreshed. Some common write policies include:

  • Write-through: every write to the cache follows a synchronous write to the backing store
  • Write-behind: updated entries are marked in the cache table as dirty and it's updated only when a dirty datum is requested.
  • No-write allocation: only read requests are cached under the assumption that the data won't change over time but it's expensive to retrieve

Caching Strategies, continued

Application Caching

  • Implicit caching happens when there is little or no programmer participation in implementing the caching. The program executes queries and updates using its native API and the caching layer automatically caches the requests independently of the application. Example: Terracotta (http://www.terracotta.org).
  • Explicit caching happens when the programmer participates in implementing the caching API and may also implement the caching policies. The program must import the caching API into its flow in order to use it. Examples: memcached (http://www.danga.com/memcached) and Oracle Coherence (http://coherence.oracle.com).

In general, implicit caching systems are specific to a platform or language. Terracotta, for example, only works with Java and JVM-hosted languages like Groovy. Explicit caching systems may be used with many programming languages and across multiple platforms at the same time. memcached works with every major programming language, and Coherence works with Java, .Net, and native C++ applications.

Web Caching

Web caching is used for storing documents or portions of documents (‘particles') to reduce server load, bandwidth usage and lag for web applications. Web caching can exist on the browser (user cache) or on the server, the topic of this section. Web caches are invisible to the client may be classified in any of these categories:

  • Web accelerators: they operate on behalf of the server of origin. Used for expediting access to heavy resources, like media files. Content distribution networks (CDNs) are an example of web acceleration caches; Akamai, Amazon S3, Nirvanix are examples of this technology.
  • Proxy caches: they serve requests to a group of clients that may all have access to the same resources. They can be used for content filtering and for reducing bandwidth usage. Squid, Apache, ISA server are examples of this technology.

Distributed Caching

Caching techniques can be implemented across multiple systems that serve requests for multiple consumers and from multiple resources. These are known as distributed caches, like the setup in Figure 7. Akamai is an example of a distributed web cache. memcached is an example of a distributed application cache.

Caching Strategies, continued

Distributed Cache

Figure 7:Distributed Cache

CLUSTERING

A cluster is a group of computer systems that work together to form what appears to the user as a single system. Clusters are deployed to improve services availability or to increase computational or data manipulation performance. In terms of equivalent computing power, a cluster is more costeffective than a monolithic system with the same performance characteristics.

The systems in a cluster are interconnected over high-speed local area networks like gigabit Ethernet, fiber distributed data interface (FDDI), Infiniband, Myrinet, or other technologies.

Load Balancing Cluster

Figure8: Load Balancing Cluster

Load-Balancing Cluster (Active/Active): Distribute the load among multiple back-end, redundant nodes. All nodes in the cluster offer full-service capabilities to the consumers and are active at the same time.

Load Balancing Cluster

High Availability Cluster

Clustering, continued

High Availability Cluster(Active/Passive): Improve services availability by providing uninterrupted service through redundant nodes that eliminate single points of failure. High availability clusters require two nodes at a minimum, a "heartbeat" to detect that all nodes are ready, and a routing mechanism that will automatically switch traffic if the main node fails.

Grid

Figure 10: Grid

Grid: Process workloads defined as independent jobs that don't require data sharing among processes. Storage or network may be shared across all nodes of the grid, but intermediate results have no bearing on other jobs progress or on other nodes in the grid, such as a Cloudera Map Reduce cluster (http://www.cloudera.com).

Figure 11

Figure 11: Computational Clusters

Computational Clusters: Exeute processes that require raw computational power instead of executing transactional operations like web or database clusters. The nodes are tightly coupled, homogeneous, and in close physical proximity. They often replace supercomputers.

REDUNDANCY AND FAULT TOLERANCE

Redundant system design depends on the expectation that any system component failure is independent of failure in the other components.

Fault tolerant systems continue to operate in the event of component or subsystem failure; throughput may decrease but overall system availability remains constant. Faults in hardware or software are handled through component redundancy. Fault tolerance requirements are derived from SLAs. The implementation depends on the hardware and software components, and on the rules by which they interact.

Redundancy and Fault Tolerance, continued

Fault Tolerance SLA Requirements

  • No single point of failure – redundant components ensure continuous operation and allow repairs without disruption of service
  • Fault isolation – problem detection must pinpoint the specific faulty component
  • Fault propagation containment – faults in one component must not cascade to others
  • Reversion mode – set the system back to a known state

Redundant clustered systems can provide higher availability, better throughput, and fault tolerance. The A/A cluster in Figure 12 provides uninterrupted service for a scalable, stateless application.

Figure 12

Figure 12:A/A Full Tolerance and Recovery

Some stateful applications may only scale up; the A/P cluster in Figure 13 provides uninterrupted service and disaster recovery for such an application. A/A configurations provide failure transparency. A/P configurations may provide failure transparency at a much higher cost because automatic failure detection and reconfiguration are implemented through a feedback control system, which is more expensive and trickier to implement.

Figure13

Figure 13:A/P Fault Tolerance and Recovery

Enterprise systems most commonly implement A/P fault tolerance and recovery through fault transparency by diverting services to the passive system and bringing it on-line as soon as possible. Robotics and life-critical systems may implement probabilistic, linear model, fault hiding, and optimizationcontrol systems instead.

Cloud Computing

Cloud computing describes applications running on distributed, computing resources owned and operated by a third-party.

End-user apps are the most common examples. They utilize the Software as a Service (SaaS) and Platform as a Service (PaaS) computing models.

Cloud Computing, continued

Figure 14

Figure 14:Cloud Computing Configuration

Cloud Services Types

  • Web services – Salesforce com, USPS, Google Maps
  • Service platforms – Google App Engine, Amazon Web Services (EC2, S3, Cloud Front), Nirvanix, Akamai, MuleSource

Fault Detection Methods

Fault detection methods must provide enough information to isolate the fault and execute automatic or assisted failover action. Some of the most common fault detection methods include:

  • Built-in Diagnostics
  • Protocol Sniffers
  • Sanity Checks
  • Watchdog Checks

Criticality is defined as the number of consecutive faults reported by two or more detection mechanisms over a fixed time period. A fault detection mechanism is useless if it reports every single glitch (noise) or if it fails to report a real fault over a number of monitoring periods.

SYSTEM PERFORMANCE

Performance refers to the system throughput under a particular workload for a defined period of time. Performance testing validates implementation decisions about the system throughput, scalability, reliability, and resource usage. Performance engineers work with the development and deployment teams to ensure that the system's non-functional requirements like SLAs are implemented as part of the system development lifecycle. System performance encompasses hardware, software, and networking optimizations.

Hot Tip

Performance testing efforts must begin at the same time as the development project and continue through deployment

System Performance, continued

The performance engineer's objective is to detect bottlenecks early and to collaborate with the development and deployment teams on eliminating them.

System Performance Tests

Performance specifications are documented along with the SLA and with the system design. Performance troubleshooting includes these types of testing:

  • Endurance testing - identifies resource leaks under the continuous, expected load.
  • Load testing - determines the system behavior under a specific load.
  • Spike testing - shows how the system operates in response to dramatic changes in load.
  • Stress testing - identifies the breaking point for the application under dramatic load changes for extended periods of time.

System Performance, continued

Software Testing Tools

There are many software performance testing tools in the market. Some of the best are released as open-source software. A comprehensive list of those is available from:

http://www.opensourcetesting.org/performance.php

These include Java, native, PHP, .Net, and other languages and platforms.

Staying Current

Do you want to know about specific projects and cases where scalability, high availability, and performance are the hot topic? Join the scalability newsletter:

http://eugeneciurana.com/scalablesystems

About The Author

Photo of author Eugene Ciurana

Eugene Ciurana

Eugene Ciurana is an open-source evangelist who specializes in the design and implementation of missioncritical, high-availability large scale systems. As Director of Systems Infrastructure, he and his team designed and built a 100% SOA and cloud system that enables millions of Internet-ready educational and handheld products and services. As chief liaison between Walmart.com Global and the ISD Technology Council, he led the official adoption of Linux and other open-source technologies at Walmart Stores Information Systems Division. He's also designed high performance systems for major financial institutions and many Fortune 100 companies in the United States and Europe.

Publications

  • Developing with the Google App Engine
  • Best Of Breed: Building High Quality Systems, Within Budget, On Time, and Without Nonsense
  • The Tesla Testament: A Thriller

Web site
http://eugeneciurana.com

Recommended Book

Google App Engine

Developing with Google App Engine introduces Google App Engine, a platform that provides developers and users with the infrastructure that Google itself uses for developing and deploying massively scalable applications. Using Python as the primary programming tool, Developing with Google App Engine makes it easy to implement scalability and high performance features like distributed databases, clustering, stateless applications, and sophisticated data caching.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

IntelliJ IDEA

Updated for 8.1

By Hamlet DArcy

7,699 Downloads · Refcard 52 of 151 (see them all)

Download
FREE PDF


The Essential IntelliJ IDEA Cheat Sheet

IntelliJ IDEA Looking to update your IntelliJ IDEA IDE? In this DZone Refcard, updated for IntelliJ IDEA 8.1, author Hamlet D’Arcy helps you navigate the various facets of this world-class IDE, including the Editor, Project, and Structure panes. With a rich collection of editing shortcuts, debugging tips and techniques for writing less code, IntelliJ newbies and IDEA-savvy developers will both benefit with this cheat sheet by their side. Still using IntelliJ IDEA 6.0? Relax, our original IntelliJ IDEA Refcard is exactly what you need.
HTML Preview
IntelliJ IDEA

IntelliJ IDEA

By Hamlet D'Arcy

ABOUT INTELLIJ IDEA

Software developers know the importance of using the best tool for the job. Often this means choosing a world-class integrated development environment (IDE), which JetBrains’ IntelliJ IDEA certainly is. But the best developers don’t just have the right tools, they are experts in those tools. This is a guide to becoming that expert. The basics of navigating and understanding the IDE are covered; but this guide is really about unlocking all the powerful features of the tool and helping you be more productive.

Getting Yourself Oriented

Editor

The three most important elements of the IDE are the Editor pane (a), where your code is shown, the Project pane (b), where your project’s contents are shown, and the Structure pane (c), where the details of the open object are shown.

Editor Pane: Shows the currently active file, with recently viewed files in the tab bar. IntelliJ IDEA shows the most recently used files in the tabs, and there is seldom a need to manually close tabs. If the maximum number of tabs is reached, then the oldest tab is closed when a new tab is opened. Also, there is seldom a need to save a file; file saving is performed automatically in the background. The IDE supports syntax highlighting for many languages, but is also language aware and shows syntax errors as they occur.

Navigate faster by learning these commands:

Back Ctrl+Alt+Left Move back to the last cursor position
Forward Ctrl+Alt+Right Move forward to the next cursor position
Next Tab Alt+Right Activate tab to the right of the active one
Previous Tab Alt+Left Activate tab to the left of the active one
Goto Line Ctrl+G Go to a specific line in the active file
Goto Last Edit
Location
Ctrl+Shift+Backspace Go to the position of the last edit

Hot Tip

Toolbar icons are shown throughout this guide, but you’ll be much faster if you learn the key bindings. The mouse is slow: stop using it! IntelliJ IDEA key bindings have received praise over the years, and many believe they are simply better than other IDE’s default bindings. If you’re switching from another tool, consider learning the new bindings rather than loading an alternate key map. The KeyPromoter plugin can help you with this.

Edit faster by learning these commands:

Move Statement Up Ctrl+Shift+Up Moves the current code block up in the file
Move Statement Down Ctrl+Shift+
Down
Moves the current code block down in the file
Copy/Paste Line Ctrl+C /
Ctrl+V
When nothing is selected, copy, cut, and paste operate on the entire line
Clipboard Stacking Ctrl+Shift+V When copying text, the IDE remembers your previous copies. Use Ctrl+Shift+V to show the clipboard history dialog and paste from a previous copy instead of the most recent clipboard contents
Select/Unselect Word at Caret Ctrl+W /
Ctrl+Shift+W
Selects and unselects the word at the caret. Quickly select or unselect the word, statement, block, and method by repeating this action. Experiment to learn how this works differently depending on where your cursor starts
Toggle Bookmark F11 Sets or removes a bookmark on the current line, which shows as black in both the left and right gutter
Comment/
Uncomment
Ctrl+/ Comments out current selection, or removes comments from current selection. This is supported across many languages
Column Mode Ctrl+Shift+
Insert
Column mode allows you to select a rectangular fragment of code. Effectively using this can greatly speed up bulk edits on structured data like SQL or csv files

Getting Yourself Oriented, continued

Project Pane: Shows the contents of the current project, allowing you to view the project as files, packages, or scopes (more about this later). Objects in the project view visually indicate their type with an icon (which also appears on the editor tabs).

Find objects faster by learning what the icons mean:

code Class code Class with main( )
(indicated by green triangle)
interface Interface interface public
Protector Abstract Class Protector protected
Enumeration Enumeration package package
Exception Exception private private
Annotation Annotation ReadOnly Read Only (indicated by lock)
TestCase Test Case (indicated by red and
green triangles)
Not in version control (object
name appears in red)
FinalClass Final Class (Indicated by pin) In version control (object name
appears black, or blue if edited)

Properly configuring the Project pane makes it more effective:

Autoscroll Autoscroll to Source When an object or method is clicked in the Project pane, that item is opened in the Editor pane.
AutoscrollFrom Autoscroll from Source When an item is opened in the Editor pane, that item is scrolled to in the Project pane
StructurePane Show structure Shows the Structure pane (explained next) as a window nested within the Project pane
FinalClass Show/Hide Members Shows the methods and properties of objects within the Project pane
FinalClass Sort by type Sorts the Java classes by type from the most abstract to the most concrete

Structure Pane: Shows the structure of the active file, including methods, properties, and inner classes. Leaving this pane open helps you quickly locate the desired point within a class. Make this pane more useful by tweaking the configuration options:

Autoscroll Autoscroll to source Properties Show properties
AutoscrollFrom Autoscroll from source inherited Show inherited
visibility Sort by visibility ShowFields Show fields
SortAlphabetically Sort alphabetically non-public Show non-public
GroupMethods Group Methods by defining type

Hot Tip

IntelliJ IDEA provides almost endless amounts of configuration through the Settings (Ctrl+Alt+S) window. Use the search box to quickly find what you need. Just start typing what the option might be called and the window will highlight to show which buttons lead to a panel containing that keyword. Wildcards work too!

Finding What You Need

IntelliJ IDEA sets itself apart by offering incredibly advanced ways to find objects and files within large projects. Mastering the act of finding what you need is key to faster development.

Goto Class Ctrl+N Provides dialog for finding classes. Accepts wildcards, camel case, and package prefixes. For example, “BOS” matches BufferedOutputStream, “Str*Buff” matches StringBuffer, and “java.lang.I” matches all objects starting with “I” in the java.lang package. Use Up/Down error to select the class, and Shift+Up/ Down or Ctrl+Click to perform multiple selections.
Goto File Ctrl+Shift+N Provides a similar dialog for finding files that are not classes. For example, “*spring*xml” matches any xml files with the word “spring” in the name, and “*Test.groovy” matches any test case implemented in Groovy.

The navigation bar is a useful alternative to the Project pane. This horizontal bar provides breadcrumb style navigation based on the active file. To navigate to a different package, simply click the + to expand a node higher up in the tree. The navigation bar can be a faster alternative to the Project pane.

navigationbar

You can also use Alt+Home to quickly open the navigation bar from the current editor pane.

Navigating a single class is done through the Structure pane (described earlier) and the file structure popup.

File Structure Popup: (Ctrl+F12) allows quick navigation to methods, fields, and properties. Use the Up/Down arrows to select an entry, or (better) use the search as you type field. Just start typing to narrow the list down. The field provides wildcard and camel case matching. Selecting an entry scrolls the active file to that entry’s declaration.

Navigating large object oriented codebases is greatly simplified by learning these commands:

Ctrl+B /
Middle Click
Go to declaration. Navigates to the declaration of the selected instance or type.
Ctrl+Alt+B Go to implementers or overriders of the selected method. Clicking the icon in the left gutter performs the same action
Ctrl+U Go to the parent of the selected method or type. Clicking the icon in the left gutter performs the same action
Ctrl+Mouse
Over
Shows the declaration of a local variable or field in a popup window
Ctrl+H Opens the Type Hierarchy pane for the active class. This pane explores the super and subclasses of the current object with a variety of different views
Ctrl+Shift+H Opens the Method Hierarchy pane for the active method. This pane explores the definitions and implementations of the current method.
F4 Jump to Source. Many tool windows display objects within project. Used from a tool window, F4 universally opens the element from the tool in the editor. If you’re in the Ant, Hierarchy, or Find window, then F4 will open the selection in the editor pane.

Finding usages is an important feature of any IDE. Being Java aware, IntelliJ IDEA offers more intelligent searching than simple string matching.

Highlight Usages in File (Ctrl+Shift+F7) takes the current mouse selection and highlights all occurrences of that element in the file. The Editor pane and the right gutter provide visual keys to where the occurrences appear. Use F3 and Shift+F3 to jump to the next and previous occurrence.

Finding What You Need, continued

Show Usages Popup (Ctrl+Alt+F7) takes the current mouse selection and searches the project for any references made to the field or type. Results appear in an in-editor popup window.

Show Usages in Find Panel (Alt+F7) behaves the same as the Show Usages Popup, except that results are displayed in the Find pane. Learning to operate the Find pane with the keyboard helps you move faster to the intended object.

Rerun Rerun the last find
Shift+Esc Rerun Close the Find pane
Ctrl+NumPad + Expand Expand all the nodes in the list
Ctrl+NumPad - Collapse Collapse all the nodes in the list
Ctrl+Alt+Up Rerun Navigate to the previous occurrence
Ctrl+Alt+Down Rerun Navigate to the next occurrence
Ctrl+E Recent Find Usages dialog. Quickly jump to a past search result.

Hot Tip

Turn on Scroll to Source in the Find pane and use Ctrl+Alt+Up and Ctrl+Alt+Down to quickly cycle through the usages in the main editor window.

Search Structurally (Ctrl+Shift+S) and Replace Structurally (Ctrl+Shift+M) allows searching (and replacing) references using patterns. Again, this is Java aware and done structurally, and is not just text string search and replace. This very rich feature is best explained with an example. Here are the steps to find any factory methods within the project (ie, methods whose name starts with “create”):

  • Open Search Structurally (Ctrl+Shift+S)
  • Click “Copy the existing template” and select method calls, which is $Instance$.$MethodCall$($Parameter$)
  • Click “Edit variables” and select MethodCall
  • For the MethodCall variable, enter “create.*” in the Text / Regular Expression. This is the regular expression for the word create followed by any number of other characters
  • Click “Find” to open the Find pane showing all the factory methods

Scopes

Often, you only want to search a subset of your project, for instance just the test or production source. IntelliJ IDEA provides Scopes to create smaller filesets used in searching, replacing, and inspections. Some default scopes are “Project Production Files”, “Project Test Files”, and “Changed Files”. Fine tune your searching by defining your own scope, perhaps based on a set of packages. Scopes can also be helpful to speed up searches on large projects. Here are the steps to define a scope:

  1. Open Settings (Ctrl+Alt+S) and select Scopes
  2. Click Rerun to create a new scope
  3. Select a package to include from the project browser. Use include and include recursively to broaden the fileset, and exclude and exclude recursively to narrow the fileset
  4. Save. New Scope is now available for many operations

Finding Documentation

There are many ways to find documentation on objects within your project and dependencies. Master these commands to get the information you need without leaving the IDE:

Ctrl+P Parameter Info. Displays quick information on the parameter types (and overloading options) of a method call when the caret is within the parenthesis of a method declaration
Ctrl+Q Quick Documentation Lookup. Displays Javadoc in a popup for the item at the caret
Ctrl+Shift+I Quick Definition. Displays the source code for the item at the caret
Shift+F1 External Javadoc. Opens an external browser to the Javadoc for the item at the caret. May require setting Javadoc locations within Settings (Ctrl+Alt+S) Project Settings (1)

Hot Tip

Is an option you need buried deep in the menu system? Use Ctrl+Shift+A to bring up the Action finder. Type the name of the action you’re looking for and IntelliJ IDEA searches the keymap, menus, and toolbars for the item you need to invoke. Wildcards and camelCase works, of course

Running and Debugging Your Project

Running and debugging the project is an essential part of any IDE. The easiest way to run an application is to right click the object within the Editor pane and select Run. This works for classes with main() and test cases. You can also right click the object and do the same thing in the Project pane. To run tests in an entire package simply right click the package.

Manage run targets by using the Run/Debug configurations window, adding any VM parameters or advanced settings you may need. Open the window by clicking Edit Configurations within the toolbar's dropdown.

Toolbar Dropdown

Common run targets can be saved here for future runs.

Running an entry point will display the Run pane. This pane provides diagnostics on the running process. Get the information you need from running processes by learning to use the pane:

Ctrl+F5 Run Run the last target
pause Pause execution
Ctrl+F2 stop Stop execution
Ctrl+Break Dump Thread Dump Thread information to a new window or clipboard
Ctrl+Alt+Up Move Up Move Up Stack Trace, opening the Editor pane to the exception location
Ctrl+Alt+Down Move Down Move Down Stack Trace, opening the Editor pane to the exception location

Running and Debugging Your Project, continued

When debugging an application, the IDE provides a variety of ways to set breakpoints and watchpoints. The easiest is to click the left gutter of the line or method on which you want a breakpoint. More advanced breakpoints are available through the Breakpoints window (Ctrl+Shift+F8).

Line Break on the specified line of code
Exception Break when the specified exception is thrown
Method Break when the specified method is called
Field Break when the specified field instance is accessed or changed

Once stopped on a breakpoint, the Debug pane will open. This pane provides features common to all debuggers, as well as more advanced, uncommon actions.

Alt+F10 ExecutionPoint Show Execution Point
F8 Step Over Step Over
F7 Step Into Step Into
Shift+F7 Smart Step Into. Pick which method to step into when multiple calls exist on one line.
Alt+Shift+F7 Force Step Force Step Into
Shift+F8 Step Out Step Out
Drop Frame Drop Frame
Ctrl+Alt+Up Previous Frame Previous Stack Frame
Ctrl+Alt+Down Next Stack Frame Next Stack Frame
Alt+F9 Cursor Run to Cursor

Hot Tip

Control what not to step into in Settings (Ctrl+Alt+S) Debugger (G). Exclude certain library classes using the “Do not step into” list, skip simple getters, skip constructors, and more.

Once in the debugger, several panels provide different views of the application state. The Frames Panel shows the current stack frames on the selected thread, and you can navigate quickly between frames and threads. The Variables Panel shows any variables currently in scope. And the Watches Panel shows expanded information on selected variables. When entering variables to watch, autocompletion and smart-type both work.

Expression Evaluation (Alt+F8) allows quick execution of code snippets or blocks. From this window you can reference any in-scope variable of the application. It works a bit like a REPL window open with the current breakpoint’s environment, and is most useful in code fragment mode, where you can evaluate multi-line statements.

Hot Tip

Drop Frame within the debugger pops the current stack frame and puts control back out to the calling method, resetting any local variables. This is very useful to repeatedly step through a function, but be warned: field mutations or global state changes will remain.

Code Coverage: IntelliJ IDEA offers code coverage statistics using the EMMA or IntelliJ IDEA toolkit. Enable tracking in the Code Coverage tab of the Run/Debug Configurations window. The built in runner provides more accurate branching coverage when tracing is enabled. Results appear in several places:

Package Coverage Project pane shows % class and % line coverage per package
Class Coverage Project pane shows % class and % line coverage per class
Line Coverage Editor pane left gutter shows red for uncovered line, green for covered line

Code Coverage Data (Ctrl+Alt+F6) displays a list of previous runs, and selecting an entry shows the coverage data for that run. You can use this to compare coverage between subsequent runs.

Hot Tip

Under certain circumstances, code coverage may make your automated tests fail because instrumented bytecode is different than normal bytecode (I’ve seen this happen when remote CORBA interfaces were invoked). If this happens then simply exclude the affected classes from code coverage within the Run/Debug Configurations window.

Write Less Code

Typing less to produce more is a feature of any modern IDE. IntelliJ IDEA provides top tier code completion support, as well as many other code generation, file template, and refactoring features.

Code Completion: Leveraging code completion is essential to productivity:

Ctrl+Space Basic. Completes the names of in-scope classes, methods, fields and keywords. Also complete paths, when appropriate
Ctrl+Shift+Space Smart Type. Displays a suggestion list where the type of the object required can be inferred from the code, such as in the right hand side of assignments, return statements, and method call parameters
Ctrl+Alt+Space Class Name. Completes the names of classes and interfaces. Accepts camel case matching on input
Ctrl+Shift+Enter Complete Statement. Adds closing punctuation and moves cursor to next line
Alt+Slash Expand Word. Cycles through suggested word choices, highlighting the prototype in the editor

Hot Tip

Confused by all the options? Just start using them and let muscle memory take over. It works.

Code Generation: Letting the IDE infer the code you need to create and drop in the appropriate template can be a huge time saver.

Ctrl+O Override Methods... quickly specify a parent method to override and create a stub implementation
Ctrl+I Implement Methods... quickly specify a parent method to implement and create a stub
Code->Delegate Methods... Delegate Methods... creates adapter classes by delegating method calls to member fields. A small wizard guides you through the delegation
Ctrl+Alt+T Surround With... surrounds the current selection with a variety of code wrappers, like if/else, for, try/catch, synchronized, Runnable, and more

Write Less Code, continued

Generate (Alt+Insert) provides its own set of powerful options for code generation:

Constructor Select any of your object’s fields from a list to create a constructor with the proper parameters and body
Getter Select a field from a list to create an accessor method
Setter Select a non-final field from a list to create a mutator method
equals() /
hashCode()
Provides a dialog to automatically create equals() and hashCode() methods based on your object’s fields

Live Templates are fragments of commonly occurring code, which can be inserted into the active file in a variety of ways. Learning the live templates will save you many, many keystrokes. A full list is available in Settings (Ctrl+Alt+S) Live Templates.

To insert a live template, press Ctrl+J followed by the following keys:

psf public static final thr throw new
itar Iterate elements of an
array
sout Prints a string to
System.out
itco Iterate elements of
collection
soutm Prints the current class and method name to System.out
ritar Iterate elements of array
in reverse order
soutv Prints the value of a variable to System.out
toar Stores members of
Collection in Array
psvm main() method declaration

Hot Tip

Logging live templates are very useful, but many projects use log4J or Commons Logging instead of System.out. Replace the System.out calls with your framework within Settings (Ctrl+Alt+S) Live Templates.

Surround with Live Template (Ctrl+Alt+J) will surround the current selection with a block of code. Some of the useful surrounds are:

B Surround with { }
R Surround with Runnable
C Surround with Callable

Hot Tip

Use the existing surrounds templates to create your own, like surround with SwingUtilities.invokeLater() or new Thread().start()

Live Template in Multiple Languages: Many live templates exist for languages other than Java. JSP, XML, Spring definitions, and more all exist. Here are some examples of templates from other platforms and toolsets:

sb Creates an XML based Spring bean definition
sbf Creates an XML based Spring bean definition instantiated by a factory method (many more Spring intentions exist, too)
itws Generate Axis web service invocation (many more flavors of web services supported, too)
CD Surround with CDATA section
T Surround with <tag></tag>

Hot Tip

The free keymap from JetBrains provides a larger list of live templates. Post the keymap next to your monitor to learn the live templates quickly.

Refactoring: IntelliJ IDEA offers excellent refactoring support. Refactoring is aware of comments, reflection, Spring, AOP, JSP, and more. When the refactoring features are unsure on the safety of a refactoring, a preview mode is invoked so that you can verify the changes. Refactoring works on more than just Java code too: many refactorings exists for XML files as well as other languages. Learning the refactoring tools (and reading the refactoring literature, for that matter) is well worth your time. Here are some of the more common refactorings:

Rename Shift+F6 Renames a package, class, method, field or variable
Move F6 Moves an entity
Change Signature Ctrl+F6 Change the method or class name,parameters, return type, and more
Extract Method Ctrl+Alt+M Moves the current selection to a new method, replacing duplicates if found
Inline Ctrl+Alt+N Takes a method, variable, or inner class and replaces usages with a unique definition
Introduce Variable Ctrl+Alt+V Moves the selected expression into a local variable
Introduce Field Ctrl+Alt+F Moves the selected local variable into a field,prompting you for how initialization should occur
Introduce Constant Ctrl+Alt+C Moves the selected variable or field into a static final field, replacing duplicates if found
Introduce Parameter Ctrl+Alt+P Moves the selected local variable into a parameter argument, updating any callers in the process
Extract Interface Moves a set of methods from the object onto an interface, updating callers to reference the interface if possible
Pull Member Up Move a method from a subclass up to an interface or parent class
Encapsulate Fields Provides getter and/or setters for the selected field

Hot Tip

Ctrl+Shift+J will join two lines together, which is a sort of shorthand for inline variable.

Improve Your Project ’s Quality

The IDE’s features aren’t just about writing code faster, they are also about coding more accurately. Understanding the intentions, inspections, and analysis tools are key to keeping code high quality.

Intentions: Keeps code clean by flagging potential problems in the Editor pane as they occur, and then offers an automated solution. An available intention is signaled by a lightbulb appearing in the left gutter, and the suggested fix can be applied by pressing Alt+Enter. There are several types of intentions:

  • n “Create from usage” intentions allow you to use new objects and methods without defining them first. Need a new method? Just call it from code; IntelliJ IDEA will prompt you to create it, inferring the parameter and result types. This works for classes, interfaces, fields, and variables. If the missing reference is in all capital letters, then it will even create a constant for you.

Improve Your Project’s Quality, continued

  • n “Quick fix” intentions find common mistakes and makes context-based suggestions on how to fix them. Examples of issues flagged with a quick fix are assigning a value to the wrong type or calling a private method.
  • “Micro-refactorings” fix code that compiles but could be improved. Examples are removing an unneeded variable and inverting an if condition.

Some of the intentions or fixes might violate your coding standard. Luckily, they can all be configured within Settings (Ctrl+Alt+S) Intentions.

Intentions and Quick Fixes are indicated by different icons in the left gutter, but in practice there is little need to differentiate between the two:

Icon Box

Inspections: Keeps code clean by detecting inconsistencies, dead code, probable bugs, and much, much more. The near-1000 default inspections can do a lot to enforce common idioms and catch simple bugs across the project. There are way too many inspections to list, but here are examples to provide a flavor of what inspections can do:

  • Flag infinite recursion or malformed regular expression
  • Catch error handling issues like continue within finally block or unused catch parameter
  • Find threading issues like await() outside a loop or non-thread safe access
  • Error on Javadoc issues like missing tags or invalid links

Inspections work with many languages and tools beyond the Java language, like Spring, JSF, Struts, XML, JavaScript, Groovy, and many others. The inspection set is highly configurable through Settings (Ctrl+Alt+S) Errors. Each inspection can carry its own set of options, and most can be shown as warnings or errors within the IDE. When an inspection violation is shown in the right gutter, Alt+Enter triggers the suggestions to be shown.

Some inspections appear within the Editor pane, while others appear within the Inspection pane when they are run as a batch. To run inspections for a scope, go to Analyze Inspect Code in the menu.

Inspection settings can be configured and shared across the team. An “IDE” inspection profile is saved within the user’s $HOME directory, but a “Project” profile is saved within the IDEA project file. This means a shared, version controlled project file can be created which contains the team’s inspections.

Hot Tip

By default, IDEA uses a great set of inspections, but many more options are not turned on by default. Check out http://hamletdarcy.blogspot.com/ 2008/04/10-best-idea-inspections-youre-not.html to see some non-default inspections you might want to use.

Code Analysis: Provides several different views of dependencies and duplicates within your project. These tools help you modularize your code and find areas of potential reuse. All of the following features are available from the Analyze menu.

The Dependency Viewer provides a split tree-view of your project with a list panel at the bottom. From here you can navigate the dependencies or mark certain undesirable dependencies as illegal. Which analysis feature chosen determines what the Viewer displays:

Dependencies Left: Your packages. Right: Packages your code depends on
Backward Dependencies Left: Your packages. Right: Packages that depend on your
code. Bottom: Line by line usages
Cyclic Dependencies Left: All of your packages that have a cyclic dependency. Right: The objects that form the cycle. Bottom: Line by line usages

Not all analysis tools report to the Dependency Viewer, however. Module Dependencies uses a separate panel to display dependencies across all the included modules within the project. This is useful for multi-module projects. Dependency Matrix launches the Dependency Structure Matrix in a separate window. This tool helps you visualize module and class dependencies across the project using a colored matrix.

Locate Duplicates: Finds suspected copy and pastes within your project or desired scope. Use this to find and consolidate duplicate modules or statements. The results are displayed in the Duplicates pane, which ranks the copy/paste violations and allows you to extract methods on the duplicates by simply clicking the Eliminate duplicates icon Icon1

Work as a Tea m

IntelliJ IDEA includes many features that allow team members to collaborate effectively.

Version Control (VC) integration exists for Subversion, Git, CVS, Perforce, StarTeam, Visual SourceSafe, TFS, and ClearCase. When enabled, local changes appear as a blue bar in the left gutter:

Version Control

Clicking the blue bar displays some VC options, including a quick line diff (displayed), a rollback of the line changes, or a full file diff in the IntelliJ IDEA Diff Viewer. More VC options are available from the menu or by right-clicking the active editor:

View History See revision history for active file with check-in comments
View
Differences
Launch the side-by-side file comparison window. Merge changes from one file to another, accept non conflicting changes, and more
Annotate Show the user ID of the last person to touch each line in the left gutter

Local History can be used even if you don’t have version control. The IDE keeps track of saves and changes to files, allowing you to rollback to previous versions if desired. Older versions can also be labeled, making it easy to find previous save points.

Shared Project: The project file can be put in version control, keeping all environments up to date as changes are made. Use this guide to the project files to determine what files need to be shared:

.ipr Contains project info like module paths, compiler settings, and library locations. This should be in version control
.iml Used in a multi-module project, each module is described by an .iml file. This should be in version control
.iws Contains workspace and personal settings. This should not be in version control

Work as a Team, continued

File Templates: Shared file templates provide a common starting point for frequently typed code. Templates exist, and can be changed, for creating new classes, interfaces, and enumerations. Templates for includes, like a copyright notice, can also be stored and shared, as well as code templates, like default catch statements and method bodies. Modify the file templates in Settings (Ctrl+Alt+S) File Templates.

Ant Integration: Many projects use Ant as a common build script, and IntelliJ IDEA offers integration with it. Features include syntax highlighting, code completion, and refactorings. Several inspections and intention settings are also available. Use the Ant Build Window to run one or several Ant targets. For larger projects with many targets, use the filter targets feature to hide uncommon targets. The Maven build system is also supported.

Work With the Database

IntelliJ IDEA 8 ships with a data source editor and JDBC console. Once configured with a JDBC or SQL data source, the console is a great environment for working with the database, providig SQL syntax completion, error and syntax highlighting, and completion of the table and column names. Middle click entities like table names or columns to navigate to their definition in the DDL view, and run the entire script (Ctrl+Enter) or snippits (Ctrl+Shift+Enter) using the controls provided. The results pane can be copied to the clipboard as comma separated values. You can also use parameters within the scripts, which are variables marked with the @, #, $, or ? characters. Any parameters found are displayed in the parameters Pane, and from there they can be edited without modifying the SQL source script.

Endless tweaking awaits

A massive amount of configuration options are available in Settings (Ctrl+Alt+S). Beyond that, you may wish to experiment with different plugins. Plugins are installed and managed using Settings (Ctrl+Alt+S) Plugins. Many plugins exist, adding features like Scala, Ruby, or web framework support. JetBrains holds plugin contests annually, so check the site periodically.

About The Author

Photo of author Hamlet D’Arcy

Hamlet D’Arcy

Hamlet D’Arcy has been writing software for over a decade, and has spent considerable time coding in Groovy, Java, and C++. He’s passionate about learning new languages and different ways to think about problems, and recently he’s been discovering the joys of both F# and Scheme. He’s an active member and speaker at the Groovy Users of Minnesota and the Object Technology User Group, and is involved with several open source projects including the Groovy language and the IDEA Jet- Groovy plugin. He blogs regularly at http://hamletdarcy.blogspot.com, tweets as HamletDRC, and can be contacted at hamletdrc@gmail.com.

Recommended Book

Easy PHP Websites with the Zend Framework

For new users, IntelliJ IDEA in Action is a logically organized and clearly expressed introduction to a big subject. For veterans, it is also an invaluable guide to the expert techniques they need to know to draw a lot more power out of this incredible tool. You get a broad overview and deep understanding of the features in IntelliJ IDEA.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

NetBeans IDE 7

Programming in Java 7

By Geertjan Wielenga

18,844 Downloads · Refcard 14 of 151 (see them all)

Download
FREE PDF


The Essential NetBeans 7 Cheat Sheet

NetBeans IDE 7: Programming in Java 7- Developers from the Java Development Kit team worked closely with developers from the NetBeans team to create a well aligned JDK 7 development experience with support for new language features, such as the diamond operator, strings in switch, and multicatch. When you use these constructs in your code, NetBeans IDE recognizes them, offers correct classes in code completion, correctly highlights errors, and lets you automatically fix old syntax. You’ll find this DZone Refcard helpful if you want to get as much out of JDK 7 and NetBeans IDE 7 as their creators intended.
HTML Preview
Netbeans Java Editor

Netbeans Java Editor

By Geertjan Wielenga and Patrick Keegan

About Netbeans IDE

The NetBeans IDE has seen adoption snowballing over the past years and now comes to you with deep Java EE 6 support in NetBeans IDE 6.8. You’ll find this reference card helpful if you want to get as much out of the Java editor (and related tools) as its authors intended when creating it. It lists all the keyboard shortcuts in carefully thought out categories and it provides a thorough exposition of optimal handling of Java code in the editor, covering viewing, navigation, source handling, and refactoring. Go to http://www.netbeans.org/downloads/ to get NetBeans IDE.

Java Editor Overview

What's New For Java In Netbeans IDE 6.8

The following features are new in NetBeans IDE 6.8 and can be of particular use to you in the context of creating Java-based applications:

Java EE 6 Support The IDE provides tools for developing applications complying with the new Java Enterpise Edition 6, specifically web, EJB, web service, and JPA support. The Java EE 6 compliant server bundled with the IDE is GlassFish v3.
Facelets Editor For Facelets (JavaServer Faces 2.0), a complete editor with coloring, code completion, namespace support, component palette, code folding, error checking, and code templates is provided.
Maven Java EE 6 archetype support, new archetype catalogs, Groovy & Scala support, dependency exclusion support in visual dependency graph, as well as several other performance and usability improvements.
Other Related Enhancements JavaFX editor, JIRA support, instant messaging, new UI for Kenai projects, and code completion enhancements in SQL editor.

Netbeans IDE Java Quick Start Tutorial

This tutorial provides a very simple and quick introduction to the NetBeans IDE workflow by walking you through the creation of a simple “Hello World” Java console application.

  1. Start NetBeans IDE. In the IDE, choose File > New Project (Ctrl-Shift-N).
  2. In the New Project wizard, expand the Java category and select Java Application. Then click Next.
  3. In the Name and Location page of the wizard, type "HelloWorld" in Project Name. Then click Finish.
  4. Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:
    // TODO code application logic here
    with the line:
    System.out.println("Hello World!");
  5. From the IDE’s menu bar, choose Run > Run Main Project (F6). The Output window should show you the "Hello World!" message.

Keyboard Shortcuts And Code Templates

Finding, Searching, and Replacing

Ctrl-F3 Search word at insert point
F3/Shift-F3 Find next/previous in file
Ctrl-F/H Find/Replace in file
Alt-F7 Find usages
Ctrl-Shift-F/H Find/replace in projects
Alt-Shift-U Find usages results
Alt-Shift-H Turn off search result highlights
Ctrl-R Inplace Rename
Ctrl-U, then U Convert selection to uppercase
Ctrl-U, then L Convert selection to lowercase
Ctrl-U, then S Toggle case of selection
Alt-Shift-V Paste formatted

Opening and Toggling Between Views

Ctrl-Tab (Ctrl-`) Toggle between open documents
Shift-Escape Maximize window (toggle)
Ctrl-F4/Ctrl-W Close currently selected window
Ctrl-Shift-F4/Ctrl-Shift-W Close all windows
Shift-F10 Open contextual menu
Alt-Shift-D Undock window
Ctrl-4 Open Output window
Ctrl-8 Open Kenai Dashboard

Navigating through Source Code

Ctrl-O/Alt-Shift-O Go to type/file
Ctrl-Shift-T Go to related JUnit test, if any
Alt-O Go to source
Ctrl-B Go to declaration
Ctrl-G Go to line
Ctrl-Shift-M Toggle add/remove bookmark
Ctrl-Shift-Period/Comma Next/previous bookmark
Ctrl-Period/Comma Next/previous usage/compile error
Ctrl-Shift-1/2/3 Select in Projects/Files/Favorites
Ctrl-[ Move caret to matching bracket
Ctrl-K/Ctrl-Shift K Next/previous word match
Alt-Left/Alt-Right/Ctrl-Q Go backward/forward/to last edit

Compiling, Testing, and Running

F9 Compile package/ file
F11 Build main project
Shift-F11 Clean & build main project
Ctrl-Q Set request parameters
Ctrl-Shift-U Create JUnit test
Ctrl-F6/Alt-F6 Run JUnit test on file/project
F6/Shift-F6 Run main project/file

Debugging

Ctrl-F5 Start debugging main project
Ctrl-Shift-F5 Start debugging current file
Ctrl-Shift-F6 Start debugging test for file (JUnit)
Shift-F5/F5 Stop/Continue debugging session
F4 Run to cursor location in file
F7/F8 Step into/over
Ctrl-F7 Step out
Ctrl-Alt-Up Go to called method
Ctrl-Alt-Down Go to calling method
Ctrl-F9 Evaluate expression
Ctrl-F8 Toggle breakpoint
Ctrl-Shift-F8 New breakpoint
Ctrl-Shift-F7 New watch

Coding In Java

Alt-Insert Generate code
Ctrl-Shift-I Fix all class imports
Alt-Shift-I Fix selected class’s import
Alt-Shift-F Format selection
Alt-Shift Left/Right/Up/Down Shift lines left/right/up/down
Ctrl-Shift-Up/Down Copy lines up/down
Ctrl/Alt-F12 Inspect members/hierarchy
Ctrl-/ Add/remove comment lines
Ctrl-E Delete current line

Refactoring

This table provides short descriptions of the refactoring operations that are available in the IDE, mostly from under the Refactoring menu and within the Java editor itself, when you right-click within it.

Refactoring Operation Description
Rename Enables you to change the name of a class, variable, or method to something more meaningful. In addition, it updates all source code in your project to reference the element by its new name.
Introduce Variable, Constant, Field, or Method Enables you to generate a statement based on the selected code and replace that block of code with a call to the statement.
Change Method Parameters Enables you to add parameters to a method and change the access modifier.
Encapsulate Fields Generates a getter method and and a setter method for a field and optionally updates all referencing code to access the field using the getter and setter methods.
Pull Up Moves methods and fields to the superclass.
Push Down Moves inner classes, methods, and fields to all subclasses of their current class.
Move Class Moves a class to another package or into another class. In addition, all source code in your project is updated to reference the class in its new location.
Copy Class Copies a class to the same or a different package.
Move Inner to Outer Level Moves an inner class one level up in hierarchy.
Convert Anonymous Class to Inner Converts an anonymous class to an inner class that contains a name and constructor. The anonymous inner class is replaced with a call to the new inner class.
Extract Interface Creates a new interface from the selected public non-static methods in a class or interface.
Extract Superclass Creates a new abstract class, changes the current class to extend the new class, and moves the selected methods and fields to the new class.
Use Supertype Where Possible Changes code that references the selected class (or other type) to instead use a supertype of that type.
Safely Delete Checks for references to a code element and then automatically deletes that element if no other code references it.

When typing in the Source Editor, you can generate the text in the right-column of the following list by typing the abbreviation that is listed in the left-column and then pressing Tab.

Java Editor Code Templates

En Enumeration
Ex Exception
Ob Object
Psf public static final
Psfb public static final boolean
Psfi public static final int
Psfs public static final String
St String
ab abstract
bo boolean
br break
ca catch (
cl class
cn continue
df default:
dowhile do { } while (condition);
eq equals
ex extends
fa false
fi final
fl float
forc for (Iterator it = collection.iterator(); it.hasNext( );) { Object elem = (Object) it.next( ); }
fore for (Object elem : iterable) { }
fori for (int i = 0; i < arr.length; i++) { }
fy finally
ie interface
ifelse if (condition){ }else { }
im implements
iof instanceof
ir import
le length
newo Object name = new Object(args);
pe protected
pr private
psf private static final
psfb private static final boolean
psfi private static final int
psfs private static final String
pst printStackTrace();
psvm public static void main(String[ ] args){ }
pu public
re return
serr System.err.println ("|");
sout System.out.println ("|");
st static
sw switch (
sy synchronized
tds Thread.dumpStack();
th throws
trycatch try {} catch (Exception e) {}
tw throw
twn throw new
wh while (
whileit while (it.hasNext()) { Object elem = (Object) it.next(); }

JSP Code Templates

ag application.getAttribute(“|”)
ap application.putAttribute(“|”,)
ar application.removeAttribute(“|”)
cfgi config.getInitParameter(“|”)
jspf <jsp:forward page=”|”/>
jspg <jsp:getProperty name=”|” property=”” />
jspi <jsp:include page=”|”/>
jspp <jsp:plugin type=”|” code=”” codebase=””></jsp:plugin>
jsps <jsp:setProperty name=”|” property=””/>
jspu <jsp:useBean id=”I” type=””/>
oup out.print(“|”)
oupl out.println(“|”)
pcg pageContext.getAttribute(“|”)
pcgn pageContext.getAttributeNamesInScope(“|”)
pcgs pageContext.getAttributesScope(“|”)
pcr pageContext.removeAttribute(“|”)
pcs pageContext.setAttribute(“|”,)
pg <%@page |%>
pga <%@page autoFlush=”false”%>
pgb <%@page buffer=”|kb”%>
pgc <%@page contentType=”|”%>
pgerr <%@page errorPage=”|”%>
pgex <%@page extends=”|”%>
pgie <%@page isErrorPage=”true”%>
pgim <%@page import=”|”%>
pgin <%@page info=”|”%>
pgit <%@page isThreadSafe=”false”%>
pgl <%@page language=”java”%>
pgs <%@page session=”false”%>
rg request.getParameter(“|”)
sg session.getAttribute(“|”)
sp session.setAttribute(“|”, )
sr session.removeAttribute(“|”)
tglb <%@taglib uri=”|”%>

Mac OS Keyboard Shortcuts

In most cases, working with the IDE on the Mac is no different from working on other operating systems. Two significant differences do exist, however. Firstly, the Options window on the Mac is found under NetBeans > Preferences. Secondly, the About box is under NetBeans > About.

Scrolling and Selecting

Keys Action
Cmd-[ Moves the insertion point to the highlighted matching bracket. Note that this shortcut only works when the insertion point is located immediately after the opening bracket.
Cmd-Shift-[ Selects the block between a pair of brackets. Note that this shortcut only works when the insertion point is located immediately after either the opening or closing bracket.
Ctrl-G Jumps to any specified line.
Cmd-A Selects all text in the file.

Code Folding

Keys Action
Cmd-Minus (-) Collapses the block of code in which the insertion point is currently located.
Cmd-Plus (+) Expands the block of code which is adjacent to the insertion point.
Cmd-Shift-Minus (-) Collapses all blocks of code in the current file.
Cmd-Shift-Plus (+) Expands all blocks of code in the current file.

Cutting, Copying, Pasting, and Deleting Text

Keys Action
Cmd-Z Undo. Reverses a series of editor actions one at a time (excluding Save).
Cmd-Y Redo. Reverses a series of Undo commands one at a time.
Cmd-X Cut. Deletes the current selection and places it on the clipboard.
Cmd-C Copy. Copies the current selection to the clipboard.
Cmd-V Paste. Pastes the contents of the clipbard at the insert point.
Backspace Delete Deletes the current selection.
Cmd-E Deletes the current line.
Cmd-K Copies the word preceding the insertion point and then pastes it after the insertion point (the insertion point must be in the whitespace preceeding or following a word). Press K multiple times to cycle through preceding words in succession.
Cmd-Shift-K Copies the word following the insertion point and pastes it at the insertion point (the insertion point must be located in the whitespace preceeding or following a word.) Press L multiple times to cycle through consecutive following words.

To Change Default Settings:

  1. Choose Tools > Options from the main menu.
  2. For code templates, select Editor and click the Code Templates tab. Here you can also change the expansion key, from Tab to something ese.
  3. For keyboard shortcuts, select Keymap and choose a profile from the Profile drop-down list.

10 Handy Editor Shortcuts

  1. Move/copy up/down. Press Ctrl-Shift-Up and the current selection is copied to the lines right above the current selection. Press Alt instead of Ctrl and it is moved instead of copied. Press Down instead of Up and the lines of code will be copied below the current selection, as below:

  2. Capture inner/outer syntactic element. Each time you press Alt-Shift-Period, the selection expands to a successively wider syntactic element.

    For example, below one statement was selected, the key combination Alt-Shift-Period was pressed, and then the complete content of the surrounding block statement was shown to be selected.

    The selection expands from the current statement to sur rounding block statements to the surrounding method and, from there, to the surrounding class and further. To successively narrow the selection, press Alt-Shift-Comma, instead of Alt-Shift-Period

  3. Generate code skeletons. Whenever you want to generate commonly needed pieces of code, such as constructors, getters, and setters, simply click Alt-Insert, and a small popup appears with a list of items from which you can select: 10 Handy Editor Shortcuts in NetBeans IDE 6.0 as constructors, getters, and setters, simply

  4. Inplace rename. If you want to change a variable, method, or other item, of which more than one are used in your code, press Ctrl-R, and you will see that all instances of the item turn blue at the same time, as shown below. Now, when you change the selected item, all the other instances change at the same time, until you press Escape, at which point the inplace rename mode comes to an end.

  5. Add/Remove comment lines. Select one or more lines, press Ctrl-/ and then the selected lines are commented out, as shown below. Press the same keys again and the commented lines will no longer be commented.

  6. Inspect members/hierarchy. Both the members of the current class as well as its hierarchy can be displayed and then filtered. Press Alt-F12 and the ancestors of the current file are shown. On the other hand, if you press Ctrl-F12, the current file’s members are displayed, as shown here:

  7. Switch between documents. When you have multiple documents open at the same time, press Ctrl and Tab, and then a small popup appears. You can scroll through the popup, which displays all the open documents, and then choose the document that you want to open:

  8. Jump to last edit. Often, you find yourself in a situation where you have edited in one document, while you currently find yourself in a completely different document. How do you get back to the place where you were last editing your code? That is likely to be the place where you want to get back to, in order to do some more editing. Now, whenever you click Ctrl-Q, the last edited document is found, and the cursor lands on the line where the last edit took place. Alternatively, you can click the button shown below, in the top left corner of the Source Editor:

  9. Bookmarks. When you press Ctrl-Shift-M, the current line is “bookmarked”. What this means is that you can later quickly cycle back/forward to it (with Ctrl-Shift-Period and Ctrl-Shift-Comma). The bookmarked line gets a small icon in the left sidebar, as shown below, until you press Ctrl-Shift-M on the line again, to remove the bookmark:

  10. Highlight exit points. Place the cursor on the return type and you will immediately see all exit points highlighted:

Quick Options Window Overview

General Sets the IDE-wide browser and proxy settings
  • Web Browser
  • Proxy Settings
Editor Sets the editor-specific options, specifically those relating to code folding, code completion, camel case behavior, indentation, code templates, and macros.
  • Code Folding
  • Code Completion
  • Camel Case Behavior
  • Indentation
  • Code Templates
  • Macros
Fonts & Colors Sets the fonts and colors for syntax, highlighting, annotations, and diff viewer.
  • Syntax
  • Highlighting
  • Annotations
  • Diff
Keymap Sets the keyboard profile to be used throughout the IDE. By default, profiles are provided for NetBeans, Eclipse, and Emacs. A legacy profile is also provided, for NetBeans 5.5 keyboard shortcuts, which were radically rewritten in NetBeans IDE 6.0.
  • NetBeans Profile
  • Eclipse Profile
  • Idea Profile
  • Emacs Profile
  • Netbeans 5.5 Profile
Miscellaneous Sets the options for Ant processing, appearance, diffing, files, the Matisse GUI Builder, issue tracking, Java Debugger, JavaScript, Maven, Profiler, ToDo Tasks, and Versioning.
  • Ant
  • Appearance
  • Diff
  • Files
  • GUI Builder
  • Issue Tracking
  • Java Debugger
  • JavaScript
  • Maven
  • Profiler
  • Tasks
  • Versioning

Resources

Resource URL
NetBeans DZone Community http://netbeans.dzone.com/
NetBeans Tutorials http://www.netbeans.org/kb/index.html
NetBeans Video Tutorials http://www.netbeans.org/kb/60/screencasts.html
NetBeans Blogs http://planetnetbeans.org/
NetBeans TV http://netbeans.tv/
NetBeans Weekly Newsletter http://www.netbeans.org/community/news/newsletter/latest.html

Thanks to the following people who kindly gave of their time and expertise in reviewing this refcard: Adam Bien, Tonny Kohar, Varun Nischal, Kristian Rink, and Tom Wheeler.

Geertjan Wielenga

Photo of author Geertjan Wielenga

Geertjan Wielenga is the NetBeans technical writer responsible for documentation related to the NetBeans Java editor. He is co-author of the book Rich Client Programming: Plugging into the NetBeans Platform. He is known for his popular blog at http://blogs.sun.com/geertjan, as well as for his role as a Zone Leader at Javalobby.

Patrick Keegan

Photo of author Patrick Keegan

Patrick Keegan has been writing about the NetBeans IDE for over 9 years. In addition to writing help and tutorials, he is co-author of the NetBeans IDE Field Guide and has contributed to other books on NetBeans and Java.

Recommended Book

Book cover of Pro Netbeans IDE 6

Pro NetBeans IDE 6 Rich Client Platform Edition focuses on the new features of NetBeans 6 as well as what has changed since NetBeans 5.5, empowering you to be a more effective and productive developer.

Book cover of Definitife Guide to the Netbeans Platform

The Definitive Guide to NetBeans™ Platform is a thorough and definitive introduction to the NetBeans Platform, covering all its major APIs in detail, with relevant code examples used throughout.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Flex Mobile Development

Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

9,696 Downloads · Refcard 146 of 151 (see them all)

Download
FREE PDF


The Essential Flex Mobile Cheat Sheet

The Flex Mobile Development cheat sheet will walk you through the easiest process yet for developing and deploying cross-platform applications on multiple devices and platforms with the richness that you expect out of an Adobe creative tool. You can now develop mobile ActionScript and Flex applications for Google Android, Apple iOS, and BlackBerry Tablet OS with the same ease and quality as on desktop platforms, and with most of the same code! Get a rundown of the new Flash Builder 4.5s mobile app capabilities through a series of sections on app creation, mobile packaging, testing, and debugging.
HTML Preview
Flex Mobile Development: Build Apps for Android, iOS, and BlackBerry Tablet OS

Flex Mobile Development:Build Apps for Android, iOS, and BlackBerry Tablet OS

By Mihai Corlan

Adobe® Flash® Builder™ is an integrated development environment (IDE) based on the Eclipse platform. Available for Windows and Mac, it is used for creating Flex and Flash applications accessible via a web browser with Flash Player or as standalone apps.

Because it is based on the Eclipse platform (version 3.6.1), it can be installed as a standalone IDE or as a plug-in within another Eclipse installation.

You can run this version along with previous versions (Flash Builder 4 or Flash Builder 3) without any problems.

This version comes in two flavors: standard or premium. Each flavor is also available as Flash Builder 4.5 for PHP, which has all the features of Flash Builder plus Zend Studio 8.1 and a number of plug-ins that integrate these two IDEs.

Flash Builder Premium provides the following features in addition to those included with the standard version:

  • Network Monitor
  • Memory Profiler
  • HP QuickTest Professional and FlexUnit integration
  • Command-line support for automated build processes
  • ColdFusion Builder (an Eclipse-based IDE for ColdFusion application developers)

You can download Flash Builder 4.5 from here and Flash Builder 4.5 for PHP from here. Select the installer for the version you are interested in and for your operating system. The same installer can be used for installing the standalone version or the plug-in version.

Each version offers a 60-day trial period. Every time you start the product during the trial period you will see a reminder that enables you to buy the product or enter the serial number if you’ve already bought it.

To enable support for BlackBerry Tablet OS development you’ll have to download an Eclipse plug-in from RIM. Once installed in Flash Builder 4.5, this plug-in will enable a new platform target.

What’s new in Flash Builder 4.5

Here is a high level view of what is new in this release:

Support for mobile development. Flex 4.5 version marks the extension of the Flex framework to mobile development. Flash Builder 4.5 includes several mobile-specific features, including new project types, desktop simulation and design view, and support for packaging projects as native installers for Android, iOS, and BlackBerry Tablet OS.

Improved productivity. Code templates, quick assist, code hinting for metadata, and an improved profiler.

Expanded PHP support. Flash Builder for PHP integrates Zend Studio with Flash Builder:

  • New wizards for creating Flex and PHP projects for desktop or mobile.
  • Integrated debugging for PHP and Flex.

Flash Builder 4.5, Flex 4.5, and the screen metaphor

While it is possible to create mobile applications using pure ActionScript and Flash Builder 4.5, developing mobile apps using the Flex 4.5 framework, with its support for the screen metaphor, provides a substantial productivity boost.

There is almost always enough resolution and area on a desktop computer to fit all the information you want on the screen. By using hierarchical menus and pop-up windows you can fit even more content. Compared to this, a smartphone screen feels (almost) like a postage stamp. Besides screen size, pixel density plays an important role. The Nexus One, for example, has a resolution of 480 x 800 pixels and 254 pixels per inch. This means that you have to enlarge the text roughly two to four times to make it appear similar to the app running on a desktop or laptop screen. Thus you end up with less space to display information.

Window 1

Using the screen metaphor you can split the information and the UI of your application among multiple screens. For example, consider the MAX Companion 2010 app, which shows conference session information. When you want to see details for a particular session (see the images above) another screen is presented. When you return to the previous screen, the session list is shown again.

Elegant as it might be, writing an app using the screen metaphor is not rocket science. However, there are some issues to be considered, such as:

  • Memory management – pushing dozens of screens can consume all the memory available on the device
  • Transitions from one screen to another – nice effects will help you create an application like a professional UX Designer
  • Passing data from one screen to another – you need some way of exchanging data between screens
  • Preserving application state – when the OS closes your app, you’ll want to save its state to restore when it reopens
  • Integration with hardware buttons – you press the Back button of the device, for example, to navigate to the previous screen

The Flex framework has built-in support for the screen metaphor so you don’t have to reinvent the wheel as you address these issues

Supported mobile platforms

The June 2011 release of Flash Builder 4.5 and the Flex 4.5 SDK support Android, iOS, and BlackBerry Tablet OS. The initial launch (in May 2011) supported Flex development for Android only, although you could still develop pure ActionScript apps for all three platforms (Android, iOS, and BlackBerry Tablet OS).Applications created in Flash Builder run differently depending on the target platform:

  • On Android and BlackBerry Tablet OS the APK or BAR files are run using the Adobe AIR runtime installed on the devices. PlayBook devices (running BlackBerry Tablet OS) come with Adobe AIR pre-installed. Some Android devices have Adobe AIR pre-installed, while others don’t. If AIR is not installed already, you will be prompted to install it from the Android Market the first time an AIR application is opened.
  • On iOS, the application is cross-compiled to a native IPA file together with the Adobe AIR runtime.

FLASH BUILDER 4.5 MOBILE PROJECT TYPES

When you choose File > New in Flash Builder 4.5, you will see two new mobile applications project types to choose from: ActionScript Mobile Project and Flex Mobile Project.

In Flash Builder for PHP you’ll see those two types plus one more for creating a Flex Mobile and PHP project.

CREATING A FLEX MOBILE PROJECT

To use the Flex framework to create a mobile app:

  1. 1choose File > New > Flex Mobile Project. In the first page of the wizard, specify the project name.
  2. Window 2
  3. In the second page of the wizard, choose the target platforms. In the following image, BlackBerry Tablet OS and Google Android are selected; in the June 2011 release you can also select iOS. You can also use the Permissions tab on this page to set additional mobile application permissions for Android and BlackBerry Tablet OS. In the Application Template tab you’ll see three options: Blank, View-Based Application, and Tabbed Application. If you want Flex support for the screen metaphor, choose either View-Based Application or Tabbed Application. The Tabbed Application option is preferable if your application has lots of screens and you want to use a tab group at the bottom of the page to group these screens.

    if you choose Blank, you can use Flex components but you will have to handle events such as device orientation changes or pressing the Back button on an Android device yourself.

    When creating a Flex mobile and PHP project with Flash Builder 4.5 for PHP (File > New > Flex Mobile and PHP Project), the process is quite similar except you also set up a PHP project at the same time:
Window3

  • The second screen is for setting up the Flex project
  • The third screen is for setting up mobile specific settings

You can watch my video tutorial on this topic. Creating an ActionScript mobile project is similar to the Flex one.

Understanding Flex mobile View and ViewNavigator class

If you choose to use View-Based Application or Tabbed Application, it is important to understand the following classes: View, ViewNavigator, ViewNavigatorApplication, and TabbedViewNavigatorApplication.

The top application class will be ViewNavigatorApplication or TabbedViewNavigatorApplication depending on the Application Template you used when creating the project. You create your application user interface by extending the View class. Basically each screen of your application will be represented by a component that extends the View class. To create a new screen, choose File > New > MXML Component and then set the spark.components.View class as the class to base the component on.

The View class has two important properties: data and navigator. You use the navigator property (which refers to an instance of the ViewNavigator class) to control the screens. When you want to push a new view to the screen, you call navigator.pushView(new-viewclass- name). When you want to return to the previous view, you call navigator.popView(). When you want to jump to the first view you call navigator.popToFirstView().If you don’t want to have the View destroyed, you can set the destructionPolicy attribute of the View tag to “never”.

To pass data from the current View to the next one, simply set the second argument of the pushView() method to the data you want to pass; for example, navigator.pushView(view-class-name, dataToBeUsed); There are some applications that need to preserve their entire state when they are closed by the OS. To do this, just set the persistNavigatorState attribute in your main application file to true. This is a neat feature that allows you to support (with almost no effort) scenarios in which the user has navigated several screens into the application when the application gets closed (for example if the user switched to a new application or decided to close the app); when the application opens again, the user will see the same screen as in the previous session.

There are also events you can listen for in each View:

  • viewActivate (FlexEvent.VIEW_ACTIVATE) – Dispatched when the current view has been activated.
  • viewDeactivate (FlexEvent.VIEW_DEACTIVATE) – Dispatched when the current view has been deactivated.
  • removing (FlexEvent.REMOVING) – Dispatched when the screen is about to be removed in response to a screen change. If you call preventDefault() you can cancel the screen change. This event is triggered before the FlexEvent.VIEW_DEACTIVATE event.

TESTING AND DEBUGGING MOBILE PROJECTS

One of the most powerful features of Flash Builder 4.5 is its ability to run mobile projects right from the IDE. If you have a physical device you can deploy the app and debug on the device from Flash Builder

If you don’t have a device you can use the Flash Builder simulator to test the app. In either case, you start by choosing Run > Running Configuration or Run > Debug Configurations.

To add a new configuration, select the Mobile Application entry (or Mobile (PHP) Application if the project type is Flex Mobile and PHP) and then click the top-left icon to add a new configuration. Select the project that you want to create the configuration for and then select the Target Platform (Android, iOS, or BlackBerry Tablet OS).

Window4

For the Launch Method, select On Desktop if you want to run the app on the desktop simulator or select On Device if you want to deploy the app to the device. The simulator is quick and easy to use. Using the second option—On Device—is less straightforward; depending on the target platform you will need certificates, provisioning files, debug tokens, and so on. For both options you can run the application with or without debugging support.

PACKAGING A MOBILE PROJECT AS A MOBILE APP

Flash Builder 4.5 supports packaging your mobile projects (ActionScript or Flex) as native applications that is, as an APK for Android, an IPA for iOS, or a BAR for BlackBerry Tablet OS.

To access this feature, select the project for which you want to create the native app, choose File > Export, and select Flash Builder > Release Build.

Window5

Follow the directions on screen for the rest of the process, which is different for each supported target (Android, BlackBerry Tablet OS, or iOS).

Packaging mobile apps for Android

To package a mobile app for Android, right-click the project name in the Package Explorer view and select Export > Flash Builder > Release Build. On the first page of the wizard make sure you select the Google Android platform and select Signed Package For Each Target Platform.

Window6

On the second page of the wizard in the Digital Signature section, click Create to begin creating a self-signed certificate. Type the publisher name, organizational unit, organizational name, and country. Select 2040-RSA for the type, set the password, and specify the location and the file name for the certificate. When you click OK, Flash Builder will create the certificate. When you complete the wizard by clicking Finish, Flash Builder will create the APK file. By default, the APK file is created inside the root of your project. You can upload this file to the Android Market.

Window7

Every time you want to release an update for your application, first increase the versionNumber in your application descriptor file and then use the same workflow to create the APK. This time, however, instead of creating a new certificate, just select the one you created earlier.

Packaging mobile apps for BlackBerry Tablet OS

There are two main steps you have to complete to package AIR projects for BlackBerry Tablet OS:

  • Request permission from RIM to sign BlackBerry Tablet OS apps and get the CSJ registration files.
  • Configure Flash Builder for signing PlayBook apps and sign your application.

The credit card is required only for verification purpose. Once you finish this registration you will receive a confirmation email. Then, you should receive by email a number of CSI and CSJ files within 24 hours. Save all these files in the same folder. (Note that the number part of the filename is different for each registration). If you forget the PIN or if you want to sign from another computer, you can submit another request.

Package the project for PlayBook

Once you have the files from RIM, you are ready to use Flash Builder 4.5 to sign mobile ActionScript and Flex projects. Begin by opening the Preferences dialog box (choose Window > Preferences). Then expand the Flash Builder entry on the left side and choose Target Platforms > BlackBerry Tablet OS > Signing.

The top section is for providing a developer certificate for signing the code. To create one, click Create Certificate. Pay attention to what password you set and what value you set for the Publisher–this value must be the same as the one you provided when requesting permission to sign PlayBook apps. When you click OK in the Create Developer Certificate dialog box, a new certificate will be generated. Now, add this certificate by clicking the Select Certificate button.

Window8

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate.

Next you need to register and configure the RIM certificate. First click Create in the RIM Certificate section and set a password (it must be at least 6 characters long). Then click the Register button, select the last of the five CSJ files you received via email, and provide the same PIN you set when you completed the online form. Flash Builder will communicate with RIM servers (this step requires you to have your computer connected to the Internet) to register your RIM certificate. To save the configuration, click OK.

Window9

After you’ve registered your certificates with the BlackBerry Signing Authority you should receive an email confirmation. The next step is to open the application descriptor file for your project in Flash Builder and make sure you set a version number for <versionNumber>. Each time you export a release build you’ll have to increase this number. Next, open the blackberry-tablet. xml file and make sure that the value for the <publisher> node is the same as the one you set for the company value when you registered for signing PlayBook apps and when you generated the developer certificate. Then right-click the project name in the Package Explorer view and select Export.

In the wizard that opens, select Flash Builder > Release Build and click Next. In the second page of the wizard make sure you select BlackBerry Tablet OS in the Target Platforms section. By default the BAR file will be created in the root folder of the project you are exporting. If you want to use a different path, type a new Export To Folder value. You also need to select Export And Sign A Platform-specific Application Package. Click Next.

Window10

In the third page of the wizard select Enable Digital Signing on the Digital Signature tab. This option will use the certificates (Developer and RIM) you set earlier. Finally, click Finish.

Window11

After a few seconds you should have a new BAR file. If you encounter any errors, see BlackBerry’s page on application signing errors for additional information.

You can submit the BAR file to the BlackBerry App World portal (if you have registered as a vendor) via https://appworld.blackberry. com/isvportal/.

Packaging mobile apps for iOS

To package applications for testing and debugging on iOS devices or for deployment to the Apple App Store you will need to enroll in the Apple Developer Program (fees apply). For more information on the Apple Developer Program and to create an account, visit Apple’s Developer Program Enrollment page.

Once registered, you will need to login to the iOS Provisioning Portal and complete the following tasks:

  • Generate a development certificate
  • Register any devices to which you wish to deploy applications during development
  • Define an App ID for the application you are developing
  • Create a development provisioning profile

You will also use the iOS Provisioning Portal to distribute your application via the App Store. That part of the process is not covered in this article; instead refer to Apple’s documentation. The development certificate (in P12 format) and the provisioning profile are required before you can package your application for iOS in Flash Builder.

Generate a development certificate

Follow the guide on the iOS Provisioning Portal to generate your development certificate. This guide assumes you are using a Mac OS based computer, but it is possible to generate the certificate using Windows; details are available in the Adobe AIR documentation.

Convert the developer certificate into a P12 format

To use the certificate with Flash Builder, you must convert into P12 format. Instructions on how to do this are provided in the Adobe AIR documentation on signing AIR applications.

Store the P12 (.p12) file on your computer; you will need to use it with Flash Builder later.

Register devices to which you wish to deploy applications during development

You must specify any devices on which you intend to run or debug the application in the provisioning profile used to package the application; as such, you must register the devices on the iOS Provisioning Portal.

To register a device you need its Unique Device Identifier (UDID). To get this, connect your device to your computer and launch iTunes. In iTunes, select your device in the Devices section and navigate to the Summary tab. Click the Serial Number label to reveal the Identifier field and the 40 character UDID. Press Command/CTRL+C to copy the UDID to your clipboard.

Define an App ID for the application you are developing

Each application that you wish to deploy must have an App ID, which comprises a Bundle Seed ID (also called the App ID Prefix) and a Bundle Identifier (also called the App ID Suffix). Follow the guide on the iOS Provisioning Portal to create your

App ID.
Note that the Bundle Identifier must be the same as the value of the <id> attribute in your application’s app.xml descriptor file. For example, if you create a Bundle Identifier as “com.adobe. myApp”, then your app.xml file must contain the following:

<!-- A universally unique application identifier. Must be unique across all AIR applications. Using a reverse DNSstyle name as the id is recommended. Required. --> <id>com.adobe.myApp</id> You can use a wildcard in the Bundle Identifier to create a provisioning profile that is valid for a number of applications; for example a provisioning profile with a Bundle Identifier specified as “com.adobe.*” can be used with applications with an id of “com.adobe.myApp” and “com.adobe.myOtherApp”. Also note that once created, you cannot remove an App ID from the iOS Provisioning Portal.

Create a development provisioning profile

The final step you need to complete using the iOS Provisioning Portal is to create an iOS Development Provisioning Profile. You will define a profile name, specify the certificate you created, select an App ID, and choose the device or devices the application can be deployed to. More information on creating a Provisioning Profile can be found in the guide on Apple’s site. Download the provisioning file to your computer; you will need to use it with Flash Builder later.

Specify build packaging information for the project in Flash Builder

Before you are ready to deploy an application to an Apple iOS device you need to specify the information required to package the application as an IPA file.

In the Package Explorer view in Flash Builder, right-click your project and select Properties. In the Properties dialog box, select ActionScript Build Packaging > Apple iOS (for an ActionScript project) or Flex Build Packaging > Apple iOS (for a Flex project). In the Digital Signature tab, specify the previously saved P12 certificate file and the provisioning file for your project. Click Apply and then click OK.

When you want to create an IPA file simply right-click the project name in the Package Explorer view and select Export > Flash Builder > Release build. Follow the steps in the wizard to create your IPA file.

CONCLUSIONS

If you want to learn more about mobile development for Android, iOS, and PlayBook using Adobe AIR, Flash Builder, and Flex I encourage you to check these resources:

  • Adobe Mobile and Devices Development Center
  • Creating Flex Mobile Apps with Flash Builder for PHP tutorial
  • Great list of resources for designing and skinning mobile applications

About The Authors

Mihai Corlan

Mihai Corlan is a world wide developer evangelist at Adobe focusing on Flex, AIR, Flash Builder, and Flex, and HTML. Before that he worked with Flex Builder as a computer scientist. Prior to joining Adobe, Mihai was a senior web developer with InterAKT Online (acquired by Adobe in 2006), where he built web applications, frameworks, desktop software, and RIAs. Since 2008 he’s been writing about RIAs and mobile development at http:// corlan.org

You can follow him on Twitter http://twitter.com/mcorlan

Recommended Book

Continuous Delivery

Adobe Flex: Training from the Source was written by a team of authors with practical experience as consultants, mentors and developers of courseware, this book/CD uses project-based tutorials, and is designed to teach beginning Flex developers the details of building and architecting real-world rich internet applications using Flash Builder incorporating MXML and ActionScript 3.0.Flex 4.5 features, such as new enhancements to the Spark architecture and component set. It will also show you how to take advantage of the improvements to core Flex infrastructure for large application development.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Continuous Delivery

Patterns and Antipatterns in the Software Lifecycle

By Paul M. Duvall

19,629 Downloads · Refcard 145 of 151 (see them all)

Download
FREE PDF


The Essential Continuous Delivery Cheat Sheet

This Continuous Delivery cheat sheet from DZone is loaded with over 40 different patterns and antipatterns for configuration management, continuous integration (CI), infrastructure, incremental development, and deployment. Continuous Delivery: Patterns and Antipatterns in the Software Lifecycle encourages you to follow the mantra: "Release early and often." The key is for software production teams to minimize the time it takes to go from idea to usable software by using agile techniques and automating the entire software delivery system: build, deploy, test, release.
HTML Preview
Continuous Delivery Patterns and Antipatterns in the Software Lifecycle

Continuous DeliveryPatterns and Antipatterns in the Software Lifecycle

By Paul M. Duvall

ABOUT CONTINUOUS DELIVERY

With Continuous Delivery (CD), teams continuously deliver new versions of software to production by decreasing the cycle time between an idea and usable software through the automation of the entire delivery system: build, deployment, test, and release. CD is enabled through the Deployment Pipeline, which encompasses a collection of patterns described in this Refcard.

CD is concerned with “…how all the moving parts fit together: configuration management, automated testing, continuous integration and deployment, data management, environment management, and release management.” (1)

THE DEPLOYMENT PIPELINE

Figure 1

The purpose of the deployment pipeline is threefold:

  • Visibility: All aspects of the delivery system - building, deploying, testing, and releasing – are visible to all team members promoting collaboration.
  • Feedback: Team members learn of problems as soon as they occur so that issues are fixed as soon as possible.
  • Continually Deploy: Through a fully automated process, you can deploy and release any version of the software to any environment. (1)

In the Deployment Pipeline diagram above, all of the patterns are shown in context. There are some patterns that span multiple stages of the pipeline, so I chose the stage where it’s most predominately used.

BENEFITS

  • Empowering Teams: Because the deployment pipeline is a pull system, testers, developers, operations, and others can self service the application version into an environment of their choice.
  • Reducing Errors: Ensuring the correct version, configuration, database schema, etc. are applied the same way every time through automation.
  • Lowering Stress: Through push-button releases to production and Rehearsing Deployments, a release becomes commonplace without the typical stress.
  • Deployment Flexibility: Instantiate a new environment or configuration by making a few changes to the automated delivery system.
  • Practice makes Perfect: Through the deployment pipeline, the final deployment into production is being rehearsed every single time the software is deployed to any target environments. (1)

CONFIGURATION MANAGEMENT

Configuration Management is “the process by which all artifacts relevant to your project, and the relationships between them, are stored, retrieved, uniquely identified, and modified”. (1)

Note: Each pattern is cited with a number in parentheses that corresponds to the source in the References section.

Configurable Third-Party Software (1)

Pattern Evaluate and use third-party software that can be easily configured, deployed, and automated.
Anti-patterns Procuring software that cannot be externally configured. Software without an API or commandline interface that forces teams to use the GUI only.

Configuration Catalog (1)

Pattern Maintain a catalog of all options for each application, how to change these options and storage locations for each application. Automatically create this catalog as part of the build process.
Anti-patterns Configuration options are not documented. The catalog of applications and other assets is “tribal knowledge”.

Mainline (3)

Pattern Minimize merging and keep the number of active code lines manageable by developing on a mainline.
Anti-patterns Multiple branches per project.

Merge Daily (1)

Pattern Changes committed to the mainline are applied to each branch on at least a daily basis.
Anti-patterns Merging every iteration once a week or less often than once a day.

Protected Configuration (5) ,(1)

Pattern Store configuration information in secure remotely accessible locations such as a database, directory, or registry.
Anti-patterns Open text passwords and/or single machine or share.

Repository (3) , (1)

Pattern All source files - executable code, configuration, host environment, and data - are committed to a versioncontrol repository.
Anti-patterns Some files are checked in, others, such as environment configuration or data changes, are not. Binaries – that can be recreated through the build and deployment process – are checked in.

Short-Lived Branches (1)

Pattern Branches must be short lived – ideally less than a few days and never more than an iteration.
Anti-patterns Branches that last more than an iteration. Branches by product feature that live past a release.

Single Command Environment (1)

Pattern Check out the project’s version-control repository and run a single command to build and deploy the application to any accessible environment, including the local development.
Anti-patterns Forcing the developer to define and configure environment variables. Making the developer install numerous tools in order for the build/deployment to work.

Single Path to Production (1)

Pattern Configuration management of the entire system - source, configuration, environment and data. Any change can be tied back to a single revision in the version-control system.
Anti-patterns Parts of system are not versioned. Inability to get back to a previously configured software system.

CONTINUOUS INTEGRATION (CI)

Build Threshold (5)

Pattern Fail a build when a project rule is violated – such as architectural breaches, slow tests, and coding standard violations.
Anti-patterns Manual code reviews. Learning of code quality issues later in the development cycle.

Commit Often (6)

Pattern Each team member checks in regularly to trunk - at least once a day but preferably after each task to trigger the CI system.
Anti-patterns Source files are committed less frequently than daily due to the number of changes from the developer.

Continuous Feedback (6)

Pattern Send automated feedback from CI system to all Cross-Functional Team members.
Anti-patterns Notifications are not sent; notifications are ignored; CI system spams everyone with information they cannot use.

Continuous Integration (6)

Pattern Building and testing software with every change committed to a project’s version control repository.
Anti-patterns Scheduled builds, nightly builds, building periodically, building exclusively on developer’s machines, not building at all.

Stop the Line (5) , (1) , (4), (12)

Pattern Fix software delivery errors as soon as they occur; stop the line. No one checks in on a broken build as the fix becomes the highest priority.
Anti-patterns Builds stay broken for long periods of time, thus preventing developers from checking out functioning code.

Independent Build (6)

Pattern Write build scripts that are decoupled from IDEs. These build scripts are executed by a CI system so that software is built at every change.
Anti-patterns Automated build relies on IDE settings. Builds are unable to be run from the command line.

Visible Dashboards

Pattern Provide large visible displays that aggregate information from your delivery system to provide highquality feedback to the Cross-Functional Team in real time.
Anti-patterns Email-only alerts or not publicizing the feedback to the entire team.

TESTING

Automate Tests

Pattern Automate the verification and validation of software to include unit, component, capacity, functional, and deployment tests
Anti-patterns Manual testing of units, components, deployment, and other types of tests.

Unit- Automating tests without any dependencies.

Component- Automating tests with dependencies to other components and heavyweight dependencies such as the database or file system.

Deployment- Automating tests to verify the deployment and configuration were successful. Sometimes referred to as a “smoke tests”.

Functional- Automating tests to verify the behavior of the software from a user’s perspective.

Capacity- Automating load and performance testing in nearproduction conditions.

Isolate Test Data (1)

Pattern Use transactions for database-dependent tests (e.g.,component tests) and roll back the transaction when done. Use a small subset of data to effectively test behavior.
Anti-patterns Using a copy of production data for Commit Stage tests. Running tests against a shared database.

Parallel Tests (1)

Pattern Run multiple tests in parallel across hardware instances to decrease the time in running tests.
Anti-patterns Anti-patterns Running tests on one machine or instance. Running dependent tests that cannot be run in parallel.

Stub Systems (1)

Pattern Use stubs to simulate external systems to reduce deployment complexity.
Anti-patterns Manually installing and configuring interdependent systems for Commit Stage build and deployment.

DEPLOYMENT PIPELINE

Pattern A deployment pipeline is an automated implementation of your application’s build, deploy, test, and release process.
Anti-patterns Deployments require human intervention (other than approval or clicking a button). Deployments are not production ready.

Value-Stream Map (4)

Pattern Create a map illustrating the process from check in to the version-control system to the software release to identify process bottlenecks.
Anti-patterns Separately defined processes and views of the checkin to release process.

BUILD AND DEPLOYMENT SCRIPTING

Dependency Management (5)

Pattern Centralize all dependent libraries to reduce bloat, classpath problems, and repetition of the same dependent libraries and transitive dependencies from project to project.
Anti-patterns Multiple copies of the same binary dependencies in each and every project. Redefining the same information for each project. Classpath hell!

Common Language (1)

Pattern As a team, agree upon a common scripting language - such as Perl, Ruby, or Python - so that any team member can apply changes to the Single Delivery System.
Anti-patterns Each team uses a different language making it difficult for anyone to modify the delivery system reducing cross-functional team effectiveness.

Externalize Configuration (5)

Pattern Changes between environments are captured as configuration information. All variable values are externalized from the application configuration into build/deployment-time properties.
Anti-patterns Hardcoding values inside the source code or per target environment.

Fail Fast (6)

Pattern Fail the build as soon as possible. Design scripts so that processes that commonly fail run first. These processes should be run as part of the Commit Stage.
Anti-patterns Common build mistakes are not uncovered until late in the deployment process.

Fast Builds (6)

Pattern The Commit Build provides feedback on common build problems as quickly as possible - usually in under 10 minutes.
Anti-patterns Throwing everything into the commit stage process, such as running every type of automated static analysis tool or running load tests such that feedback is delayed.

Scripted Deployment (5)

Pattern All deployment processes are written in a script, checked in to the version-control system, and run as part of the Single Delivery System.
Anti-patterns Deployment documentation is used instead of automation. Manual deployments or partially manual deployments. Using GUI to perform a deployment.

Unified Deployment (5)

Pattern The same deployment script is used for each deployment. The Protected Configuration – per environment - is variable but managed.
Anti-patterns Different deployment script for each target environment or even for a specific machine. Manual configuration after deployment for each target environment.

DEPLOYING AND RELEASING APPLICATIONS

Binary Integrity (5)

Pattern Build your binaries once, while deploying the binaries to multiple target environments, as necessary.
Anti-patterns Software is built in every stage of the deployment pipeline.

Canary Release

Pattern Release software to production for a small subset of users (e.g. , 10%) to get feedback prior to a complete rollout.
Anti-patterns Software is released to all users at once.

Blue-Green Deployments (1)

Pattern Deploy software to a non-production environment (call it blue) while production continues to run. Once it’s deployed and “warmed up”, switch production (green) to non-production and blue to green simultaneously.
Anti-patterns Production is taken down while the new release is applied to production instance(s).
Figure 2

Dark Launching (11)

Pattern Launch a new application or features when it affects the least amount of users.
Anti-patterns Software is deployed regardless of number of active users.

Rollback Release (5)

Pattern Provide an automated single command rollback of changes after an unsuccessful deployment.
Anti-patterns Manually undoing changes applied in a recent deployment. Shutting down production instances while changes are undone.

Self-Service Deployment (1)

Pattern Any Cross-Functional Team member selects the version and environment to deploy the latest working software.
Anti-patterns Deployments released to team are at specified intervals by the “Build Team”. Testing can only be performed in a shared state without isolation from others.

INFRASTRUCTURE AND ENVIRONMENTS

Automate Provisioning (1)

Pattern Automate the process of configuring your environment to include networks, external services, and infrastructure.
Anti-patterns Anti-patterns Configured instances are “works of art” requiring team members to perform partially or fully manual steps to provision them.

Behavior-Driven Monitoring (1)

Pattern Automate tests to verify the behavior of the infrastructure. Continually run these tests to provide near real-time alerting.
Anti-patterns No real-time alerting or monitoring. System configuration is written without tests.

Immune System (9)

Pattern Deploy software one instance at a time while conducting Behavior-Driven Monitoring. If an error is detected during the incremental deployment, a Rollback Release is initiated to revert changes.
Anti-patterns Non-incremental deployments without monitoring.

Lockdown Environments (1)

Pattern Lock down shared environments from unauthorized external and internal usage, including operations staff. All changes are versioned and applied through automation.
Anti-patterns The “Wild West”: any authorized user can access shared environments and apply manual configuration c hanges, putting the environment in an unknown state leading to deployment errors.

Production-Like Environments (1)

Pattern Target environments are as similar to production as possible.
Anti-patterns Environments are “production like” only weeks or days before a release. Environments are manually configured and controlled.

Transient Environments

Pattern Utilizing the Automate Provisioning, Scripted Deployment and Scripted Database patterns, any environment should be capable of terminating and launching at will.
Anti-patterns Environments are fixed to “DEV, QA” or other predetermined environments.

DATA

Database Sandbox (7)

Pattern Create a lightweight version of your database – using the Isolate Test Data pattern. Each developer uses this lightweight DML to populate his local database sandboxes to expedite test execution.
Anti-patterns Shared database. Developers and testers are unable to make data changes without it potentially adversely affecting other team members immediately.

Decouple Database (1)

Pattern Ensure your application is backward and forward compatible with your database so you can deploy each independently
Anti-patterns Application code data are not capable of being deployed separately.

Database Upgrade (7)

Pattern Use scripts to apply incremental changes in each target environment to a database schema and data.
Anti-patterns Manually applying database and data changes in each target environment.

Scripted Database (7)

Pattern Script all database actions as part of the build process.
Anti-patterns Using data export/import to apply data changes. Manually applying schema and data changes to the database.

INCREMENTAL DEVELOPMENT

Branch by Abstraction (2)

Pattern Instead of using version-control branches, create an abstraction layer that handles both an old and new implementation. Remove the old implementation.
Anti-patterns Branching using the version-control system leading to branch proliferation and difficult merging. Feature branching.

Toggle Features (10)

Pattern Deploy new features or services to production but limit access dynamically for testing purposes.
Anti-patterns Waiting until a feature is fully complete before committing the source code.

COLLABORATION

Delivery Retrospective (1)

Pattern For each iteration, hold a retrospective meeting where everybody on the Cross-Functional Team discusses how to improve the delivery process for the next iteration.
Anti-patterns Waiting until an error occurs during a deployment for Dev and Ops to collaborate. Having Dev and Ops work separately.

Cross-Functional Teams (1)

Pattern Everybody is responsible for the delivery process. Any person on the Cross-Functional Team can modify any part of the delivery system.
Anti-patterns Siloed teams: Development, Testing, and Operations have their own scripts and processes and are not part of the same team.

Amazon.com has an interesting take on this approach. They call it “You build it, you run it”. Developers take the software they’ve written all the way to production.

Root-Cause Analysis (1)

Pattern Learn the root cause of a delivery problem by asking “why” of each answer and symptom until discovering the root cause.
Anti-patterns Accepting the symptom as the root cause of the problem.

TOOLS

This is meant to be an illustrative list, not an exhaustive list, to give you an idea of the types of tools and some of the vendors that help to enable effective Continuous Delivery. The Java, .NET and Ruby platforms are represented. The tools that span categories have been assigned to the most appropriate category or duplicated when necessary.

Category Example Software Tools
Configuration Management Subversion (SVN), git, Perforce, PassPack, PasswordSafe, ESCAPE, ConfigGen
Continuous Integration Bamboo, Jenkins, AntHill Pro, Go, TeamCity, TFS 2010, Electric Commander. Supporting tools: , Doxygen, Grand, GraphViz, JavaDoc, NDoc, SchemaSpy, UmlGraph, CheckStyle, Clover, Cobertura, FindBugs, FxCop, JavaNCSS, JDepend, PMD, Sonar, Simian
Testing Twist , AntUnit, Cucumber, DbUnit, webrat, easyb, Fitnesse, JMeter, JUnit, NBehave, SoapUI, Selenium, RSpec, SauceLabs
Deployment Pipeline Go, AntHill Pro
Build and Deployment Scripting Ant, AntContrib, NAnt, MSBuild, Buildr, Gant, Gradle, make, Maven, Rake, Java Secure Channel, ControlTier, Altiris, Capistrano, Fabric, Func
Infrastructure and Environments AWS EC2, AWS S3, Windows Azure, Google App Engine, AWS Elastic Beanstalk, Heroku, Capistrano, Cobbler, BMC Bladelogic, CFEngine, IBM Tivoli Provisioning Manager, Puppet, Chef, Bcfg2, AWS Cloud Formation, Windows Azure AppFabric, rPath, JEOS, BoxGrinder, CLIP, Eucalyptus, AppLogic, CloudKick, CloudWatch, Nagios, Zabbix, Zenoss
Data Hibernate, MySQL, Liquibase, Oracle, PostgreSQL, SQL Server, SimpleDB, SQL Azure, Ant, MongoDB, dbdeploy
Components and Dependencies Ivy, Archiva, Nexus, Artifactory, Bundler
Collaboration Mingle, Greenhopper, JIRA

REFERENCES

  1. Jez Humble and David Farley, “Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation”, Addison Wesley Professional, 2010

  2. Paul Hammant and www.continuousdelivery.com

  3. Stephen P. Berczuk and Brad Appleton, “Software Configuration Management Patterns.”, Addison Wesley Professional, 2003

  4. Mary and Tom Poppendieck, “Leading Lean Software Development”, Addison Wesley, 2009

  5. Paul M. Duvall, “Continuous integration. Patterns and Antipatterns”, DZone refcard #84, 2010 http://bit.ly/l8rfVS

  6. Paul M. Duvall, “Continuous integration. Improving Software Quality and Reducing Risk”, Addison Wesley, 2007

  7. Scott W. Ambler and Pramodkumar J. Saladage, “Refactoring Databases. Evolutionary Database Design”, Addison Wesley, 2006.

  8. Paul M. Duvall, IBM developerWorks series “Automation for the people” http://ibm.co/iwwvPX

  9. IMVU: http://bit.ly/jhqP5f

  10. Martin Fowler and Facebook: http://on.fb.me/miBrOM

  11. Facebook Engineering: http://on.fb.me/miBrOM

  12. Paul Julius, Enterprise Continuous Integration Maturity Model, http://bit.ly/m7h5vC

About The Authors

Paul Duvall

Paul M. Duvall is the CTO of Stelligent, (http://stelligent. com/) a company that helps organizations with Continuous Integration and Delivery, Cloud Migrations and Elastic Operations. Paul is the author of many books including the Jolt-award winning book Continuous Integration: Improving Software Quality and Reducing Risk (http://amzn.to/cibook) and the recently published Startup@Cloud: 33 tips for running your company using cloud-based software (http://amzn.to/startupatcloud). He is passionate about the cloud and automation and blogs at http://devopscloud.com/.

Recommended Book

Continuous Delivery
Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation

The book has two themes: automation and collaboration. Delivering software of any complexity involves people with a bunch of skills: testers, developers, and sysadmin / operations personnel. The last group of people often gets left out of the process of delivering software until the end, and even testers are often not as heavily involved in the development process as they should be.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.