java ee

  • submit to reddit

JavaServer Faces 2.0

By Cay Horstmann

28,367 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 JBoss Enterprise Application Platform 5

By Scott Marlow, Jaikiran Pai, Shelly McGowan, Brian Stansberry and Len DiMaggio

15,329 Downloads · Refcard 97 of 151 (see them all)

Download
FREE PDF


The Essential JBoss EAP 5 Cheat Sheet

JBoss Enterprise Application Platform 5 is an open source implementation of the Java EE suite of services. This DZone Refcard provides an in-depth introduction to JBoss Enterprise Application Platform 5. It comprises a set of offerings for enterprise customers who are looking for preconfigured profiles of JBoss Enterprise Middleware components that have been tested and certified together to provide an integrated experience. We take you all the way from installation to the deployment of your application. This Refcard is a must have for both users starting out with Java EE as well as senior architects.
HTML Preview
Getting Started With JBoss Enterprise Application Platform 5

Getting Started with JBoss Enterprise Application Platform 5

By Scott Marlow, Jaikiran Pai, Shelly McGowan, Brian Stansberry, and Len DiMaggio

WHAT IS JBOSS EAP 5?

JBoss Enterprise Application Platform is an open source implementation of the Java EE suite of services. It comprises a set of offerings for enterprise customers who are looking for preconfigured profiles of JBoss Enterprise Middleware components that have been tested and certified together to provide an integrated experience. Its easy-to-use server architecture and high flexibility makes JBoss the ideal choice for users just starting out with Java EE, as well as senior architects looking for a customizable middleware platform.

Because it is Java-based, JBoss Enterprise Application Platform is cross platform, easy to install and use on any operating system that supports Java. The readily available source code is a powerful learning tool to debug the server and understand it. It also gives you the flexibility to create customized versions for your personal or business use.

Visit the http://www.jboss.com/products/community-enterprise/ website to download JBoss Enterprise Application Platform 5.

INSTALLING JBOSS EAP 5

1. Installation using the Graphical Installer

The graphical installer will guide you through the installation steps. Invoke the installer using the command:


java -jar enterprise-installer-5.0.1.GA.jar

2. Installation using the Zip Distribution

Use the unzip command:


unzip jboss-eap-5.0.1.GA.zip

Use the same steps to install optional native package:


unzip jboss-eap-native-5.0.1.GA-<operating-system>-<arch>.zip

DIRECTORY STRUCTURE

Contents of jboss-as:

Directory Description
bin Contains startup, shutdown and other system-specific scripts. All entry point JAR files and start scripts are here.
client JAR files used by external Java client applications. Choose JAR files as required or use jbossall-client.jar
common/lib Shared JAR files common to profiles are here.
docs XML DTD and schemas for reference. Also example configuration files for setting up datasources (e.g. MySQL, Oracle, PostgreSQL).
lib Contains server startup JARs and not intended to hold application JAR files.
server Contains the JBoss server profile sets.

DIRECTORY STRUCTURE

JBoss EAP 5 configuration profiles are located within the jboss-as/server directory (specified with "run -c PROFILE" ):

default JavaEE 5 server profile. Has most frequently used EE services. Default does not include JAXR, IIOP, clustering services.
all Bundles all services (including clustering and RMI/IIOP).
production based on "all" profile, tuned for production; with log verbosity reduced, deployment scanning every 60 seconds, and memory usage tuned to accommodate production deployment requirements, configured to require authorization checks.
standard based on 'all' profile and is a fully certified Java EE 5 configuration.
web lightweight configuration created around JBoss Web and provides services required for web application deployment and a subset of Java EE technologies. Does not include JBoss Transaction JTS or XTS, Enterprise Java Bean 1.x or 2.x capabilities, JBoss Messaging, JCA, or JBoss IIOP
minimal Bare minimum required to start. Includes logging, JNDI and URL deployment scanner. Use JMX/JBoss to start your own services. No web container, EJB or JMS support is included.

ADMINISTRATION

To start the JBoss EAP server, simply change to the EAP_DIST/ jboss-as/bin directory. Set the environment variable JAVA_ HOME. Execute the run.bat (for Windows) or run.sh (for Linux, Unix, Mac OSX) script, as appropriate for your operating system.

Administering your JBoss EAP 5 server instance is easy with the administration consoles provided in this distribution. Once the server is started, simply point your browser to:


http://localhost:8080

This brings you to the consoles to manage your instance as well as links to on-line resource references.

Use the Administration Console for managing and monitoring a server instance. Deploy, undeploy, and update enterprise applications, persist configuration changes for Datasources, JMS topics and queues, Connection Factories, and Service Binding Manager, monitor standard JVM metrics, and view statistics and invoke operations on many other components.

The JMX Console provides a server view. It lists all registered services (MBeans). Administration Console shares the same username/password as JMX console.

Command-line scripts are available in the jboss-as/bin directory. In addition to scripts for starting and stopping the server, JBoss provides a command line tool that allows for interaction with a remote server instance. This tool is called twiddle (for twiddling bits via JMX) and is located in the bin directory. Twiddle is a command execution tool, not a general command shell. Run using the twiddle.sh/twiddle.bat scripts, and passing in a -h(-- help) argument provides the basic syntax, and --help-commands shows commands. Twiddle defaults to the localhost at port 1099 to lookup the default jmx/rmi/RMIAdaptor binding of the RMIAdaptor service as the connector for communicating with the JMX server. To connect to a different server/port combination, can use the -s (--server) option:


$ ./twiddle.sh -s servername serverinfo -d jboss
$ ./twiddle.sh -s servername:1099 serverinfo -d jboss

MANAGEMENT

The JBoss Operations Network (JON) management platform delivers centralized systems management that allows you to:

  • Coordinate stages of application’s life-cycle datasources and messaging services
  • Expose cohesive view of middleware components through complex environments
  • Improve operational efficiency/reliability through visibility into production availability and performance
  • Configure and roll out applications across complex environments through a single tool

APPLICATION DEPLOYMENT

There are multiple ways to deploy applications to JBoss:

Simplest way

  • Choose the server profile to which you want to deploy the application (let's consider the "default" server profile in this example)
  • Copy your application (for example: .war or .ear or a .jar file) to JBOSS_HOME/server/<profilename>/deploy folder.
  • Start the server:

./run.sh

  • JBoss will deploy your application when it boots up.
  • That's it!

Hot Tip

This approach does not require the server to be started when you are deploying your application. If you want to undeploy the application then just move (or delete) the application from the deploy folder. You can develop simple scripts (like an Ant script) to deploy the application to JBoss. All it takes is a file copy command.

Using the admin console

  • Start the server

./run.sh

  • On the left hand side of the admin console page, under JBoss AS -> Applications, select the type of application you want to deploy. Let's consider a web application (.war) in this example
  • Click the "Web Application (WAR)" link
  • In the right side section, under the "Summary" tab, click on "Add a new resource" button

  • "Browse" to the .war file to deploy (e.g. /home/me/myapp.war)
  • If you want to deploy the application in exploded format (instead of an archive) then select "Yes" radio button for "Deploy Exploded" option Click on the "Continue" button
  • On successful deployment, you will see your application listed in the Summary tab
  • To undeploy the application, click on the "Delete" button next to the application you want to undeploy, in the "Summary" tab

Hot deployment

JBoss has a built-in hot deployer which can:

  • Detect new applications in the deploy folder and trigger an application deployment
  • Detect an application which was removed from the deploy folder and trigger an application undeployment
  • Detect that the deployment descriptor of an application (for example, the web.xml of .war or application.xml of .ear) has changed and trigger an application redeployment

Hot Tip

The hot deployer is configured to run every X milliseconds. This value can be changed by changing the "scanPeriod" attribute in JBOSS_HOME/server/lt;profilename>/deploy/ hdscanner-jboss-beans.xml:

<!-- Hotdeployment of applications -->
<bean name="DScanner" class="org.jboss.system.server.profileservice
.hotdeploy.HDScanner">
<property name="deployer"><inject bean="ProfileServiceDeployer"/></property>
<property name="profileService"><inject bean="ProfileService"/></property>
<property name="scanPeriod">5000</property>
<property name="scanThreadName">HDScanner</property>
</bean>

To disable hot deployment, remove the hdscanner-jboss-beans. xml from the deploy folder or rename it to hdscanner-jbossbeans. xml.bak (.bak files are ignored).

Clustering

Getting started with JBoss clustering is very simple. If two JBoss server instances using the all configuration are started on the same network, those servers will detect each other and automatically form a cluster.

Initial Preparation

Preparing a set of servers to act as a JBoss cluster involves a few simple steps:

  • Install JBoss on all your servers.
  • For each node, determine the address to bind sockets to.
  • Ensure multicast is working. Make sure each server's networking configuration supports multicast and that multicast support is enabled for any switches or routers between your servers. JBoss clustering also offers nondefault configuration options that do not use multicast.
  • Determine a unique integer "ServerPeerID" for each node. JBoss Messaging requires that each node in a cluster has a unique integer id, known as a "ServerPeerID", that should remain consistent across server restarts. A simple 1, 2, 3, ..., x naming scheme is fine.

Launching Your Cluster

We'll look at two scenarios for doing this. In each scenario we'll be creating a two node cluster, where the ServerPeerID for the first node is 1 and for the second node is 2.

Scenario 1: Nodes on Separate Machines

On node1, to launch JBoss:


$ ./run.sh -c all -b 192.168.0.101 -Djboss.messaging.ServerPeerID=1

On node2, it's the same except for a different -b value and ServerPeerID:


$ ./run.sh -c all -b 192.168.0.102 -Djboss.messaging.ServerPeerID=2

The -c switch says to use the all config, which includes clustering support. The -b switch sets the address on which sockets will be bound. The -D switch sets the system property from which JBoss Messaging gets its unique id.

Scenario 2: Two Nodes on a Single, Non-Multihomed, Machine

Running multiple nodes on a single machine that only has a single IP address is a common scenario in a development environment. You need to be sure each server instance has its own work area. One way to do this is to simply make copies of the all configuration. For example, assuming the root of the JBoss distribution was unzipped to /var/jboss, you could:


$ cd /var/jboss/server
$ cp -r all node1
$ cp -r all node2

Two processes can't bind sockets to the same address and port, so we'll have to tell JBoss to use different ports for the two instances. This can be done by setting the jboss.service. binding.set system property.

To launch the first instance, open a console window and:


$ ./run.sh -c node1 -b 192.168.0.101 -Djboss.messaging.ServerPeerID=1 \
-Djboss.service.binding.set=ports-default

For the second instance, in a second console window:


$ ./run.sh -c node2 -b 192.168.0.101 -Djboss.messaging.ServerPeerID=2 \
-Djboss.service.binding.set=ports-01

This tells the ServiceBindingManager on the first node to use the standard set of ports (e.g. JNDI on 1099). The second node uses the “ports-01" binding set, with which by default each port has an offset of 100 from the standard port number (e.g. JNDI on 1199).

Web Application Clustering Quick Start

Web application clustering involves two aspects: setting up an HTTP load balancer and telling JBoss to make the application’s user sessions HA. How to do the former depends on what load balancer you choose (mod_cluster is a good choice); the latter couldn't be simpler – just add the <distributable/> to your application’s web.xml.

EJB3 Session Bean Clustering Quick Start

To add load balancing and failover capabilities to your EJB3 session beans, simply add the org.jboss.ejb3.annotation. Clustered annotation to the bean class for your stateful or stateless bean:


@javax.ejb.Stateful
@org.jboss.ejb3.annotation.Clustered
public class MyBean implements MySessionInt {
	public void test() {
		// Do something cool
	}
}

PERFORMANCE AND TUNING

Identify peak application workload and difference from normal workload. In understanding peak workloads, don’t go by averages as the peaks may be much more than the averages calculated over a period. Start testing with a low load and increase until expected peak load. Tune until target performance is achieved. There are a number of possible performance optimizations. Always load test before and after making changes to verify the intended effect. Make one change at a time so it's clear what change has what effect.

Use OS monitoring tools to identify system performance bottlenecks. In a multiple machine installation, find the machine(s) that are the bottleneck.

Instrument the application for performance measurement (make optional for production ). Also, turn on container call statistics and Hibernate statistics.

Taking successive thread dumps indicates what is going on. Do this prior/after hitting a performance wall. Generate a thread dump once a minute over a five minute performance problem and compare your findings. Use "jps -l" command to get the Java process ids and then run the “jstack ProcessID" command (generates the thread dump.)

The HotSpot Java Virtual Machine contains other information gathering tools which can help tune applications. More information is in http://java.sun.com/javase/technologies/hotspot/.

jmap generates a memory heap dump file that can easily be read by the Eclipse Memory Analyzer tool (http://www.eclipse.org/mat/). jstat shows details of the memory space.

Clustering Tuning

Ensuring Adequate Network Buffers

Inadequately sized network buffers can cause lost packets. Steps to increase max buffer sizes are OS specific. For Linux change /etc/sysctl.conf file:


# Allow a 25MB UDP receive buffer for JGroups
net.core.rmem_max = 26214400
# Allow a 1MB UDP send buffer for JGroups
net.core.wmem_max = 1048576

Isolating Intra-Cluster Traffic

isolate intra-cluster traffic from external request traffic. This requires multiple NICs on your server machines, with request traffic coming in on one NIC and intra-cluster traffic using another.


./run.sh -c all -b 10.0.0.104 -Djgroups.bind_addr=192.168.100.104

JGroups Message Bundling

Message bundling queues small messages until a configurable number of bytes have accumulated, then sent as a large message. Use of bundling can have significant performance benefits for high-volume asynchronous session replication. However, it is not enabled by default, as bundling can add significant latency to other types of intra-cluster traffic, particularly clustered Hibernate/JPA Second Level Cache traffic.

To use a JGroups channel with message bundling enabled, edit the <JBoss_Home>/server/<profilename>/deploy/cluster/ jboss-cache-manager.sar/META-INF/jboss-cache-jboss-beans. xml file. For example, for the cache used by default for web sessions:


. . .
<!-- Standard cache used for web sessions -->
<entry><key>standard-session-cache</key>
<value>
	<bean name="StandardSessionCacheConfig" class="org.jboss.cache.config.
	Configuration">
. . .
<!-- Replace standard 'udp' JGroups stack with one that uses message
bundling -->
	<property name="multiplexerStack">udp-async</property>
. . .

For FIELD granularity web sessions, in the same file the same change can be made to the cache configuration with the fieldgranularity- session-cache key. For EJB3 stateful session beans, in the same file the same change can be made to the cache configuration with the sfsb-cache key.

Enabling Buddy Replication for Session Caches

In a cluster of more than two nodes, you can improve performance by enabling "buddy replication" in the web session and stateful session bean caches. With buddy replication, instead of replicating a copy of sessions to all nodes in the cluster, a copy is only replicated to a configurable number of "buddy" nodes.

Buddy replication is enabled by editing the <JBoss_Home>/ server/<profilename>/deploy/cluster/jboss-cache-manager. sar/META-INF/jboss-cache-jboss-beans.xml file. For example, for the cache used by default for web sessions:


. . .
<!-- Standard cache used for web sessions -->
<entry><key>standard-session-cache</key>
<value>
	<bean name="StandardSessionCacheConfig" class="org.jboss.cache.config.
	Configuration">
. . .
<property name="buddyReplicationConfig">
	<bean class="org.jboss.cache.config.BuddyReplicationConfig">
<!-- Just set to true to turn on buddy replication -->
	<property name="enabled">true</property>
. . .

For FIELD granularity web sessions, in the same file the same change can be made to the cache configuration with the fieldgranularity- session-cache key. For EJB3 stateful session beans, in the same file the same change can be made to the cache configuration with the sfsb-cache key.

Reducing the Volume of Web Session Replication

Reducing the amount data being replicated can obviously improve performance. This can be accomplished both by avoiding replication when a request hasn't actually updated the session and by limiting replication to only the session data that has actually changed. See the discussion of replicationtrigger and replication-granularity in "http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5.0.0/html/Administration_And_Configuration_Guide/clustering-http-state.html" for how to configure your application to limit the amount of data replicated.

Monitoring JGroups via JMX

When clustering services create a JGroups Channel to use for intra-cluster communication, the JMX console will include the following:

jboss.jgroups:cluster=<cluster_name>,protocol=UDP,type=protocol Statistics on two thread pools used to carry incoming messages up the channel’s protocol stack.

jboss.jgroups:cluster=<cluster_name>,protocol=UNICAST,type=protocol Information on lossless, ordered delivery of unicast (i.e. point-to-point) messages.

jboss.jgroups:cluster=<cluster_name>,protocol=NAKACK,type=protocol Information on lossless, ordered delivery of multicast (i.e. point-to-multipoint) messages.

jboss.jgroups:cluster=<cluster_name>,protocol=FC,type=protocol Information on ensuring fast message senders do not overwhelm slow receivers.

Web deployer

Other key configurations required for performance tuning of your Enterprise Application Platform include the <JBoss_ Home>/server/<your_configuration>/deployers/jbossweb. deployer/server.xml file that sets your HTTP requests pool.

Thread pool

JBoss Enterprise Application Platform 5 has a robust thread pooling, that should be sized appropriately. The server has a jboss-service.xml file in the <JBoss_Home>/server/<your_ configuration>/conf directory that defines the system thread pool. There is a setting that defines the behavior if there isn't a thread available in the pool for execution. The default is to allow the calling thread to execute the task. You can monitor the queue depth of the system thread pool through the JMX Console, and determine from that if you need to make the pool larger.

TROUBLESHOOTING

Startup problems

If you are having trouble starting JBoss, the first thing to check is the JAVA_HOME environment variable. This should point to the home of your JDK (or JRE installation). For example, if your JDK is installed at /opt/Java/jdk1.5.0 then JAVA_HOME should be set as follows:


JAVA_HOME=/opt/Java/jdk1.5.0

On Windows OS, if your JDK installation is at C:/Java/jdk1.5.0, you can set it as follows:


set JAVA_HOME=C:/Java/jdkl.5.0

Hot Tip

It's highly recommended not to install JBoss or Java in a folder containing a space in its path. For example, do not install Java at C:/Program Files/Java/jdk1.5.0 on Windows OS.

Logs

JBoss by default is configured to log messages to the JBOSS_HOME/server/<servername>/log server.log file. This file can be checked for any exceptions or other informational logging. Logging levels can be controlled in JBOSS_HOME/ server/<servername>/conf/jboss-log4j.xml

Thread dumps

Sometimes, if you notice that the application is not responding, you can generate thread dumps to check what each thread is currently doing. Thread dumps can be generated in multiple ways - 2 of which are explained below:

From jmx-console

  • Access jmx-console (http://localhost:8080/jmx-console)
  • Look for the jboss.system:type=ServerInfo MBean and click on the link
  • On the page that comes up, look for the listThreadDump operation and click on the Invoke button

Using Twiddle:

  • From the command prompt, cd to JBOSS_HOME/bin folder
  • Run the following command:
    • ./twiddle.sh invoke "jboss.system:type=ServerInfo" listThreadDump > threads.html
    • Note: Use twiddle.bat for Windows OS

This command will generate the thread dump and redirect the output to threads.html (you can redirect it to any file of your choice)

It's best to generate multiple thread dumps between a span of few seconds and compare those thread dumps to find any blocked threads.

Reporting problems

Also, search the community forums to see if someone else is experiencing the same problem. The forums are at link http://community.jboss.org/. You can also obtain a support contract via http://www.jboss.com/services/subscriptions/ and then access https://www.redhat.com/wapps/sso/jboss/login.html?redirect=http%3A%2F%2Fsupport.redhat.com%2Fjbossnetwork

Search for existing issues that also report the same problem. Access the JIRA issue search via link https://jira.jboss.org/jira/secure/IssueNavigator.jspa

When filling in the JIRA, be as precise as possible when reporting the bug. Include as much information as possible. Include the steps needed to reproduce the problem.

If possible, create a standalone test case that reproduces the bug that can be attached to a JIRA issue. The JIRA issue is more likely to be fixed if a unit test is attached (or at least a test case). Even better is if a solution, in the form of a patch (output of doing "svn diff > fix.patch"), is attached.

JBOSS EAP 5 VS AS 5

The focus of the JBoss AS project is continuous innovation - fueled by Open Source community collaboration - on the bleeding edge of Java Middleware. Quickly bringing emerging standards and technology into the mainstream through it's large user base and active community. This focus implies continuous change and a rapid release cycle with minor releases every one or two months and major releases every six months. Red Hat does not provide support for JBoss community projects.

Red Hat does provide world-class support, consulting and training for the JBoss Enterprise Platforms. JBoss Enterprise Platforms balance innovation with enterprise class stability by integrating the best of Open Source projects like JBoss AS. The JBoss Enterprise Platforms are certified against a broad range of Operating Systems, Databases and other 3rd party applications and tools; meet very strict industry security standards; are pre-tuned and secured by default so are ready to support your business critical applications and services.

Red Hat recommends JBoss projects as a place to get involved in shaping the Open Source middleware landscape and as a way to understand how the technology landscape is evolving. Red Hat recommends JBoss Enterprise Platforms for demanding business critical production workloads where security, performance, reliability and long-term, world-class support are imperative.

See this link for information on training http://www.jboss.com/services/training/

About The Authors

Scott Marlow

Core Engineer on the JBoss AS team. Over 20 years experience building enterprise development software, from database server to developer tools (such as PowerBuilder and four different application servers). Five years experience contributing to JBoss OSS projects { Application Server, Clustering, JGroups, JBoss Cache, Hibernate }. Scott enjoys coaching and playing soccer in his spare time.

Jaikiran Pai

Employed at RedHat and is part of the JBoss EJB3 development team. Jaikiran completed his graduation in 2004 and started working in a software company in Pune, India. In his role as a software developer, he was part of projects which involved Java and JavaEE. During this period, he developed interest in JBoss Application Server and started spending his spare time in JBoss community forums. In 2009, Jaikiran was offered a job at RedHat to be part of his favourite project - JBoss Application Server.

Jaikiran can often be found either at the JBoss forums or at his other favourite place http://www.javaranch.com/. Occasionally, Jaikiran blogs at http://www.jaitechwriteups.blogspot.com/

Shelly McGowan

Member of the JBoss Application Server development team. She has several years of software development experience most recently on Java Enterprise Edition technologies such as EJB and EJB 3 persistence.

Brian Stansberry

My background is in International Business and East Asian Studies, with a B.A. from Michigan State and an M.A. from Stanford. Before getting bitten by the software bug, I had a successful career in corporate finance in the semiconductor industry. Part of that oddly enough involved web application and other types of software development. But since I realized in the late 1990s that my true interest was in software, not finance, I've focused on server-side development and Java. I started working on JBoss in 2003 and joined the company in 2005. My other main interests are China (I speak Mandarin Chinese and visit China regularly) and hanging out with my family. I live in St. Louis, MO.

Expertise: JBoss AS Clustering JBoss AS in general JBoss Cache PojoCache JGroups mod_cluster

Occupation: Lead, JBoss AS Clustering

Len DiMaggio

JBoss middleware QE engineer and team lead. Len is a frequent contributor to JBoss blogs and DZone (http://soa.dzone.com/users/ldimaggi).

Recommended Book

JBoss AS5 Development

This book will kick-start your productivity and help you to master JBoss AS development. The author's experience with JBoss enables him to share insights on JBoss AS development, in a clear and friendly way. By the end of the book, you will have the confidence to apply all the newest programming techniques to your JBoss applications.



JBoss in Action

JBoss in Action is the first book to focus on teaching readers in detail how to use the JBoss application server. Unlike other titles about JBoss, the authors of JBoss in Action go deeper into the advanced features and configuration of the server. In particular, it focuses on enterprise-class topics, such as high availability, security, and performance.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Get Started with Java EE Security - Free Cheat Sheet

Click here to download your free DZone Refcard on Getting Started with Java EE Security now! 

0 replies - 24737 views - 05/17/10 by Lyndsey Clevesy in Announcements

Getting Started with Java EE Security

By Masoud Kalali

20,126 Downloads · Refcard 99 of 151 (see them all)

Download
FREE PDF


The Essential Java EE Security Cheat Sheet

Getting Started With Java EE Security is a DZone Refcard that will provide you with an in-depth introduction to Java EE Security, which supports a fine set of security functionalities in the specification level. These capabilities include authentication, authorization, data integrity and transport security. Other topics covered in this Refcard include Web Module, EJB and Application Client security, securing Java EE Web Services, Hot Tips and more. Highly recommended reading for Java EE users and Java enthusiasts of all kinds.
HTML Preview
Getting Started With Java EE Security

Getting Started with Java EE Security

By Masoud Kalali

SECURITY IN JAVA EE APPLICATIONS

Java EE security supports a fine set of security functionalities in the specification level. These capabilities include authentication, authorization, data integrity and transport security. Before going deep into the Java EE security, everyone should know the following terms:

A User is an individual identity which is defined in the identity storage. The storage which can be an RDBMS, flat file or LDAP server contains user attributes like username and password.

A Group is a set of users classified with a set of common characteristics which usually lead to a set of common permissions and access levels.

A Security Realm is the access channel for the application server to storage containing user's authentication and grouping information.

A Role is a Java EE concept to define access levels. A Java EE application developer specifies which roles can access which set of the application functionalities. These roles are then mapped to users and groups using the vendor specific configuration files.

A Principal is an identity with known credentials which can be authenticated using an authentication protocol.

A Credential contains or references information used to authenticate a principal for Java EE product services. Password is a simple credential used for authentication.

Different application servers use different methods to map users, groups and roles to each other.

Authentication and authorization in Java EE

A Java EE application server consists of multiple containers including the Web/ Servlet container, an EJB container and finally an Application Client Container (ACC).

The Web container as the door to EJB container performs authentication and propagates the authenticated subject to EJB container. EJB container then performs the authorization prior to letting the EJB invocation go through.

When EJB container is accessed by an application client, EJB container itself performs authentication and authorization on the credentials collected and provided by the ACC.

Web and EJB containers host different sets of resources and therefore each one of them has its separate authorization mechanism suitable for its deployed components.

Each Java EE application can consist of multiple modules as shown in Figure 2. Each one of these modules can have zero or more deployment descriptors which can contain different types of configuration for the application components (JSPs, Servlets, EJBs, Etc.) including but not limited to their security descriptions. Figure 3 shows these files and their locations.

Although all of the vendor specific deployment descriptors are in XML format that is not a requirement.

Hot Tip

In Java EE 6, more annotations are introduced which we can use to plan the application deployment and we can override any standard Java EE annotation used in the source code using the corresponding Java EE deployment descriptors elements.

WEB MODULE SECURITY

In the Web module we can apply authentication, authorization and transport level encryption using the provided annotations and deployment descriptors.

Authentication and Authorization in Web Module

The following snippet instructs the application server to only let manager role to access a resource with a URL matching /mgr/* in our Web application.

Listing 1: Declaring security constraint in web.xml

<security-constraint>
	<display-name>mgr resources</display-name>
	<web-resource-collection>
		<web-resource-name>managers</web-resource-name>
		<description/>
		<url-pattern>/mgr/*</url-pattern>
		<http-method>GET</http-method>
		<http-method>PUT</http-method>
		<http-method>POST</http-method>
	</web-resource-collection>
	<auth-constraint>
		<description/>
		<role-name>manager</role-name>
	</auth-constraint>
</security-constraint>
<security-role>
	<description>All Manager </description>
	<role-name>manager</role-name>
</security-role>

We defined a security constraint, defined a collection of resources matching the /mgr/* URL and defined a constraint over the GET, PUT, and POST methods. Then we permitted the manager role to access the constrained resources. The URL pattern can specify anything from a Servlet to a set of JSP files. We can include as many roles as we need in the auth-constraint element.

Any security role referenced in the auth-constraint elements should be defined using a security-role element as we did for the manager role.

So far we told which role has access to the secured resource but we still need to let the application server know how to authenticate the users and later on how to determine which roles the user has.

Java EE containers provide some standard authentication mechanisms for using in the Web modules. These methods with their specification names are as follow:

  1. HTTP Basic Authentication: BASIC
  2. Digest Authentication: DIGEST
  3. HTTPS Client Authentication: CLIENT-CERT
  4. Form-Based Authentication: FORM

In the first two methods container initiates an HTTP basic authentication and usually the Web client (Browser) shows the standard dialog to collect the user name and the password. The only difference is that when using DIGEST, client sends a digest of the password instead of sending it in clear text. To use any of these methods we only need to include the following snippet in the web.xml.


<login-config>
	<auth-method>BASIC</auth-method>
	<realm-name>file-realm</realm-name>
</login-config>

In the CLIENT-CERT method, clients authenticate the server by asking the server for its digital certificate and the server also asks the client to provide its digital certificate to authenticate its identity. In this mode nothing is required to be done except that the client and the server must have a certificate issued by a certificate authority trusted by the other side.

Finally the FORM method lets the developer have more control over authentication by letting them provide their own credentials collecting pages. So we basically create a login and login-err page and let the application server know about our pages. Application server will use these pages to collect the user credentials and verifying them. To use this method we should include the following snippet into the web.xml.


<login-config>
	<auth-method>FORM</auth-method>
	<realm-name>file-realm</realm-name>
	<form-login-config>
		<form-login-page>auth/login.jsp</form-login-page>
		<form-error-page>auth/login-error.jsp</form-error-page>
	</form-login-config>
</login-config>

The simplest content for the login.jsp is as follow:


<form action="j_security_check" method="POST">
<input type="hidden" name="A" value="1">
<input type="hidden" name="B" value="2">
</form>

The login-error.jsp page can contain any sort of information you feel necessary for the users to understand they provided wrong credentials and they can probably recover the password and so on.

Now it is time to let the application server know where the users credentials are stored so it can authenticate the received credentials with them and decide whether the user is authentic or not. This is where vendor specific deployment descriptor comes into play. Basically we need to map the roles we used in the standard deployment descriptor to users and groups (in some cases users and roles) defined in security realm. Different vendors use different configuration elements to map roles to individual users and groups of users in the security realm. The following table shows how a role can be mapped to users and groups in different application servers.

Application Server Mapping Sample
GlassFish: sun-web.xml

<security-role-mapping>
	<role-name>manager</role-name>
	<principal-name>JoneDoe</principal-name>
	<group-name>managers</group-name>
</security-role-mapping>

Geronimo: geronimo-web.xml

<security-realm-name>file-realm

<security>
	<role-mapping>
		<role role-name="manager">
			<principal class="org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal" name="JohnDoe" />
			<principal class="org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal" name="managers" />
		</role>
	</role-mapping>
</security>

The realm need to be created as a top level realm in the application server management console or it can be added to the web application as a deployment module. Using the second way, the security realm will be deployed along with the application and will be underployed when we undeploy the application.

JBoss: jboss-web.xml

The JBoss case is different because JBoss uses the concept of Security Domain which is defined in a separate descriptor file named jboss-web.xml and is located in the conf directory of server instance. Following element is used to specify the security domain.


<security-domain>java:/jaas/jboss-sec-domain</security-domain>

For JBoss application server some of the declaration we specified in *-web.xml is moved to login-config.xml which includes both role mappings and security realm definition. A security domain can be deployed with the enterprise application itself or it can be defined in the global login-conf.xml file. A sample security domain definition is shown in the listing 2.

Table 1: Application server specific role mappings

Listing 2: Sample security domain for JBoss

<application-policy name="jboss-sec-domain">
	<authentication>
		<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
			<module-option name="dsJndiName">java:/user-data-source</module-option>
			<module-option name="principalsQuery">select passwd from users where userid=?</module-option>
			<module-option name="rolesQuery">select roleid, ‘Roles’ from roles where userid=?</module-option>
		</login-module>
	</authentication>
</application-policy>

This sample domain specifies that the user information is stored in a database which is accessible through a data source named user-data-source. Two other elements specify how a username can be searched in the users table and how the associated roles can be extracted from the roles table.

So far we specified how we can perform authentication using the container provided features. Now we need to conduct access control or authorization.

Hot Tip

Passwords and user names are not protected from eavesdropping when we use FORM or BASIC authentication methods. To protect them from being viewed and intercepted by third parties we should enforce transport security.

Enforcing Transport Security

Transport security ensures that no one can tamper with the data being sent to a client or data we receive from a client. Java EE specification lets us enforce the transport security in two levels.

CONFIDENTIAL: By using SSL, this level guarantees that our data is encrypted so that it cannot be deciphered by third parties and the data remains confidential.

INTEGRAL: By using SSL, this level guarantees that the data will not be modified in transit by third parties.

NONE: This level does not apply SSL, and lets the data transport happen as usual.

We can enforce transport security in web.xml using the user-dataconstraint element which we should place inside the security-constraint tag containing the resource which need transport protection. For example we can add the following snippet inside the security-constraint of Listing 1 to enforce use of SSL when user is accessing manager resources.


<user-data-constraint>
	<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>

Hot Tip

We can define as many security-constraints as required and each one of them can use a different user-data-constraint level.

When we specify CONFIDENTIAL or INTEGRAL as transport guarantee level, the application server will use the HTTPS listener (HTTP listener with SSL enabled) to communicate with client. Different application servers use a variety of methods to define and configure the HTTPS listeners. Each listener will have a dedicated port like 8080 for HTTP and 8181 for HTTPs.

Hot Tip

In production environment we usually front the application server with a Web server or a dedicated hardware appliance to accelerate the SSL access among other tasks like hosting static content, load distribution, decorating HTP headers and so on.

For the security purpose the front end Web server or appliance (like a Cisco PIX 535, F5 Big IP, etc) can be used to accelerate SSL certificate processing, unify the access port to both HTTP and HTTPS, act as a firewall and so on.

Other Security Elements of Web application deployment descriptors

Other elements which we can use in web.xml for security purposes which are listed in the Table 2.

Element Description
security-role

Each role must be referenced in a security-role tag before it can be used in the auth-constraint element of a security-constraint. For example:


<security-role>
	<description>All Manager </description>
	<role-name>manager</role-name>
</security-role>

session-config

To specify for how long a session should remain valid. For example:


<session-config>
	<session-timeout>120</session-timeout>
</session-config>

run-as

To use an specific internal role for any out going call from the Servlet.


<run-as>
	<role-name>internal_role</role-name>
</run-as>

This element resides inside the Servlet tag.

security-role-ref

We can alias a role with a more meaningful title and then link the alias to real realm using this element. For example:


<security-role-ref>
	<role-name>mid_level_managers</role-name>
	<role-link>manager</role-link>
</security-role-ref>

Table 2: Complete list of Security related elements of web.xml

Hot Tip

We use the run-as element or its counterpart annotation to assign a specific role to all outgoing calls from a Servlet or an EJB. We use this element to ensure that an internal role which is required to access some secured internal EJBs is never assigned to a client and stays fully in control of the developers.

Using Annotations to enforce security in Web modules

We can use annotations to enforce security in a Web module. For example, we can specify which roles can access a Servlet by adding some annotations in the Servlet or we can mark a method in a Servlet stating that no one can access it.

List of all Java EE 6 annotations and their descriptions are available in the Table 3.

Annotation Description
@DeclareRoles Prior to referencing any role, it should be defined. The @DeclareRoles acts like security-role element in defining the roles used in application.
@RunAs Specifies the run-as role for the given Components.
@ServletSecurity The @ServletSecurity can optionally get a @HttpMethodConstraint and @HttpConstraint as its parameters. The @HttpMethodConstraint is an array specifying the HTTP methods specific constraint while @HttpConstraint specifies the protection for all HTTP methods which are not specified in the @HttpMethodConstraint.
@PermitAll Permitting users with any role to access the given method, EJB or Servlet
@DenyAll If placed on a method, no one can access that method. In case of class level annotation, all methods of annotated EJB are inaccessible to all roles unless a method is annotated with a @RolesAllowed annotation.
@RolesAllowed In case of method level annotation, it permits the included roles to invoke the method. In case of class level annotation, all methods of annotated EJB are accessible to included roles unless the method is annotated with a different set of roles using @RolesAllowed annotation.

Table 3: Security Annotations in Java EE 6

Each of the annotations included in table 3 can be placed on different targets like methods, classes or both and on different Java EE components like Servlets and EJBs. Table 4 shows what kind of targets are supported for each one of these annotations.

Annotation Targets Level Target Kind
@DeclareRoles Class EJB, Servlet
@RunAs Class EJB, Servlet
@ServletSecurity Class Servlet
@PermitAll Class, Method EJB
@DenyAll Method EJB
@RolesAllowed Class, Method EJB

Table 4: Security Annotation targets in Java EE 6

Some of the security annotations can not target a method like @DeclareRoles while some other can target both methods and classes like @PermitAll. Annotation applied on a method will override the class level annotations. For example if we apply @RolesAllowed("employee") on an EJB class, and we apply @RolesAllowed("manager") on one specific method of that EJB, only admin role will be able to invoke the marked method while all other methods will be available to the employee role.

Hot Tip

A role can be mapped to one or more specific principals, groups, or to both of them. The principal or group names must be valid in the specified security realm. The role name we use in the mapping element must match the role-name in the security-role element of the deployment descriptor [web.xml, ejb-jar.xml] or the role name defined in the @DeclareRoles annotation.

Programmatic Security in Web Module

We can access some of the container security context programmatically from our Java source code. Table 5 shows the seven methods of HTTPServletRequest class which we can use to extract security related attributes of the request and decide manually about how to process the request.

Method Descriptions
String getRemoteUser() If the user is authenticated returns the username otherwise returns null.
boolean isUserInRole(String role) Returns whether the current user has the specified roles or not.
Principal getUserPrincipal() Returns a java.security.Principal object containing the name of the current authenticated user.
String getAuthType() Returns a String containing authentication method used to protect this application.
void login(String username, String password) This method authenticates the provided username and password against the security realm which the application is configured to use. We can say this method does anything that the BASIC or FORM authentication does but gives the developer total control over how it is going to happen.
Void logout() Establish null as the value returned when getUserPrincipal, getRemoteUser, and getAuthType is called on the request.
String getScheme() Returns the schema portion of the URL, for example HTTP or HTTPS.

Table 5: Programmatic Security functionalities in Web modules

The following snippet shows how we check the user role and decide where to redirect him.


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
	throws ServletException, IOException {
	
		if (request.isUserInRole("manager")) response.sendRedirect("/mgr/index.jsp");
		else response.sendRedirect("/guests/index.jsp");
	}

This snippet demonstrates the use of login method to programmatically login a user using the container security.


String userName = request.getParameter("user");
String password = request.getParameter("password");
try {
request.login(userName, password);
}catch(ServletException ex) {
	//Handling Exception
		return;
}

In the sample code, which can happen inside the doGet or doPost of a Servlet we are extracting the username and password from the request and then we use the login method to ask the container to authenticate the given username and password against the configured realm.

EJB MODULE SECURITY

Like Web Container and Web module we can enforce security on EJB modules as well.

In an EJB module we can enforce security (Authentication & Authorization) on Entity Beans and Session Beans. No Security enforcement for the MDBs.

In figure 1 you can see that we either access the EJBs through Web container or the ACC. In the first method, the Web container conducts the authentication and propagate the subject to EJB container when using EJBs. In the second method, the ACC performs authentication and pass on the subject during context initialization to the EJB container for authorization.

EJB module deployment descriptors

Each EJB module has one or more deployment description which contains standard EJB module deployment elements and vendor specific information.

During this section we assume we have an Entity Bean named Employee as follows:

Listing 3: Sample Employee EJB

@Entity
public class Employee implements Serializable {
	public String getName() {
	return "name";
	}
	public void promote(Position toPosition) {
	//promote the emplyee
	}
	public List<EvaluationRecords> getEvaluationRecords() {
	List<EvaluationRecords> evalRecord;
	//return a list containing all
	// EvaluationRecords of
	//this employee
	return evalRecord;
	}
	public List<EvaluationRecords> getEvaluationRecords(Date from, Date to)
	{
		List<EvaluationRecords> evalRecord;
		//return a list containin all
		//productivity evaluation of
		//this employee in the given time range
		return evalRecord;
	}
	@Id
	private Integer id;
	public Employee() {
	}
}

Now in the standard deployment descriptor we have can have something like the following snippet to restrict execution of the Employee Bean methods to certain roles:

Listing 4: Enforcing access restriction on EJB methods invocation

<method-permission>
	<role-name>manager</role-name>
	<method>
		<ejb-name>Employee</ejb-name>
		<method-name>getName</method-name>
	</method>
</method-permission>
<method-permission>
	<role-name>manager</role-name>
	<method>
		<ejb-name>employee</ejb-name>
		<method-name>getEvaluationRecords</method-name>
		<method-params>
			<method-param>from</method-param>
			<method-param>to</method-param>
		</method-params>
	</method>
</method-permission>

<method-permission>
	<role-name>hr_manager</role-name>
	<method>
		<ejb-name>Employee</ejb-name>
		<method-name>*</method-name>
	</method>
</method-permission>

This snippet should be placed inside the EJB declaration to invoke any method of the EJB under the given role.

The snippet is instructing EJB container to allow any subject with manager role to invoke getName method, and only the getEvaluationRecords overloads which takes a date range. Then it allows any subject with hr_manager role to invoke all methods of the Employee EJB.

Like web.xml we will need to include role definitions in the deployment descriptor. So we will need to add three security-role elements in the ejb-jar.xml file to define the roles we are using. The syntax is the same as web.xml element which is included in listing 1.

We said that the EJB module performs authentication only when it is accessed from ACC and all configurations for the authentication is provided by the vendor specific deployment descriptors.

Vendor specific deployment descriptors for EJB module are below.

Application Server Description
GlassFish: sun-ejb-jar.xml
  1. Define the role mapping using the same syntax used in the sun-web.xml
  2. Adding transport security on EJBs using the ior-security-config subelement of the ejb element.
  3. Adding Web Services security declarations using webservice-endpoint subelement of the ejb element.
  4. Specifying the authentication realm for EJBs when they are accessed by the ACC using:

<ior-security-context>
	<as-context>
		<realm>myrealm</realm>
	</as-context>
</ior-security-context>

Geronimo: openejb-jar.xml
  1. Adding role mapping using the same syntax as geronimo-web.xml
  2. Adding web services security using web-service-security subelement of the enterprise-beans element.
  3. Adding the security realm using the same syntax as geronimo-web.xml
JBoss: jboss.xml
  1. Specifying the security domain similar to jboss-web.xml
  2. Adding EJB transport security using the ior-security-config subelement of the message-driven, ejb, service, and session elements.

Table 6: Different application server's EJB deployment descriptors

Security Annotation of EJB modules in Java EE 6

Java EE provides a rich set of security related annotations for the EJB modules. Each of these annotations can be applied on one or more types, as explained previously in Table 3 and Table 4.

Following snippet shows how we can use these annotations to apply the same security restrictions we declared in the deployment descriptor showed in listing 4 on the entity source code shown in Listing 3.

Listing 5: Using annotations to enforce acces restriction on EJBs

@Entity
@DeclareRoles({"manager","hr_manager"})
public class Employee implements Serializable {
@RolesAllowed({"manager","hr_manager"})
	public String getName() {
		return "name";
	}
	
@RolesAllowed("hr_manager")
	public void promote(Position toPosition) {
		//promote the emplyee
	}
	
@RolesAllowed({"manager","hr_manager"})
	public List<EvaluationRecords> getEvaluationRecords() {
		List<EvaluationRecords> evalRecord;
		//return a list containing all
		// EvaluationRecords of
		//this employee
		return evalRecord;
	}
@RolesAllowed("hr_manager")
	public List<EvaluationRecords> getEvaluationRecords(Date from, Date to) {
		List<EvaluationRecords> evalRecord;
		//return a list containin all
		//productivity evaluation of
		//this employee in the given time range
		return evalRecord;
	}
	@Id
	private Integer id;
	public Employee() {
	}
}

Using only two annotations, @RolesAllowed and @DeclareRoles, frees us from adding all deployment descriptor elements.

Similar to Web module which had a run-as element in the standard deployment descriptor, here in EJB module we have the same element. This element will allow outgoing calls from the EJB to use a specific role included in the role-name element.


<security-identity>
	<run-as>
		<description/>
		<role-name>internal_role</role-name>
	</run-as>
</security-identity>

This snippet should be placed inside the EJB declaration element of the deployment descriptor.

Hot Tip

Different vendors may have specific non-Java EE compliant annotations for different Java EE components. Like JBoss @SecurityDomain annotation. Using non-standard compliant annotations will make it harder to port an application between different application server.

Securing EJB Modules programmatically

We can use EJB context, javax.ejb.EJBContext, to check whether the current user has a specific role using isCallerInRole method or we can extract the principal name of the subject using getCallerPrincipal method. For example:


@Stateless
public class EmployeeServiceBean
	{
	@Resource
	SessionContext ctx;
public void raiseEmployeePaygrade(int amount, long empID){
Employee employee = null;
//find the employee
String raisedBy =ctx.getCallerPrincipal().getName();
employee.raisePayGrade(850000, raisedBy);
//persist the employee
}
}

In the above sample code we injected the context and then we used it to get the principal name. Then we used it to keep record of who changed the salary of employee.

We can use Around Invoke Interceptors to intercept an EJB business methods call. Intercepting the call lets us access the method name, its parameters, EJB context (and therefore isCallerInRole and getCallerPrincipal methods). We can perform tasks like security check, logging and auditing or ever changing the values of method parameters using interceptors.


public class SampleInterceptor {
	@Resource
		private EJBContext context;
	@AroundInvoke
	protected Object audit(InvocationContext ctx) throws Exception {
	Principal p = context.getCallerPrincipal();
		if (userIsValid(p)) {
			//do some logging...
		}else{
			//logging and raising exception..
		}
		return ctx.proceed();
	}
}

To use this interceptor we need only to place an Annotation on the designated EJB, for example to intercept any method call on EmployeeServiceBean we can do the following:


@Interceptors(SampleInterceptor.class)
@Stateless
public class EmployeeServiceBean {
// Source code omitted.
}

The @Interceptors can target classes, methods or both. To exclude a method from a class level interceptor we can use @ExcludeClassInterceptors annotation for that method.

We can use interceptor element of ejb-jar.xml deployment descriptor to specify interceptors if preferred.

APPLICATION CLIENT SECURITY

Application Client Container, which can host first tier client for enterprise applications, conducts the authentication by itself and when communicating with the EJBs, sends the authenticated subject along with the call. In the standard deployment descriptor we can configure the callback handler which collect the user credentials for authentication and all other measures are configured in the vendor specific deployment descriptor.

For example, the following snippet specifies the callback handler to collect user identity information.


<callback-handler>
security.refcard.SwingCallBackHandler
</callback-handler>

Hot Tip

The callback-handler element specifies the name of a callback class provided by the application for JAAS authentication. This class must implement the javax.security.auth.callback.CallbackHandler interface.

<resource-ref>
	<res-ref-name>TaskQueueFactory</res-ref-name>
	<jndi-name>jms/TaskQueueFactory</jndi-name>
	<default-resource-principal>
		<name>user</name>
		<password>password</password>
	</default-resource-principal>
</resource-ref>

Application Client Container will use the authentication realm specified in the application.xml file to authenticate the users when a request for a constrained EJB is placed.

Security enforcement in Geronimo ACC

Similar to GlassFish, Geronimo provides some configuration elements in the vendor specific file named geronimo-application-client.xml.

Notable configuration elements are default-subject, realm-name and callback-handler. For example to configure the callback handler we can use the following snippet.


<callback-handler>
security.refcard.SwingCallBackHandler
</callback-handler>

Security enforcement in JBoss ACC

Configuration for the JBoss ACC container is stored in the jbossclient. xml file. This configuration file provides no further security customization for the application client.

DEFINING SECURITY IN ENTERPRISE APPLICATION LEVEL

As we saw in the Figure 3, the enterprise application archive (EAR) file can contain multiple modules intended to be deployed into different containers like Web, EJB or ACC. This EAR module has the deployment descriptor of its ow which we can use to include the share deployment plan details in addition to EAR specific declarations.

We can use the application level deployment descriptors to define roles, include the required role mappings and to specify the default security realm of all included modules.

We can use the standard deployment descriptor to define security roles. The syntax is the same as what we used in the web.xml and the ejb-jar.xml.

Similar to other vendor specific deployment descriptors, we can use the application level descriptor to define the application-wide role mapping and also to define the default security realm for all included modules.

The following table shows how we can use different vendor specific deployment descriptors for role mapping and specifying the default security realm and shows what security measures are accessible through the vendor specific enterprise application deployment descriptor.

Application Server Description
GlassFish: sun-application.xml

Role mapping is similar to other Sun specific deployment descriptors. Defining the default security realm is as follow:


<realm>
	jdbc_realm
</realm>

The element is an immediate child of the sun-application

Geronimo: geronimo-application.xml

Roles mapping syntax is similar to other Geronimo specific deployment descriptor.

Specifying the default security realm is as follow:


<dependency>
	<groupId>console.realm</groupId>
	<artifactId>file_realm</artifactId>
	<version>1.0</version>
	<type>car</type>
</dependency>

This element is immediate child element of the dependencies element which is a subelement of the environment element

JBoss: jboss-app.xml

Role mapping and specifying the security realm is the same as with jboss-web.xml and jboss.xml using the security domain element.

SECURING JAVA EE WEB SERVICES

In the Java EE specification, Web services can be deployed as a part of a Web module or an Enterprise module.

Web Services Security in Web Modules

In the Web module we can protect the Web service endpoint the same way we protect any other resource. We can define a resource collection and enforce access management and authentication on it. The most common form of protecting a Web service is using the HTTP Basic or HTTP Digest authentication.

For example if we use the HTTP basic authentication and our Web service client uses the Dispatch client API to access the Web service we we can use a snippet like the following one to include the username and password with the right access role to invoke a Web service.


sourceDispatch.getRequestContext().put(Dispatch.USERNAME_PROPERTY,"user");
sourceDispatch.getRequestContext().put(Dispatch.PASSWORD_PROPERTY,"password");

The user and the password should be valid in the configured realm of Web application and should have access right to the endpoint URL.

Hot Tip

Another way of authenticating the client to the server in HTTP level is using the Authenticator class which provides more functionalities and flexibilities. For more information about the authenticator class check http://java.sun.com/javase/6/docs/technotes/guides/net/http-auth.html

Web Services Security in EJB Modules

We can expose a Stateless Session Bean as a Web Service and therefore we can use all security annotations like @RolesAllowed, @PermitAll and their corresponding deployment descriptor elements to define its security plan.

But the authentication enforcement of the Web Services is vendor specific and each vendor uses its own method to define the authentication, security realms and so on.

Web Services Authentication in GlassFish

For GlassFish we should specify the authentication method and the security realm in the sun-ejb-jar.xml. For example, to specify HTTP Basic authentication method and a realm named file_realm as the security realm for a Web service called Echo we will have something similar to the following snippet.


<ejb>
	<ejb-name>Echo</ejb-name>
	<webservice-endpoint>
		<port-component-name>Echo</port-component-name>
		<login-config>
			<auth-method>BASIC</auth-method>
			<realm>file_realm</realm>
		</login-config>
	</webservice-endpoint>
</ejb>

Web Services Authentication in Geronimo

In Geronimo we can use the annotations to define the security plan and then the EJB deployment descriptor to specify the authentication mechanism and the security realm. For if the following snippet is placed inside the openejb-jar.xml we can expect an HTTP Basic authentication to protect the Echo Web service.


<enterprise-beans>
	<session>
	<ejb-name>Echo</ejb-name>
	<web-service-security>
		<security-realm-name>file_realm</security-realm-name>
		<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		<auth-method>BASIC</auth-method>
	</web-service-security>
	</session>
</enterprise-beans>

We simply specified HTTP Basic authentication and the file_realm to be used for this Web service.

Web Services Authentication in JBoss

To specify the authentication realm for a Web service deployed as a Stateless Session Bean we can use both annotation and deployment descriptor elements in JBoss. For example using annotation to secure a Web service can be as follows:


@WebService()
@WebContext(contextRoot="/EchoService",
	urlPattern="/Echo",
	authMethod="BASIC",
	secureWSDLAccess = false)
@SecurityDomain(value = “jboss-sec-domain")
@Stateless
...

The @WebContext annotation simply specifies the Web service endpoint, the authentication method which can be CLIENT-CERT, BASIC or DIGEST and finally it specifies whether clients need to provide credentials to view the WSDL or not.

The @SecurityDomain specify which security domain should be used for this Web service authentication.

We can access EJB Web services in the same way we access the Servlet powered Web services using Dynamic Proxy or the Dispatch API.

Hot Tip

Each one of the studied application servers provides plethora of configuration and tweaking for Web services security to comply with WS-Security profiles. You can check their Websites to see what are the available options.

For a basic comparison and a quick start for these application servers take a look at: http://weblogs.java.net/blog/kalali/archive/2009/11/17/state-open-source-java-ee-application-servers.

About The Author

Photo of author Masoud Kalali

Masoud Kalali

Masoud Kalali has 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 published several articles at Java.net and Dzone. He has authored multiple refcards, published by Dzone, including Using XML in Java, Berkeley DB Java Edition and GlassFish v3. Masoud is author of GlassFish security book published by Packt and he is one of founder members of NetBeans Dream Team and a GlassFish community spotlighted developer.

Masoud blog on Java EE, Software Architecture and Security at http://weblogs.java.net/blog/kalali/ and you can follow him at http://twitter.com/MasoudKalali

Masoud can be reached via Kalali@gmail.com in case you had some queries about the book or if you just felt like talking to him about software engineering.

Recommended Book

Glassfish Security

Security was, is, and will be one of the most important aspects of Enterprise Applications and one of the most challenging areas for architects, developers, and administrators. It is mandatory for Java EE application developers to secure their enterprise applications using Glassfish security features.

Learn to secure Java EE artifacts (like Servlets and EJB methods), configure and use GlassFish JAAS modules, and establish environment and network security using this practical guide filled with examples. One of the things you will love about this book is that it covers the advantages of protecting application servers and web service providers using OpenSSO.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

JBoss Enterprise Application Platform 5

Download your free copy of Refcard #97: Getting Started with JBoss Enterprise Application Platform 5 now!

0 replies - 28618 views - 05/03/10 by Lyndsey Clevesy in Announcements

Contexts and Dependency Injection for the Java EE Platform

By Norman Richards

19,531 Downloads · Refcard 83 of 151 (see them all)

Download
FREE PDF


The Essential Java CDI Cheat Sheet

Contexts and Dependency Injection for the Java EE Platform introduces a standard set of component management services to the Java EE platform. CDI manages the lifestyle and interactions of stateful components bound to well-defined contexts. CDI provides typesafe dependency injection between components. The Java EE 6 platform includes CDI as part of both the full profile and the web profile. This DZone Refcard will be useful for anyone interested in getting a better understanding of Contexts and Dependency Injection so that they can get the most out of the Java EE Platform.
HTML Preview
Contexts and Dependency Injection for the Java EE Platform

Contexts and Dependency Injection: for the Java EE Platform

By Norman Richards

ABOUT CDI

Contexts and Dependency Injection for the Java EE Platform (CDI) introduces a standard set of component management services to the Java EE platform. CDI manages the lifecycle and interactions of stateful components bound to well-defined contexts. CDI provides typesafe dependency injection between components. CDI provides interceptors and decorators to extend the behavior of components, an event model for loosely coupled components, and an SPI allowing portable extensions to integrate cleanly with the Java EE environment.

CDI and Java EE

The Java EE 6 platform includes CDI as part of both the full profile and the web profile. The EE 6 platform was designed to make sure all EE components make use of CDI services, putting CDI directly at the heart of the platform, welding together the various EE technologies.

CDI and Seam

CDI was influenced by many technologies, with Seam in particular pioneering many of the concepts that have been formalized in CDI. However, Seam is not CDI, and not all of Seam's innovations are part of the CDI specification. As such, the latest version of Seam, Seam 3, will be based on CDI and will provide a collection of portable extensions to CDI that can be integrated cleanly into any CDI environment. Seam 3 will also provide a legacy Seam 2 mode, giving existing Seam applications a migration path onto CDI.

ABOUT WELD

Weld is the CDI reference implementation. It is a great place to get started with CDI. Weld can be downloaded from http://seamframework.org/Download.

Running the examples

Weld comes with an extensive library of examples that is a great starting point to learn CDI. These examples run in Java EE containers such as JBoss AS and Glassfish as well as in servlet containers like Tomcat and Jetty.

Example name Description
examples/jsf/login A simple example demonstrating a user login component
examples/jsf/numberguess A number guessing game
examples/jsf/permalink A blog example
examples/jsf/translator A text translation example using EJBs
examples/wicket/numberguess The number guessing game implemented with Wicket
examples/wicket/gae An alternative version of the Wicket number guess that runs on Google App Engine

Building the examples

Each example can be built using Maven 2.


$ mvn clean install

The target directory contains the built archive, which can be deployed to EE containers like JBoss AS and Glassfish. The examples that build to WAR files can also be deployed to Tomcat and Jetty.

For convenience, each example contains an Ant file with targets to build and deploy directly to JBoss AS and Tomcat.


ant -Djboss.home=/path/to/jboss-6.0 deploy
ant -Djboss.home=/path/to/jboss-6.0 undeploy
ant '"Dtomcat.home=/path/to/tomcat tomcat.deploy
ant '"Dtomcat.home=/path/to/tomcat tomcat.undeploy

Creating a Weld project

New project stubs can be created using Maven 2 archetypes.

Interactive Mode


mvn archetype:generate

Non-interactive mode


mvn archetype:generate
    -DinteractiveMode=n
    -DarchetypeArtifactId=weld-jsf-servlet-minimal
    -DarchetypeGroupId=org.jboss.weld.archetypes
    -Dversion=1.0.01
    -DgroupId=com.mycompany
    -DartifactId=myproject


Weld archetypes

Weld archetype Description
weld-jsf-servlet-minimal A Weld web application using JavaServer Faces (JSF)
weld-jsf-jee-minimal A Weld application using EJB and JSF but no persistence
weld-jsf-jee A Weld application using EJB and JSF with a persistence context

Building a Weld project


mvn clean install

welt screen shot

THE BEAN

CDI, at the most basic level, revolves around the notion of beans. Beans are instantiated by CDI, and their lifecycle is managed according to the stateful context to which they belong. So, it's natural to start by asking what is a bean? In CDI, almost any object can be a bean. When using CDI in a Java EE environment, any Java EE component is a bean if it is defined to be a managed bean by its EE specification. This includes session beans, message-driven beans, servlets, filters, etc.

Most non-EE POJOs are also automatically managed beans and no special declarations are required to define a managed bean. A bean definition consists of the following:

Bean Type The bean type is the set of Java types that the bean provides. CDI injection always uses type as the primary identifier for determining the bean that will provide an instance. Unless otherwise restricted, a bean's type includes all the superclasses and interfaces in the Java type hierarchy
Qualifier There may be multiple beans that implement a desired Java type. It is possible to distinguish between multiple types using qualifier annotations. Qualifiers are developer-defined and provide a type-safe way to distinguish between multiple beans implementations.
Scope All beans have a well-defined scope that determines the lifecycle and visibility of instances. The set of scopes is fully extensible, with built-in scopes including request scope, conversation scope, session scope and application scope. Beans can also be dependent and inherit the scope of their injection point.
EL name Although it's completely optional, beans may define an EL name that can be used for non-type safe access. One common usage of EL name is for binding components to JavaServer Faces (JSF) views.
Interceptors A bean's behavior can be extended or overridden by adding interceptors and decorators to the bean.
Implementation All beans must of course provide an implementation of the types they provide. This is normally the Java class that defines the bean.

USING INJECTION

Not all instances of a bean type are managed instances. Instances created with the Java new operator are not managed. Only instances provided by the CDI BeanManager or through an injection point are managed instances.

Managed instances can have injection performed on them when they are created. Injection points are declared using the @javax.inject.Inject annotation.

Injection is performed at creation time for any fields annotated @Inject.


public class Foo
{
@Inject Bar bar;
}

Injection is also performed for any methods annotated @Inject.


public class Foo
{
@Inject
public void setBar(Bar bar) {
// '
}
}

Method injection points can be thought of as initializer methods. Method injection points can support multiple injected arguments.


public class Foo
{
@Inject
public void initializeMe(Bar bar, Baz baz) {
// '
}
}

Beans can have any number of field or method injection points. Additionally, a bean may have a constructor annotated @Inject. Any declared parameters will be injected when the instance is created.


public class Foo
{
@Inject
public Foo(Bar bar, Baz baz) {
// '
}
}

If a bean doesn't designate a constructor using @Inject, the no argument constructor will be used.

Producers

If CDI needs to instantiate a new instance, it will normally call the designated constructor. However, it's possible to directly control the creation of new instances with producer methods. Producer methods are annotated @javax.enterprise.inject.Produces and return the object to be produced. Any arguments to a producer method will be injected by CDI./p>


public class FooProducer {
@Produces
public Foo makeFooFromBar(Bar bar) {
return new Foo(bar);
}
}

An alternative form of producer is the producer field. The value of the producer field is the value to be injected.


public class AnotherFooProducer {
@Produces Foo foo;
@Inject
public void initalizeMe(Bar bar) {
foo = new Foo(bar);
}
}

Producer fields can be combined with Java EE injection annotations such as @Resource, @EJB and @PersistenceContext.


@Produces
@WebServiceRef(lookup='java:app/service/PaymentService')
PaymentService paymentService;
@Produces
@EJB(ejbLink='../their.jar#PaymentService')
PaymentService paymentService;

New instances

CDI injects the contextual, and thus possibly shared, instance of a bean. When this is not desired, the @javax.enterprise. inject.New annotation can be used to force a new instance to be created and injected.


public class FooProducer {	
@Produces public Foo makeFoo(@New Bar bar) {
return new Foo(bar);
}
}

Programmatic lookup

Injection occurs when a component is created and initialized by CDI. There are many cases where this is not desirable. In those cases, programmatic lookup is available by injecting the corresponding javax.enterprise.inject.Instance for a bean.


public class Foo {
@Inject Instance<Bar> bar;
public Bar getBar() {
return bar.get();
}
}

The get method performs the actual lookup defined by the injection point.

Qualifiers

CDI does injection by type, but most systems have the need for more than one instance of a given type. Rather than giving them unique names or identifiers, CDI handles this through qualifiers. Qualifiers are annotations on bean types and injection points that differentiate between types. If a type is a noun, then a qualifier is an adjective that can be used to describe and distinguish the nouns.

A qualifier is an annotation that itself is annotated with the @javax.inject.Qualifier meta-annotation.>


@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Synchronous {
}

Qualifiers can be added to a class to define a qualified bean type. Typically this will be a subclass of a parent type or the implementation of an interface.


@Synchronous
public class SynchronousPaymentProcessor
implements PaymentProcessor
{
// ...
}

Producer methods and fields can also use qualifiers to distinguish between the types.


@Produces
@Asynchronous
public PaymentProcessor createAsynchronousProcessor() {
return new AsynchronousPaymentProcessor();
}

It's now possible to distinguish between the two types by adding the qualifier to any injection point. It's not necessary to know the specific subtype or implementation class.

Qualifiers annotations may have members.


@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Qualifier
public @interface Currency {
public String code();
}

All members must be equal, so the following injection point and producer field would not match.


@Inject @Currency(code='USD') PaymentProcessor processor;
@Produces @Currency(code='EUR') PaymentProcessor processor;

However, if the qualifier annotation member is marked as @javax.enterprise.util.Nonbinding, then the member values would not be considered and the injection point would match the producer field.


@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Qualifier
public @interface Currency {
@Nonbinding public String code();
}

Nonbinding values can provide useful metadata to a method. These nonbinding values can be retrieved by injecting the javax.enterprise.inject.spi.InjectionPoint and querying the qualifiers.


@Produces
@Currency(code='USD')
public PaymentProcessor processor(InjectionPoint injectionPoint) {
      PaymentProcessor processor = new PaymentProcessor();
      for (Annotation qualifier:injectionPoint.getQualifiers()) {
        if (qualifier instanceof Currency) {
           Currency currency = (Currency) qualifier;
           processor.setBaseCurrency(currency.code());
           break;
        }
      }
      return processor;
}

The built-in qualifiers

Qualifier Description
@javax.enterprise.inject.Any Every bean and every injection point has the @Any qualifier,even if it is not specified, unless the @New annotation isspecified.
@javax.enterprise.inject.New The @New annotation forces a new instance to be created by the container instead of using the contextual instance.
@javax.enterprise.inject.Default Any bean or injection point that does not declare the @Named qualifier has the default qualifier added.
@javax.enterprise.inject.Named This qualifier declares a text name that can be used to reference the bean. This is used for un-typed access such as through EL.

Bean names

The @javax.inject.Named qualifier specifies a textual that can be used in places where CDI's type-based lookup is not possible. The primary use case is EL access in places such as JSF views.


@Inject @Named('foo') Foo foo;

The String value of the annotation is the name of the bean. If the @Named annotation doesn't explicitly specify a name, the container will derive a default name. The default name is the unqualified class name of the bean class, after converting the first character to lower case. The following two injection points use the exact same name.


@Inject @Named Bar namedBar1;
@Inject @Named('bar') Bar namedBar2;

Bean Scopes

CDI manages contextual objects. Contextual objects are stateful and have a distinct lifecycle determined by the scope they belong to. When a contextual bean is needed, CDI looks in the appropriate shared context for the instance to inject. If

there is no shared instance, CDI creates one and stores it in the context for future use. When the enclosing scope is destroyed, the beans inside will be destroyed.

Bean Scope Description
@javax.enterprise.context. RequestScoped @RequestScoped beans are shared for the length of a single request. This could be an HTTP request, a remote EJB invocation, a web services invocation or message-delivery to an MDB. These beans are destroyed at the end of the request.
@javax.enterprise.context. ConversationScoped @ConversationScoped beans are shared across multiple requests in the same HTTP session but only if there is an active conversation maintained. Conversations are supported for JSF requests through the javax.enterprise.context.Conversation bean.
@javax.enterprise.context. SessionScoped @SessionScoped beans are shared between all requests that occur in the same HTTP session and are destroyed when the session is destroyed.
@javax.enterprise.context. ApplicationScoped An @ApplicationScoped bean will live for as long as the application is running and is destroyed when the application is shut down.
@javax.enterprise.context.Dependent @Dependent beans are never shared between injection points. Any injection of a dependent bean is a new instance whose lifecycle is bound to the lifecycle of the object it is being injected into.

The set of scopes is extensible. New scopes are declared with the @javax.inject.Scope or @javax.enterprise.context.NormalScope meta-annotation.

Bean Destruction

When a contextual bean goes out of scope, it is destroyed. To destroy a bean, the container calls any @PreDestroy callbacks for the bean and destroys any @Dependent objects before disposing of the object.

An application can perform custom cleanup of created objects by using a dispose method. A dispose method is the analog of a producer method and is designated by marking the parameter with @javax.enterprise.inject.Disposes.


@ApplicationScoped
public class BarProducer {
   ArrayList<Bar> allBars = new ArrayList<Bar>();
   @Produces
   public Bar createBar() {
      Bar newBar = new Bar();
      allBars.add(newBar);
      return newBar;
   }
   public void disposeBar(@Disposes Bar bar) {
      allBars.remove(bar);
   }
}

As with producer methods, disposer methods may take additional arguments to receive injected values. Only the one argument to be disposed is annotated @Disposes.

Alternatives

Alternatives allow for deployment-time selection of bean implementation. An alternative is a bean marked with the @javax.enterprise.inject.Alternative annotation. Alternatives provide an alternate implementation of a bean that is not enabled unless is specifically enabled in the beans.xml file, in which case it overrides the original bean.


@Alternative
public class AlternativeFoo
   extends Foo
{
   // alternative implementation
}

Alternatives are enabled only when activated in the beans.xml file.


<beans xmlns='http://java.sun.com/xml/ns/javaee'>
    <alternatives>
       <class>org.example.AlternativeFoo
   </alternatives>
</beans>


If the @Alternative annotation is applied to a stereotype, all beans with the stereotype may be enabled as a group.


<beans xmlns='http://java.sun.com/xml/ns/javaee'>
    <alternatives>
       <stereotype>org.example.MyAlternatives
    </alternatives>
</beans>

An alternative that extends the object it replaces will normally want to directly inherit the metadata (qualifiers, name, etc.) of the parent. In that case, the alternative should include the @javax.enterprise.inject.Specializes annotation to ensure that the original class is completely replaced by the alternative.


@Alternative
@Specializes
public class AlternativeFoo
    extends Foo
{
    // alternative implementation
}

EXTENDING BEAN FUNCTIONALITY

CDI supports two mechanisms for dynamically adding or modifying the behavior of beans: interceptors and decorators.

Interceptors

Interceptors provide a mechanism for implementing functionality across multiple beans and bean methods that is orthogonal to the core function of those beans.

Interceptor

An interceptor is a bean declared with the @javax.interceptor.Interceptor annotation. Method interceptor should have a method annotated @javax.interceptor.AroundInvoke that takes the javax.interceptor.InvocationContext as a parameter.


@Interceptor
public class TransactionInterceptor {
    @AroundInvoke
    public Object manageTransaction(InvocationContext ctx) {
       // '
    }
}

Interceptor Binding Type

Interceptors are bound using an interceptor binding type. An interceptor binding type may be declared by specifying the @javax.interceptor.InterceptorBinding meta-annotation.


@Inherited
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@InterceptorBinding
public @interface Transactional {
}

The interceptor binding is applied to both the interceptor and the interception point to bind the two together.


@Interceptor
@Transactional
public class TransactionInterceptor {
    // '
}
@Tranactional
public class Foo {
   //'
}

An interceptor bound to a class will intercept all methods. Alternatively, the interceptor can be bound to specific methods.


public class Foo {
    @Transactional
    public void someTransactionalWork() {
       // '
    }
}

As with qualifiers, binding types may declare members. For an interceptor binding to match, all members must be equal unless they are declared @NonBinding.

Interceptors are not enabled unless they are declared in the beans.xml file.


<beans xmlns='http://java.sun.com/xml/ns/javaee'>
    <interceptors>
        <class>org.example.TransactionInterceptor
        <class>org.example.LoggingInterceptor
    </interceptors>
</beans>

If multiple interceptors are defined for a call, the interceptors calls are chained. The ordering is determined by the order they are listed in beans.xml.

Decorators

Decorators also dynamically extend beans but with a slightly different mechanism than interceptors. Where interceptors deliver functionality orthogonal to potentially many beans, decorators extend the functionality of a single bean type with functionality that is specific to that type.

A decorator is bean with the @javax.decorator.Decorator annotation. A decorator only decorates the interfaces that it implements.


@Decorator class TimestampLogger
    implements Logger
{
    @Inject @Delegate Logger logger;
    public void log(String message) {
        logger.log( timestamp() + ': ' + message);
    }
}

A decorator must declare a single delegate injection point annoted @javax.decorator.Delegate. The delegate injection point is the object to be decorated. Any calls to the delegate object that correspond to a decorated type will be called on the decorator, which may in turn invoke the method directly on the delegate object.

The decorator bean does not need to implement all methods of the decorated types and may be abstract. Decorators are called after interceptors.

Decorators are not active unless they are explicitly enabled in beans.xml.


<beans xmlns='http://java.sun.com/xml/ns/javaee'>
    <decorators>
        <class>org.example.TimestampLogger
        <class>org.example.IdentityLogger
    </decorators>
</beans>

EVENTS

Events provide a mechanism for loosely coupled communication between components. An event consists of an event type, which may be any Java object, and optional event qualifiers.

The event object

Events are managed through instances of javax.enterprise.event.Event. Event objects are injected based on the event type.


@Inject Event<LoggedInEvent> normalEvent;
@Inject @Admin Event<LoggedInEvent> adminEvent

;

Events are fired by calling fire() with an instance of the event type to be passed to the observer.


event.fire(new LoggedInEvent(username));

Observers

Observers listen for events with observer methods. The event type is annotated @javax.enterprise.event.Observes. Additional parameters to an observer method are normal CDI injection points.


public void afterLogin(@Observes LoggedInEvent event) {
   //...
}
public void afterAdminLogin(@Observes @Admin LoggedInEvent event) {
  // ...
}

Conditional observers

If an instance of a component with an observer method doesn't exist when the corresponding event is fired, the container will instantiate a new instance to handle the event. This behavior is controllable using the receive value of @Observes.


public void refreshOnDocumentUpdate(@Observes(receive=IF_EXISTS)
                                    @Updated Document doc) {
   // ...
}

javax.enterprise.event.Reception

Reception value Reception value
IF_EXISTS The observer method is only called if an instance of the component already exists.
ALWAYS The observer method is always called. If an instance doesn't exist, one will be created. This is the default value.

Transactional observer

Events are normally processed when the event is fired. For transactional methods, it is often desirable for the event at a certain point in the transaction lifecycle, such as after the transaction completes. This is specified with the during value of @Observes. If a transaction phase is specified but no transaction is active, the event is fired immediately.

TransactionPhase value Meaning
IN_PROGRESS The event is called when it is fired, without regard to the transaction phase. This is the default value.
BEFORE_COMPLETION The event is called during the before completion phase of the transaction.
AFTER_COMPLETION The event is called during the after completion phase of the transaction.
AFTER__FAILURE The event is called during the after completion phase of the transaction, only when the transaction fails.
AFTER_SUCCESS The event is called during the after completion phase of the transaction, only when the transaction completes successfully

STEREOTYPES

A stereotype is a meta-annotation that bundles multiple annotations together for re-use. A stereotype may be declared by specifying the @javax.enterprise.inject.Stereotype


meta-annotation.

@RequestScoped @Secure @Transactional @Named @Stereotype @Target(TYPE) @Retention(RUNTIME) public @interface Action { }

Any bean that is annotated @Action will inherit all of the annotations of the stereotype.

CDI defines the stereotype, @javax.enterprise.inject.Model for declaring the model layer of a web application.


@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface Model {
}

CONVERSATIONS

Conversations are available in JSF only. Programmatically accessible through javax.enterprise.context.Conversation component.


public interface Conversation {
   public void begin();
   public void begin(String id);
   public void end();
   public String getId();
   public long getTimeout();
   public void setTimeout(long milliseconds);
   public boolean isTransient();
}

Any conversation is in one of two states: transient or long-running. Switch between states by calling begin/end. Long running conversations and their state will be maintained by requests in that conversation. Transient conversations are destroyed at the end of the request.

If a conversation is requested that is timed out or otherwise destroyed, a javax.enterprise.context.NonexistentConversationException is thrown.

DEPLOYMENT

Bean archive

Bean classes of enabled beans must be deployed in bean deployment archives. A bean deployment archive is any JAR, EE archive, or directory on the classpath that contains a beans.xml file in the META-INF directory. For WAR files, the WEB-INF classes directory is also considered if there is a beans.xml file in the WEB-INF directory.

beans.xml structure

The beans.xml file is defined by the XSD at http://java.sun.com/xml/ns/javaee/beans_1_0.xsd

About The Author

Photo of author Norman Richards

Norman Richards

Norman Richards is a senior software engineer at Socialware in Austin, Texas. He is an independent contributor to the Seam and Weld projects and was formerly a core developer on Seam at Red Hat and JBoss. He is the author of numerous articles and several books, including JBoss: A Developer’s Notebook, JBoss 4.0: The Official Guide and JBoss: A developer's Notebook. Norman is a graduate of the University of Texas at Austin. Norman can be contacted through his website at http://nostacktrace.com/

Recommended Book

Beginnning Java EE 6 platform with Glassfish 3

Step by step and easy to follow, this book describes many of the Java EE 6 specifications and reference implementations, and shows them in action using practical examples. This book uses the new version of GlassFish 3 to deploy and administer the code examples.


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 - 23547 views - 11/16/09 by Lyndsey Clevesy in Announcements

Getting Started with GlassFish Application Server v3

By Masoud Kalali

13,441 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 - 7170 views - 06/15/09 by Lyndsey Clevesy in Announcements