Académique Documents
Professionnel Documents
Culture Documents
March 2008 Volume I Issue IX We are back here with the Holi (Mar 2008) issue of
Java Jazz-up. The current edition is specially designed
for the sprouting technocrats. This issue highlights the
interesting Java technologies especially for the
“Optimism with determination lets you
hit the goal harder” beginners.
Santosh Kumar
Amardeep Patel
“Free”
12 Introduction to XSL | XSL stands for EXtensible Stylesheet Language. The World Wide Web
Consortium (W3C) started to develop XSL because there was a need for an XML-based
Stylesheet Language. Thus it is a language for expressing Stylesheets.
18 JAXP API using DOM Parser |In the previous issue of Java Jazz Up, you have read about
the JAXP APIs and learned how an XML document is parsed using the serially access mode
(SAX) parser.
24 Struts 1.1 | This tutorial provides you a better understanding to develop a robust application
using Jakarta Struts Framework.
36 Design Pattern | These types of design patterns are used as templates. These design patterns
are used in such conditions when we need a parent class having one or more methods to be
implemented by their child classes.
38 Visitor Design Pattern| The design pattern provides additional functionality to a class. The
Visitor pattern allows us to create an external class to act on data in other classes.
40 Dojo Tutorial| Dojo: Dojo is an Open Source JavaScript toolkit libraries that provides a
simple API(Application Programming Interface) for building the serious applications in less time.
45 Hibernate Query Language| In the previous issue of Javajazzup you learned about Hibernate
Query Language and its different kind of clauses. Lets quickly focus on the overview of HQL.
52 Using the Desktop class to launch a URL with default browser in Java| This article describes
the new Desktop API, which allows Java applications to interact with the default applications
associated with specific file types on the host platform.
55 Advertise with Us | We are the top most providers of technology stuffs to the java
community. Our technology portal network is providing standard tutorials, articles, news
and reviews on the Java technologies to the industrial technocrats.
Load Balancing Tomcat with Apache Apache Geronimo 2.1 Released -- Java EE
5 server
Tomcat is the most popular application server
that is used for hosting web applications. Recently, Apache Geronimo team announced
Apache is also popular web server that enables the release of Apache Geronimo 2.1.
services such as https encryption and Apache Geronimo 2.1 is developed on the Java
decryption, URL rewriting etc. Apache also EE 5 certified 2.0 release of Geronimo. Geronimo
serves as a load balancer for balancing the load 2.1 provides the following new features:
between several Tomcat application servers.
Custom Server Assemblies:
Profiles in the Java EE 6 Platform Geronimo 2.1 greatly simplifies the build-time
customization. It allows the users to follow a
Profiles are an attempt to modularize the function-centric approach, choosing the desired
different parts in Java EE so that the set of server plugins (e.g. Web
technologies can be combined in a product. This Container+JMS+Deploy capabilities).
will help in solving the issue of compatibility
requirements in order to provide the natural Flexible Administration Console:
approach by spanning the multiple technologies. Now the Geronimo Administration Console
E.g: Java EE 5 specification contains matches the dynamic capabilities of the server
requirements to which the servlet containers runtime.
must honor with respect to the availability of
JTA. The idea behind Java EE 6 is to rewrite Gshell:
such type of requirements, which can be applied It is a command-line processing environment
to any profiles and implementations, concerning required to execute Geronimo administrative
the relevant combination of technologies. E.g: commands.
any product corresponding to any Java EE
profile including servlets as well as JTA will have WADI Clustering:
to be sincere to those requirements. The logic Now WADI enables to cluster Web Applications
includes two components: the first one is that, for both Tomcat and Jetty-based configurations
we think that the Java EE requirements add of Geronimo.
significant value to standalone technologies, as
testified e.g. by the large number of servlet Comet: Reverse Ajax for streaming data
containers implementing JTA so that it is from the server
compatible with what Java EE mandates;
simultaneously, calling out the requirements Comet is a technology that pushes the events
that helps to ensure that applications that from the server side to a browser client. It
target profiles will work on the full platform. avoids the issues related to having a browser
poll a server to check for new events. Comet
This whole phenomena makes profiles more looks at the nature of real-time events, such
than just collections of independently tested as those occurring in the stock market or in
technologies, as those technologies will be tied sporting matches. Rich-client technologies such
together in interesting ways, deliver more as Flash or Java this process seems original
functionality than they would on their own. particularly since these last technologies have
combined mechanisms such as remoting and
steaming that deals with asynchronous
requests from both server to client and vice
versa. But Comet is all about concerning the
last process having the same vanilla
technologies like Ajax namely JavaScript and
It provides a bug tree. User can select an item Java so it is very expandable. It is available for
in the bug tree and may get an explanation in Windows and Linux environment.
the text panel.
RTE3 provides some new capabilities like multi-
FindBugs quickly provides an overview of items threaded, multi-processor aware, easy socket
required by the programmer in the java code. communication, MP3 and MPEG capabilities,
access dlls, shell scripting, unlimited run time
New Networking features with PPF grid editing/ scripting, multiple windows, multiple
toolkit: Releases in v1.1 pages, grouping, group editing, built-in
database access, unlimited undo/redo etc.
Recently JPPF i.e. Java Parallel Processing
Framework was released with version 1.1. Theory and Practice of Ropes for Java String
New features of JPPF: Manipulations
Several bugs are fixed Java language’s default String and StringBuilder
classes poorly serves to large quantities of data
• Provides a new networking tool i.e. the manipulated by the Systems. A rope data
TCP port multiplexer that allows it even structure may be a better alternative. A rope
to work in the fire walled environments implementation for the Java platform; provides
• Addition of new node monitoring feature pointers for effective use of the library and
• PPF grid takes no time to be up and run defines performance issues. Iteration over a flat
Rope (a Rope having depth of 1) is much faster
• provides highly scalable, distributed
than pulling data character by character from a
framework for the execution of Java String is the most considerable thing for an
tasks. enterprise Java developer. If you do not need
• Better graphical and programmatic tools to do this, then Ropes are completely
• reliability through redundancy meaningless to you.
• failover recovery capabilities
Apache Tuscany SCA Java 1.1 -incubating Carlos Perez: Top Five Java Technologies to
released Learn in 2008
Apache Tuscany team has announced the Carlos Perez has posted a list of the top five
release of the Java SCA project of version 1.1. Java-based technologies to learn in 2008.
It provides a runtime environment based on
SCA (Service Component Architecture), which They are:
is a set of specifications to simplify SOA
application development, standardized by • OSGi, a specification for dynamic
OASIS. modules for Java
• The Java Content Repository spec,
This release has added features like JMS binding, appeared first time in the JCP in
improved policy support and an implementation February 2002
extension for representing client side JavaScript
• Google Web Toolkit, first version
applications as SCA components.
released in May, 2006
New Run Time Editor 3 (RTE3) for Java Released • Groovy, first version released in May,
2004
The new RTE3 is the control system interface • Cloud computing, a concept designed
design environment that has been designed for around the use of virtual servers, or
network control in java. RTE3 is fully written in distributed computing without using
EJB
However all the above technologies are holder having 220 new features, improvements and
technologies perhaps are “coming of age” and bug fixes on the basis of feedback and
became matured to the point of contributions from the user community.
recommendation. But definitely all these
technologies are still useful as OSGi works as Sun Microsystems has agreed to buy MySQL
module system behind Eclipse, while Groovy is AB for $1B
continuously accepting by the developer with
its formal specification and continually improved Sun Microsystems has acceded to buy MySQL
releases, GWT is already mature and stable, AB for $1B, by providing additional leverage in
and cloud computing is becoming more and the open source community and also allowing
more famous in this growing marketplace. access to MySQL to its larger corporations. The
grand question that arises is that: what does
On the other hand, JCR and cloud computing this mean in the long term? Sun already offers
are the least accepted of these technologies, a small-scale database as compared to
and vendors are trying to address that, with compared to 'large offerings' like Oracle9 and
competitions to spur awareness or active IMS. Is Sun considerably looking for an
community involvement. additional revenue stream from MySQL AB's
customers, or shifting away from JavaDB/
Derby?
Apache Jackrabbit 1.4 released
Apache Jackrabbit 1.4 is the latest and greatest JVM Lies: The OutOfMemory Myth
version of Content Repository for Java
Technology API (or JCR in short) conforming The concept "JVM Lies: The OutOfMemory Myth,"
that Apache Jackrabbit 1.4 provides the full open tells about the happening when a JVM throws
source implementation of JCR. an OutOfMemoryError – the developers who
have encountered it have noticed, it seems like
JCR is a standard API to access the content it's out of memory, but it always doesn't look
repositories in a uniform manner and is specified like it, and throws more RAM at the JVM may
in JSR 170. A content repository is a hierarchical help, but that's the wrong solution.
representation storage media similar to an
advanced file system supporting different levels
of content structure and granularity. The API Shades of HotJava: LoboBrowser, a web
provides various functionalities such as browser in Java
browsing, modifying, and searching the content
in full text search in a content repository. JavaLobby have introduced a LoboBrowser, a
Standard allows advanced features like fully Java web browser. Although it is not
versioning, observation, locking, and XA HotJava, yet it runs JavaScript if memory is
transactions as optional. available while HotJava did not. It is big deal to
develop a workable and installable fully Java
Apache Jackrabbit provides one of the best JCR based browser even if it can't render TSS very
implementations and was also used as the well. It also includes a rendering engine, Corba
reference implementation of JSR 170. Apache that can be used to watch DOM of a page even
Jackrabbit 1.4 is a stable and feature-rich after JavaScript has been run over it. Integration
content repository aimed having a wide range into IDEs, can be seen to anyone. E.g providing
of content applications including Magnolia, browser support without allowing explicit
OpenKM, Hippo, and Mindquarry. Jackrabbit browser tie-ins.
provides implementation for all the mandatory
and optional JCR features as well as a number
of extensions and related JCR tools.
New Atlanta has released ServletExec 6.0 for Every client/server application may have
download and purchase: different remoting requirements, but the main
criteria include performance. At least, you would
http://www.newatlanta.com/products/ to know that how much performance you are
servletexec sacrificing in order to fulfilling other
requirements.
Key new features contained in ServletExec
6.0 are: Java Remoting: Protocol Benchmarks examines
Java's RMI/JRMP, Spring’s HttpInvoker, Oracle's
• Java Servlet API 2.5 ORMI (with and without HTTP tunneling enabled),
• JavaServer Pages (JSP) 2.1 and three flavors of Apache XML-RPC and
• JSP Standard Tag Library (JSTL) 1.2 Caucho's Hessian, Hessian 2 and Burlap. Two
graphs are added named as a small list having
• JavaServer Faces (JSF) 1.2
250 items or less and a large list having from
• JavaMail 1.4 500 to 5000 items. The two graphs are
• Java Web Services support through consistent (a good sign for the libraries involved)
JAX-WS 2.0 - and (surprise!) the binary protocols did far
• Updated Web Server support (IIS 7, better on average than the XML-based
Apache 2.2.x, SJSWS 7.0u1) protocols.
• Updated OS support (Windows 2008
Vista, Solaris 10, AIX 5.3, HP-UX Article: Integrating Java and Erlang
11v2)
• AMD/Intel 64-bit support (x64) Enterprise software development world
introduces a new face: Erlang. Erlang is nothing
Additional improvements are: but a functional programming language having
native constructs for concurrency and reliability.
• Improved Performance Erlang is a programming language and Jinterface
is an open source component of Ericsson's Open
• IPv6 Protocol support
Telecom Platform having capability to integrate
• Improved Administrative Interface Java with Erlang.
Before processing can begin, the part of the If the selected node contains all elements in
XML document with the information to be copied the root, all of the ‘Employee-Detail’ elements
to the output must be selected with an XPath will be selected.
expression. The selected section of the
document is called a node and is normally <xsl:for-each select=”Employee”>
selected with the match operator. <xsl:value-of select=”Emp_Id”/>
<xsl:value-of select=”Emp_Name”/>
In the above statements, the <xsl:template> </xsl:for-each>
element defines a template. The match=”/”
attribute associates the template with the root Introduction to XSLT
node of the XML source document. Another
approach is to match the document element Extensible Stylesheet Language
(the element that includes the entire document). Transformations (XSLT) is an XML-based
language that transforms an XML documents
The <xsl:apply-templates> Element and generates output into a different format
The <xsl:apply-templates> element applies a such as HTML, XML or another type of
template to the current element or to the document that is recognized by a browser like
current element’s child nodes. WML, and XHTML.
If we add a select attribute to the <xsl:apply-
templates> element it will process only the child XSLT is an extension of XSL, which is a
element that matches the value of the attribute. stylesheet definition language for XML.
We can use the select attribute to specify the With XSLT you can add/remove elements and
order in which the child nodes are processed. attributes to or from the output file. You can
also rearrange and sort elements, and make
The <xsl:value-of> Element decisions about which elements to hide and
The <xsl:value-of> element can be used to display.
extract the value of an XML element and add it
to the output stream of the transformation. XSLT uses XPath to find information in an XML
For example, the given expression will select document. XPath is used to navigate through
the value of Emp_Id attribute of the specified elements and attributes in XML documents.
element and write to the output:
<xsl:value-of select=”Emp_Id”/>
or
<xsl:value-of select=”Employee-Detail/
Employee/Emp_Id”/>
the Xerces parser, and the .jar file for the Xalan
The following figure shows the working stylesheet engine itself. The .jar files are named
process of XSLT: xercesImpl.jar, and xalan.jar.
used to create
input and output
objects from an
I/O stream.
<Employee-Detail>
XML parsers can be validating or nonvalidating. DOM is very useful when the document is small.
Validating parser checks the contents of a DOM reads the entire XML structure and holds
document against a set of specific rules i.e. in the object tree in memory, so it is much more
what order they must appear. These rules CPU and memory intensive. The DOM is most
appear in an XML document either as an optional suited for interactive applications because the
XML structure called a document type definition, entire object model is present in memory, where
or DTD, or as an XML Schema. it can be accessed and manipulated by the user.
Nonvalidating parsers are smaller and faster, The Document Object Model implementation is
but they do not check documents against the defined in the following packages:
DTD. They only check whether the XML
document is structurally well formed or not. JAXP APIs Description
Parsing XML Documents org.w3c.dom Defines the Document
class (a DOM) along with
To manipulate an XML document, XML parser is the classes for all of the
needed. The parser loads the document into components of a DOM.
the computer’s memory. Once the document is
loaded, its data can be manipulated using the javax.xml.parsers The JAXP APIs provide a
appropriate parser. common interface for
different vendors’ to use
In this section, we will discuss about DOM SAX and DOM parsers.
parsers of JAXP APIs and for accessing XML
documents in random access mode. The The DOM API is defined in org.w3c.dom package
specifications to ensure the validity of XML of JAXP-APIs. The DOM API is easier to use. It
documents are DTDs and the Schemas. provides a tree structure of objects. The DOM
API is used to manipulate the hierarchy of
DOM (Document Object Model) application objects it encapsulates.
An finally we will print the DOM tree on the //create child element
console with the following code: Element childElement =
doc.createElement(“Child”);
TransformerFactory tranFactory = //Add the atribute to the child
TransformerFactory.newInstance(); childElement.setAttribute(“attribute1”,”The
Transformer aTransformer = value of Attribute 1");
tranFactory.newTransformer(); root.appendChild(childElement);
Source src = new DOMSource(doc);
Result dest = new TransformerFactory tranFactory =
StreamResult(System.out); TransformerFactory.newInstance();
aTransformer.transform(src, dest); Transformer aTransformer =
tranFactory.newTransformer();
Here is the full source code of
CreateDomXml.java Source src = new DOMSource(doc);
Result dest = new
import org.w3c.dom.*; StreamResult(System.out);
import javax.xml.parsers.DocumentBuilder;
import
Download the Program To parse the xml file you need the
DoucnemtBuilderFactory and DocumentBuilder.
Lets see another example that helps you to The object of the DocumentBuilder uses parse
retrieve the elements as well as their method and determines that the parsed xml is
corresponding data from the DOM tree. well formed or not. If xml document is will-
In this example you need a well-formed XML formed, it will display a message “emp.xml is
file that has some data (Emp_Id, Emp_Name well-formed!” Otherwise prints “emp.xml isn’t
and Emp_E-mail in our case). well-formed!”.
Here is the XML File (emp.xml) to be parsed: Now, lets see the sample code to retrieve the
elements from the xml file:
<?xml version = “1.0” ?>
<Employee-Detail> NodeList list =
<Employee> doc.getElementsByTagName(“*”);
<Emp_Id> E-001 </Emp_Id> for (int i=0; i<list.getLength(); i++){
<Emp_Name> Vinod </Emp_Name> // Get element
<Emp_E-mail> Vinod1@yahoo.com </ Element element =
Emp_E-mail> (Element)list.item(i);
</Employee> //Source src = new
<Employee> DOMSource(element);
<Emp_Id> E-002 </Emp_Id> System.out.println(element.getNodeName());
<Emp_Name> Amit </Emp_Name> }
<Emp_E-mail> Amit2@yahoo.com </Emp_E-
mail> The doc object helps in create a NodeList
</Employee> through the getElementByTagName()
<Employee> method. The NodeList helps you in getting the
<Emp_Id> E-003 </Emp_Id> length and Element. For getting the node name
<Emp_Name> Deepak </Emp_Name> you use the getNodeName() method.
<Emp_E-mail> Deepak3@yahoo.com </
Emp_E-mail> Now, lets see the sample code to retrieve the
</Employee> data from the elements:
</Employee-Detail>
//Create transformer
Transformer tFormer = NodeList list =
TransformerFactory.newInstance().newTransformer(); doc.getElementsByTagName(“*”);
// Output text type for (int i=0; i<list.getLength(); i++){
// Get element
tFormer.setOutputProperty(OutputKeys.METHOD, Element element =
“text”); (Element)list.item(i);
//Write the document to a file //Source src = new
Source source = new DOMSource(element);
DOMSource(doc); System.out.println(element.getNodeName());
Result result = new }
StreamResult(System.out); // Create transformer
tFormer.transform(source, result); Transformer tFormer =
TransformerFactory.newInstance().newTransformer();
The setOutputProperty method of the // Output text type
Transformer class set the output key as a text
to print the data on console. Then the tFormer.setOutputProperty(OutputKeys.METHOD,
transform() method displays the data source “text”);
and the given destination. This program uses // Write the document to a file
the “System.out” to display the data on the Source source = new DOMSource(doc);
console. Result result = new
StreamResult(System.out);
Here is full source code of GetDomData.java: tFormer.transform(source, result);
import java.io.*; }
import org.w3c.dom.*; else{
import org.xml.sax.*; System.out.println(“File not found!”);
import javax.xml.parsers.*; }
import javax.xml.transform.*; }
import javax.xml.transform.dom.DOMSource; catch (Exception e){
import System.err.println(e);
javax.xml.transform.stream.StreamResult; System.exit(0);
}
}
public class GetDomData{ }
static public void main(String[] arg) {
try{
BufferedReader bf = new Output of the Program:
BufferedReader(new
InputStreamReader(System.in)); C:\nisha>javac GetDomData.java
System.out.print(“Enter XML file name:
“); C:\nisha>java GetDomData
String xmlFile = bf.readLine(); Enter XML file name: emp.xml
File file = new File(xmlFile); emp.xml is well-formed
if (file.exists()){ Employee-Detail
DocumentBuilderFactory factory = Employee
DocumentBuilderFactory.newInstance(); Emp_Id
DocumentBuilder builder = Emp_Name
factory.newDocumentBuilder(); Emp_E-mail
Document doc = builder.parse(xmlFile); Employee
System.out.println(xmlFile + “ is well- Emp_Id
formed “); Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
E-001
Nisha
nisha1@yahoo.com
E-002
Amit
amit2@yahoo.com
E-003
Deepak
deepak3@yahoo.com
C:\nisha>
<html:base/> input=”/pages/MappingDispatchAction.jsp”
</head> scope=”request”
<body> validate=”false”>
<p align=”center”><font size=”5" <forward name=”add” path=”/pages/
color=”#800000">Welcome to the Simple MappingDispatchActionAdd.jsp” />
Struts Application</font></p> </action>
<div align=”center”> <action
<center> path=”/MappingDispatchAction”
<table border=”1" cellspacing=”1" type=”roseindia.net.MappingDispatch_Action”
width=”400"> parameter=”edit”
<li> input=”/pages/
<html:link page=”/pages/ MappingDispatchAction.jsp”
MappingDispatchAction.jsp”>Demo of a scope=”request”
Simple Struts Application</html:link> validate=”false”>
</li> <forward name=”edit” path=”/pages/
</table> MappingDispatchActionEdit.jsp” />
</center> </action>
</div> <action
</body> path=”/MappingDispatchAction”
</html:html> type=”roseindia.net.MappingDispatch_Action”
parameter=”search”
struts-config.xml input=”/pages/
MappingDispatchAction.jsp”
<?xml version=”1.0" encoding=”ISO-8859-1" scope=”request”
?> validate=”false”>
<!DOCTYPE struts-config PUBLIC “-//Apache <forward name=”search” path=”/
Software Foundation//DTD Struts pages/MappingDispatchActionSearch.jsp”/>
Configuration 1.2//EN””http:// </action>
jakarta.apache.org/struts/dtds/struts- <action
config_1_2.dtd”> path=”/MappingDispatchAction”
<struts-config> type=”roseindia.net.MappingDispatch_Action”
<action-mappings> parameter=”save”
<action path=”/LookupDispatchAction” input=”/pages/
type=”roseindia.net.LookupDispatch_Action” MappingDispatchAction.jsp”
parameter=”parameter” scope=”request”
input=”/pages/LookupDispatchAction.jsp” validate=”false”>
scope=”request” <forward name=”save” path=”/pages/
validate=”false”> MappingDispatchActionSave.jsp” />
<forward name=”add” path=”/pages/ </action>
LookupDispatchActionAdd.jsp” /> <forward </action-mappings>
name=”edit” path=”/pages/ </struts-config>
LookupDispatchActionEdit.jsp” />
<forward name=”search” path=”/pages/ web.xml
LookupDispatchActionSearch.jsp”/>
<forward name=”save” path=”/pages/ <?xml version=”1.0" encoding=”ISO-8859-
LookupDispatchActionSave.jsp” /> 1"?>
</action> <!DOCTYPE web-app PUBLIC “-//Sun
<action Microsystems, Inc.//DTD Web Application 2.2/
path=”/MappingDispatchAction” /EN” “http://java.sun.com/j2ee/dtds/web-
type=”roseindia.net.MappingDispatch_Action” app_2_2.dtd”>
parameter=”add” <web-app>
CheckValidUser.java
package net.javajazzup;
import
com.opensymphony.xwork2.ActionSupport;
import java.util.*;
validuser.jsp
Create a login jsp page as shown:
<%@ taglib prefix=”s” uri=”/struts-tags” %>
login.jsp
<html>
<%@ taglib prefix=”s” uri=”/struts-tags” %> <head>
<title>Actionerror Tag Example</title>
<html> <body>
<head> <h1>
<title>Actionerror Tag Example</title> <s:actionmessage />
<body> </h1>
<s:form action=”login” method=”POST”> </body>
<s:textfield label=”User Name” </html>
name=”username” size=”20" maxlength=”10"
/> You will see the output of the login.jsp as shown
<s:password label=”Password” below. Put correct user name and password.
name=”password” size=”20" maxlength=”10"
/>
<s:submit value=”Submit” />
</s:form>
</body>
</html>
error.jsp
<html>
</head>
<body>
<s:url id=”test” value=”/pages/
nonformTags/mask.jsp” />
<s:div
id=”one”
theme=”ajax”
href=”%{test}”>
You will get the following output: </s:div>
</body>
</html>
mask.jsp
<html>
<head>
<title>Enter first and last name</title>
2. Div (Ajax Tag) tag Example <s:head theme=”ajax” debug=”false”/>
</s:div> fielderrorTag.jsp</result>
</body> <result>/pages/nonformTags/
</html> validuser.jsp</result>
</action>
Output:
Develop an action class using
addFieldError(String fieldName, String
errorMessage) method. This method adds an
error message for a given field to the
corresponding jsp page.
CheckField.java
package net.javajazzup;
import
com.opensymphony.xwork2.ActionSupport;
loginFielderrorTag.jsp
Create a jsp page that will display your field Enter the wrong user name and correct
error messages (when fails to logged-in) password in the login page. You will get the
using the empty <s:fielderror/> tag as following output:
shown:
fielderrorTag.jsp
<html>
<head>
<title>Fielderror Tag Example!</title>
<body>
Enter incorrect values in both fields of the login
<h1><s:fielderror /></h1>
page. You will get the following output:
<a href=”/struts2nonformuitags/
javajazzup/fieldError.action”>Go Back</a>
</body>
</html>
tab).
<s:div id=”three” label=”Tab 3"
To use tabbedPanel tag, the head tag must be theme=”ajax”>
included on the jsp page and must be Third Panel.<br>
configured for performance or debugging JavaJazzUp
purposes. However, If you want to use the </s:div>
cookie feature then you must provide a unique
id for the tabbedpanel component. This is used </s:tabbedPanel>
for identifying the name of component that is
stored by the cookie. </td>
</tr>
Add the following code snippet into the </table>
struts.xml file. </body>
</html>
struts.xml
Output:
<action name=”tabbedPanel”>
<result>/pages/nonformTags/ When you run the above example, you get the
tabbedpanel.jsp</result> output as:
</action>
tabbedpanel.jsp
<html>
<head>
<s:head theme=”ajax” debug=”true”/>
</head>
<body>
<table border=”1" width=”30%”>
<tr> 5. tree and treenode (Ajax Tag) tags
<td width=”100%”> Example
<s:tabbedPanel id=”test” > In this section, you will learn about the tree
and treenode tags. These both work with the
<s:div id=”one” label=”Tab 1" Ajax support.
theme=”ajax” labelposition=”top” >
First Panel.<br> tree: This is a tree widget with AJAX support.
Tabbed Panel Example<br> Normally this tag uses the “id” attribute. The
JavaJazzUp “id” attribute is required if the
</s:div> “selectedNotifyTopic” or the “href” attribute is
going to be used.
<s:div id=”two” label=”Tab 2"
theme=”ajax”> treenode: This is a tree node which renders a
Second Panel.<br> tree node within a tree widget with AJAX
JavaJazzUp support. The following of the two combinations
</s:div> are used depending on the requirement like
the tree is needed to be constructed dynamically
or statically. <body>
<s:tree theme=”ajax” id=”root”
Dynamically label=”Root”>
<s:treenode theme=”ajax” id=”child1"
• id - This is an id of tree node. label=”<b>Child 1</b>” />
• title - This is as like a label to be <s:treenode theme=”ajax”
displayed for the tree node id=”subchild1" label=”SubChild 1">
<s:treenode theme=”ajax”
Statically id=”subchild2" label=”SubChild 2" />
<s:treenode theme=”ajax”
• rootNode - This is the parent node id=”subchild3" label=”SubChild 3" />
</s:treenode>
where the tree is derived form.
<s:treenode theme=”ajax” id=”child2"
• nodeIdProperty - This is the current
label=”<b>child 2</b>” />
tree node’s id.
</s:tree>
• nodeTitleProperty - This is the current </body>
tree node’s title. </html>
• childCollectionProperty - This is the
current tree node’s children. Output:
Add the following code snippet to the struts.xml When you run the above example, you get:
file.
struts.xml
<action name=”TreeNode”>
<result>/pages/nonformTags/
treenode.jsp</result>
</action>
treenode.jsp
<html>
<head>
<s:head theme=”ajax” debug=”true”/>
</head>
System.out.println(“\nChecking “ + System.out.println(addanytype
Clientdtls.getName()+ “ (client) loan details. Number.addnumbers(d1,d2));
“); System.out.println((float)addanytype
Clientdtls.checkdetails(); Number.addnumbers(f1,f2));
System.out.println((long)addanytype
LoanApplication Clientloandtls = new Number.addnumbers(l1,l2));
LoanApplication(“Aqueel”); System.out.println((int)addanytype
System.out.println(“\nChecking “ + Number.addnumbers(i1,i2));
Clientloandtls.getName()+ “ (client) loan System.out.println((short)addanytype
details. “); Number.addnumbers(s1,s2));
Clientloandtls.checkdetails(); System.out.println((byte)addanytype
} Number.addnumbers(b1,b2));
} }
}
Best example of template design pattern is
method overloading and method overriding. For
example,
AddAnyTypeOfNumber
addanytypeNumber = new
AddAnyTypeOfNumber();
Dojo: Dojo is an Open Source JavaScript toolkit The following example we are going to create a
libraries that provides a simple API(Application button “Hello World!”. To create a button in dojo
Programming Interface) for building the serious you need to a Button Widget that contains
applications in less time. The main functionality three visual states as: mouseOut, mouseOver
of Dojo is to make HTTP requests and receive and mouseDown. To follow the following steps
their responses. It also provides packages for for creating a dojo button widget:
string manipulation, DOM manipulation, drag-
and-drop support and DS (Data Structures) <script type=”text/javascript”>
such as lists, queues and stacks. Dojo // Load Dojo’s code relating to
applications are used where the JavaScript and widget managing functions
browsers don’t work far enough, in which place dojo.require(“dojo.widget.*”);
the dojo application gives you the powerful,
portable, lightweight and tested tools for // Load Dojo’s code relating to the
creating a dynamic interfaces. Button widget
dojo.require(“dojo.widget.Button”);
Dojo Directory Structure: </script>
Whenever you use Dojo then you follow the dojo.require(“dojo.widget.*”): It instructs
following directory structure and set up the you to include the dojo widget (Not load all the
files of the specified location. widgets) for managing functions.
dojo.require(“dojo.widget.Button”): This
line instructs you to load the Dojo button widget.
If you don’t include this line, the markup code
for the button would not be evaluated by Dojo
upon loading, resulting in a plain HTML button
instead of what you expect.
<button dojoType=”Button”
w i d g e t I d = ” h e l l o B u t t o n ”
onClick=”helloPressed();”>Hello World!</
button>
<html>
<head>
<title>button</title>
<script type=”text/javascript”>
dojo.require(“dojo.event.*”);
dojo.require(“dojo.widget.*”);
dojo.require(“dojo.widget.Button”);
Tool tips Example
function helloPressed()
{ Tool tips: This is a GUI (Graphical User
alert(‘Click on the Hello World Button’); Interface) element that is used in conjunction
} with a cursor and usually a mouser pointer.
@import “../dijit/themes/tundra/
tundra.css”;
</style>
<script type=”text/javascript”
src=”dojo.xd.js” djConfig=”parseOnLoad:
true”></script>
<script type=”text/javascript”>
dojo.require(“dojo.parser”); Inline DateTextBox
dojo.require(“dijit.Tooltip”);
</script> Here,you will learn about the dojo inline
DateTextBox and how to create a inline
</head> DateTextBox and how to make its editable.
<body class=”tundra”> The following code is the InlineEditBox that edits
<b>Tooltips:</b> <br><br> date of dijit.form.DateTextBox save it
<span id=”site1">Roseindia.net</span> automatically. The inner textarea tag is the
<div dojoType=”dijit.Tooltip” Textarea widget. When a user run this code
connectId=”site1" then they see the paragraph of rich text. If
label=”This is a software developement user clicks the text, the plain text appears in
company!”> paragraph. If you want to change the value then
</div><br><br><br> click the date text and select the appears date.
<span id=”site2">Newstrackindia.com</
span> The InlineEditBox has methods get/
<div dojoType=”dijit.Tooltip” setDisplayedValue, inline. The following code
connectId=”site2" label=”This is a news shows the DateTextBox that makes inline in
publishing site!”> HTML.
</div>
Here is the code of program:
</body>
</html> <html>
</style>
<script type=”text/javascript”
src=”dojo.xd.js” djConfig=”parseOnLoad:
true”></script>
<script type=”text/javascript”>
Whenever your mouse pointer goes on the
dojo.require(“dojo.parser”);
Newstrackindia.com then you get:
dojo.require(“dijit.form.InlineEditBox”);
dojo.require(“dijit.form.DateTextBox”);
</script>
<style type=”text/css”>
@import “../resources/dojo.css”;
@import “../dijit/themes/tundra/
tundra.css”;
</style>
<script type=”text/javascript”
src=”dojo.xd.js” djConfig=”parseOnLoad:
true”></script>
<script>
dojo.require(“dojo.data.ItemFileReadStore”);
dojo.require(“dijit.Tree”);
dojo.require(“dojo.parser”);
</script>
</head>
<body class=”tundra”>
Simple Tree:<br><br>
<div
Dojo Tree
dojoType=”dojo.data.ItemFileReadStore”
url=”tree.txt” jsid=”popStore” />
In this section, you will learn about the tree
<div dojoType=”dijit.Tree”
and how to create a tree in dojo.
store=”popStore” labelAttr=”sname”
label=”Tree”></div>
Tree : The tree is a GUI that helps to lists the
</body>
hierarchical lists. The tree widget is a simple
</html>
{ label: ‘name’,
identifier: ‘name’,
items: [
{ name:’Students’, type:’cat’,
children: [
{ name:’Vinod’, type:’st’ },
{ name:’Suman’, type:’st’ },
{ name:’Deepak’, type:’st’ }
]
},
{ name:’Fruits’, type: ‘cat’,
children: [
{ name:’Apple’, type:’fr’ },
{ name:’Mango’, type:’fr’ },
{ name:’Graps’, type:’fr’,
children: [
{ name:’Sweets’, type:’gr’ },
{ name:’Sour’, type:’gr’ },
{ name:’Salt’, type:’gr’ }
]
}
]
},
{ name:’Vegetables’, type: ‘cat’},
{ name:’Education’, type:’cat’}
]
}
To get a reference to the Criteria interface, use Expression.eq This is used to apply
the createCriteria() method by invoking the an “equal” constraint to
Session class. This method takes the name of the named property
the ORM class on which the query has to be
executed. In essence the Session acts as a Expression.ge This is used to apply a
factory for the Criteria class. The statement for “greater than or equal”
it would be written as: constraint to the
named property
Criteria criteria=
session.createCriteria(Insurance.class) Expression.gt This is used to apply a
“greater than”
The above statement returns a reference to constraint to the
Criteria for the Order ORM class. named property
Once created, you add Criterion objects Expression.lt This is used to apply a
(generally obtained from static methods of the “less than” constraint
Expression class) to build the query. Methods to the named property
such as setFirstResult(), setMaxResults(),
and setCacheable() may be used to customize Expression.in This is used to apply
the query behavior in the same way as in the an “in” constraint to
Query interface. Finally, to execute the query, the named property
the list() method is invoked.
Expression.le This is used to apply a
For example: “less than or equal”
constraint to the
crit.add(Expression.gt(“investementAmount”, named property
new Integer(900))); Expression.and This returns the
List list = crit.list(); conjunctions of two
expressions.
The above statements are fired on the
investementAmount field of the Insurance Expression.or This returns the
class, which specify the list of those records disjunction of the two
that have the investment amount greater than expressions.
900. 2. Criterion
Criterion types.
Restriction.isNotNull This is used to apply
In code this would be:Criterion an “is not null”
crit=Restriction.eq(lngInsuranceId,5); constraint to the
criteria.add(crit); named property
public class
HibernateCriteriaQueryExpressionEq {
Projections are used to customize the results Here is the full source code of
from the database. In general Projection means projectionExample.java:
to retrieve; while in case of SQL Projection
means “Select” clause. The above code package javajzzup.hibernate;
retrieves all the rows from the ‘insurance’ table.
But what if only the data contained in one of import java.util.Iterator;
the fields has to be retrieved, as in the following import java.util.List;
SQL query:
import org.hibernate.Criteria;
SELECT NAME FROM PRODUCT import org.hibernate.Session;
import org.hibernate.SessionFactory;
Here, the Projection class comes into play. The import org.hibernate.cfg.Configuration;
above query can be rewritten into a Criteria import org.hibernate.criterion.ProjectionList;
query as: import org.hibernate.criterion.Projections;
List orde r=
session.createCriteria(Product.class)
.add(Expression.lt(“price”, new
Integer(2000)))
.addOrder( Order.asc(“name”) )
.list();
The given code in the DispalyTooltip.java file Lets see the outputs from the three kinds of
has a label component. Whenever we move the ToolTips.
mouse on the particular component, a related
tooltip is displayed with the specified text. 1. Move the mouse on the Label component.
DispalyTooltip.java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolTip;
public class DisplayTooltip {
public static void main(String args[]) {
String title = “Tooltip Sample”;
JFrame frame = new JFrame(title);
2. Move mouse outside of the component
frame.setDefaultCloseOperation
area.
(JFrame.EXIT_ON_CLOSE);
Container container =
frame.getContentPane();
JPanel panel = new JPanel();
panel.setToolTipText(“<HtMl>
Tooltip<br>Message”);
container.add(panel,
BorderLayout.CENTER);
JLabel label = new JLabel(“Hello World”) {
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setBackground(Color.red);
tip.setForeground(Color.green);
return tip;
} 3. Move mouse outside of the frame area.
public boolean contains(int x, int y) {
if (x < 100) {
setToolTipText(“Got Component”);
} else {
setToolTipText(“Got Frame”);
}
return super.contains(x, y);
}
};
label.setToolTipText(“Hello World”);
frame.getContentPane().add(label,
BorderLayout.NORTH);
frame.setSize(300, 150);
frame.setVisible(true); Download Example
}
} 3. Shuffle the elements of a Collection using
ArrayList interface.
DnDFieldDemo.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class DnDFieldDemo {
public static void main(String[] args) {
JFrame frame = new JFrame(“Drag and
Drop Demo”);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new JPanel());
JTextField textField = new JTextField(25);
http://www.roseindia.net
http://www.newstrackindia.com
http://www.javajazzup.com
http://www.allcooljobs.com
Advertisement Options:
Deepak Kumar
deepak@roseindia.net
If theres something youre curious about, were Present a question, problem, or puzzle
confident that your curiosity, combined with the
knowledge of other participants, will be enough Were inviting people from lots of different
to generate a useful and exciting Readers worlds. We do not expect everybody at Readers
Forum. If theres a topic you feel needs to be Forum to be an expert in some areas. Your
discussed at JavaJazzup, its up to you to get it expertise is a real resource you may contribute
discussed. to the Java Jazzup. We want your curiosity to
be a resource, too. You can also present a
Convene a discussion on a specific subject question, problem, or puzzle that revolves
around java technologies along with their
If you have a topic youd like to talk about . solution that you think would get really
Whether its something you think lots of people appreciated by the java readers around the
will be interested in, or a narrow topic only a globe.
few people may care about, your article will
attract people interested in talking about it at Post resourceful URLs
the Readers Forum. If you like, you can prepare
a really a good article to explain what youre If you think you know such URL links which
interested to tell java technocrates about. can really help the readers to explore their java
skills. Even you can post general URLs that
Sharing Expertise on Java Technologies you think would be really appreciated by the
readers community.
If youre a great expert on a subject in java,
the years you spent developing that expertise Anything else
and want to share it with others. If theres
something youre an expert on that you think If you have another idea for something youd
other technocrates might like to know about, like to do, talk to us. If you want to do
wed love to set you up in the Readers Forum something that we havent thought of, have a
and let people ask you questions. crazy idea, wed really love to hear about it.
Were open to all sorts of suggestions, especially
Show your innovation if they promote readers participation.