Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Server-side

  • submit to reddit

JavaServer Faces 2.0

By Cay Horstmann

28,377 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,704 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.

Getting Started with BIRT

By Virgil Dodson

12,397 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.

Vaadin

A Familiar Way to Build Web Apps with Java

By Marko Grönroos

12,596 Downloads · Refcard 85 of 151 (see them all)

Download
FREE PDF


The Essential Vaadin Cheat Sheet

Vaadin is a server-side Ajax web application development framework that allows you to build web applications just as you would with traditional desktop frameworks, such as AWT or Swing. An application is built from user interface components contained hierarchically in layout components. In the server-driven model, the application code runs on a server, which the actual user interaction is handled by a client-side engine running in the browser. This DZone Refcard will cover how to create an application, components, themes, data binding, and more.
HTML Preview
Getting Started with Vaadin

Vaadin: A Familiar Way to Build Web Apps with Java

By Marko Grnroos

ABOUT VAADIN

Vaadin is a server-side Ajax web application development framework that allows you to build web applications just like with traditional desktop frameworks, such as AWT or Swing. An application is built from user interface components contained hierarchically in layout components.

In the server-driven model, the application code runs on a server, while the actual user interaction is handled by a client-side engine running in the browser. The client-server communications and any client-side technologies, such as HTML and JavaScript, are invisible to the developer. As the client-side engine runs as JavaScript in the browser, there is no need to install plug-ins. Vaadin is released under the Apache License 2.0.

Client-Server Architecture

Figure 1: Vaadin Client-Server Architecture

If the built-in selection of components is not enough, you can develop new components with the Google Web Toolkit (GWT) in Java.

CREATING AN APPLICATION

An application that uses the Vaadin framework needs to inherit the com.vaadin.Application class and implement the init() method.


import com.vaadin.ui.*;

public class HelloWorld extends com.vaadin.Application {
	public void init() {
		Window main = new Window(“Hello window”);
		setMainWindow(main);
		main.addComponent(new Label(“Hello World!”));
	}
}

The basic tasks in writing an application class and the initialization method are:

  • inherit the Application class
  • create and set a main window
  • populate the window with initial components
  • define event listeners to implement the UI logic

Optionally, you can also:

  • set a custom theme for the window
  • bind components to data
  • bind components to resources

The application can change the components and the layout dynamically according to the user input.

Architecture for Vaadin Applications

Figure 2: Architecture for Vaadin Applications


You can get a reference to the application object from any component attached to the application with getApplication()

Event Listeners

In the event-driven model, user interaction with user interface components triggers server-side events, which you can handle with event listeners.

In the example below, we handle click events for a button with an anonymous class:


Button button = new Button(“Click Me!”);
button.addListener(new Button.ClickListener() {
	public void buttonClick(ClickEvent event) {
		getWindow().showNotification(“Thank You!”);
	}
});

Download Vaadin

Below is a list of the most important event interfaces; their corresponding listener interfaces are named -Listener.

Event Interface Description
Property.ValueChangeEvent Field components except Button
Button.ClickEvent Button click
Window.CloseEvent A sub-window or an application-level window has been closed

Unless the immediate property (see below) is set, value change events are not communicated immediately to the server-side when the user changes the values, but are delayed until the first immediate interaction. Certain events, such as button clicks, are immediate by default.

Deployment

To deploy an application as a servlet, you must define a WEB-INF/web.xml deployment descriptor. The application class must be defined in the application parameter.


<web-app>
	<display-name>myproject
	
	<servlet>
		<servlet-name>Myproject Application
		<servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet
		</servlet-class>
		<init-param>
			<description>Vaadin application class to start
			<param-name>application
			<param-value>com.example.myproject.HelloWorld
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>Myproject Application
		<url-pattern>/*
	</servlet-mapping>
</web-app>

COMPONENTS

Vaadin components include field, layout, and other components. The component classes and their inheritance hierarchy are illustrated in Figure 4 (page 3).

Component Properties

Common component properties are defined in the Component interface and the AbstractComponent base class for all components.

Property Description
caption A label that identifies the component for the user, usually shown above, left of, or inside a component, depending on the component and the containing layout.
description A longer description usually displayed as a tooltip when mouse hovers over the component.
enabled If false, the user can not interact with the component. The component is shown as grayed. (Default: true)
icon An icon for the component, usually shown left of the caption.
immediate If true, value changes are communicated immediately to the server-side, usually when the selection changes or (a text field) loses input focus. The default is false for most components, but true for Button.
locale The current country and/or language for the component. Meaning and use are application-specific for most components. (Default: application locale)
readOnly If true, the user can not change the value. (Default: false)
visible Whether the component is actually visible or not. (Default: true)

Field Properties

Field properties are defined in the Field interface and the AbstractField base class for fields.

Property Description
required Boolean value stating whether a value for the field is required. (Default: false)
requiredError Error message to be displayed if the field is required but empty. Setting the error message is highly recommended for providing user feedback about a failure.

Sizing

The size of components is defined in the Sizeable interface.

Method Description
setWidth()
setHeight()
Set the component size in either fixed units (px, pt, pc, cm, mm, in, or em) or as a relative percentage (%) of the containing layout. The value "-1" means undefined size (see below).
setSizeFull() Sets both dimensions to 100% relative size of the space given by the containing layout.
setSizeUndefined() Sets both dimensions as undefined, causing the component to shrink to fit the content.

Notice that a layout with an undefined size must not contain a component with a relative (percentual) size.

Validation

All components implementing the Validatable interface, such as all fields, can be validated with validate() or isValid(). You need to implement a Validator and its validate() and isValid() methods, and add the validator to the field with addValidator().

Built-in validators are defined in the com.vaadin.data.validator package and include:

Validator Description
DoubleValidator A floating-point value
EmailValidator An email address
IntegerValidator An integer value
RegexpValidator String that matches a regular expression
StringLengthValidator Length of string is within a range

Resources

Icons, embedded images, hyperlinks, and downloadable files are referenced as resources.


Button button = new Button("Button with an icon");
button.setIcon(new ThemeResource("img/myimage.png"));

The external and theme resources are usually static resources. Application resources are served by the Vaadin application servlet, or by the user application itself.

Resource classes and interfaces

Figure 3: Resource classes and interfaces

Class Name Description
ExternalResource Any URL
ThemeResource A static resource served by the application server from the current theme. The path is relative to the theme folder.
FileResource Loaded from the file system
ClassResource Loaded from the class path
StreamResource Provided dynamically by the application

User Component Classes Class Diagram

Figure 4: The Class Diagram presents all user interface component classes and the most important interfaces, relationships, and methods.

LAYOUT COMPONENTS

The layout of an application is built hierarchically from layout components, or more generally component containers, with the actual interaction components as the leaf nodes of the component tree.

You start by creating a root layout for the main window and set it with setContent(), unless you use the default, and then add the other layout components hierarchically with addComponent().

Margins

The margin of layout components is controlled with the margin property, which you can set with setMargin(). Once enabled, the HTML element of the layout will contain an inner element with <layoutclass>-margin style, for example, v-verticallayoutmargin for a VerticalLayout. You can use the padding property in CSS in a custom theme to set the width of the margin:


.v-verticallayout-margin {
	padding-right: 20px;
	padding-top: 30px;
	padding-bottom: 40px;
}

Spacing

Some layout components allow spacing between the elements. You first need to enable spacing with setSpacing(true), which enables the <layoutclass>-spacing-on style for the layout, for example, v-gridlayout-spacing-on for GridLayout. You can then set the amount of spacing in CSS in a custom theme with the padding-top property for vertical and padding-left for horizontal spacing, for example as follows:


.v-gridlayout-spacing-on {
	padding-left: 50px; /* Horizontal spacing */
	padding-top: 100px; /* Vertical spacing */
}

Alignment

When a layout cell is larger than a contained component, the component can be aligned within the cell with the setComponentAlignment() method as in the example below:


VerticalLayout layout = new VerticalLayout();
Button button = new Button("My Button");
layout.addComponent(button);
layout.setComponentAlignment(button, Alignment.MIDDLE_CENTER);

Custom Layout

The CustomLayout component allows the use of a HTML template that contains location tags for components, such as <div location="hello">. The components are inserted in the location elements with the addComponent() method as shown below:


CustomLayout layout = new CustomLayout("mylayout");
layout.addComponent(new Button("Hello"), "hello");

The layout name in the constructor refers to a corresponding .html file in the layouts subfolder in the theme folder, in the above example layouts/mylayout.html. See Figure 5 for the location of the layout template.

THEMES

Vaadin allows customization of appearance of the user interface with themes. Themes can include CSS style sheets, custom layout HTML templates, and any graphics.

Custom themes are placed under the WebContent/VAADIN/ themes/ folder of the web application. This location is fixed the VAADIN folder specifies that these are static resources specific to Vaadin.

The name of a theme folder defines the name of the theme, to be used for the setTheme() method:


public void init() {
	setTheme("mytheme");
	...

The theme folder must contain the styles.css style sheet and custom layouts must be placed in the layouts sub-folder, but other contents may be named freely.

Custom themes need to inherit a base theme in the beginning of the styles.css file. The default theme for Vaadin 6 is reindeer


@import url(../reindeer/styles.css);

Theme contents

Figure 5: Theme contents

Hot Tip

During development, you can let the built-in themes and the default widget set be loaded dynamically from the Vaadin JAR. For production, it is more efficient to let them be served statically by the web server. You just need to extract the VAADIN folder from the JAR.

DATA BINDING

Vaadin allows binding components directly to data. The data model, illustrated in Figure 4, is based on interfaces on three levels of containment: properties, items, and containers.

Properties

The Property interface provides access to a value of a specific class with the setValue() and getValue() methods.

All field components provide access to their value through the Property interface, and the ability to listen for value changes with a Property.ValueChangeListener. The field components hold their value in an internal data source by default, but you can bind them to any data source with setPropertyDataSource().

For selection components, the property value points to the item identifier of the current selection, or a collection of item identifiers in the multiSelect mode.

The ObjectProperty is a wrapper that allows binding any object to a component as a property.

Items

An item is an ordered collection of properties. The Item interface also associates a name with each property. Common uses of items include Form data and Table rows. You can set the data source of a Form with setItemDataSource().

The BeanItem is a special adapter that allows accessing any Java bean (or POJO with proper setters and getters) through the Item interface. This is especially useful for binding a Form or a Table to beans.

Containers

A container is a collection of items. It allows accessing the items with an item identifier associated with each item.

Common uses of containers include selection components, as defined in the AbstractSelect class, especially the Table and Tree components. (The current selection is indicated by the property of the field, which points to the item identifier of the selected item.) You can set the container data source of a field with setContainerDataSource().

Vaadin includes the following built-in container implementations:

Container Class Description
IndexedContainer Container with integer index keys
BeanItemContainer Container for BeanItems
HierarchicalContainer Tree-like container, used especially by the Tree component
FilesystemContainer Direct access to the file system

Buffering

All field components implement the Buffered interface that allows buffering user input before it is written to the data source. Buffering is enabled by default.

Method Description
commit() Writes the buffered data to the data source
discard() Discards the buffered data and re-reads the data from the data source
set-/getWriteThrough() When the writeThrough property is true, write buffering is disabled
set-/getReadThrough() When the readThrough property is true, read buffering is disabled

CREATING NEW COMPONENTS

Creating a Client-Side Widget

The basic tasks of a client-side component are:

  • Implement the Paintable interface
  • Maintain a reference to the ApplicationConnection object
  • Implement updateFromUIDL() to deserialize state changes from server-side
  • Serialize state changes to server-side with calls to updateVariable()

Creating a Server-Side Component

The basic tasks of a server-side component are:

  • Use @ClientWidget annotation for the server-side component class to bind the component to the client-side counterpart
  • Implement paintContent() to serialize state changes to client-side with addVariable() and addAttribute() calls
  • Implement changeVariables() to deserialize state changes from client-side

TWidget integration

Figure 6: Widget integration within the Vaadin client-server communication architecture

Defining a Widget Set

A widget set is a collection of widgets that, together with the communication framework, form the Client-Side Engine of Vaadin, when compiled with the GWT Compiler into JavaScript.

A widget set is defined in a .gwt.xml GWT Module Descriptor. You need to specify at least one inherited base widget set, typically the DefaultWidgetSet or a custom set.


<module>
	<inherits name="com.vaadin.terminal.gwt.DefaultWidgetSet" />
</module>

The client-side source files must be located in the client subpackage under the package of the descriptor.

You can associate a stylesheet with a widget set with the <stylesheet> element in the .gwt.xml descriptor:


<stylesheet src="/sites/all/modules/dzone/assets/refcardz/085/colorpicker/styles.css"/>

Widget Project Structure

Widget set source structure

Figure 7: Widget set source structure.

Figure 7 illustrates the source code structure of a widget project (for the Color Picker example).

Using Widget Sets

You can generate the descriptor of a combining widget set automatically with the com.vaadin.terminal.gwt.widgetsetutils. WidgetSetBuilder application. It searches the class path to find all widget sets, including ones packaged in JARs, and generates the required <inherit> elements.

  • Give the full name (including the package name) of the widget set as a parameter. This is the name of the .gwt.xml file without the extension.
  • Give path to the top-level source directory as the first element of the class path

For more information on Vaadin, visit the Vaadin Blog at http://vaadin.com/blog or the Forum at http://vaadin.com/forum

About The Author

Photo of Marko Grnroos

Marko Grnroos

CMarko Grnroos is a professional writer and software developer working at IT Mill Ltd, the company behind Vaadin. He has been involved in web application development since 1994 and has worked on several application development frameworks in C, C++, and Java. He has been active in many open source software projects and holds an M.Sc. degree in Computer Science from the University of Turku. He lives in Turku, Finland.

Website: http://iki.fi/magi

Blog: http://markogronroos.blogspot.com/

Recommended Book

Book of Vaadin

Book of Vaadin is a comprehensive documentation of Vaadin. It shows how to get started, gives a good overview of the features, and tutors you through advanced aspects of the framework.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Node.js

Building for Scalability with Server-Side JavaScript

By Todd Eichel

13,199 Downloads · Refcard 141 of 151 (see them all)

Download
FREE PDF


The Essential Node.js Cheat Sheet

Node.js is a set of libraries for writing high-performance, scalable network programs in JavaScript. It has an asynchronous programming model for lightning-fast speeds, and it allows programs to run JavaScript on the server-side so that both client and server can run using the same language. Until recently, highly concurrent programs were the sole province of hardcore network programmers, but now any JavaScript-savvy web developer can write the same kinds of highly concurrent programs quickly and easily. Take a deep dive into this innovative technology and learn how to get started by reading this DZone Refcard.
HTML Preview
Node.js: Building for Scalability with Server-Side JavaScript

Node.js:Building for Scalability with Server-Side JavaScript

By Todd Eichel

WHAT IS NODE?

In its simplest form, Node is a set of libraries for writing highperformance, scalable network programs in JavaScript. Take a look at this application that will respond with the text “Hello world!” on every HTTP request:


// require the HTTP module so we can create a server object
var http = require(‘http’);

// Create an HTTP server, passing a callback function to be
// executed on each request. The callback function will be
// passed two objects representing the incoming HTTP
// request and our response.
var helloServer = http.createServer(function (req, res) {

	// send back the response headers with an HTTP status
	// code of 200 and an HTTP header for the content type
	res.writeHead(200, {‘Content-Type’: ‘text/plain’});
	
	// send back the string “Hello world!” and close the
	// connection
	res.end(‘Hello world!’);
});

// tell our hello world server to listen for HTTP requests
// on localhost’s port 8124
helloServer.listen(8124, “127.0.0.1”);

// log a message to the console
console.log(‘Server running at http://127.0.0.1:8124/’);


By itself, Node provides only very simple, low-level functionality. However, several external factors have created excitement and interest around it:

  1. Developers are increasingly focused on scalability. Node’s asynchronous programming model is well suited to building highly scalable web applications.
  2. JavaScript is naturally asynchronous, being born and developed inside web browsers.
  3. A huge base of developers are already familiar with both JavaScript and asynchronous programming from years developing JavaScript in web browsers.
  4. Huge advances in execution speed have made it practical to write serverside software entirely in JavaScript.

Let’s take a closer look at the qualities of Node that make these four things possible.

Asynchronous

Node’s speed and scalability comes largely from its asynchronous programming model. Traditional web application software is based around the request-response cycle. A request arrives; the application routes it, builds up a response by consulting databases, disks, APIs, etc., and finally sends the completed response back to the client in one piece.

This monolithic approach is very simple but leaves a lot of potential performance on the table. This is easiest to illustrate with a realworld analogy.

analogy 1

Consider a food vending truck on a city street or at a festival. A food truck operating like a traditional synchronous web server would have a worker take an order from the first customer in line, and then the worker would go off to prepare the order while the customer waits at the window. Once the order is complete, the worker would return to the window, give it to the customer, and take the next customer’s order.

analogy 2

Contrast this with a food truck operating like an asynchronous web server. The workers in this truck would take an order from the first customer in line, issue that customer an order number, and have the customer stand off to the side to wait while the order is prepared. The worker and window is freed to take the next customer’s order. When orders are finished, customers are called back to the window by their number to pick them up.

In the real world, food trucks operate on the asynchronous model. It’s the clear choice for efficiency and effective use of resources, at the cost of a little extra complexity with calling people back to the window for pick up. Node works the same way, with similar tradeoffs. Node strives to never block subsequent code from executing, just like a real-world food truck operator would never hold a customer at the window waiting for their order, blocking other customers.

Server Side JavaScript

Asynchronous programming is not a new concept in computer science by any means, and many asynchronous web servers are in use in all corners of the web (e.g., Ruby has EventMachine, Python has Twisted). But Node has one thing that sets it apart from the others: JavaScript.

JavaScript is an inherently asynchronous language. It was born in the web browser, where making blocking calls meant holding up the rendering of web pages or responses to user actions. As a result, JavaScript has no standard library full of blocking file I/O functions or network code. This is where Node comes in— to provide all that functionality we’d expect in a programming language in a completely asynchronous, non-blocking way.

In contrast, normal synchronous languages have standard libraries and open-source packages chock full of blocking code. Writing an asynchronous web server in a synchronous language makes it really easy to trip up and call a blocking function, stopping your web server process cold while the blocking call completes. In Node, it’s impossible to accidentally do this because everything has been written from the ground up to be asynchronous.

Common Language

There is a certain elegance to writing both the server- and clientside application code in the same language. Doing this makes it simple to share data back and forth, and it becomes natural to share code as well. This decreases the cost of development and maintenance for shared functionality (e.g., custom string formatting functions).

Speed

Server Side JavaScript owes its growing prominence largely to recent advances in the speed of JavaScript engines. Over the past few years, browser makers like Google and Mozilla have been making huge investments in their JavaScript engines to improve the speed of both their browsers and the web applications running within them. As software is increasingly delivered over the web, JavaScript execution speed has become a larger and larger factor in application performance. The competition between browser makers over JavaScript execution speed has resulted in many orders of magnitude of improvement, to the point that JavaScript now beats many other interpreted languages in common benchmarks[1]. The result of this has been increased interest in running JavaScript on the server, which Node enables in a practical and useful way.

Developer Familiarity

Almost any developer working with web software will have touched JavaScript at some point in his career. JavaScript has been around since the dawn of the web in the mid-nineties, and at least some JavaScript is present in almost every non-trivial web site. This has yielded a huge base of JavaScript-savvy developers already familiar with working in asynchronous programming models. Node is beginning to blur the lines between front-end and back-end developers, and some are starting to cross over from the front-end to the server-side. Developing JavaScript in the browser turns out to be excellent preparation for writing highly scalable network (and web) applications.

See the following two examples. In the first, we have client-side code setting up a callback to be executed on every click of a button. On each click, we print the message “Hello, button clicker!”. In the second example, we have Node code setting up an HTTP server to execute a function on every request. Every time an HTTP request comes in, we respond with the message “Hello, web request maker!”.


document.getElementById(‘helloButton’).onclick = function () {
 	 alert(‘Hello, button clicker!’);
};
http.createServer(
	function (req, res) {
		res.writeHead(200, {‘Content-Type’: ‘text/plain’});
		res.end(“Hello, web request maker!”);
	}
).listen(8124);

This is a powerful demonstration of how developer familiarity with asynchronous programming in JavaScript on the client side translates to the server side. Any developer who has set up an event handler in the browser should be immediately familiar with Node’s asynchronous way of doing things.

WHERE DOES NODE FIT?

Where does Node fit into the web development ecosystem? Where should you use it? What is it good at? What can you do with Node that you can’t already do now?

Node’s specialty is high-concurrency, real-time applications: anything where you need to have a large number of users connected at the same time. But Node can be used to serve any website or application, and it will do so with its characteristic speed and efficiency.

A couple of years ago, the explosion in popularity of MVC web frameworks like Rails and Django opened up the possibility of building database-backed applications to a whole new class of developers who had never been able to do that before. Those frameworks made that type of application development accessible to a large number of people who before wouldn’t have known where to start.

Node is doing the same thing for real-time, high concurrency applications. The kind of highly concurrent programs that can now be written quickly and easily in Node—until recently the sole province of hardcore network programmers—can now be written by any JavaScript-savvy web developer.

Fundamentally, it is important to understand that Node exists on a different level of the stack than web frameworks like Rails; it’s actually much closer to the language level than the framework level. Those who try to use it like a framework will walk away disappointed (they should try out Express at http://expressjs.com, a web micro-framework written in Node which we’ll cover later). Node is not the new Rails or the new PHP. It is a different tool entirely, and it actually fits in well as a complement to existing tools.

Hybrid Apps

Currently, a common practice is to use Node to supplement existing applications where real-time features are desired. Though it is not impossible to add those types of features using existing tools, Node is so well suited to the task that it’s a natural fit.

A typical scenario involves an existing monolithic application with a small additional feature added on being served by a Node application. Typical features to be served this way are chat functionality (like Facebook or Gmail chat) or real-time push notifications (which sites like Quora use extensively). In this scenario, the clients interact with both sides simultaneously, and both sides are probably accessing the same datastores. The main application features are served by the existing application, and the real-time features are served by a small Node application running alongside.

feature 1

Node Specialties

Node handles some real-world examples in web architecture completely naturally, but these examples are very difficult or impossible to do with existing frameworks. These are where Node can really shine when added to an existing application or used standalone.

Push Notifications

As the web moves towards more highly interactive web sites, a common feature to add to them is push notifications. Push notifications are a hallmark of the emerging real-time web. This is something that is very difficult to implement inside of traditional synchronous application frameworks.

The way push notifications are implemented now is a bit of a stop-gap measure. There are three main ways to get fresh data from the server to the client, illustrated below.

feature 2

The first is traditional polling. The client makes a request to the server on an interval, asking for any new data. This can only be as real-time as the polling interval, but decreasing the polling interval results in increased server load as every client hits the server on that interval even if there is no new data for them. This model does not scale well and is not commonly used for high-traffic sites.

The second is the holy grail of client-server communications: the real-time socket. A persistent, full-duplex, bi-directional channel is opened between the client and the server, and both can push data through at any time with almost no overhead (compared to HTTP).

This is the goal of the WebSocket protocol. The trouble with this method is that most clients and many web servers do not support it currently. While WebSocket support is improving, it represents a big shift in the way the web works and it will be a long time before we can depend on it as developers working in the real world.

So neither of our first two models for implementing push notifications actually work in the real world. Traditional polling is too heavy on the server and doesn’t get data out fast enough. Real-time sockets are perfect for this but aren’t supported by most browsers.

The third and final model is long polling. This is actually the way most of the real-time web currently works. Clients are instructed to always open a request to the server waiting for new data. If the server doesn’t have anything, it holds the request open and doesn’t return it until it has a piece of data to push out. Upon receiving data, the client always immediately reopens a new connection to the server waiting for more data. This is an effective way to implement push notifications; however, the cost is that for each client using the site, a connection on the server must be kept open indefinitely. Since most traditional web frameworks can only support one client connection per server thread, this can get expensive quickly in terms of CPU and memory usage. Node, however, can handle many thousands of concurrent client connections with a single server process.

Node’s ability to transparently handle huge numbers of concurrent connections makes it perfectly suited for implementing long polling-based push notifications in a web application, where other synchronous frameworks struggle.

Streaming Responses

As mentioned before, current web technologies are heavily based around the request-response cycle. The server software receives a request from the client, routes it to the appropriate handler, and begins to render a response. It may consult one or more databases, it might call external APIs, or it may perform some computation. It will then probably render a view template with the resulting data; and only after all that is done, it will ship the finished, rendered response off to the client.

This monolithic approach is easy to develop for but leaves a lot of potential performance benefits sitting on the table. Browsers were built from the beginning to work with partial responses trickling in over slow dial-up connections. Browsers would still start rendering the page as best they could to give the user a good initial experience while still downloading the remainder of the page in the background.

By waiting on the server until the entire response is rendered before returning anything at all, we’re leaving this capability untapped. Why shouldn’t we first send down the header for our document, which likely contains a bunch of CSS and JavaScript assets that the browser could start loading while we’re building the rest of our response?

Streaming responses provides a better way to do this. We can return a little bit of the page at a time, as soon as we have it ready. This is impossible under many existing frameworks, which are entirely built around the request-response cycle. But it’s a completely natural model for Node.

Here’s an example illustrating streaming responses in Node. As soon as the request comes in, we immediately write out the headers and the first line “Starting...”. Then we set up an interval to write the word “data” to the client every half a second. Finally, we set a timeout to end the response with the word “Done!” after five seconds have elapsed. If you connected to this Node application in your browser, you would see the first line immediately and then each subsequent line as it comes in. If you wrote a similar example program in a synchronous language using sleep functions instead of callbacks, the browser would show nothing for the first five seconds and then show the full result all at once.

feature 3

var http = require(‘http’);

http.createServer(function (request, response) {

	response.writeHead(200, {‘Content-Type’: ‘text/plain’});
	
	response.write(“Starting...\n”);
	
	var dataWriter = setInterval(function () {
	  response.write(“data\n”);
	}, 500);
	
	setTimeout(function () {
	  clearInterval(dataWriter);
	  response.end(“Done!”);
	}, 5000)

}).listen(8124);

INSTALLATION

Node

Node falls into the category of software that is under such rapid development that the recommended installation method is to compile it from source code. Pre-packaged binaries do exist, but the recommended method is still to install from source. The following will work on any POSIX-compliant system (Mac OS, Linux, Cygwin on Windows, etc.).

Sidebar: Windows

Node does not run natively on Windows. It does run fine under Cygwin (http://www.cygwin.com/), which is an easily installed, self-contained POSIX environment that runs on top of Windows. Or you can always install Node inside a Linux virtual machine.

If you do choose to run Node under Cygwin, you will need to use the Cygwin package manager to install several additional packages that are not included by default in order for the following commands to work. You’ll have an opportunity to do this inside the Cygwin installer. At the time of this writing, the following Cygwin packages need to be selected to install Node and npm (a Node package manager that is explained later):

  • python
  • openssl
  • openssl-devel
  • gcc4-g++
  • git
  • make
  • pkg-config
  • zlib-devel

Some troubleshooting steps are available on the Node Wiki: https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows).

Compiling Node
  1. First make sure you have the build prerequisites. You’ll need to have a C compiler (like gcc) installed if you don’t already. Other than that, the only required packages are python and libssl-dev. Use your OS’s package manager to install these before proceeding.
  2. Grab the latest version of the source (v0.4.7 as of this writing), extract, and switch into the resulting folder. The latest version can always be obtained from the Node web site (http://nodejs.org/#download).
  3. 
    wget http://nodejs.org/dist/node-v0.4.7.tar.gz
    tar xzvf node-v0.4.7.tar.gz
    cd node-v0.4.7/
    
    
  4. Configure, make, and make install, as with any other package you’d compile from source:
  5. 
    ./configure
    make
    make install
    
    

After you complete these steps, you should have access to the node binary from your command line. Try it out with node -v, which should print the version number. You can also try running it with no arguments, which will start up an interactive REPL (readeval- print loop) session where you can type lines of JavaScript and have the result evaluated and printed immediately. In normal use when developing Node programs, you would run this with a filename, e.g. node myapp.js.

npm

The other essential piece of software for developing in Node is npm (http://npmjs.org/), the most popular Node package manager. A great number of useful Node libraries and open-source projects are distributed through npm, and you can use npm to distribute your own programs or simply manage their dependencies.

npm offers a one-line installer. Just paste the following into your terminal.


curl http://npmjs.org/install.sh | sh

You can test it by running npm -v to get the version number.

When running npm commands (e.g., to install or uninstall packages), you should always use sudo for better security. Because npm packages can execute arbitrary scripts during different parts of their lifecycles (install, uninstall, etc.), npm attempts to downgrade its permissions to the nobody user before running any package scripts. Running npm with sudo allows it to do this, whereas if you ran them as your own user, the package scripts would execute with whatever permissions you have.

npm’s authors recommend setting the following configuration to enforce this security measure:


npm config set unsafe-perm false

QUICK START

As a way to get started with Node development, we’ll demonstrate installing the Express web framework and using it to make a simple web application. Make sure you have both Node and npm installed, as described above.

  1. Install Express. It’s distributed as an npm package, so it’s as easy as:
  2. 
    sudo npm install express
    
    
  3. Express also installs a binary, which you can use to generate new skeleton applications. If you’ve used other frameworks like Rails or Django, this will seem familiar. We’ll call our app “demoapp”.
  4. 
    express demoapp	
    
    
  5. You’ll see some output as Express generates your application skeleton. Note at the end that it suggests installing Jade, which is a JavaScript templating library along the lines of Ruby’s HAML. Express uses Jade for templating by default. We can go ahead and install that with npm:
  6. 
    sudo npm install jade
    
    
  7. At this point, you can take a look at the files Express created using your text editor. The main application file is app.js, and there are folders for view templates, static files, tests, etc. that you would expect in a web framework. If you take a look at app.js, you’ll see some app setup and configuration lines, a route handler for the root path (/) that renders the index.jade template; and at the end is the call to start up the app server on port 3000.
    Once you’re done looking through the code, we can start up the server using Node and take a look at our new application.
  8. 
    node app.js
    
    
  9. If you open up http://localhost:3000/ in your web browser, you should see a simple “Welcome to Express” message. Let’s try changing part of this and reloading the page. In app.js, find the handler for the root path and change the title attribute to “Demo App”. If we reloaded the page in the browser, we’d expect to see the change reflected as “Welcome to Demo App”. But unless you’ve also restarted the node process, we’ll still see the original message. This is a common trap that new Node developers coming from the browser or Rails/Django/ etc. worlds experience. While those other more involved frameworks will reload your source files on every request, Node is very simple. So restarting the process is up to you. Libraries do exist to make this easier. See the next section for an example.

NODE ECOSYSTEM

The Node ecosystem is in its infancy and still rapidly evolving, but some important projects have emerged for solving common problems.

Express

http://expressjs.com
Express, as demonstrated in the quick start guide, is a web microframework along the lines of Ruby’s Sinatra or Python’s Bottle.

Socket.IO

http://socket.io
Socket.IO is a library for making real-time web apps easy to write by abstracting away browser differences and incompatibilities. It will automatically select the best available transport mechanism (including WebSocket) supported by both the browser and the server. Use Socket.IO whenever you want to add realtime features to you application or if you’re writing something inherently real-time like a game or chat app.

streamline.js, step, flow-js

https://github.com/Sage/streamlinejs
https://github.com/creationix/step
https://github.com/willconant/flow-js
As you start to write more complex asynchronous code, you’ll begin to see that the complexity of nested callbacks can easily get out of control. This is especially true in the case of database interactions where you may need to perform operations in sequence or only perform a cleanup operation after several others have completed. Several libraries can help you untangle your callback functions in these situations. Because each one is a little different, the best approach would be to take a look at each one and see which best suits your present situation.

Mongoose

http://mongoosejs.com
Mongoose is an ORM for interacting with a MongoDB database. MongoDB is a popular choice of datastore for Node apps, and Mongoose makes it easy to use.

NowJS

http://nowjs.com
NowJS is an excellent demonstration of the things you can do when the client-side and server-side language are the same. It lets you share functions and variables back and forth between the client and the server as well as call client functions from the server and server functions from the client.

Supervisor

http://nowjs.com
NowJS is an excellent demonstration of the things you can do when the client-side and server-side language are the same. It lets you share functions and variables back and forth between the client and the server as well as call client functions from the server and server functions from the client.

Supervisor

https://github.com/isaacs/node-supervisor
This package solves the problem mentioned at the end of the Quick Start section. When you start a Node program using supervisor (supervisor myapp.js), it will monitor your application directory and reload Node on the fly whenever it detects changes. This is an indispensible tool for Node development.

Additional Resources

If you need help with Node development, here are some places you can go.

Official Sites

Homepage: http://nodejs.org
Manual and documentation: http://nodejs.org/docs/v0.4.7/api/
Wiki: https://www.github.com/joyent/node/wiki
Blog: http://blog.nodejs.org/
Source code: https://github.com/joyent/node

Articles and Tutorials

Screencast tutorials for beginners: http://nodetuts.com Advanced articles by Node community leaders: http://howtonode.org

Community
Node official mailing list: http://groups.google.com/group/nodejs Node Official IRC channel: #node.js on irc.freenode.net Node User Q&A via StackOverflow: http://stackoverflow.com/questions/tagged/node.js

NODE API GUIDE

Below is a list of the most commonly used Node modules and how you might typically use them. View the full list in the Node documentation http://nodejs.org/docs/v0.4.7/api/.

Timers

Functions for setting and clearing timeouts and intervals just like you would in a browser.

Process

Use for accessing stdin, stdout, command line arguments, the process ID, environment variables, and other elements of the system related to the currently-executing Node process.

Utilities

Logging, debugging, and object inspection functions.

Events

Contains the EventEmitter class used by many other Node objects. Defines the API for attaching and removing event listeners and interacting with them.

Buffers

Functions for manipulating, creating, and consuming octet streams, which you may encounter when doing your own network or file system I/O. You likely won’t interact with these much if you’re only doing web application programming.

Streams

An abstract interface for streaming data which is implemented by other Node objects, like HTTP server requests, and even stdio. Most of the time you’ll want to consult the documentation for the actual object you’re working with rather than looking at the interface definition.

Crypto

Functions for dealing with secure credentials that you might use in an HTTPS connection.

TLS/SSL

Functions for making or serving requests over SSL. See also the HTTPS module.

File System

File system interaction functions. Read/write files and directories, move, copy, rename files. Some functions have synchronous versions alongside the normal asynchronous ones, as noted in their names. These are useful in the setup phases of an application’s execution, where speed is unimportant and the simplicity of a synchronous function is desired.

Path

Complements the File System module; provides functions to manipulate paths and filenames, resolve relative paths, etc.

Net

The meat of Node’s functionality. Create network server objects to listen for connections and act on them. Read from and write to sockets. Most of the time if you’re working on web applications, you won’t interact with this directly. Instead you’ll use the HTTP module to create HTTP-specific servers. If you want to create TCP servers and sockets and interact with them directly, look here.

UDP/Datagram

Functions for handling UDP servers and messages. If you don’t know what UDP is, then you probably don’t need to worry about this module.

DNS

Contains functions for doing regular or reverse DNS lookups (e.g. of a domain name to an IP address) and fetching DNS records (e.g. A, CNAME, MX) for a domain.

HTTP

This is the most important and most used module for a web developer. Create HTTP servers and have them listen on a given port. This also contains the request and response objects that hold information about incoming requests and outgoing responses. You can also use this to make HTTP requests from your application and do things with their responses.

HTTPS

Contains functions for creating HTTPS servers or requests. This is regular HTTP secured with SSL. See also the TLS/SSL module.

URL

Interact with URLs: parsing, formatting, resolving an absolute URL from a relative URL with a base URL

Query String

Handle parsing or composing query string parameters (including escaping/unescaping strings).

REPL

Short for read-eval-print-loop. You can add a REPL to your own programs just like Node’s standalone REPL (which you get if you run node with no arguments).

VM

Allows you to compile arbitrary JavaScript code and optionally execute it new sandboxed context.

Child Processes

Functions for spawning new processes and handling their input and output.

Assertion Testing

Basic facilities for writing and running unit tests.

TTY

Functions for interacting with TTYs. This will probably only be useful to you if you’re writing Node programs to be run on the console (e.g. devops or system administration scripts), rather than accessed over the web via HTTP requests (web apps).

OS

Get information from the operating system. Your hostname, OS name and type, uptime, load averages, memory, CPUs.

Debugger

You can access the V8 engine’s debugger with Node’s built-in client and use it to debug your own scripts. Just launch node with the debug argument (node debug server.js). See the documentation for more usage details.

[1] http://shootout.alioth.debian.org/u32/benchmark. php?test=all&lang=v8&lang2=yarv

About The Authors

Todd Eichel

Todd Eichel is a co-founder of Duostack, a cloud platform for Node and Ruby applications. Prior to Duostack, Todd led the development of a Pittsburgh-based local e-commerce company, where he intensively developed his JavaScript and Ruby expertise. Todd has a Master of Information Systems Management degree from Carnegie Mellon University, where he also earned his B.S. in Information Systems with an additional major in Statistics.

When Todd isn’t working on apps in the cloud, he’s flying through the clouds as a recreational pilot. He currently resides in San Francisco. Find him online at http://toddeichel.com/, on Twitter at http://twitter.com/toddeichel, or on GitHub at https://github.com/tfe.

Recommended Book

Node

Written by a core contributor to the framework, Node: Up and Running shows you how Node scales up to support large numbers of simultaneous connections across multiple servers, and scales down to let you create quick one-off applications with minimal infrastructure. Built on the V8 JavaScript engine that runs Google Chrome, Node is already winning the hearts and minds of many companies, including Google and Yahoo! This book shows you why.

Pre-order it now!

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Daily Dose: Chrome Gets Flash Cookie Protection

Clearing cookies out of your web browser just got a bit easier.  Easier if you're using Google Chrome, that is.  Local Shared Objects, or "Flash Cookies", usually can't be be disabled or deleted through normal browser settings.  With Chrome...

0 replies - 20625 views - 04/27/11 by Katie Mckinsey in Daily Dose

Getting Started with Caucho Resin

By Emil Ong

4,863 Downloads · Refcard 88 of 151 (see them all)

Download
FREE PDF


The Essential Caucho Resin Cheat Sheet

Caucho Technology’s Resin® is a Java Application Server with a reputation for being lightweight and fast, yet reliable and scalable enough to power the most demanding enterprise sites. Resin comes in two flavors: Resin Open Source and Resin Professional. Resin Open Source is licensed under the GPL and has all the features for Java EE 6 Web Profile development. Resin Professional builds on Resin Open Source and offers features such as clustering, fast native I/O, and OpenSSL integration. This DZone Refcard starts with the basics and covers many of the features Resin 4.0 has to offer emerging technologies.
HTML Preview
Getting Started with Caucho Resin

Getting Started with Caucho Resin

By Emil Ong

ABOUT RESIN

Caucho Technology's Resin® is a Java Application Server with a reputation for being lightweight and fast, yet reliable and scalable enough to power the most demanding enterprise sites. Beginning as a Servlet and JSP engine in 1998, Resin has since evolved to support the Java EE 6 Web Profile within highly integrated implementations of Servlet 3.0, CDI, and EJB 3.1 Lite. In addition to the Web Profile standards, Resin also includes a high performance JTA transaction manager, a JMS provider, clustering, connection pooling, and a management console.

Resin is available in two flavors: Resin Open Source and Resin Professional. Resin Open Source is licensed under the GPL and has all the features necessary for Java EE 6 Web Profile development. Resin Professional builds on Resin Open Source and offers advanced features such as clustering (both traditional and cloud), fast native I/O, proxy caching, and OpenSSL integration.

DOWNLOADING RESIN

Resin is maintained in two branches: stable and development. At the time of writing, the stable branch is Resin 3.1 and the development branch is Resin 4.0. Users should note that despite the name, each release of the development branch is production ready. It's termed “development” because all new features and APIs go into this branch, but core technologies like Web Profile APIs are stable. This Refcard will deal entirely with Resin 4.0 because it contains the Java EE 6 Web Profile implementation (Resin 3.1 focused on Java EE 5) and has many new exciting features that are useful for emerging technologies such as cloud deployment.

All currently available versions of Resin are listed for download at http://caucho.com/download. Most users will want to download Resin Professional, even if they haven't purchased a license. Without the license, Resin Professional operates just like Resin Open Source. If you decide to upgrade later, all you have to do is drop in a license file. Developers who want a purely GPL version can download Resin Open Source.

INSTALLING RESIN

Resin is available in tar.gz and .zip formats for Unix, Mac OS X, and Windows users. While Resin can run in a pure Java mode, it also features some native (JNI) code that offers functionality like dropping root privileges in Unix and OpenSSL integration. Because of these features, you'll need to compile the JNI code if you're running on Unix or Mac OS X. Windows DLLs are provided in the distribution. Ubuntu Linux users can use Caucho's Ubuntu repository to install Resin as a .deb.

Hot Tip

Resin 4.0 now requires Java SE 6. This latest version of Java introduces a number of API improvements and Caucho's internal testing shows performance benefits as well. Make sure to get the JDK, not just the JRE.

Unix and Mac OS X installation

To install Resin on Unix and Mac OS X, you'll need to compile the JNI code for Resin. Before you compile, you'll need an environment capable of compiling C code (gcc, etc.). You'll probably also want OpenSSL, though this isn't strictly required. Once you've unpacked Resin, it should create a directory with the full Resin version name (e.g. resin-pro-4.0.4). Change to this directory and run the following commands:


$ ./configure
$ make
$ sudo make install

You'll need to run the last command (make install) as root so you can install Resin system wide. By default, this installs Resin in /usr/local/resin-<version>, but you can change this behavior by passing the --prefix= to the configure command. For more options, pass -- help to the configure command.

Windows Installation

Resin includes precompiled DLLs for the native code, so no compilation is necessary. Simply unpack the Resin .zip file directly where you'd like to install Resin and you're done. Typically, we recommend C:\Resin.

Once you have Resin installed, you should see two .exe files in the top-level Resin directory, resin.exe and setup.exe. resin. exe launches Resin from the command line, but is used for backwards compatibility. setup.exe installs Resin as a Windows Service, which we will discuss in a later section.

Ubuntu Installation

Ubuntu users can use Caucho's Ubuntu repository to install Resin. Add the following lines to your /etc/apt/sources.list:


deb http://caucho.com/download/debian/ unstable universe
deb http://caucho.com/download/debian/ unstable multiverse

After adding these lines, then run


$ sudo apt-get update

This command will update your Ubuntu database with information about the latest Resin releases. To install Resin, run:


$ sudo apt-get install resin-pro

This will install Resin Professional. Use “resin” instead of “resin-pro” if you'd prefer to install Resin Open Source. This installation will start Resin for you automatically on startup.

RESIN DIRECTORY LAYOUT

Resin uses a number of directories for the server itself, application files, and logging. These are all configurable (as you saw in the installation section), but we'll need to refer to them by name later. The following table will give the names, descriptions, and standard locations of commonly used Resin directories:

Directory Description Recommended
Resin Home Contains Resin server jars, JNI, and licenses. /usr/local/resin-<version> (Unix)
C:\Resin (Windows)
Root Directory Contains application content, log files, and server data /var/www (Unix)
C:\www (Windows)
Web App Deploy Directory Contains applications (.war files and exploded applications) webapps/ (Subdirectory of root directory)
Log Directory Contains server and access log files log/ (Subdirectory of root directory)

Resin separates the Resin Home directory, where Resin's libraries and licenses are contained, from the root directory, where your applications and logs are maintained. This structure makes it easier for you to upgrade Resin without disturbing your applications. In other words, you can just replace your Resin Home directory with the new Resin installation to upgrade.

STARTING RESIN

Resin command line

Resin can be started from the command line for debugging and development purposes. To run Resin with its output sent to the console, use the following command:


$ java -jar $RESIN_HOME/lib/resin.jar console

Resin can also open a standard Java debugging port on startup using the -debug-port option:


$ java -jar $RESIN_HOME/lib/resin.jar -debug-port 8000 console

Similarly, you can have Resin open a JMX port using the jmxport option:


$ java -jar $RESIN_HOME/lib/resin.jar -jmx-port 9000 console

To have Resin run in the background with its log output placed in the log directory, run:


$ java -jar $RESIN_HOME/lib/resin.jar start

You may also want to set the root directory of Resin and a specific configuration file on the command line as well:


$ java -jar $RESIN_HOME/lib/resin.jar --root-directory /var/www --conf /etc/resin/resin.xml start

If you need to stop Resin, you can run:


$ java -jar $RESIN_HOME/lib/resin.jar stop

This command stops the Resin instance, but the Resin Watchdog will still be running. The Resin Watchdog (see the Hot Tip below for more info) and all Resin processes can be stopped by running:


$ java -jar $RESIN_HOME/lib/resin.jar shutdown

Starting Resin at Boot

Once you have installed Resin system-wide, you may want to have it start when your server boots up. Resin provides start scripts for Unix and Windows.

Unix boot-time start up

Resin provides an init.d script and installs it in /etc/init.d/resin. This script is editable and essentially just starts the Resin server using the command line interface shown above. For standard installations, it shouldn't be necessary to modify this file, but you can configure alternate directories.

Windows Server Installation

Resin includes a Windows installation program called setup. exe to create a Windows Service. You can set parameters such as the Resin Home, Resin Root, and Log Directory for the service. You can also set the Service name or remove an existing service.

Resin Setup

Hot Tip

Even though we showed Resin run as a single Java process above, there are actually two processes being run, Resin and a Watchdog. The Watchdog is in charge of launching and monitoring the Resin process. This architecture provides additional reliability by restarting Resin if there's an error.

CONFIGURING RESIN

Configuring the Resin Server

Resin's server configuration is XML-based and contained largely within one file called resin.xml. The default resin.xml should work fine for most users with single-server deployments or developers. For more advanced configurations however, you'll want to understand and modify the resin.xml file.

Structure of resin.xml

The XML structure of the resin.xml file models the organization of Resin. At the top level there is the full Resin deployment which contains clusters. Each cluster is a set of servers and (virtual) hosts. (Note that even when running a single server, Resin considers this to be a cluster with one server.) Each host contains web applications.

Resin XML Structure

With this hierarchical structure, you can share resources and policies across applications. For example, you could configure a database pool shared by all applications in a single host or a distributed cache shared by all servers in a cluster.

Configuring JVM parameters

One of the most common tasks that administrators first do when setting up a new server is to configure JVM parameters. Because of Resin's Watchdog architecture, you can configure these parameters directly in your resin.xml file. When the Watchdog launches (or relaunches) a server, it will start a new JVM with these parameters:


<resin>
	<cluster>
		<server id=“a”>
			<jvm-arg>-Xmx512m </jvm-arg>
		</server>
...

Configuring Applications with resin-web.xml

Resin supports a number of features for applications that go beyond what Java EE standards specify, such as database pooling, custom logs and log rotation, and security authenticators. All of these facilities can be configured in the top-level resin.xml or in a Resin-specific application deployment descriptor file named WEB-INF/resin-web.xml. This file is recognized by Resin and can be used alongside of the portable web.xml descriptor file to configure Resin-specific resources. You can think of the resin-web.xml file as providing the <web-app> configuration in the resin.xml structure above. The sections below will discuss how to configure resources in the resin-web.xml file.

MONITORING AND ADMINISTRATION

Setting up an administrator password

Once you've started Resin, one of the first tasks you'll want to do is set up a password for administration tasks. To do this, just browse to http://localhost:8080/resin-admin (replace localhost with the host on which you've installed Resin if it's different). There you should see a login page with a section called Don't have a login yet? Enter a username and password, then submit and follow the directions on the next page for copying the generated password file to your Resin installation.

Once you've installed the password file, Resin will restart automatically and you can login with the password you've set up. The administration application features a number of monitoring resources for web applications, the proxy cache, server configuration, cluster status, memory usage, CPU usage, sampling-based profiling, and post-mortem failure analysis.

Resin Admin

DEPLOYING APPLICATIONS

File system deployment

Resin offers file system-based “hot deployment” with which you can deploy an application by copying it to the Resin “webapps” directory. The application can be either in .war form or an “exploded” war. If you deploy the application as a .war, Resin will expand and start it automatically by default.

Many developers may also prefer to copy their application in “exploded” form for development. Resin is able to detect changes to the code base (both JSPs and Java files) within the application and automatically recompile and redeploy. This feature can help developers iterate quickly to see code changes in their application.

While file system-based deployment is great for developing applications and deploying applications on a single machine, it can be difficult to manage when deploying to multiple machines in a cluster. Resin offers a distributed deployment mechanism for these cases.

Distributed Deployment

Resin 4.0 introduced a new clustering mechanism and a new deployment tool for distributed applications. This tool lets users deploy their application once and have it distributed across all servers in a cluster, even dynamic servers that are added after the application is deployed! (See the Clustering section for more information about dynamic servers.)

This tool is accessible via Ant and Maven. To use the Resin Maven plugin to deploy, add Caucho's Maven repository to your pom.xml:


<pluginRepositories>
	<pluginRepository>
		<snapshots>
		<enabled>true</enabled>
			<updatePolicy>always</updatePolicy>
			<checksumPolicy>ignore</checksumPolicy>
		</snapshots>
	<id>caucho</id>
	<name>Caucho</name>
	<url>http://caucho.com/m2-snapshot</url>
	</pluginRepository>
</pluginRepositories>

Once you have the plugin available, add it to your build configuration and specify the administrator username and password that you setup in the administration application:


<build>
	<finalName>foo</finalName>
	<plugins>
		<plugin>
			<groupId>com.caucho</groupId>
			<artifactId>resin-maven-plugin</artifactId>
			<version>4.0.4</version>
			<configuration>
				<server>127.0.0.1</server>
				<port>80</port>
				<user>admin</user>
				<password>my-admin-pass</password>
			</configuration>
		</plugin>
	</plugins>
</build>

Once you have this configuration in your pom.xml, you can deploy to Resin simply by using the upload .war goal:


$ mvn resin:upload-war

For more Maven options, see http://wiki.caucho.com/Maven2 For the related Ant plugin, see http://wiki.caucho.com/Ant

CONNECTING DATABASES

Resin features a built-in database pool which allows multiple database servers, load balancing, and connection checking. Resin's database pools are integrated with Resin's CanDI (CDI implementation) so that developers can use annotations to inject the database easily into their code.

The following code shows a sample database pool configuration that you might include in your resin-web.xml for a pool of up to 150 simultaneous connections:


<web-app xmlns="http://caucho.com/ns/resin">
	<database jndi-name="jdbc/myDb">
		<driver type="org.postgresql.Driver">
			<url>jdbc:postgresql://localhost/test</url>
			<user>myUser</user>
			<password>myPassword</password>
		</driver>
	<max-connections>150</max-connections>
	</database>
</web-app>

Once you've configured the pool in your resin-web.xml, you can either use JNDI to access the DataSource or use CDI annotations as in the following class:


public class MyBusinessLogic {
	@javax.inject.Inject
	DataSource myDatabase;
	...
}

LOGGING

Resin uses standard java.util.logging facilities for all its internal logging and implements several custom log handlers to manage log output and log rotation. The default logging configuration in the resin.xml file provides INFO-level logging for all Resin output. The XML for this configuration is:


<log-handler name=“” level=“all” path=“stdout:” timestamp=“[%y-%m-%d %H:%M:%S.%s] {%{thread}}” />
<logger name=“com.caucho” level=“info”/>

You can configure additional loggers for your classes simply by adding another <logger> tag either to resin.xml or your application's resin-web.xml. The default log-handler will output all log messages to the log directory (or standard output, if running in console mode). You can also configure additional log-handlers to deal specifically with your classes' log messages. For example, if all of your packages started with “com.example”, you could configure a logger and log-handler:


<log-handler name=“com.example” level=“all” path=“example.log” archive-format=“example-%Y%m%d.log.gz” rollover-period=“1D”/>
<logger name=“com.example” level=“info”/>

Notice that the names of both the logger and log-handler are “com.example”. We also changed the path to an explicit file name. We also added a rollover-period and an archive format. In this case, the log will be rolled over (rotated) once a day and the old log will be stored as example-%Y%m%d.log.gz, where the %Y%m%d will be replaced with the year, month, and date when the log was rolled over. The .gz extension also indicates to Resin that this log should be gzipped.

THE RESIN HTTP SERVER

Resin includes its own powerful HTTP server which features comparable performance to C-based servers such as Apache or nginx without the overhead of requiring multiple processes. Using the Resin HTTP server is recommended. In addition to its solid performance, the Resin HTTP server also has a number of convenient features for configuring SSL, rewriting requests, and managing virtual hosts.

OpenSSL

One of Resin Professional's most useful features is OpenSSL integration which offers far faster SSL performance than pure Java solutions. To configure OpenSSL, add an <http> tag with an <openssl> tag to your server configuration:


<resin xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<cluster id=“app-tier”>
		<server id=“” address=“192.168.0.10” port=“6800”>
		<http port=“443”>
		<openssl>
			<certificate-file>example.crt</certificate-file>
			<certificate-key-file>example.key</certificate-key-file>
			<password>my-password</password>
		</openssl>
		</http>
		</server>
	</cluster>
	...
</resin>

Rewrite Dispatch

Resin offers a URL rewriting mechanism similar to Apache's mod_rewrite in its HTTP server. Rules for rewriting URLs can be configured on an application, host, server, or cluster level. For example, you may want to allow all requests for specific static resources (such as images, CSS, JavaScript, etc.) to be served as usual, but redirect all other requests to a central controller Servlet. You could achieve that within your resin-web.xml with the following configuration:


<web-app xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<resin:Dispatch regexp=“\.(php|js|gif|png|css|html)$”/>
	<resin:Dispatch regexp=“^” target=“/controller”/>
</web-app>

The <resin:Dispatch> tag here is an internal redirection (i.e. the request is passed within the server without an HTTP redirect). You can use tags for HTTP forwarding, FastCGI integration, load balancing, and more:

Tag Behavior
<resin:Dispatch> Redirect a request internally
<resin:Redirect> Send an HTTP redirect
<resin:Forbidden> Send an HTTP forbidden response
<resin:Forward> Send an HTTP forward
<resin:FastCgiProxy> Redirect requests to a backend FastCGI process
<resin:HttpProxy> Redirect requests to a backend HTTP service
<resin:LoadBalance> Redirect the request to a backend cluster for processing

Virtual Hosts

For many deployments, you may not need to use specialized virtual hosts (e.g. you only use example.com and www.example. com). In these cases, you can deploy to the standard web app deploy directory and Resin will serve all your applications regardless of the virtual host specified by the client.

If you have a deployment with more virtual hosts however (store.example.com, blog.example.com, etc.), you'll need to organize your applications in the appropriate virtual hosts. Virtual hosts are a native concept to Resin and you can create them two different ways:

  • Use Resin's host deploy directory
  • Create an explicit host with the <host> tag in resin.xml

The host deploy directory allows you to create a directory structure such as:


/var/www/hosts/store.example.com/webapps

Then any applications deployed in this webapps directory will be served from Resin as store.example.com.

You may prefer to use an explicit <host> tag in your resin.xml. This approach allows you to create a custom directory structure and make your hosts explicit in configuration.

SECURITY

Resin provides two aspects of security for web applications: authorization and authentication.

Authentication

Resin provides an authentication framework that allows applications to authenticate users from a wide variety of sources including LDAP, a JDBC database, JAAS, or a simple XML database.

Authenticator Description
XmlAuthenticator For basic applications with few users (such as the Resin administration console).
LdapAuthenticator Can reference an LDAP database for users and passwords. Specify a distinguished name prefix and/or suffix to select users.
JdbcAuthenticator Specify a table and columns against which users, passwords, and roles will be authenticated.
JaasAuthenticator Use any JAAS plugin to authenticate users.

For example, to configure the XmlAuthenticator, you might add this XML to your resin.xml or resin-web.xml:


<web-app xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<resin:XmlAuthenticator>
		<password-digest>md5-base64</password-digest>
		<user name='myuser' password='IXiMnz7P2cJU18MSJjKiaA=='>
			<role>user</role>
			<role>foo</role>
		</user>
	</resin:XmlAuthenticator>
</web-app>

Authorization

While Resin supports the Servlet standard <securityconstraint> mechanism, it also provides an easy-to-use, yet powerful alternative that is integrated with the Rewrite Dispatch architecture. This integration makes it possible to handle requests for authorized and unauthorized users with custom logic. As an example, you may want to allow all accesses to an “/admin” application only if the user is in the proper “admin” role:


<web-app xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<resin:Forbidden regexp=“^/admin”>
		<resin:Not>
			<resin:IfUserInRole role=“admin”/>
		</resin:Not>
	</resin:Forbidden>
	<resin:Dispatch regexp=“^/admin”>
		<resin:IfUserInRole role=“admin”/>
		<resin:AddHeader name=“Cache-Control” value=“no-cache”/>
	</resin:Dispatch>
</web-app>

Notice that we also changed the caching behavior of the response to indicate that browsers should not cache this secure content.

DEVELOPING WITH RESIN

Eclipse Integration

Resin features a development plugin for Eclipse based on the WTP framework. With this plugin, developers have all of the facilities of the WTP environment with the ability to deploy to Resin using a variety of file system and remote deployment options.

New server runtime dialog

The plugin includes built-in configuration files for the development environment, but you can use any configuration file as well.

To download and install the Eclipse plugin for Resin, add http://caucho.com/eclipse as an update site within Eclipse and install the Caucho Resin plugin.

Testing Resin

Resin features an embedded server interface which can be used in test frameworks such as JUnit. The following example code shows how this API can be used to test a service injected using Resin CDI implementation, CanDI:


package qa;
import org.junit.*;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import com.caucho.junit.ResinBeanContainerRunner;
@RunWith(ResinBeanContainerRunner.class)
@TestConfiguration(beanXML="beans-test.xml")
public class AccountServiveTest {
	@Inject
	private AccountService accountService;
	@Test
	public void testGetAccount()
		throws Exception
	{
		Account account = accountService.getAccount(1007);
		assertNotNull(account);
	}
}

CLUSTERING RESIN

Resin provides clustering capabilities for both traditional clusters and cloud deployments. This functionality includes:

  • Smart load balancing
  • Distributed session replication
  • Distributed object caching
  • Dynamic server addition and removal
  • Distributed application deployment

To get started with Resin clustering, you can add configurations to a <cluster>:


<resin xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<cluster id=“app-tier”>
		<server id=“app-a” address=“192.168.0.10” port=“6800”/>
		<server id=“app-b” address=“192.168.0.11” port=“6800”/>
		...
	</cluster>

The default resin.xml file has distributed sessions already enabled, so by adding these servers you've already got a cluster that can share data.

The start up procedure for Resin changes a bit when you have a cluster. When you have multiple servers configured in your resin.xml, you need to specify which of the servers you will use:


$ java -jar $RESIN_HOME/lib/resin.jar -server app-a start

In this case, you would run this command from the machine with the network interface assigned the IP 192.168.0.10, as per the configuration above.

Load Balancing

Once you've got a backend cluster set up as we did above, you'll probably want to add load balancing. In the same resin.xml as the app-tier cluster, add the following cluster configuration for a web-tier:


<resin xmlns=“http://caucho.com/ns/resin” xmlns:resin=“urn:java:com.caucho.resin”>
	<cluster id=“app-tier”>
	...
	</cluster>
	<cluster id=“web-tier” root-directory=“web-tier”>
		<server id=“web-a” address=“123.45.67.89” port=“6800”>
			<http address=“*” port=“80”/>
		</server>
		<host id=“”>
			<web-app id=“/”>
			<resin:LoadBalance regexp=“” cluster=“app-tier”/>
		</web-app>
		</host>
	</cluster>
</resin>

This configures a third Resin instance that will load balance requests from the outside world back to the app-tier servers. Because the <resin:LoadBalance> tag is part of the Rewrite Dispatch architecture, you can route load balanced requests with custom dispatch rules.

About The Author

Photo of Emil Ong

Emil Ong

Emil Ong is the Chief Evangelist and a lead developer of Caucho Technology. He comes from an academic research background, having studied security, systems, and peer-to-peer technology to gain his M.S. in Computer Science at UC Berkeley. When Emil joined Caucho in 2006, he began by working on Quercus, Caucho's 100% Java implementation of PHP, and Resin, Caucho's screamingly fast Java application server. In 2007, Emil became the Chief Evangelist of Caucho, adding public speaking engagements, community management, and press relations to his engineering duties. Emil is based in the San Francisco Bay Area.

Recommended Book

EJB 3 in Action

A comprehensive tutorial on EJB 3 co-authored by Caucho's Reza Rahman, this book features code samples, performance tips, and design patterns for using EJB and JPA. Novice and experienced Java programmers alike will find this book useful and informative.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Free Cheat Sheet: GlassFish Application Server v3

Getting Started with GlassFish Application Server v3 begins by introducing you to what GlassFish is and how to get it.  Then it goes on to prove its worth as a lasting resouce by going into detail on Daily Administration Tasks, Security, Monitoring, and...

0 replies - 23558 views - 11/16/09 by Lyndsey Clevesy in Announcements

Getting Started with GlassFish Application Server v3

By Masoud Kalali

13,448 Downloads · Refcard 12 of 151 (see them all)

Download
FREE PDF


The Essential GlassFish 3 Cheat Sheet

GlassFish is a Java EE application server hosted at http://glassfish.dev.java.net. It is distributed under two open source licenses- GPL v2 with the Classpath exception and CDDL. This DZone Refcard on the GlassFish Application Server has been updated for Version 3. Getting Started with GlassFish Application Server v3 proves its worth as a lasting resource by going into detail on Daily Administration Tasks, Security, Monitoring, and more. This Refcard is a must have for anyone new to GlassFish, or anyone looking for a quick go-to resource.
HTML Preview
Getting Stared With GlassFish Application Server v3

Getting Stared With GlassFish Application Server v3

By Masoud Kalali

About Glassfish

GlassFish is a Java EE application server hosted at http://glassfish.dev.java.net and is sponsored mainly by Sun Microsystems. Based on the Java EE reference implementation, GlassFish is the first application server to support new specifications and standards. It is distributed under two open source licenses - GPL v2 with the Classpath exception and CDDL.

What Makes GlassFish Different

Several unique features differentiate GlassFish v3 from other application servers: it’s the first to support Java EE 6 and Web Profile; modularity based on OSGi; session retention on application redeploy; support for the latest Web services specification and proven interoperability with Microsoft WCF; easy-to-use administration console and command line; lowoverhead, fine grained monitoring, in addition to already available monitoring facilities in its administration channels; and runs dynamic languages and frameworks like RoR using native containers. For now, those requiring high availability clustering and centralized administration with Java EE 5 applications should consider GlassFish v2. These features are in the GlassFish v3 roadmap.

Support for GlassFish is available in a community driven mode (free) and commercial support provided by Sun Microsystems. It’s worth noting that to move from community driven support to commercial support there is no need to re-install. Install the Sun Branding and license from the Update Center, enter a commercial relationship with Sun Microsystems, and have best of the breed application server along with support from a leading Java EE vendor.

GlassFish v3

GlassFish v3 is the first application server based on OSGi with full support of Java EE 6 umbrella specification. OSGi and a highly modular architecture turn GlassFish v3 into the most flexible and extensible application server available on the market. It offers many GlassFish v2 features, and many new features and enhancements introduced in different layers - from application server security and stability to developer productivity improvements. Some additional new features include:

  • Embeddable; dynamically extensible
  • IPS as main packaging, distribution and updating system
  • Uses OpenInstaller for installation; optional zip installer
  • RESTful monitoring interface

Web and Enterprise Profiles

GlassFish v3 fully supports Java EE 6 and also provides both Web Profile and Java EE distributions. These distributions are different in terms of provided services and footprint. The beauty of modularity is the option to install the Java EE or Web Profile distributions and simply use the update center to download/install/uninstall the desired modules. The Web Profile distribution does not provide enterprise integration services such as JCA and JMS.

Downloading And Installing

To download GlassFish visit https://glassfish.dev.java.net/public/downloads/index.html and selecting the appropriate operating system. JDK 6 (version 1.6.0_13) or a newer version is required for installation. Supported operating systems on different architectures include: Solaris, OpenSolaris, Linux, AIX, and Windows. Installing GlassFish is as easy as following the automatic installer’s steps. Alternatively, GlassFish v3 can be installed using a zip installer; just download, unzip, and go. For the remainder of this Refcard, assume GlassFish is installed in gf_home.

GlassFish Domains

GlassFish, like other application servers, uses the concept of domains: entities which define the scope of administration. Each GlassFish v3 installation has its own domain, although support for multiple domains – an existing GlassFish v2 feature - is in the GlassFish v3 roadmap.

GlassFish Directory Structure

The directory structure of GlassFish v3 has changed to cope with new architecture and features. Figure 1 (page1) shows the new directory layout and Table 1 provides descriptions of important directories.

All directories in Figure 1 are numbered to ease locating them in the table and in Figure 2 (page3).

Table 1: Directory structure description
Dir Description
1 Contains links to asadmin and update center scripts. Directory no. 13 contains Java EE related scripts in addition to what is available in this directory.
2 GlassFish configuration files.
3 This is where new OSGi modules are placed to allow the application server platform to pick them up.
4 OSGi platform used by GlassFish
5 OpenInstaller and un-installation related scripts.
6 The default directory which GlassFish domains are created in. Domain related CLI commands look for target domain inside this directory
7 Domain start and stop scripts.
8 Default document root for serving http://IP:PORT/ Another set of files may be included here if required.
9 This is where shared libraries such as JDBC drivers, Apache Commons, etc. are placed.
10 Stores all logs, including server logs, access logs, and transaction logs.
11 Includes domain related configuration files like domain.xml, default-web.xml, key stores, etc.
12 Deployed applications, ready to be deployed applications and container generated files for deployed applications are stored in these directories
13 Update center scripts and PKG (5) image packaging system are located inside these directories.
14 Open MQ which is the default MQ implementation of GlassFish is located here.

GlassFish Administration

GlassFish provides multiple administration channels for administration flexibility.

Web Based Administration Console

To access the Web Console, point a browser to http://IP_ ADDRESS:PORT/. By default the port number is 4848 and the listener listens on all available network interfaces of the server machine. The default administration credentials are admin with no password, although one can be provided during installation. GlassFish uses a separate Virtual Server for Web Console for independent configuration.

Command Line Administration Console

This is the preferred approach for experienced administrators who choose to use CLI for administration purposes. Some tasks like creating/removing/backing up and restoring a domain are only possible using the CLI. The CLI also enables automation of routine tasks through shell scripts, as well as integration with provisioning tools. The administration CLI is accessible through the asadmin utility located at gf_home/bin directory. It is either a batch file named asadmin.bat for Windows or a shell script named asadmin for Linux and UNIX. The asadmin script has two modes. The first, invoking schema, is more suitable for creating custom scripts or for executing only one command:

./asadmin [ program options] command_name *[[--param] values]

The asadmin options are shown in Table 2:

Table 2: The asadmin program options
--host The application server administration listener IP address or host name.
--port The administration listener port number.
--user A username in admin realm. admin by default.
--passwordfile The password file containing administrator’s password.
--terse Add new type of container to host; for example another dynamic language applications.
--interactive If specified, CLI utility will ask for required parameter in an interactive way.
--secure If specified, CLI utility will use HTTPs to communicate with administration application to prevent possible security breach.

Not all of these parameters are required for executing a command and only important items are detailed in this Refcard.

The second mode of using asadmin script is entering the shell and running commands inside the shell. This is a bit faster than the first method which needs to run the asadmin utility each time a command is invoked.

To enter the shell and invoke commands, execute the asadmin script without any trailing command or parameter. The following example shows the asadmin shell and how to execute a command inside it.

asadmin>help create-domain

The invoking schema is the same for both methods but there are some usage differences. The CLI can execute most commands against a remote server by providing the address and port number of the administration listener. If not, it will execute the command against the default local server which is 127.0.0.1:4848.

Hot Tip

You can get a list of all commands along with a brief explanation about them by invoking help command. To save the output for later review use the following command: ./asadmin help > path_to_file.txt

JMX/AMX Administration Channel

This channel is widely preferred by developers who need to interact with GlassFish administration and management layer using the Java language. Administration tasks can also be executed by writing Java code using JMX. The GlassFish JMX listener listens on port 8686 by default. The username and password are the same as those for the CLI and Web Console. Any JMX console can be used, like the JDK’s JConsole or MC4J, to examine the GlassFish JMX MBeans and see what functions are availble.

RESTful Administration Channel

This interface exposes complete GlassFish management and monitoring functionalities through a RESTful interface, where output can be formatted using HTML, JSON or XML. The root URL for RESTful administration is http://ADMIN_ ADDRESS:ADMIN_PORT/management/domain/, which can accept requests from a browser, tools like curl or wget, or even Java applications using JAX-RS client libraries. Use the POST method to update the configuration, and use the GET method to view the configuration. For example to view the monitoring levels, send the following GET request from any web browser:

http://localhost:4848/management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels

To create a new HTTP listener we can POST the following command to the server.

curl -X POST -d “web-container=ON” -H “Accept: application/json”
http://localhost:4848/management/domain/configs/config/server-config/
monitoring-service/module-monitoring-levels

Daily Administration Tasks

Administration is performed on a day-to-day basis. Some tasks may be easier using the CLI, others with the Web Console.

Common Administration Tasks in CLI

Table 3 shows the list of common CLI commands. Some are exclusive to CLI, and others are easier to perform this way. Local commands are marked using an asterisk *.

Table 3: Common CLI Commands
Command Description
list-commands List local and remote commands. Remote commands are listed if the remote server is up and running.
create-domain* Create a new domain.
start-domain* Start the given domain.
stop-domain* Stop the given domain.
deploy Deploy an application.
undeploy Undeploy an application.
backup-domain* Create a backup of domain configurations. It does not include deployed applications.
restore-domain* Restore the given backup
list-domains* List all domains in the default or the given domains directory.
verify-domain-xml* Command to verify the the domain.xml file. Useful when edited manually

More CLI commands are covered in the Security section of this Refcard. There are tens of other commands for administrating Java EE managed resources and application server functionalities. The complete list of commands can be viewed by invoking the help command. An example of how to execute the create-domain command to create a domain named domain2 is as follows:

create-domain --adminuser admin --adminport 4848 --instanceport 8080
--domainproperties domain.jmxPort=8686:http.ssl.port=8181 domain2

Administration Tasks in Web Console

The Web Console is suitable for tasks where there are several parameters and attributes involved, or where the CLI is unavailable. It is very easy to create JDBC connection pools, JMS destinations, configure listeners and thread pools, some security related configuration, containers configuration, cluster-wide configuration and management, and so on. The Web Console has a very organized structure to make it easy to find and locate tasks. Figure 2 shows a part of the tree based menu structure of Web administration console.

Administration Tasks and JMX Console

GlassFish v2 can be monitored and managed using JMX and AMX-enabled tools such as jconsole, or by developing simple custom applications to take care of repetitive daily tasks or automatic response to some events. Figure 3 shows the GlassFish v3 MBeans tree in JConsole. The AMX Beans form a dynamic tree which represents the entire application server and any manageable object inside it. The AMX is a dynamic proxy layer on top of JMX MBeans to ease interaction with the GlassFish management core.

Security

It is wise to spend time securing the application server instead of gazing at the disaster a security leak caused.

Passwords Security

The administration and master passwords should be changed frequently. Change them using provided CLI commands. Table 4 lists the required tasks for overall password security along with a description and command used to complete that security task.

Table 4: Security tasks and related commands
Task Description and Command
Change administrator password Change the administrator password from time to time using changeadmin- password command.
Change master password which protects the key store files Change the default master password from “changeit” to something else using change-master-password command.
Alias of the passwords used for connection pools, JMS hosts and so on Passwords required for connection pools are stored in plain text; to avoid this, use password aliasing. For example: create-password-alias Alias_Name and use the alias name in the following format instead of the password: ${ALIAS=sample-alias} A complete set of commands for creating, updating, listing and deleting aliases is provided.
Do not enter passwords The CLI is typically used to administer multiple servers; to prevent entering clear-text the passwords on the command line, use a password file containing AS_ADMIN_PASSWORD=${ALIAS=Alias_name} AS_ADMIN_MASTERPASSWORD=${ALIAS=Al_name} and pass it to commands invoked using --passwordfile parameter. And yes, use password aliases here too.
Do not enter passwords The login command is helpful in interactive mode. After successfully logging into a server, asadmin will store the password and re-use it when a command is invoked on that server. The format is: asadmin login --host HOST_ADDRESS --port ADMIN_PORT The command will enter the interactive mode and ask for passwords.

Listeners Security (Network Security)

Listeners are the interaction channels of the application server with the outside world. Both the administration listener and the ORB listener should be protected from un-authorized access. Sometimes securing listeners means binding them to a specific network interface of the server machine, and sometimes it means mutual authentication protection using digital certificates. Table 5 lists the listeners, security measures and how to access them through Web Console.

Table 5: Listeners and Listeners Security Measures
Listener How to access Security Measures
HTTP Listeners Tree>Configuration>Network Config> Network Listeners Listeners should listen on specific interfaces, not on 0.0.0.0 (all available interfaces).
HTTP Listeners Tree>Configuration>Network Config> Protocols Check off the Security check box if HTTPS is required for this listener.
ORB Listeners Tree>Configuration>ORB>IIOP Listeners Make sure to leave required listeners active. Be sure to change the network address to the appropriate one. Use secure listeners if possible.
JMX Listeners Tree>Configuration>Admin service Enable security (SSL) if required. Use only required network addresses. Change authentication realm if required.

Hot Tip

New users with administration permission can be added to admin-realm. To do this, navigate to Tree> Configuration>Security>Realms>admin-realm and then click on the Manage Users button. Add as many users as needed.

Security Audition

Auditing is useful for checking logged events and conducting analysis to locate potential problems. Security auditing makes it possible to review events like failed logins. The default auditing module provided with GlassFish logs all security events in the server.log file. To enable auditing hit Tree>Con figuration>Security>Audit Modules>default and then enable the module by changing the auditOn property’s value to true. Implementing new auditing modules is as simple as extending the com.sun.appserv.security.AuditModule class, putting the implementation in the domain classpath and adding it as a new audit module in Tree>Configuration>Security>Au dit Modules>. After adding the auditing module, it can be enabled by changing the appropriate attribute defined, if any.

HTTP Access Log

Storing HTTP access logs can help with reviewing HTTP access events. Access logs can be enabled in two ways: HTTP Service enables it for all HTTP listeners (Tree>Configuration>HTTP Service) and Virtual Server level enables HTTP Access Log for a particular Virtual Server (Tree>Configuration>Virtual Server). Access logs are stored in a directory named access inside the logs directory of each domain.

Hot Tip

A virtual server, sometimes called a virtual host, is an object that allows the same physical server to host multiple Internet domain names. Virtual Servers can use dedicated HTTP listeners and configurations for authentication realms and default web applications. You can create Virtual Server by navigating to Tree>Configuration>Virtual Server.

Monitoring

Monitoring is an essential part of enterprise applications, either in application server services layers or in enterprise applications themselves. GlassFish provides advanced and extensible monitoring capabilities for both applications deployed in GlassFish and for GlassFish services themselves. The monitoring information is accessible though different channels, including all three administration channels in addition to the newly included RESTful interface.

Web Console and Monitoring

To monitor a GlassFish services like JDBC connection pools, HTTP services and so on, enable monitoring for the services of interest. To enable monitoring for a service navigate to Tree>Configuration>Monitoring and change the monitoring level of the services and containers of interest. Three levels of monitoring are available:

  1. OFF: No monitoring information is gathered.
  2. LOW: Cumulative statistics are gathered.
  3. HIGH: Detailed statistics are gathered.

When enabled, monitoring affects the overall performance of the application server, specifically the observed services. It is better not to use HIGH in a production environment. After changing the monitoring level, GlassFish starts gathering monitoring information which can be viewed in the Web Console or other channels. To view the monitoring information, navigate to Tree>Application Server and select the Monitor tab. This page shows all gathered statistics for any service with statistics collection enabled.

For example, the JDBC Connection Pools performance metrics, with counts the maximum number of connections, maximum available connections, and more, and various timing factors like maximum wait time, and so on.

CLI and Monitoring

For CLI advocates, the CLI provides thorough monitoring capabilities. The CLI offers fine-grained control on which performance factors to monitor. Table 6 lists all CLI commands related to monitoring.

Table 6: CLI monitoring commands
Command Description
get Getting the value for any configuration attribute in the system. View the monitoring level of a service or multiple services using this command.
set Setting the value for any configuration attribute in the system. Set the monitoring level of a service or multiple services using this command.
monitor Monitoring one or multiple attributes of GlassFish services like transaction, JMS, JDBC connection pools and so on. The command is very flexible about information representation.

Configuration attributes can be accessed using a concept called Dotted Names. Dotted names, as the name may imply, is a hierarchy of attributes representing all servers, services, and managed objects of the GlassFish Application Server in a tree which starts with father nodes and comes down to attribute leafs. Each level is separated from the adjacent level by a dot. The following dotted names can further clarify the concept.

resources.jdbc-connection-pool.DerbyPool.allow-non-component-callers
servers.server.server.resource-ref.jdbc/__TimerPool.enabled
configs.config.server-config.ejb-container.max-pool-size

Now, let’s use these three commands to do some monitoring.

asadmin get server.monitoring-service.module-monitoring-levels.*

Checks the monitoring levels of all services using the wild-card character.

asadmin set server.monitoring-service.module-monitoring-levels.jdbcconnection-
pool=HIGH

This last command set the JDBC connection pools monitoring level to HIGH.

asadmin monitor --type jdbcpool --filter sample-mysql-pool --filename
/opt/out2.csv --interval 5 server

This monitor command will gather sampling data each 5 seconds for a JDBC connection pool named sample-mysqlpool which is managed by a server instance named server. The command will store the sampling data to a CSV file located at /opt/out2.csv.

JMX and Monitoring

JMX enables application server to be monitored directly from Java source code, and can respond to sampling data in an appropriate way. An example would be a swing-based monitoring console or integration of GlassFish monitoring into a bigger monitoring console to monitor the entire infrastructure from a single console. Another common example is monitoring and changing application server configuration in a headless way.

RESTful Monitoring Interface

One of the unique features of GlassFish v3 is the RESTful monitoring interface that allows virtually any programming language to access GlassFish monitoring information using a RESTful interface.

The RESTful interface represents a hierarchy of GlassFish services, server environment, JVM, deployed applications and managed resources like JDBC connection pools.

To access monitoring information using the RESTful interface, send a GET request to http://ADMIN_ADDRESS:ADMIN_PORT/monitoring/domain/ which will return a list of all child objects for this node (monitoring must be enabled). Going down the hierarchy to get monitoring information along with a list of children for any node in the hierarchy. For example sending a get request to http://localhost:4848/monitoring/domain/server/jvm/memory (with JVM monitoring enabled) will result in an output similar to Figure 4.

The RESTful interface can format the output to JSON or XML when the appropriate trailing parameters are included. For JSON format include application/json in the URL and for XML include application/xml in the URL trail. For example: curl http://localhost:4848/monitoring/domain/server/jvm/ memory -H “application/xml” The RESTful monitoring interface enables developing monitoring solutions using scripting languages like Perl, Python and so on.

For GlassFish Enterprise Server v3 commercial customers, Sun Microsystems provides a monitoring scripting client, which enable ad-hoc querying using fine-grained probes, similar to DTrace on Solaris.

Performance Tuning

Enterprise application performance is a big concern, and performance tuning is a hurdle which all enterprise application developers are involved with. While Java EE performance tuning is out of the scope of this refcard, some GlassFish performance tuning information is provided. Additional tuning information is a available through performance whitepapers available through Sun (http://www.sun.com/software/products/glassfish_portfolio/resources.jsp). In addition, GlassFish Enterprise Server subscriptions include Enterprise Manager, which offers tools to “auto-tune” the configuration based on a simple set of questions about the deployment environment.

Although the JVM uses sophisticated garbage collection algorithms, performance and memory can be tuned by changing memory management and garbage collection parameters, depending on the deployment environment.

Tools like VisualVM give a good sense of what is going on the application server. VisualVM is now included in JDK and is accessible using the java_home/bin/visualvm. Installing visual GC plug-in for Visual VM can help with memory tuning. More information about Visual VM is available at http://visualvm.dev.java.net or JDK documentation. To change the application server’s JVM option navigate to Tree> Configuration>JVM Settings and select the JVM Options tab.

Web Container Performance Tuning

Tuning the Web container will lead to the application server processing Web requests in a more efficient way and will result in higher throughput. Some determining factors for Web container performance are:

  • HTTP listener thread pool attributes.
  • File cache support in HTTP Protocol of each HTTP listener
  • Disabling the access log.
  • Disabling monitoring.

Thread pool attributes customization highly depends on the deployed applications’ characteristics in relation to whether they are memory consumers, process consumers, IO bound and so on.

Tuning the Web container is easier by analyzing the statistics driven from monitoring the Web container and deployed applications. Web Container configuration is available at Tree>Configuration>Web Container node. Listener and protocols configuration are available at Tree>Configuration>Network Config>Protocols.

EJB Container Performance Tuning

The EJB container can affect performance more than the Web container if deployed applications use EJBs extensively for business logic processing. Fine-tuning the EJB container involves tuning the EJB container thread pool and its cache size. Although the timer service effects are usually not intensive, for applications with a large number of timers it is recommended to reduce the timer service load by reducing the service precision.

Fine-tuning Message Driven Beans pool affects the overall performance of the system if it is highly dependent on JMS and message processing.

Decreasing the pool size results in fewer MDBs processing the JMS messages and less overhead on the system. However it will also result in longer wait time for asynchronous tasks and requests.

Monitoring the EJB container using GlassFish builtin capabilities helps to tune the EJB container. Enable monitoring, let the system work for some time, and then decide on new values for container attributes. EJB container configuration is accessible through Tree>Configuration>EJB Container.

JDBC Connection Pool Performance Tuning

JDBC connection pools often cause bottlenecks in Web applications which use JDBC to access a database. Monitoring JDBC connection pools using GlassFish monitoring can give a fair amount of information about whether application performance is related to JDBC connection pool configuration. Usually, maximum wait time, average wait time, high watermark and minimum available free connections are parameters that help us decide whether to further limit the size of the connection pool, or expand it (to prevent requests processing waits longer than necessary for a connection to become free).

Detecting connection leaks is another very helpful feature of GlassFish JDBC monitoring. Simply scan the monitoring results to determine if there aree JDBC connection leaks.

JMS Server Interaction

GlassFish supports three different methods for integration with a JMS broker. A local or embedded broker means the JMS broker load is on the same machine running the application server. If the JMS service integration type is set to REMOTE, processing load is transferred from the application server machine to another machine which only hosts the JMS broker or set of brokers. However, this change only affects JMS-bound applications that rely heavily on messaging. JMS Service configuration is available at Tree>Configuration>Java Message Service.

Embedded GlassFish

Embedded GlassFish is available at https://embeddedglassfish.dev.java.net/. The embedded distribution hosts applications embedded into a larger, single JVM process. For example, use embedded distribution for unit testing. The following sample code shows how to create a server instance, start it, and deploy a Web application into the embedded instance.

Server server = new Server.Builder(“emServer”).build();
server.createPort(8080);
server.addContainer(new org.glassfish.web.embed.impl.
EmbeddedWebContainer());
server.start();
File sampleWar = new File(“sample.war”);
server.getDeployer().deploy(sampleWar);
// Insert customer logic here
server.stop();

Using the embedded mode is as simple as the few lines above. The embedded mode is useful for unit testing and cases when Web or enterprise applications run in-process instead of being hosted in a stand-alone server.

GlassFish Update Tool

GlassFish v3 is a modular application server, and update and distribution mechanisms can benefit from the modular architecture. GlassFish v3 uses IPS/PKG(5) for distribution and updating. The IPS/PKG(5) is an operating system-independent, network-based distribution mechanism for applications, from a simple phone book to systems as large as operating systems like OpenSolaris.

Bootstrapping the Update Tool

During the installation process installer provides us with the option of installing and configuring the Update Tool for us. If we do select this option we can use the updatetool script located in the gf_home/bin to bootstrap it at any time after the installation. To start the bootstrapping we just need to run ./updatetool or updatetool.bat; it will automatically detect whether the update center is installed or not and will continue accordingly.

Using Update Tool

The PKG 5 IPS provides a command line script for using IPS to install, update, upgrade and remove an application. The script is named pkg and is located inside the gf_home/bin. In addition to the CLI command, there is a very polished GUI named Update Tool which we can run using the updatetool script available in the same directory. Running the update tool will open a GUI similar to Figure 5. This shows what new updates are available for our installed modules, or what new modules are available which we many need to install. We can use the update tool and IPS to distribute our Web or Enterprise application updates, to create our own update centers, to distribute our GlassFish modules, and even to distribute our custom applications using IPS.

Another good feature of the Update Tool is that it can manage multiple installation images of different applications and different versions. We just need to register new images using File menu.

Like many other applications, the GlassFish Update Tool will notify of available updates through a system tray icon. To register its system try icon we need to open a command window, navigate to gf_home/updatetool and then execute the following command.

./updatetool --register

It will simply sit in the system tray and let us know when an update for our installed modules is available. Imagine that we can update the Hibernate or Spring or any other framework’s libraries automatically and through a notification system.

Architecture

GlassFish v3 benefits from a modular architecture based on OSGi modularity system for platform and bundle management, and HK2 for service layer modularity. The HK2, available at http://hk2.dev.java.net, forms the GlassFish micro-kernel and is roughly based on Java Platform Modularity specification. The whole modularity in the service layer is based on the concept of contracts and contracts providers which are simply Java interfaces and interface implementations along with some annotations.

GlassFish can be extended by developing new providers for contracts, and the good news is that a registry of extension information is not required; instead, all of the extension discovery and life cycle management is completely automatic. Extensions are “installed” by simply placing them in the modules directory.

Table 7: GlassFish extensibility points
Extension point Sample use case
CLI Extensibility Add new CLI command; for example a command to start or stop a new type of container.
Web Administration Console Extensibility Add a whole new set of pages and nodes to administration console to address new administration requirements like administrating a new container.
Monitoring Extensibility Export monitoring information to a specific format or from a specific container.
Container Extensibility Add new type of container to host; for example applications developed by another dynamic language.

Masoud Kalali

Photo of author Masoud Kalali

Masoud Kalali

Masoud Kalali holds a software engineering degree and has been working on software development projects since 1998. He has experience with a variety of technologies (.Net, J2EE, CORBA, and COM+) on diverse platforms (Solaris, Linux, and Windows). His experience is in software architecture, design and server side development. Masoud has several articles in Java.net. He is one of founder members of NetBeans Dream Team. Masoud’s main area of research and interest includes Web Services and Service Oriented Architecture along with large scale and high throughput systems’ development and deployment.

Blog
Contact

Recommended Book

Book cover of Java EE 5 Development using GlassFish Application Server

The complete guide to installing and configuring the GlassFish Application Server and developing Java EE 5 applications to be deployed to this server.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

JSF 2.0: the Long-Awaited Successor to JSF 1.x

Check out our latest DZone Refcard on JSF 2.0!

0 replies - 7173 views - 06/15/09 by Lyndsey Clevesy in Announcements

Have you started using Spring Dynamic Modules yet?

Get started now! Download the latest DZone Refcard: Getting Started with Spring-DM. 

0 replies - 5273 views - 06/08/09 by Lyndsey Clevesy in Announcements

Spring Annotations

By Craig Walls

34,723 Downloads · Refcard 26 of 151 (see them all)

Download
FREE PDF


The Essential Spring Annotations Cheat Sheet

Spring Annotations From its beginning, Spring’s most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this DZone Refcard, youll find a guide to all of the annotations supported in Spring 2.5. This card also covers Core Spring Annotations, Spring MVC Annotations, AspectJ Annotations, JSR-250 Annotations, Testing Annotations, Hot Tips and more.
HTML Preview
Spring Annotations

Spring Annotations

By Craig Walls

Spring Annotations

From its beginning, Spring's most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this reference card, you'll find a guide to all of the annotations supported in Spring 2.5.

Core Spring Annotations

Context Configuration Annotations

These annotations are used by Spring to guide creation and injection of beans.

Annotation Use Description
@Autowired Constructor, Field, Method Declares a constructor, field, setter method, or configuration method to be autowired by type. Items annotated with @Autowired do not have to be public.
@Configurable Type Used with to declare types whose properties should be injected, even if they are not instantiated by Spring. Typically used to inject the properties of domain objects.
@Order Type, Method, Field Defines ordering, as an alternative to implementing the org. springframework.core.Ordered interface.
@Qualifier Field, Parameter, Type, Annotation Type Guides autowiring to be performed by means other than by type.
@Required Method (setters) Specifies that a particular property must be injected or else the configuration will fail.
@Scope Type Specifies the scope of a bean, either singleton, prototype, request, session, or some custom scope.

Autowiring Bean Properties

A typical Spring bean might have its properties wired something like this:

<bean id="pirate" class="Pirate">
<constructor-arg value="Long John Silver" />
<property name="treasureMap" ref="treasureMap" />
</bean>

But it's also possible to have Spring automatically inject a bean's properties from other beans in the context. For example, if the Pirate class were annotated with @Autowired like this...

public class Pirate {
private String name;
private TreasureMap treasureMap;
public Pirate(String name) { this.name = name; }
@Autowired
public void setTreasureMap(TreasureMap treasureMap) {
this.treasureMap = treasureMap;
}
}

...and if you were to configure annotation configuration in Spring using the <context:annotation-configuration> element like this...

<beans ... >
<bean id="pirate" class="Pirate">
<constructor-arg value="Long John Silver" />
</bean>
<bean id="treasureMap" class="TreasureMap" />
<context:annotation-config />
</beans>

...then the "treasureMap" property will be automatically injected with a reference to a bean whose type is assignable to TreasureMap (in this case, the bean whose ID is "treasureMap").

Autowiring Without Setter Methods

@Autowired can be used on any method (not just setter methods). The wiring can be done through any method, as illustrated here:

@Autowired
public void directionsToTreasure(TreasureMap
treasureMap) {
this.treasureMap = treasureMap;
}

And even on member variables:

@Autowired
private TreasureMap treasureMap;

To resolve any autowiring ambiguity, use the @Qualifier attribute with @Autowired.

@Autowired
@Qualifier("mapToTortuga")
private TreasureMap treasureMap;

Ensuring That Required Properties are Set

To ensure that a property is injected with a value, use the @Required annotation:

@Required
public void setTreasureMap(TreasureMap treasureMap) {
this.treasureMap = treasureMap;
}

In this case, the "treasureMap" property must be injected or else Spring will throw a BeanInitializationException and context creation will fail.

Stereotyping Annotations

These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration.

In addition, if a PersistenceExceptionTranslationPostProcessor is configured in Spring, any bean annotated with @Repository will have SQLExceptions thrown from its methods translated into one of Spring's unchecked DataAccessExceptions.

Annotation Use Description
@Component Type Generic stereotype annotation for any Spring-managed component.
@Controller Type Stereotypes a component as a Spring MVC controller.
@Repository Type Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the component's methods should be translated into Spring DataAccessExceptions.
@Service Type Stereotypes a component as a service.

Automatically Configuring Beans

In the previous section, you saw how to automatically wire a bean's properties using the @Autowired annotation. But it is possible to take autowiring to a new level by automatically registering beans in Spring. To get started with automatic registration of beans, first annotate the bean with one of the stereotype annotations, such as @Component:

@Component
public class Pirate {
private String name;
private TreasureMap treasureMap;
public Pirate(String name) { this.name = name; }
@Autowired
public void setTreasureMap(TreasureMap treasureMap) {
this.treasureMap = treasureMap;
}
}

Then add <context:component-scan> to your Spring XML configuration:

<context:component-scan
base-package="com.habuma.pirates" />

The base-package annotation tells Spring to scan com.habuma. pirates and all of its subpackages for beans to automatically register.

You can specify a name for the bean by passing it as the value of @Component.

@Component("jackSparrow")
public class Pirate { ... }

Hot Tip

Specifying Scope For Auto-Configured Beans

By default, all beans in Spring, including auto-configured beans, are scoped as singleton. But you can specify the scope using the @Scope annotation. For example:

@Component
@Scope("prototype")
public class Pirate { ... }

This specifies that the pirate bean be scoped as a prototype bean.

Creating Custom Stereotypes

Autoregistering beans is a great way to cut back on the amount of XML required to configure Spring. But it may bother you that your autoregistered classes are annotated with Spring-specific annotations. If you're looking for a more non-intrusive way to autoregister beans, you have two options:

  1. Create your own custom stereotype annotation. Doing so is as simple as creating a custom annotation that is itself annotated with @Component:
    @Component
    public @interface MyComponent {
    String value() default "";
    }
  2. Or add a filter to <context:component-scan> to scan for annotations that it normally would not:
    <context:component-scan
    base-package="com.habuma.pirates">
    <context:include-filter type="annotation"
    expression="com.habuma.MyComponent" />
    <context:exclude-filter type="annotation"
    expression=
    "org.springframework.stereotype.Component" />
    </context:component-scan>

In this case, the @MyComponent custom annotation has been added to the list of annotations that are scanned for, but @Component has been excluded (that is, @Componentannotated classes will no longer be autoregistered).

Regardless of which option you choose, you should be able to autoregister beans by annotating their classes with the custom annotation:

@MyComponent
public class Pirate {...}

Spring MVC Annotations

These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications with minimal XML configuration and without extending one of the many implementations of the Controller interface.

Annotation Use Description
@Controller Type Stereotypes a component as a Spring MVC controller.
@InitBinder Method Annotates a method that customizes data binding.
@ModelAttribute Parameter, Method When applied to a method, used to preload the model with the value returned from the method. When applied to a parameter, binds a model attribute to the parameter. table
@RequestMapping Method, Type Maps a URL pattern and/or HTTP method to a method or controller type.
@RequestParam Parameter Binds a request parameter to a method parameter.
@SessionAttributes Type Specifies that a model attribute should be stored in the session.

Setting up Spring for Annotated Controllers

Before we can use annotations on Spring MVC controllers, we'll need to add a few lines of XML to tell Spring that our controllers will be annotation-driven. First, so that we won't have to register each of our controllers individually as <bean>s, we'll need a <context:component-scan>:

<context:component-scan
base-package="com.habuma.pirates.mvc"/>

In addition to autoregistering @Component-annotated beans, <context:component-scan> also autoregisters beans that are annotated with @Controller. We'll see a few examples of @Controller-annotated classes in a moment.

But first, we'll also need to tell Spring to honor the other Spring MVC annotations. For that we'll need <context:annotation-config> : <context:annotation-config/>

Hot Tip

Use a conventions-based view resolver.

If you use a conventions-based view resolver, such as Spring's UrlBasedViewResolver or InternalResourceViewResolver, along with <context:component-scan> and <context:annotation-config>, you can grow your application indefinitely without ever touching the Spring XML again.

Creating a Simple MVC Controller

The following HomePage class is annotated to function as a Spring MVC controller:

@Controller
@RequestMapping("/home.htm")
public class HomePage {
@RequestMapping(method = RequestMethod.GET)
public String showHomePage(Map model) {
List<Pirate> pirates = pirateService.
getPirateList();
model.add("pirateList", pirates);
return "home";
}
@Autowired
PirateService pirateService;
}

There are several important things to point out here. First, the HomePage class is annotated with @Controller so that it will be autoregistered as a bean by <context:component-scan>. It is also annotated with @RequestMapping, indicating that this controller will respond to requests for "/home.htm".

Within the class, the showHomePage() method is also annotated with @RequestMapping. In this case, @RequestMapping indicates that HTTP GET requests to "/home.htm" will be handled by the showHomePage() method.

Creating a Form-Handling Controller

In a pre-2.5 Spring MVC application, form-processing controllers would typically extend SimpleFormController (or some similar base class). But with Spring 2.5, a form-processing controller just has a method that is annotated to handle the HTTP POST request:

@Controller
@RequestMapping("/addPirate.htm")
public class AddPirateFormController {
@RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
return "addPirate";
}
@ModelAttribute("pirate")
public Pirate setupPirate() {
Pirate pirate = new Pirate();
return pirate;
}
@RequestMapping(method = RequestMethod.POST)
protected String addPirate(@ModelAttribute("pirate")
Pirate pirate) {
pirateService.addPirate(pirate);
return "pirateAdded";
}
@Autowired
PirateService pirateService;
}

Here the @RequestMapping annotation is applied to two different methods. The setupForm() method is annotated to handle HTTP GET requests while the addPirate() method will handle HTTP POST requests. Meanwhile, the @ModelAttribute is also pulling double duty by populating the model with a new instance of Pirate before the form is displayed and then pulling the Pirate from the model so that it can be given to addPirate() for processing.

Transaction Annotations

The @Transactional annotation is used along with the <tx:annotation-driven> element to declare transactional boundaries and rules as class and method metadata in Java.

Annotation Use Description
@Transactional Method, Type Declares transactional boundaries and rules on a bean and/or its methods.

Annotating Transactional Boundaries

To use Spring's support for annotation-declared transactions, you'll first need to add a small amount of XML to the Spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/
beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/
springbeans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-
2.5.xsd">
<tx:annotation-driven />
...
</beans>

The <tx:annotation-driven> element tells Spring to keep an eye out for beans that are annotated with @Transactional. In addition, you'll also need a platform transaction manager bean declared in the Spring context. For example, if your application uses Hibernate, you'll want to include the HibernateTransactionManager:

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.
HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"
/>
</bean>

With the basic plumbing in place, you're ready to start annotating the transactional boundaries:

@Transactional(propagation=Propagation.SUPPORTS,
readOnly=true)
public class TreasureRepositoryImpl implements
TreasureRepository {
...
@Transactional(propagation=Propagation.REQUIRED,
readOnly=false)
public void storeTreasure(Treasure treasure) {...}
...
}

At the class level, @Transactional is declaring that all methods should support transactions and be read-only. But, at the method-level, @Transactional declares that the storeTreasure() method requires a transaction and is not read-only. Note that for transactions to be applied to @Transactionalannotated classes, those classes must be wired as beans in Spring.

JMX Annotations

These annotations, used with the <context:mbean-export> element, declare bean methods and properties as MBean operations and attributes.

Annotations Use Description
@ManagedAttribute Method Used on a setter or getter method to indicate that the bean's property should be exposed as a MBean attribute.
@ManagedNotification Type Indicates a JMX notification emitted by a bean.
@ManagedNotifications Type Indicates the JMX notifications emitted by a bean.
@ManagedOperation Method Specifies that a method should be exposed as a MBean operation.
@ManagedOperationParameter Method Used to provide a description for an operation parameter.
@ManagedOperationParameters Method Provides descriptions for one or more operation parameters.
@ManagedResource Type Specifies that all instances of a class should be exposed a MBeans.

Exposing a Spring Bean as a MBean

To get started with Spring-annotated MBeans, you'll need to include <context:mbean-export> in the Spring XML configuration:

<context:mbean-export/>

Then, you can annotate any of your Spring-managed beans to be exported as MBeans:

@ManagedResource(objectName="pirates:name=PirateService")
public interface PirateService {
@ManagedOperation(
description="Get the pirate list")
public List<Pirate> getPirateList();
}

Here, the PirateService has been annotated to be exported as a MBean and its getPirateList() method is a managed operation.

Aspect Annotations

For defining aspects, Spring leverages the set of annotations provided by AspectJ.

Annotation Use Description
@Aspect Type Declares a class to be an aspect.
@After Method Declares a method to be called after a pointcut completes.
@AfterReturning Method Declares a method to be called after a pointcut returns successfully.
@AfterThrowing Method Declares a method to be called after a pointcut throws an exception.
@Around Method Declares a method that will wrap the pointcut.
@Before Method Declares a method to be called before proceeding to the pointcut.
@DeclareParents Static Field Declares that matching types should be given new parents,that is, it introduces new functionality into matching types.
@Pointcut Method Declares an empty method as a pointcut placeholder method.

What's important to note, however, is that while you can use AspectJ annotations to define Spring aspects, those aspects will be defined in the context of Spring AOP and will not be handled by the AspectJ runtime. This is significant because Spring AOP is limited to proxying method invocations and does not provide for the more exotic pointcuts (constructor interception, field interception, etc.) offered by AspectJ.

Annotating Aspects

To use AspectJ annotations to create Spring aspects, you'll first need to provide a bit of Spring XML plumbing:

<beans xmlns="http://www.springframework.org/schema/
beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/
spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/springaop-
2.5.xsd">
...
<aop:aspectj-autoproxy/>
...
</beans>

The <aop:aspectj-autoproxy> element tells Spring to watch for beans annotated with AspectJ annotations and, if it finds any, to use them to create aspects. Then you can annotate bean classes to be aspects:

@Aspect
public class ChantySinger {
@Pointcut("execution(* Pirate.plunder(..))")
public void plunderPC() {}
@Before("plunderPC()")
public void singYoHo() {
...
}
@AfterReturning("plunderPC()")
public void singAPiratesLifeForMe() {
...
}
}

This simple annotation-based aspect has a pointcut that is triggered by the execution of a plunder() method on the Pirate class. Before the Pirate.plunder() method is executed, the singYoHo() method is called. Then, after the Pirate.plunder() method returns successfully, the singAPiratesLifeForMe() method is invoked. (For more advanced examples of AspectJ annotations, see the AspectJ documentation at http://www.eclipse.org/aspectj/docs.php.)

Note the rather odd looking plunderPC() method. It is annotated with @Pointcut to indicate that this method is a pointcut placeholder. The key thing here is that the most interesting stuff happens in the annotation itself and not in the method. In fact, pointcut placeholder methods must be empty methods and return void.

JSR-250 Annotations

In addition to Spring's own set of annotations, Spring also supports a few of the annotations defined by JSR-250, which is the basis for the annotations used in EJB 3.

Annotation Use Description
@PostConstruct Method Indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary.
@PreDestroy Method Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary.
@Resource Method, Field Indicates that a method or field should be injected with a named resource (by default, another bean).

Wiring Bean Properties with @Resource

Using @Resource, you can wire a bean property by name:

public class Pirate {
@Resource
private TreasureMap treasureMap;
}

In this case, Spring will attempt to wire the "treasureMap" property with a reference to a bean whose ID is "treasureMap". If you'd rather explicitly choose another bean to wire into the property, specify it to the name attribute:

public class Pirate {
@Resource(name="mapToSkullIsland")
private TreasureMap treasureMap;
}

Initialization and Destruction Methods

Using JSR-250's @PostConstruct and @PreDestroy methods, you can declare methods that hook into a bean's lifecycle. For example, consider the following methods added to the Pirate class:

public class Pirate {
...
@PostConstruct
public void wakeUp() {
System.out.println("Yo ho!");
}
@PreDestroy
public void goAway() {
System.out.println("Yar!");
}
}

As annotated, the wakeUp() method will be invoked just after Spring instantiates the bean and goAway() will be invoked just before the bean is removed from the Spring container.

Testing Annotations

These annotations are useful for creating unit tests in the JUnit 4 style that depend on Spring beans and/or require a transactional context.

Annotation Use Description
@AfterTransaction Method Used to identify a method to be invoked after a transaction has completed.
@BeforeTransaction Method Used to identify a method to be invoked before a transaction starts.
@ContextConfiguration Type Configures a Spring application context for a test.
@DirtiesContext Method Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes.
@ExpectedException Method Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown.
@IfProfileValue Type, Method Indicates that the test class or method is enabled for a specific profile configuration.
@NotTransactional Method Indicates that a test method must not execute in a transactional context.
@ProfileValueSourceConfiguration Type Identifies an implementation of a profile value source. The absence of this annotation will cause profile values to be loaded from system properties.
@Repeat Method Indicates that the test method must be repeated a specific number of times.
@Rollback Method Specifies whether or not the transaction for the annotated method should be rolled back or not.
@TestExecutionListeners Type Identifies zero or more test execution listeners for a test class.
@Timed Method Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail.
@TransactionConfiguration Type Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class.

Writing a Spring-Aware Test

The key to writing a Spring-aware test is to annotate the test class with @RunWith, specifying SpringJUnit4ClassRunner as the class runner behind the test:

@RunWith(SpringJUnit4ClassRunner.class)
public class PirateTest {
...
}

In this case, the Spring test runner will try to load a Spring application context from a file named PirateTest-context.xml. If you'd rather specify one or more XML files to load the application context from, you can do that with @ContextConfiguration:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "pirates.xml" })
public class PirateTest {
...
}

With test configured to load a Spring application context, you now may request that Spring autowire properties of the test class with beans from the Spring context:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "pirates.xml" })
public class PirateTest {
@Autowired
private Pirate pirate;
@Autowired
private TreasureMap treasureMap;
@Test
public void annotatedPropertyShouldBeAutowired() {
assertNotNull(pirate.getTreasureMap());
assertEquals(treasureMap, pirate.getTreasureMap());
}
}

In this case, the pirate and treasureMap properties will be wired with the beans whose ID are "pirate" and "treasureMap", respectively.

Accessing the Spring Context in a Test

If you need the Spring application context itself in a test, you can autowire it into the test the same as if it were a bean in the context:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "pirates.xml" })
public class PirateTest {
@Autowired
private Pirate pirate;
@Autowired
private ApplicationContext applicationContext;
@Test
public void annotatedPropertyShouldBeAutowired() {
assertNotNull(pirate.getTreasureMap());
assertEquals(applicationContext.
getBean("treasureMap"), pirate
.getTreasureMap());
}
}

About The Author

Photo of author Craig Walls

Craig Walls

Craig Walls is a Texas-based software developer with more than 13 years, experience working in the telecommunication, financial, retail, educational, and software industries. He's a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring on his blog. When he's not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, three dogs, and an ever-fluctuating number of tropical fish.

Publications
Blog
Projects
  • Committer to XDoclet project
  • Originator of Portlet and Spring modules for XDoclet

Recommended Book

Book cover of Spring in Action

Spring in Action, 2nd Edition is a practical and comprehensive guide to the Spring Framework, the framework that forever changed enterprise Java development. What's more, it's also the first book to cover the new features and capabilities in Spring 2.


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

By Cay S. Horstmann

32,467 Downloads · Refcard 21 of 151 (see them all)

Download
FREE PDF


The Essential JSF Cheat Sheet

JavaServer Faces (JSF) is the “official” component-based view technology in the Java EE web tier. JSF consists of a Java-based Web application framework that is meant to simplify development integration of web-based user interfaces. It 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 DZone Refcard describes the JSF development process, standard JSF tags, the JSF expression language, and the faces-config.xml configuration file.
HTML Preview
JavaServer Faces

JavaServer Faces

By Cay S. Horstmann

About This Refcard

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 the JSF development process, standard JSF tags, the JSF expression language, and the faces-config.xml configuration file.

Development Proces

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. Entries in faces-config.xml contain navigation rules and instructions for loading managed beans.

Development Process

A JSF page has the following structure:

JSP Style Proper XML
<html>
<%@ taglib
uri="http://
java.sun.com/jsf/
core"
prefix="f" %>
<%@ taglib
uri="http://
java.sun.com/jsf/
html"
prefix="h" %>
<f:view>
<head>
<title>...</
title>
</head>
<body>
<h:form>
...
</h:form>
</body>
</f:view>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<jsp:root xmlns:jsp="http://java.sun.com/
JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
version="2.0">
<jsp:directive.page contentType="text/
html;charset=UTF-8"/>
<jsp:output omit-xml-declaration="no"
doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0
Transitional//EN"
doctype-system="http://www.w3.org/TR/
xhtml1/
DTD/xhtml1-transitional.dtd"/>
<f:view>
<html xmlns="http://www.w3.org/1999/
xhtml">
<head>
<title>...</title>
</head>
<body>
<h:form>...</h:form>
</body>
</html>
</f:view>
</jsp:root>

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

Text Field

page.jspx

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

faces-config.xml

<managed-bean>
<managed-bean-name>bean1</managed-bean-name>
<managed-bean-class>com.corejsf.SampleBean</
managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

com/corejsf/SampleBean.java

public class SampleBean {
public int getLuckyNumber() { ... }
public void setLuckyNumber(int value) { ... }
...
}
Button

page.jspx

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

faces-config.xml

<navigation-rule>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/success.jspx</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>error</from-outcome>
<to-view-id>/error.jspx</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>

com/corejsf/SampleBean.java

public class SampleBean {
public String login() { if (...) return
"success"; else return "error"; }
...
}
Radio Buttons

page.jspx

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

com/corejsf/SampleBean.java

public class SampleBean {
private Map<String, Object> condimentItem = null;
public Map<String, Object> getCondimentItems() {
if (condimentItem == null) {
condimentItem = new LinkedHashMap<String,
Object>();
condimentItem.put("Cheese", 1); // label, value
condimentItem.put("Pickle", 2);
...
}
return condimentItem;
}
public int getCondiment() { ... }
public void setCondiment(int value) { ... }
...
}

Validation and Conversion

page.jspx

<h:inputText value="#{payment.amount}"
required="true">
<f:validateDoubleRange maximum="1000"/>
</h:inputText>
<h:outputText value="#{payment.amount}">
<f:convertNumber type="currency"/>
<!-- number displayed with currency symbol and
group separator: $1,000.00 -->
</h:outputText>

Error Messages

Error Messages

page.jspx

<h:outputText value="Amount"/>
<h:inputText id="amount" label="Amount"
value="#{payment.amount}"/>
<!-- label is used in message text -->
<h:message for="amount"/>

Resources and Styles

page.jspx

<head>
<link href="styles.css" rel="stylesheet"
type="text/css"/>
...
</head>
<body>
...
<h:outputText value="#{msgs.goodbye}!"
styleClass="goodbye">
...
</body>

faces-config.xml

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

com/corejsf/messages.properties

goodbye=Goodbye

com/corejsf/messages_de.properties

goodbye=Auf Wiedersehen

styles.css

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

Table with links

Name  
Washington, George Delete
Jefferson, Thomas Delete
Lincoln, Abraham Delete
Roosevelt, Theodore Delete

page.jspx

<h:dataTable value="#{bean1.entries}" var="row"
styleClass="table" rowClasses="even,odd">
<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>

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() {...}
...
}

LifeCycle

Lifecycle

faces-config.xml

The faces-config.xml file contains a sequence of the following entries.

  • managed-bean
    1. description , display-name, icon (optional)
    2. managed-bean-name
    3. managed-bean-class
    4. managed-bean-scope
    5. managed-property (0 or more, other optional choices are map-entries and list-entries which are not shown here)
      1. description, display-name, icon (optional)
      2. property-name
      3. value (other choices are null-value, map-entries, list-entries which are not shown here)
  • navigation-rule
    1. description, display-name, icon (optional)
    2. from-view-id (optional, can use wildcards)
    3. navigation-case (1 or more)
      • from-action (optional, not common)
      • from-outcome
      • to-view-id
  • application
    • resource-bundle
      1. base-name
      2. var
    • action-listener, default-render-kit-id, resource-bundle, view-handler, state-manager, elresolver, property-resolver, variable-resolver, application-extension (details not shown)
  • converter
    • converter-id
    • converter-class
    • Optional initialization (not shown here)
  • validator
    • validator-id
    • validator-class
    • Optional initialization (not shown here)
  • lifecycle
    • phase-listener
  • component, factory, referenced-bean, render-kit, faces-config-extension (details not shown)

web.xml

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</
servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Add this element to change the extension for
JSF page files (Default: .jsp) -->
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</paramname>
<param-value>.jspx</param-value>
</context-param>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
<!-- Another popular URL pattern is /faces/* -->
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.faces</welcome-file>
<!-- Create a blank index.faces (in addition to
index.jspx) -->
<welcome-file>index.html</welcome-file>
<!-- Use <meta http-equiv="Refresh" content=
"0; URL=index.faces"/> -->
</welcome-file-list>
</web-app>

The JSF Expression Language (EL)

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 name defined in faces-config.xml.

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 A Map of all request scope attributes.
sessionScope A Map of all session scope attributes.
applicationScope A Map of all application scope attributes.
facesContext The FacesContext instance of this request.
view The UIViewRoot instance of this request.

There are two expression types:

  • n 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, ...)
  • n 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.

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.

JSF Core Tags

Tag Description/Attributes
f:view Creates the top-level view
localeThe locale for this view.
renderKitId (JSF 1.2)The render kit ID for this view
beforePhase, afterPhasePhase listeners that are called in every phase except "restore view"
f:subview Creates a subview of a view
binding, id, renderedBasic attributes
f:facet Adds a facet to a component
namethe name of this facet
f:attribute Adds an attribute to a component
name, valuethe name and value of the attribute to set
f:param Constructs a parameter child component
nameAn optional name for this parameter component.
valueThe value stored in this component.
binding, idBasic attributes
f:actionListener
f:valueChangeListener
Adds an action listener or value change listener to a component
typeThe name of the listener class
f:setPropertyChange Listener (JSF 1.2) Adds an action listener to a component that sets a bean property to a given value.
valueThe bean property to set when the action event occurs
binding, idThe value to set it to
f:converter Adds an arbitary converter to a component
converterIdThe ID of the converter
f:convertDateTime Adds a datetime converter to a component
typedate (default), time, or both
dateStyledefault, short, medium, long, or full
timeStyledefault, short, medium, long, or full
patternFormatting pattern, as defined in java. text.SimpleDateFormat
localeLocale whose preferences are to be used for parsing and formatting
timezoneTime zone to use for parsing and formatting
f:convertNumber Adds a number converter to a component
typenumber (default), currency , or percent
patternFormatting pattern, as defined in java.text.DecimalFormat
maxFractionDigitsMaximum number of digits in the fractional part
minFractionDigitsMinimum number of digits in the fractional part
maxIntegerDigitsMaximum number of digits in the integer part
minIntegerDigitsMinimum number of digits in the integer part
integerOnlyTrue if only the integer part is parsed (default: false)
groupingUsedTrue if grouping separators are used (default: true)
localeLocale whose preferences are to be used for parsing and formatting
currencyCode ISO 4217 currency code to use when converting currency values
currencySymbolCurrency symbol to use when converting currency values
f:validator Adds a validator to a component
validatorIdThe ID of the validator
f:validateDoubleRange
f:validateLongRange
f:validateLength
Validates a double or long value, or the length of a string
minimum, maximumthe minimum and maximum of the valid rang
f:loadBundle Loads a resource bundle, stores properties as a Map
basenameThe resource bundle name
valueThe name of the variable that is bound to the bundle map
f:selectitems Specifies items for a select one or select many component
binding, idBasic attributes
valueValue expression that points to a SelectItem, an array or Collection of SelectItem objects, or a Map mapping labels to values.
f:selectitem Specifies an item for a select one or select many component
binding, idBasic attributes
itemDescriptionDescription used by tools only
itemDisabledBoolean value that sets the item's disabled property
itemLabelText shown by the item
itemValueItem's value, which is passed to the server as a request parameter
valueValue expression that points to a SelectItem instance
f:verbatim Adds markup to a JSF page
escapeIf set to true, escapes <, >, and & characters. Default value is false.
rendered (JSF 1.2)Basic attributes

JSF HTML TAGS

Tag Description
h:form HTML form
h:inputText Single-line text input control Single line input text
h:inputTextarea Multiline text input control multi-line input text
h:inputSecret Password input control password
h:inputHidden Hidden field
h:outputLabel Label for another component for accessibility
h:outputLink HTML anchor javanet
h:outputFormat Like outputText, but formats compound messages
h:outputText Single-line text output
h:commandButton Button: submit, reset, or pushbutton Button
h:commandLink Link that acts like a pushbutton. register
h:message Displays the most recent message for a component Message
h:messages Displays all messages
h:grapicImage Displays an image Image
h:selectOneListbox Single-select listbox Single-select listbox
h:selectOneMenu Single-select menu Single-select menu
h:selectOneRadio Set of radio buttons Set of radio buttons
h:selectBooleanCheckbox Checkbox Checkbox
h:selectManyCheckbox Multiselect listbox Multiselect listbox
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

Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component's value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that's created and attached to a component required A boolean; if true, requires a value to be entered in the associated field

Attribute Description
id Identifier for a component
binding Reference to the component that can be used in a backing bean
rendered A boolean; false suppresses rendering
styleClass Cascading stylesheet (CSS) class name
value A component's value, typically a value binding
valueChangeListener A method binding to a method that responds to value changes
converter Converter class name
validator Class name of a validator that's created and attached to a component
required A boolean; if true, requires a value to be entered in the associated field

Attributes for h:form

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

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

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
valueChangeListener A specified listener that's notified of value changes
binding, converter, id, rendered, required, styleClass, value, validator Basic attributes
accesskey, alt, dir, disabled, lang, maxlength, readonly, size, style, tabindex, 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.
binding, converter, id, rendered, styleClass, value Basic at tributes
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 Image

Attribute Description
binding, id, rendered, styleClass, value Basic attributes
alt, dir, height, ismap, lang, longdesc, style, 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 Button

Attribute Description
action If specified as a string: Directly specifies an outcome used by the navigation handler to determine the JSF page to load next as a result of activating the button or link If specified as a method binding: The method has this signature: String methodName(); the string represents the outcome
actionListener A method binding that refers to a method with this signature: void methodName(ActionEvent)
charset For h:commandLink only,The character encoding of the linked reference
image 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: 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. You can specify a string or a value reference expression.
accesskey, alt, binding, id, lang, rendered, styleClass, value Basic attributes
coords (h:commandLink only), dir, disabled (h:commandButton only), hreflang (h:commandLink only), lang, readonly, rel (h:commandLink only), rev (h:commandLink only), shape (h:commandLink only), style, tabindex, target (h:commandLink only), title, type HTML 4.0
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect DHTML events

Attributes for h:outputLink outputLink

Attribute Description
accesskey, binding, converter, id, lang, rendered, styleClass, value Basic attributes
charset, coords, dir, hreflang, lang, rel, rev, shape, style, 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
Radio

Attribute Description
disabledClass CSS class for disabled elements,for h:selectOneRadio and h:selectManyCheckbox only
enabledClass CSS class for enabled elements,for h:selectOneRadio and h:selectManyCheckbox only
layout Specification for how elements are laid out: lineDirection (horizontal) or pageDirection (vertical),for h:selectOneRadio and h:selectManyCheckbox only
binding, converter, id, immediate, styleClass, required, rendered, validator, value, valueChangeListener Basic attributes
accesskey, border, dir, disabled, lang, readonly, style, size, tabindex, title HTML 4.0,border is applicable to h:selectOneRadio and h:selectManyCheckbox only. size is applicable to h:selectOneListbox and h:selectManyListbox only
onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onselect DHTML events

Attributes for h:message and h:messages
Attributes for h:message and h:messages

Attribute Description
for The ID of the component whose message is displayed,applicable only to h:message
errorClass CSS class applied to error messages
errorStyle CSS style applied to error messages
fatalClass CSS class applied to fatal messages
fatalStyle CSS style applied to fatal messages
globalOnly Instruction to display only global messages,applicable only to h:messages. Default: false
infoClass CSS class applied to information messages
infoStyle CSS style applied to information messages
layout Specification for message layout: table or list,applicable only to h:messages
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
warnClass CSS class for warning messages
warnStyle CSS style for warning messages
binding, id, rendered, styleClass Basic attributes
style, 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
columnClasses Comma-separated list of CSS classes for columns
columns Number of columns in the table
footerClass CSS class for the table footer
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 CSS class for the table header
rowClasses Comma-separated list of CSS classes for 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, styleClass, value Basic attributes
dir, lang, style, 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, styleClass Basic attributes
style 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
columnClasses Comma-separated list of CSS classes for columns
first Index of the first row shown in the table
footerClass CSS class for the table footer
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 CSS class for the table header
rowClasses Comma-separated list of CSS classes for rows
rules Specification for lines drawn between cells; valid values: groups, rows, columns, all
summary Summary of the table's purpose and structure used for nonvisual 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, styleClass, value Basic attributes
dir, lang, style, title, width HTML 4.0
onclick, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup DHTML events

Attributes for h:column

Attribute Description
headerClass (JSF 1.2) CSS class for the column's header
footerClass (JSF 1.2) CSS class for the column's footer
binding, id, rendered Basic attributes

About The Author

Photo of author Cay S. Horstmann

Cay S. Horstmann

Cay S. Horstmann has written many books on C++, Java and objectoriented 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.

Publications
  • Core Java, with Gary Cornell, Sun Microsystems Press 1996 - 2007 (8 editions)
  • Core JavaServer Faces, with David Geary, Sun Microsystems Press, 2004-2006 (2 editions)
  • Big Java, John Wiley & Sons 2001 - 2007 (3 editions)
Blog
Web site

Recommended Book

Book cover of Core JavaServer Faces

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.

JavaServer Faces Refcard Available - Download Now

DZone has released it's latest Refcardz, the essential JSF cheat sheet.  Get it now! 

0 replies - 7478 views - 09/14/08 by Jill Tomich in News

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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