Enterprise Java Technologies Tech Tips
Tips, Techniques, and Sample Code
Welcome to the Enterprise Java Technologies Tech Tips for
February 25, 2006. Here you'll get tips on using enterprise
Java technologies and APIs, such as those in Java 2 Platform,
Enterprise Edition (J2EE) and Java Platform, Enterprise
Edition (Java EE).
This issue covers:
* Using AJAX With Non-HTML Markup in JSF
* Accessing a Secure Enterprise Bean From a Java Client
or Through Java Web Start Technology
These tips were developed using an open source reference
implementation of Java EE 5 called GlassFish. You can
download GlassFish from the GlassFish Community Downloads page
(http://java.sun.com/javaee/glassfish/getit.jsp).
You can view this issue of the Tech Tips on the Web at
http://java.sun.com/developer/EJTechTips/2006/tt0225.html.
You can download the sample archive for the tip "Using AJAX
With Non-HTML Markup in JSF" at
http://java.sun.com/developer/EJTechTips/download/ttfeb2006renderkits.zip.
There are two sample archives for the tip "Accessing a Secure
Enterprise Bean From a Java Client". One is for a standalone
client example, the other is for a Java Web Start example. You
can download the archive for the Java Web Start example at
http://java.sun.com/developer/EJTechTips/download/ttfeb2006stand_alone_client.zip.
You can download the archive for the standalone client example at
http://java.sun.com/developer/EJTechTips/download/ttfeb2006acc-mejbClient.jar.
Any use of this code and/or information below is subject to the
license terms at
http://developers.sun.com/dispatcher.jsp?uid=6910008.
See the Subscribe/Unsubscribe note at the end of this newsletter
to subscribe to Tech Tips that focus on technologies and products
in other Java platforms.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
USING AJAX WITH NON-HTML MARKUP IN JSF
by Roger Kitain
JavaServer Faces (JSF) technology
(http://java.sun.com/j2ee/javaserverfaces/index.jsp) is
a framework that simplifies building user interfaces for Java EE
and J2EE applications. The March 24, 2004 Tech Tip, "Introducing
JavaServer Faces Technology"
(http://java.sun.com/developer/EJTechTips/2004/tt0324.html#2)
gave a brief overview of the technology. It also showed how to
create a JSF application that includes GUI components that are
modeled by the JSF framework. A later tip showed how to create
custom components with JavaServer Faces technology
(http://java.sun.com/developer/EJTechTips/2004/tt1123.html#2).
Since the publishing of those tips, the technology has gone to
the 1.2 level. One of the new features in JSF 1.2
(http://jcp.org/en/jsr/detail?id=252) is the ability to support
multiple render kits in a single JSF application. In JSF, render
kits are used to present the user interface in a markup such as
HTML. JSF comes with an HTML render kit, but you could write
a render kit to display user interface components in other
markup languages such as Scalable Vector Graphics (SVG) or XML
User Interface Language (XUL).
You might want to take advantage of the strengths that each
markup language provides by combining them in a single JSF
application. For example, you can use SVG to create
sophisticated graphics and animations for an application.
However SVG does not have a widget set which includes buttons or
other components. You have to create these widgets using
a markup. In contrast, XUL has a complete set of user interface
controls that can easily be used, but it lacks the graphical
capabilities that SVG provides. Common to both of these markups
is the lack of a built-in form submission mechanism like the one
available in HTML. However Asynchronous JavaScript and XML
(AJAX) can be used with some JSF 1.2 features to effectively
produce form submissions from non-HTML markup. In this tip
you'll see a demonstration that uses AJAX and three render kits
(HTML, SVG, and XUL) in a JSF application. (For more information
about AJAX see the November 22, 2005 Tech Tip, "Using AJAX with
Java Technology".)
JSF Life Cycle Example
User interactions with a JSF application are processed in
a series of steps known as the "JSF life cycle". Typically the
life cycle is illustrated as a set of connected boxes, with each
box identifying a phase in the process. Lines with arrows show
the flow from one phase to the next. Accompanying this tip is an
example JSF application that displays an animated version of the
JSF life cycle. As mentioned earlier, the application uses the
HTML, SVG and XUL render kits.
The application begins with the display of an HTML page that
gives some background and design details pertinent to the
demonstration.
This page is produced with the standard HTML render kit. If you
click the Next button at the bottom of the page it displays an
SVG page that is rendered with an SVG render kit. The SVG page
graphically illustrates the JSF life cycle.
If you click on any box that represents a life cycle phase (such
as Restore View Phase), it uses AJAX to generate a form
submission. In response, you should see an XUL page that
displays more detail about that JSF life cycle phase.
Below the JSF life cycle illustration is a larger box that
contains various buttons with labels such as Initial Request and
Validation Error. If you click on these buttons you'll see an
animated display of a specific process flow through the
life cycle phases (for instance, the process flow for handling
an initial request).
Let's take a look at some of the code for the demonstration.
Posting From The Client
First, let's examine the SVG page. Here is a snippet of the SVG
page written with JSF tags:
<%@ page contentType="image/svg+xml"%>
<%@ taglib uri="http://java.sun.com/jsf/svg" prefix="g" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
...
...
...
Notice the page directive that indicates the content type of the
page:
<%@ page contentType="image/svg+xml"%>
and the tag that indicates that SVG is the rendering technology
for the page:
You can learn more about the directives, tags, and attributes
that need to appear on a page that uses a render kit such as
SVG, in the article "Creating and Using a Custom Render Kit"
(http://java.sun.com/j2ee/javaserverfaces/reference/docs/customRenderKit.html).
In response to the information on the SVG page, the SVG render
kit on the server produces the following SVG markup:
This code is produced by various renderers in the SVG render
kit. The encodeBegin() method of the FormRenderer produces the
following ECMAScript file references:
and also the starting "form" group:
The action attribute in the starting "form" group is used to
identify this SVG element as a "form" element. The
element is widely used in SVG.
The ButtonRenderer and TextRenderer encode methods produce the
starting and ending group elements for the button control, and
the associated dimensions and label for the button control:
RestoreView
Note that the onclick method name, form_post, is determined from
the button control's parent form component:
public void encodeBegin(FacesContext context,
UIComponent component)
throws IOException {
...
UIComponent root = context.getViewRoot();
UIComponent myForm = component;
while (!(myForm instanceof UIForm) && root != myForm) {
myForm = myForm.getParent();
}
String formMethodName = myForm.getClientId(context) +
"_post(evt)";
writer.writeAttribute(
"onclick", formMethodName, "onclick");
The FormRenderer.encodeEnd() method writes out page state and
the ending group element for the form control:
_id4:_id6SVG
It also produces the JavaScript function that will collect the
post data and send the request:
The mapping is such that the request goes to the JSF controller.
The functions getForm, getPostData and sendRequest are all
defined in the http-svg.es ECMAScript file. (You can find the
http-svg.es file in the renderkits\src\script directory of
the example JSF application.) For example, here's part of the
definition of the getPostData function:
function getPostData(form, control) {
var formValues = new Array();
formValues[0] = new Object();
formValues[0].id = control.parentNode.id;
formValues[0].value = control.parentNode.id;
formValues[1] = new Object();
formValues[1].id = form.id;
formValues[1].value = form.id;
...
var postData = "";
for (var i=0; i requestHeaderMap =
event.getFacesContext().getExternalContext().
getRequestHeaderMap();
if (requestHeaderMap.get(XML_HTTP) == null) {
return;
}
// If we're dealing with an XMLHttpRequest...
// Get the URI and stuff it in the response header.
FacesContext context = event.getFacesContext();
String viewId = context.getViewRoot().getViewId();
String actionURL =
context.getApplication().getViewHandler()
.getActionURL(context, viewId);
HttpServletResponse response = (HttpServletResponse)
context.getExternalContext().getResponse();
response.setHeader("Cache-Control", "no-cache");
response.setHeader(VIEW_URI, actionURL);
}
...
}
The processResponse method gets the view identifier from the
response header. The client then loads that location. The
processResponse method is defined in the http-svg.es ECMAScript
file.
function processResponse() {
var request = getXMLHttpRequest();
if (request.readyState == 4) {
if (request.status == 200) {
var action =
request.getResponseHeader("VIEW-URI");
window.location.href = action;
return;
}
}
}
For more information using render kits in JSF, see the technical
article "Creating and Using a Custom Render Kit"
(http://java.sun.com/j2ee/javaserverfaces/reference/docs/customRenderKit.html).
Running the Sample Code
A sample package accompanies this tip that demonstrates the
techniques covered in the tip. You can deploy the sample package
on any web container that supports the Servlet 2.5 API,
JavaServer Pages (JSP) Technology 2.1, and JSF 1.2. You will
also need to use JDK 5. For the client (browser) you need
to use a Mozilla browser with built-in SVG support, such as
Firefox 1.5.
To install and run the sample:
1. If you haven't already done so, download GlassFish from the
GlassFish Community Downloads page
(http://java.sun.com/javaee/glassfish/getit.jsp). GlassFish
supports Servlet 2.5 and the JSP 2.1 "out of the box".
2. Download the sample package
(http://java.sun.com/developer/EJTechTips/download/ttfeb2006renderkits.zip)
for the tip and extract its contents. You should now see the
newly extracted directory as /renderkits,
where is the directory in which you
installed the sample package. For example, if you extracted
the contents to C:\ on a Windows machine, then your newly
created directory should be at C:\renderkits. The renderkits
directory contains the web archive, renderkits.war, for the
application, and the subdirectories src and web for viewing
source.
3. Start the GlassFish Application Server by entering the
following command:
/bin/asadmin start-domain domain1
where is the directory in which you
installed GlassFish.
4. Deploy the sample by copying
/renderkits/jsf-renderkits.war to
/domains/domain1/autodeploy
5. Open your browser to the URL:
http://localhost:8080/jsf-renderkits/. As mentioned
previously, you need to use a Mozilla browser, such as
Firefox 1.5, with built-in SVG support.
About the Author
Roger Kitain is the JavaServer Faces co-specification lead. He
has been extensively involved with server-side web technologies
and products since 1997. Roger started working on JavaServer
Faces technology in 2001, as a member of the reference
implementation team. He has experience with Servlet and JSP
technologies. Most recently, Roger has been involved with
different rendering technologies for JSF.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ACCESSING A SECURE ENTERPRISE BEAN FROM A JAVA CLIENT OR THROUGH
JAVA WEB START TECHNOLOGY
by Sreenivas Munnangi
This Tech Tip shows you how to access a secure Enterprise
JavaBeans component (also called an "enterprise bean") from
a standalone Java client and from a Java EE application client
that uses Java Web Start technology. The tip presents examples
that show these clients accessing a secure Management Enterprise
JavaBean (MEJB) that conforms to the J2EE Management
specification, JSR 77 (http://www.jcp.org/en/jsr/detail?id=77).
The J2EE Management specification provides a standard management
model for exposing and accessing management information,
operations, and attributes for J2EE components. An MEJB provides
interoperable remote access to the model from any standard J2EE
application.
The tip assumes that you are using either the Sun Java System
Application Server 8.x or a GlassFish build. You can download
Sun Java Application Server 8.2 or 8.1 as part of the J2EE 1.4
SDK from the J2EE 1.4 Downloads page
(http://java.sun.com/j2ee/1.4/download.html). GlassFish is an
open source Java EE-based application server. You can download
GlassFish from the GlassFish Community Downloads page
(http://java.sun.com/javaee/glassfish/getit.jsp).
Securing an Enterprise Bean
Security for J2EE application components such as enterprise
beans is provided by their containers. A container provides two
kinds of security: declarative and programmatic. Declarative
security expresses an application's security structure,
including security roles, access control, and authentication
requirements, in a form external to the application (that is, in
a deployment descriptor). Programmatic security is embedded in
an application and is used to make security decisions.
Programmatic security is useful when declarative security alone
is not sufficient to express the security model of an
application.
The mechanics of providing declarative security for these
resources involve mapping in a deployment descriptor individual
user identities or groups of user identities to a role, that is,
an abstract name for the permission to access a particular set of
resources in an application.
For example, the following elements in the Sun Java Application
Server deployment descriptor, sun-application.xml, maps the
group name "asadmin" to the security role "admin-role":
admin-roleasadmin
In addition, application servers such as Sun Java System
Application Server 8.x or GlassFish provide a way to associate
groups while creating a principal (that is, an individual user
identity that can be authenticated). This is done through the
asadmin create-file-user command (whose syntax is as follows):
asadmin create-file-user --port --host
--user --passwordfile
--authrealmname admin-realm --groups
After the mapping is in place, the container can determine if
a user has the needed permission to access a protected resource
such as a secure enterprise bean.
For standalone clients, declarative security is insufficient to
communicate with a secure enterprise bean. Instead you need to
provide programmatic security.
Programmatic Security for a Secure Enterprise Bean
Programmatic security for a standalone client requires an API
that provides programmatic login for the client. The Sun Java
System Application Server 8.x and GlassFish provide this API
through the class com.sun.appserv.security.ProgrammaticLogin.
This class exposes relevant methods to perform programmatic
login operations. The examples for this tip use the following
ProgrammaticLogin method to access an MEJB:
public Boolean login(String user, String password);
The login() method supplies a username and password. This
information is used to attempt to login to the default
authentication realm (that is, the collection of users and
groups that are controlled by the same authentication policy).
If the authentication succeeds, that is, the identity of the
user is verified, a security context is established
representing the user. This allows applications to
programmatically handle authentication.
Let's look at an example of programmatic security for a secure
enterprise bean. Accompanying this tip is a package that
contains the code for a standalone client that accesses a secure
MEJB. Here's a code snippet taken from the standalone client
code:
ProgrammaticLogin pm = new ProgrammaticLogin();
pm.login(userId, password);
Context initial = new InitialContext();
Object objref = initial.lookup("ejb/mgmt/MEJB");
ManagementHome home =
(ManagementHome)PortableRemoteObject.narrow(
objref, ManagementHome.class);
Management mejb = home.create();
String domain = mejb.getDefaultDomain();
The code first instantiates ProgrammaticLogin and then accesses
its login() method, providing the userId and password. The
login() method caches this information on the client side until
an enterprise bean method is called from the client. The code
then does the processing for access to the MEJB. It instantiates
the InitialContext, and then looks up the ManagementHome object
by specifying the JNDI name of MEJB home object, ejb/mgmt/MEJB.
You might ask how are the user's credentials processed? The
user credentials are passed to the server when the client calls
the enterprise bean's method. The method call is intercepted by
the IIOP/ORB infrastructure and the credentials are stored in
the security context. If the method being invoked needs
permission, the EJB container retrieves the user credentials
from the security context and validates them. If the credentials
are not valid, the method throws a security exception.
After the lookup and narrow methods succeed, a reference to the
Management object is created. This is done by calling the
ManagementHome's create() method -- this is part of the standard
enterprise bean invocation process. This is further described in
the section "Developing Clients Without the ACC"
(http://docs.sun.com/source/819-0079/dgacc.html#wp1022105) in
the Sun Java Application Server Platform Edition 8.1 Developer's
Guide.
Now it's time to try the sample applications. The samples require
you to have access to ant or asant that is included in GlassFish
and Sun Java Application Server 8.1 or 8.2.
Running the Standalone Client Example
The standalone client works directly with a predeployed system
application. To install and run the standalone client example:
1. Ensure that either Sun Java System Application Server 8.2 or
GlassFish is installed. These instructions use GlassFish,
which you can download from the GlassFish Community Downloads
page (http://java.sun.com/javaee/glassfish/getit.jsp).
2. Download the sample package
(http://java.sun.com/developer/EJTechTips/download/ttfeb2006stand_alone_client.zip)
for the tip and extract its contents. You should now see the
newly extracted directory as
/stand_alone_client, where
is the directory in which you installed
the sample package. For example, if you extracted he contents
to C:\ on a Windows machine, then your newly created directory
should be at C:\stand_alone_client. The stand_alone_client
directory contains the source code for the client,
MEJBClient.java, a build file, build.xml, and an output file,
output.txt.
3. Start the GlassFish Application Server by entering the
following command:
/bin/asadmin start-domain domain1
where is the directory in which you installed
GlassFish.
4. Modify the section of the build.xml
file as appropriate for your application server installation.
You don't have to edit any other part of build.xml.
5. Create a default realm user using the asadmin command line
utility as follows (the command is shown on multiple lines
for formatting purposes):
/bin/asadmin create-file-user
--host --port
--user --passwordfile
--groups
You will need to create a password file that includes the
following lines:
AS_ADMIN_PASSWORD=
AS_ADMIN_USERPASSWORD=
and pass this file with the --passwordfile option.
Make sure that the values for realm.user.id and
realm.user.password match the values given in build.xml, and
the value for security-role-mapping-group-name matches the
value given in sun-application.xml as described earlier in
the tip. Substitute other values appropriately before running
the command.
Use the asadmin command 'list-file-users' to check that you
successfully created the default realm user. For further
information about the asadmin command, enter asadmin help on
the command line.
6. Compile and run MEJBClient.java.
> cd stand_alone_client
> ant run
You should see output similar to the following.
run:
[java] Jan 17, 2006 2:48:49 PM com.sun.corba.ee.spi.
logging.LogWrapperBase doLog
[java] INFO: "IOP00710299: (INTERNAL) Successfully
created IIOP listener on the specified host/port:
all interfaces/52185"
[java] ***Got the MEJB!!
[java] ***MEJB default domain = DefaultDomain
...
BUILD SUCCESSFUL
The content of the output.txt file contains the complete output.
Running the Java Web Start Technology Example
This example uses a Java EE application client that will be
deployed to the application server. As is the case for the
previous example, this example uses GlassFish. This example has
been tested to work with JDK 5.0 or JRE 5.0 only.
To install and run the example:
1. Download the sample archive
(http://java.sun.com/developer/EJTechTips/download/ttfeb2006acc-mejbClient.jar).
2. Deploy the application client using the deploy command:
/bin/asadmin deploy --host
--port --user
--passwordfile
ttfeb2006acc-mejbClient.jar
3. Open your application server log (for example,
/domains/domain1/log/server.txt). Somewhere
in the log you should see a line like the following:
[#|2006-01-17T15:10:21.112-0800|... Java Web Start
services started for stand-alone app client ...
name=acc-mejbClient, context root=/ ttfeb2006acc-mejbClient,
module name=|#]
The URL for accessing the application client using Java Web
Start is comprised of the default GlassFish instance URL and
the context root (which is the "Name=" value in the line shown
above). So, for a default instance Glassfish URL of
http://8080 and a context root of acc-mejbClient, the URL for
accessing the application client using Java Web Start is
http://localhost:8080/ttfeb2006acc-mejbClient.
4. This example displays output in the Java Console. To see the
output, you need to configure Java Web Start to show the Java
Console. To configure the Java Console option, first
determine the location of Java Web Start (this is usually
/bin/javaws or /bin/jws).
Then invoke Java Web Start and turn on the 'show console'
option. Here is how to determine the location of Java Web
Start based on the browser type and the operating system:
o Internet Explorer and FireFox on Windows:
- Click on .
- In the 'My Computer' window, select the menu item
then .
- In the 'Folder Options' window, select the
tab.
- Select the item with the extension 'JNLP'.
- Click and note the value for
'Application used to perform action', which is the Java
Web Start location.
o Netscape on Windows/Solaris:
- Invoke the Netscape browser.
- Select the menu item then .
- Expand node and select .
You should see a list of File Types on the right.
- Select application/x-java-jnlp-file.
- Click and note the value for 'Open it with', which
is the Java Web Start location.
Invoke Java Web Start in a command window using the Java Web
Start location determined above. This brings up 'the 'Java
Application Cache Viewer' window.
Then:
o In the 'Java Application Cache Viewer' window select the
menu item , then . This should display
'Java Control Panel'.
o Select the .
o Expand and select . Click
the button.
You can exit Java Web Start by selecting the menu item
, then .
5. Open a web browser and enter the URL determined in step 3.
This should launch Java Web Start. You should see prompts
for a userID and password. After you respond to the prompts,
the application client should display output similar to the
output in the standalone client example.
About the Author
Sreenivas Munnangi is a senior member of the Sun Java
Application Server Administration and Management team. He has
worked in the J2EE group for the last three years. He was a key
contributor to the Application Server Enterprise Edition design
and implementation. His earlier experience was in the areas of
eCommerce applications, web applications, and N-tier application
architecture.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GET THE PREVIEW OF THE JAVA EE 5 SDK!
On February 21, 2006, Sun announce availability of the preview
of Java EE 5 SDK
(http://java.sun.com/javaee/downloads/index.html), which
includes Application Server Platform Edition 9 beta. This
release is a simultaneous release with NetBeans Enterprise Pack
5.5 (http://www.netbeans.org/community/releases/55/index.html),
providing developers with the next generation Java platform and
tools for building and deploying enterprise Java and
Service-Oriented Architecture (SOA)-ready applications to solve
business challenges. Sun led the development of these
breakthrough technologies, incorporating key contributions from
the open source GlassFish Project and NetBeans.org communities
to create an innovative, robust, and scalable development
platform that is ideal for enterprise Web 2.0 development.
. . . . . . . . . . . . . . . . . . . . . . .
If you have your own Tech Tip that you would like to share with
others, you're encouraged to post it in an appropriate Sun
Developer Network forum (http://forum.java.sun.com/index.jspa).
Please read our Terms of Use and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://developers.sun.com/dispatcher.jsp?uid=6910008
PRIVACY STATEMENT:
Sun respects your online time and privacy (http://sun.com/privacy).
You have received this based on your e-mail preferences. If you
would prefer not to receive this information, please follow the
steps at the bottom of this message to unsubscribe.
* FEEDBACK
Comments? Send your feedback on the Enterprise Java Technologies
Tech Tips to:
http://developers.sun.com/contact/feedback.jsp?category=sdn
* SUBSCRIBE/UNSUBSCRIBE
Subscribe to other Java developer Tech Tips:
- Core Java Technologies Tech Tips. Get tips on using core
Java technologies and APIs, such as those in the Java 2
Platform, Standard Edition (J2SE).
- Wireless Developer Tech Tips. Get tips on using wireless
Java technologies and APIs, such as those in the Java 2
Platform, Micro Edition (J2ME).
To subscribe to these and other JDC publications:
- Go to the Sun Developer Network - Subscriptions page,
(https://softwarereg.sun.com/registration/developer/en_US/subscriptions),
choose the newsletters you want to subscribe to and click
"Submit".
- To unsubscribe, go to the Subscriptions page,
(https://softwarereg.sun.com/registration/developer/en_US/subscriptions),
uncheck the appropriate checkbox, and click "Submit".
- To use our one-click unsubscribe facility, see the link at
the end of this email:
- ARCHIVES
You'll find the Enterprise Java Technologies Tech Tips archives at:
http://java.sun.com/developer/EJTechTips/index.html
- COPYRIGHT
Copyright 2006 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.
This document is protected by copyright. For more information, see:
http://java.sun.com/developer/copyright.html
Enterprise Java Technologies Tech Tips
February 25, 2006
Trademark Information: http://www.sun.com/suntrademarks/
Java, J2SE, J2EE, J2ME, and all Java-based marks are trademarks
or registered trademarks of Sun Microsystems, Inc. in the
United States and other countries.