You are on page 1of 79

Sept-07 Java Jazz Up 1

2 Java Jazz Up Sept-07


Editorial
Dear Readers,

September 2007 Volume I Issue III We are here again with the third issue of Java Jazz-
up. The current edition highlights the interesting
Java articles and tutorials in a well described manner
developed by the Java Jazz-up developers team.
The roots of technology may be bitter, This issue reflects our consistent attempts to avail
but the fruits are always sweet, quality technological updates that enforce the reader
Just put a spark in your deeds and to appreciate a lot and be a part of its readers
the sky comes under your feet community.

The current release of Java Jazz-up tries to provide


new features orienting around developing enterprise
level applications that involves issues like setting up
Published by the Project Repositories within an organization,
implementing internationalization concepts, testing
RoseIndia databases within an application, how to work with
the Tomahawk tags and a lot more...
JavaJazzUp Team
Set of tutorials discussing technologies like Maven2,
Design patterns, JSF framework, web services,
Editor-in-Chief spring framework and various complementary open
source technologies are provided in such a manner
Deepak Kumar that even a novice learns and implements the
concepts in a easy manner.

Editor-Technical Java News and update section provides the latest


things going around the globe that makes the
Tamana Agarwal readers aware of the java-technological
Noor-En-Ahmed advancements. In this section you will learn about
Ravi Kant the new features introduced in the existing tools,
utilities, application servers, IDEs, along with the
Java API updates.
Sr. Graphics Designer
To make it interesting for readers we have
Suman Saurabh categorized each section with different colors and
images that lure readers while reading technological
Jr. Graphics Designer stuffs. We are providing it in a PDF format that you
can view and even download it as a whole and even
Amardeep Patel get its hard copy.

Please send us your feedback about this issue and


participate in the readers forum with your problems,
issues concerned with the topics you want us to
include in our next issues.

Editor
Deepak Kumar
Java Jazz up
Register with JavaJazzUp

and grab your monthly issue

Free*

* only Web Version.

Sept-07 Java Jazz Up 3


Content
05 Java News | Java Around the Globe- Sony Ericsson to provide new online testing
service for Java ME application...

08 New Releases | Spring Web Services 1.0 Released: Enhanced Features -


Interface21 has announced the release of Spring Web Services 1.0. With this new
release, Java programmers can develop applications for Web services with the...

10 Java Developers Desk: Internationalization | Internationalization is one of


the key features of Java language, which makes a java application...
internationalized

13 JSF Tags : Tomahawk Tags | Tomahawk tags are collection of standard


components with extended functionality and many more extra set of components
with rich set of functionality.

24 Building Project : Maven2 | Maven2 is an Open Source build tool that made the
revolution in the area of building projects.

35 Develop java persistence example with Maven2 | Download Maven2 from


maven.apache.org, unzip the archive into your local directory...

40 Database Testing with DbUnit | DbUnit is an open source Framework created


by Manuel Laflamme. This is a powerful tool for simplifying Unit Testing of the
database operations.

44 Creational Design Pattern | The singleton design pattern deals with one and
only one instance of an object that encapsulates the control of the object from a
common place. There are various ways of achieving this pattern.

49 Developing web Services with Lomboz Plug-in | Lomboz is an open source


and free JEE development environment used for businesses and individual
purposes.

55 Spring Framework: Spring Core with Data Access Framework | In this


article, we will move on to the main process of any enterprise application: Data
Persistence.

59 Web 3.0 | Web 3.0 is a term, which definition is not confirmed or defined so far
as several experts have given several meaning, which do not match to each other,
but sometimes it is referred to as a Semantic Web.

65 Tips n Tricks | This Java program lets you download files from one or more
URLs and save them in the directory where you want.

76 Advertise with JavaJazzUp | We are the top most providers of technology


stuffs to the java community.

77 Valued JavaJazzup Readers Community | We invite you to post Java-


technology oriented stuff.

4 Java Jazz Up Sept-07


JAVA AROUND THE GLOBE
Sony Ericsson to provide new online testing
service for Java ME application:

Sony Ericsson Virtual Sun adds mobile


Lab will provide Java NetBeans Going GPL
capability to messaging
developers an online testing
service to test and monitor and apps platforms:
Netbeans is in the
Java applications on Sony
Sun has planned to incorporate process to adopt the GPL
Ericsson phones. This will
mobile synchronization v2 with Classpath
make the process quicker
capabilities into its exception license as a
and cheaper than before.
communications and applications second license option along
The online service will be
platform suites. For this purpose, with CDDL that OpenJDK
available globally 24 7 to
sun has signed a licensing deal uses. GPL v2 is an open-
all members of Sony
with Synchronica to source license. This will
Ericsson Developer World.
incorporate SyncML help NetBeans in getting
This online service enables
technology from Synchronicas greater adoption in the
developers to test remotely
Mobile Gateway server into the Linux community. Not only
the pre-commercial mobile
products. this, the release of
phones, released by the
Netbeans 6.0 version is in
company (like 2007 phones)
This relationship extends Suns a process.
and will help in developing
the perfect application for reach beyond the wide range of
these new phones. Now, supported desktop clients to a Sun Open Java
developers will no longer large number of mobile devices. License Unveils:
need to invest in device labs, This collaboration also enables
shipping of phones, updating our application server developers Now the Open JDK
firmware or be physically to build feature-rich and scalable Community Technology
present on an operators mobile applications that support Compatibility Kit (TCK)
network. both connected and disconnected License is available for
operations.said Suns vice enhanced portability of the
president of software solution. This is for the Java
infrastructure, Karen Tegan Compatibility Kit (JCK) that
Padir. concludes whether an

Sept-07 Java Jazz Up 5


Java News: JAVA AROUND THE GLOBE

implementation consents Magical Java Charts in Following are few of its


with the Java Platform features:
Minutes!
Standard Edition 6
specification or not. The JCK The focus in Java EE 5 is
Developers can now design
license would be fully in made on the ease of
and configure attractive
consent of the terms of the development. With Java
graphical charts on any platform.
GNU General Public License EE 5, there is less code
These are ElegantJCharts, which
version 2 (GPLv2) which is to write.
are a collection of three charting
available at:http:// It supports latest web
utilities: ElegantJ Chart Designer
openjdk.java.net/legal/ service APIs that is an
IDE, ElegantJ Chart Library, and
openjdk-tck-license.pdf. ideal platform for
ElegantJ Indicator and Gauges.
Service-Oriented
Pioneer Java Developers can take advantage Architectures (SOA).
Spreadsheet SDK is of ElegantJCharts Designer IDE It also includes
JavaServer Faces (JSF)
now an Open Source for the visual configuration of
technology, the JSP
charts along with the flexibility
Innovation of integrating chart library in Standard Tag Library
their applications in an (JSTL), AJAX etc for
Extentech Inc, an building of new
exclusive way through a
innovative developer of Java generation web
comprehensive API.
components and applications.
development tools, Java EE 5 supports rich
announced the release of Java SOA Use Increases,
thin-client technologies
OpenXLS (under the GPL while .NET Declines such as AJAX,
license), which is an open technologies that are
source version of the Use of Java is increasing at large crucial for building
companys Java Software in SOA deployments as found by applications for Web 2.0.
Development Kit for Evans Data Corporation. They Annotations are used
Spreadsheets, ExtenXLS. observed that more companies extensively to reduce the
OpenXLS is a robust and are planning to deploy JavaV need for deployment
risk-free way to integrate based SOA solutions rather than descriptors.
spreadsheets into Java deploying .NET based SOA
Supports EJB 3.0 which
programs and web solutions. This may be because
makes programming
applications. of the newly available javas
more simpler with the
feature to virtually tie with the
use of Plain Old Java
With the release of .NET.
Objects (POJOs).
OpenXLS, Extentech has
It also introduces a new
leveled the playing field for Java EE 5.0: New persistence API.
developers who need to
Enhanced Features
embed spreadsheet
functionality in their JSR 286, Portlet 2.0
applications, states John The new version of Java EE Enters Public Review
McMahon, CEO of Extentech i.e. (Java EE) 5 is capable of
Inc. developing robust and scalable JSR 286, the portlet
enterprise applications. It specification 2.0 has entered
provides a superb platform for its public review phase. The
SOA and the development of public review held till August
the next-generation web 27th. It included the features
applications. of the new specification like

6 Java Jazz Up Sept-07


Java News: JAVA AROUND THE GLOBE

Java EE 1.4 support,


introduction of the portlet
filters, inter-portlet
communication, and
enhancements to the portlet
tag library. Several other
enhancements were also
discussed. In addition, the
specification called for
coordinating the JSF expert
group to better align JSF
with portlets.

Magnolia 2.0: First


Open Source CMS
Supporting Java
Content Repository
The launching of Magnolia
2.0, the first major upgrade
to the Magnolia Open Source
content management
project, has been
announced and it is available
for free download. Now it
has become the first CMS to
support the Java Content
Repository and also gets
improved usability and
optimizations for J2EE.
Currently, Magnolia is being
used by companies like
Siemens Enterprise and
many pharmaceutical
industries. It is available for
online testing at http://
www.magnolia.info/demo.
New Releases
Spring Web Services documentation distributions etc. Groovy MDA 1.0
1.0 Released: Released: A Code
GridGain 1.5 Released: Generation Library
Enhanced Features Brings Open Source Grid
Interface21 has announced Computing to Java Groovy MDA 1.0 has been
the release of Spring Web released and it is available
Services 1.0. With this new GridGain 1.5 has been for download from its
release, Java programmers released, it is available for official website i.e. http://
can develop applications for download at:www.gridgain.org/ groovy-
Web services with the downloads.html. It is an open mda.sourceforge.net
facilities of creation of source grid computing platform Groovy MDA library
contract-first, document- for Java with high-performance generates software project
driven Web services, development. It has a unique artifacts employing the
delivering the flexibility, set of grid computing features Groovy scripting language
productivity and ease of use. with open source LGPL from the UML models. It is
The contract-first approach licensing. even capable in generating
avoids interoperability issues JPA entity beans from a
and simplifies development. This release has new features UML model. Even it enables
with improved functionality like the user to customize the
It works with common Web integration with Spring, templates of his choice
Services technologies like Weblogic, JBoss, Coherence, with ease.
POX (plain old XML), SOAP Mule, etc. It is considered to be
and WSDL (Web Services the widest selection of
Description Language). This compatible products in its class. Portals Pluto 1.1.4
release also facilitates the
best practices such as the Released:
WS-I basic profile and loose
Google Web Toolkit 1.4 Implements Java
coupling between contract RC2 Released: 100 bugs Portlet Specification
and implementation that fixed
allows creating flexible Web
Pluto is the Reference
Services.
Finally, Google Web Toolkit Implementation of the Java
(GWT) 1.4 RC2 has been Portlet Specfication. The
Apache Struts 2.0.9 released and is available for current version of this
Released: More download from Google website. specification is JSR 168.
Elegant Framework It is being presumed to be the Portlets are designed to
best GWT release to date run in the context of a
Compared to older because in this release, near portal. They are written
versions of Struts, this about 100 bugs have been fixed. with the Portlet API which
version is more elegant for Moreover it is expected to be the is similar to the Servlet
creating enterprise-ready final 1.4 release and GWT 1.5 is API.
Java web applications and is now on the way.
the best available version GWT 1.5 will soon be released With the advent of Portals
of Struts. This new version supporting Java 5.0. Hopefully, Pluto 1.1.4, it has become
is simpler to use and includes GWT client code will be based on easier to integrate Plutos
an important security fix Java 5.0 syntax and will support portal container into a portal.
regarding a remote code all its available features. Its a major refactoring of
exploit. It is available as a Pluto 1.0.1, which allows this
separate library, source, integration. Moreover, its

8 Java Jazz Up Sept-07


Java News: New Releases

the fifth GA release of the 1.1 has made the things much easier 2.2. It also contains some
line of Pluto. It also supports as it includes upgraded features features from Python 2.3.
JSP 2.1. Current Pluto 1.1.4 like multiplexer improvements, Jython that is integrated
release has binary concurrent stack, new failure with the Java platform is an
compatability with Pluto detection protocols etc. This implementation of the high-
1.1.3 which its earlier release offers major level, dynamic, object-
versions lacked. improvements over previous oriented language.
releases most notably concurrent
Apache Geronimo messages delivery, channel The updates that have
multiplexing and full virtual been made in this
v2.0 - Release synchronous support. JGroups release are:
delayed due to users may upgrade their
security issue applications to 2.5 releases [4] Java Collections
as it is a straightforward process; integration
The Apache Geronimo API is backward compatible to Support for the iterators
project produces a server 2.2.7 release, the only change and generators
runtime framework that pulls should be made in the channel Compatible with both
together the best Open configuration files. JDK1.5 and 1.6
Source alternatives to create
runtimes that fulfil the needs Swerve Framework Beta CodeGears JGear
of developers and system 0.9 Released: Eclipse Plug-ins
a d m i n i s t r a t o r s .
Swerve SOA which is a full
Revealed:
The release of Apache stack POJO framework has
Geronimo v2.0 has been arrived for developing Flex 2 / A set of specialized plug-
delayed due to the detection Java RIA solutions with the ant ins has been revealed by
of a security bug. The origin script build support. CodeGear from Borland
of this problem has been Its provides support for: Corporation for the Eclipse
taken into consideration and open-source development
some tests are going on to platform: JGear. The new
Asynchronous processing
fix this problem. JGear has the following
that may be in-lined,
features:
queued, or fully concurrent.
JGroups 2.5 Text, XML, binary, and AMF0 JGear LiveSource for
Released: Boosting return types. Eclipse.
Group POJO based REST API to JGear Team for Eclipse
quickly implement REST based (both Client and Server
Communication services. editions).
SEDA based messaging fabric JGear Performance for
JGroups is a toolkit, which with integrated CometD. Eclipse contains
is used for the development
Fast XML Marshalling API. features such as
of distributed Java
memory and CPU
applications based on group
communication. It has a Jython 2.2 Released: profiling and debugging;
Implements Python 2.2 real-time monitoring of
feature of flexible protocol
programs use of virtual
stack, which meets the and 2.3 machine memory;
developer s application
automatic detection of
requirements. Jython 2.2 has arrived with potential memory leaks
the implementation of the etc.
The release of JGroups 2.5 internal architecture of Python
Java Developers Desk
Internationalization
Internationalization is one discussing internationalization, may response according to
of the key features of Java word localization comes to the the specific region and
language, which makes a front, which is the process of country i.e. locale
java application adapting software for a specific (Remember no code
internationalized. In other region or language by adding changes are required for
words, Internationalization is locale-specific components and different locale). Just
the process of designing an translating text. It involves follow these steps:
application, which is able to changing the language
adapt itself in different interaction, display of numbers, 1. Create Properties
countries and regions dates, currency, and so on. For Files:
without recompiling. better visualization, just go
Normally, software follows through the example below. Create . properties file
the conventions of region or containing a set of key and
country in which it is Suppose, we have a program value pair. Remember to
developed. This software is InternationalizationDemo in keep the keys same in all
supposed to be used by the which the text to display is hard the files and provide values
group of users familiar with coded so it always displays the according to the locale in
this particular convention. same text in English Language, different files.
For example, an American no matter a Spanish person
developer tends to develop wants these texts in its own Properties Files
software, which displays text mother language. Naming Convention:
in English, take the amount
of money in dollars etc. On InternationalizationDemo.java: Creating a default
the other hand, a French (Without Internationalization properties file is a good
developer is expected to Support) practice, which is available
develop software, which to the program by default.
displays text in French, take import java.util.*; You can give any name to
currency in franc. Such public class this file but remember to
software cant be considered InternationalizationDemo { use the same name that
as internationalized. Java public static void main(String[] your ResourceBundle
provides a solution of this args) { uses (MessageBundle.
issue. A truly System.out.println(The text properties file in our
internationalized program displayed is specific to example). While naming
contains no hard coded area locale+ other properties files follow
for a specific locale. For (+Locale.getDefault(). the syntax:
example, text, currency, getDisplayLanguage()+,
date, number formats, audio +Locale.getDefault(). PropertiesFileNameUsedIn
clips etc., which makes an getDisplayCountry ()+).\n); ResourceBundle_language
application locale specific. Code_countryCode.properties
Instead of hard coding, these System.out.println(Hello, how
elements are stored outside are you?); Lets create these files.
of the program. Now, the System.out.println(Thanks to Default file:
program is not required to visit.);
be compiled again when a }} Write down the following
new country or region lines in a plain-text file
requires support. When Now you want this program to (Default version) and save
get internationalized so that it it as
10 Java Jazz Up Sept-07
Java Developers Internationalization

MessagesBundle.properties: public class InternationalizationDemo {


public static void main(String[] args) {
localeInfo = The text displayed is specific to String language;
localewelcome = Hello, how are String country;
you?sayThanks = Thanks to visit. Locale locale;
ResourceBundle rb;
Other properties files: if (args.length != 2) {
Write down the following lines in a plain- language = new String(en);
text file (for the French version) and save it country = new String(US);
as MessagesBundle_fr_FR.properties: }
else {
localeInfo = Le texte affich est spcifique language = new String(args[0]);
la scne country = new String(args[1]);
welcome = Bonjour, comment allez-vous ? }
sayThanks = Merci pour visiter. locale = new Locale(language, country);
rb = ResourceBundle.get
Write down the following lines in a plain- Bundle(MessagesBundle, locale);
text file (for the Spanish version) and save System.out.println(rb.getString(localeInfo)+
it as (+locale.getDisplayLanguage()+,
MessagesBundle_es_ES.properties: +locale.getDisplayCountry ()+).\n);
System.out.println(rb.getString
localeInfo = El texto mostrado es especfico (welcome));
al lugar System.out.println(rb.getString
welcome = Hola, Cmo est usted?. (sayThanks));
sayThanks = Gracias a visita. }
}
Notice that localeInfo, welcome,
sayThanks keys are same in English,
French, Spanish files and values are A Locale object represents a specific
replaced with the converted value of the geographical, political, or cultural region.
particular language. In other words, Locale is an identifier for a
particular combination of language and
region. One of its constructors is:
2. Remove hard coded text from the
source file: Locale(String language, String country)

Our next step is to remove the hard coded First argument specifies the language and
text from our source file and use the keys of the second one specifies the country to
properties file. These values are picked up at support. The language argument is a valid
the run time from the properties file according ISO language code (two letter code and in
to the locale provided to the program. So lower case) defined by ISO-639. In the same
this source file doesnt require to be compiled way, country argument is also a valid ISO
while dealing with the different locales. You country code (two letter code but in upper
can be sure of this fact viewing the code case) defined by ISO-3166. For example, the
modified below: list of some language code and country code
is given below:
InternationalizationDemo.java:
(Internationalization Support)
import java.util.*;

Sept-07 Java Jazz Up 11


Java Developers Internationalization

Language CodeCountry CodeDescription Output:


en US English & USA
fr FR French & France When the set of language code and country
es ES Spanish & Spain code is provided at run time, the output is
en GB English & Great shown according to that particular locale. For
Britain example, in the output below, for es and
fr CA French & Canada ES the output is displayed in Spanish
language. The text displayed is fetched from
Find full list of language codes from: MessageBundle_es_ES.properties file. If
fr and FR codes are provided at run time
http://www.ics.uci.edu/pub/ietf/http/ then values are displayed in French language.
related/iso639.txt Now this text is fetched from
MessageBundle_fr_FR.properties file.
Find full list of country codes from: Here we are not changing and compiling the
source code to work for different locale
http://www.chemie.fu-berlin.de/diverse/ because the program references the keys,
doc/ISO_3166.html not the values.

12 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags
Tomahawk tags are collection of prefix=t%>
standard components with extended <html>
functionality and many more extra set of <head>
components with rich set of functionality. If <title>t:jscookMenu example</title>
you are going to create a web application </head>
in JSF then Tomahawk will be a great <body>
weapon because it contains all the <f:view>
commonly used set of components with <h:form>
large options of functionalities. The best <t:jscookMenu layout=hbr
way to justify the above fact is exploring theme=ThemeIE >
some examples of Tomahawk tags. Have a <t:navigationMenuItem id=nmi1"
glance on some good tomahawk tags itemLabel=Menu1">
below. <t:navigationMenuItem id=nmi1_1"
itemLabel=Menu11" action=welcome />
1.Tomahawk jscookMenu tag: <t:navigationMenuItem id=nmi1_2"
itemLabel=menu12" action=welcome />
This tag is used to create a menu <t:navigationMenuItem id=nmi1_3"
component in a web page. To display the itemLabel=menu13" action=welcome />
items navigationMenuItem or <t:navigationMenuItem id=nmi1_4"
navigationMenuItems tag are used. In the itemLabel=menu14" split=true>
following example, we have used theme <t:navigationMenuItem id=nmi14_1"
that looks just as in Internet Explorer. itemLabel=menu141" action=welcome />
<t:navigationMenuItem id=nmi14_2"
itemLabel=menu142" action=welcome/>
Code Description: <t:navigationMenuItem id=nmi14_3"
itemLabel=menu143" action=welcome />
The layout attribute provides the layout <t:navigationMenuItem id=nmi14_4"
for the components. The values for this itemLabel=menu144"action=welcome/>
attribute can be hbr, hbl, hur, hul, vbr, vbl, </t:navigationMenuItem>
vur, vul. The theme attribute is used to </t:navigationMenuItem>
specify the theme to be applied on the </t:jscookMenu>
component. The values for this attribute </h:form>
may be ThemeIE, ThemeMiniBlack, </f:view>
ThemeOffice, ThemePanel. ThemeIE </body>
value gives a look like Internet Explorer. </html>
The navigationMenuItem tag is used to
provide the menu items and sub items. The
label for the item is set using itemLabel
attribute and the action to perform is
specified in the action attribute. The icon
displayed before the item is set to the icon
attribute. Its split attribute is used when
we want its sub items.

<%@ taglib uri=http://java.sun.com/jsf/


core prefix=f%>
<%@ taglib uri=http://java.sun.com/jsf/
html prefix=h%>
<%@ taglib uri=http://
myfaces.apache.org/tomahawk
Sept-07 Java Jazz Up 13
JSF Tags: Tomahawk Tags

10m - 10 MB
1g - 1 GB
</description>
<param-name>uploadMaxFileSize
</param-name>
<param-value>100m</param-value>
</init-param>
<init-param>
<description>Set the threshold size - files
below this limit are stored in memory, files
above this limit are stored on disk.
Format: 10 - 10 bytes
10k - 10 KB
10m - 10 MB
1g - 1 GB
</description>
<param-name>uploadThresholdSize
</param-name>
<param-value>100k</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>extensionsFilter
Rendered Output: </filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
2.Tomahawk inputFileUpload tag :
<filter-mapping>
<filter-name>extensionsFilter
File uploading is the concept of uploading </filter-name>
the file to the server. In Tomahawk, the <url-pattern>/faces/*</url-pattern>
component for this purpose can be created </filter-mapping>
using <t:inputFileUpload> tag. Do
remember to include enctype attribute
Code Description:
in the form tag and set to multipart/
form-data. You must enable the MultiPart
Filter to make the component work. For In the code below, inputFileUpload tag
this, you have to add the code below in the creates the file upload component. We
web.xml file. have also created a button that when
clicked, causes a method upload() of the
<filter> backing bean(FileUploadForm.java) to
<filter-name>extensionsFilter be called. In this code, the output text for
</filter-name> showing success and failure is rendered
<filter-class> based on the condition of success / failure
org.apache.myfaces.webapp.filter.ExtensionsFilter in uploading the file. For this, rendered
</filter-class> attribute has been used.
<init-param>
<description>Set the size limit for
uploaded files.
Format: 10 - 10 bytes
10k - 10 KB

14 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags

<%@taglib uri=http://java.sun.com/jsf/ boolean rendFailure=false;


html prefix=h%>
<%@taglib uri=http://java.sun.com/jsf/ public FileUploadForm(){
core prefix=f%> }
<%@ taglib uri=http://
myfaces.apache.org/tomahawk prefix=t public UploadedFile getUpFile(){
%> return upFile;
<html> }
<head>
<title>t:inputFileUpload example</title> public void setUpFile(UploadedFile
</head> upFile){
<body> this.upFile = upFile;
<f:view> }
<h:form id=welcomeForm
enctype=multipart/form-data> public boolean getRendSuccess(){
<t:inputFileUpload id=fileupload return rendSuccess;
value=#{FileUploadForm.upFile} }
size=20" />
<p/> public void setRendSuccess(boolean
<h:commandButton value=Load the rendSuccess){
file this.rendSuccess = rendSuccess;
action=#{FileUploadForm.upload} }
/>
<t:outputText value=File Uploaded public boolean getRendFailure(){
Successfully. return rendFailure;
rendered=#{FileUploadForm.rendSuccess} }
style=color:green;font-weight:bold/>
<t:outputText value=Error in File public void setRendFailure(boolean
Uploading. rendFailure){
rendered=#{FileUploadForm.rendFailure} this.rendFailure = rendFailure;
style=color:red;font-weight:bold/> }
</h:form>
</f:view> public String upload() throws
</body> IOException{
</html> try {
InputStream stream =
FileUploadForm.java : upFile.getInputStream();
long size = upFile.getSize();
package net.roseindia.web.ui; byte [] buffer = new byte[(int)size];
stream.read(buffer, 0, (int)size);
import java.io.*; stream.close();
import javax.servlet.http.*; rendSuccess=true;
import rendFailure=false;
org.apache.myfaces.custom.fileupload.UploadedFile; System.out.println(File Upload
import javax.faces.context.FacesContext; Successful.);
return ok;
public class FileUploadForm{ }
private UploadedFile upFile; catch (Exception ioe) {
boolean rendSuccess=false; System.out.println(File Upload
Unsuccessful.);

Sept-07 Java Jazz Up 15


JSF Tags: Tomahawk Tags

rendSuccess=false; The following figure appears when a file is


rendFailure=true; successfully uploaded.
return no;
}
}
}

Rendered Output:

This is the output of the above code. The


file upload component is the combination of
an input box and a button for choosing a
file to be uploaded.

The following figure appears when there is


any problem in uploading a chosen file.

The browse button and select one file to


upload it.

3. Tomahawk inputCalendar tag:

This tag is used to create calendar


component in the page. It can be created
in different styles depending on the value
of renderAsPopup attribute of the
component. If renderAsPopup attribute is
set to true then it creates an input box
along with a button which when clicked
renders a popup calendar. We can select
any date and it is displayed in the input box
in our required format. A help text can also
be given in the input box to help the user

16 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags

to input the date in the specified format. monthYearRowClass=yearRowStyle


The current date can be displayed in the weekRowClass=weekRowStyle
popup window in our required format with currentDayCellClass=selectedDayCellStyle
some string. Many attributes are there to value=#{Calendar.selectedDate1}/
use CSS in different parts of the >
component. In the following example, we <t:htmlTag value=pre></t:htmlTag>
can see how the component can be used in <t:inputCalendar id=secondOne
our page. value=#{Calendar.selectedDate2}
renderAsPopup=true
Code Description :
popupDateFormat=MM/dd/yyyy
<%@ taglib uri=http://java.sun.com/jsf/
html prefix=h%> popupTodayDateFormat=dd-MMM-yyyy
<%@ taglib uri=http://java.sun.com/jsf/
core prefix=f%> popupWeekString=Week
<%@ taglib uri=http://
myfaces.apache.org/tomahawk popupTodayString=The date today is :
prefix=t%>
renderPopupButtonAsImage=true
<f:view>
<t:document> popupButtonImageUrl=images/cal.gif
<t:documentHead> helpText=MM/DD/YYYY
<meta http-equiv=Content-Type forceId=true/>
content=text/html;
charset=iso-8859-1"> </h:form></center>
<title>t:inputCalendar example</ </t:documentBody>
title> </t:document>
<style type=text/css> </f:view>
<!
.yearRowStyle { Rendered Output :
background-color: #A8D1E8;
color: green;
text-align: center;
font-weight: bold;
font-style:italic;
}
.weekRowStyle {
background-color: #D6EBFC;
}
.selectedDayCellStyle {
background-color: #ECD5D2;
}
>
</style>
</t:documentHead>
<t:documentBody ><center>
<h:form>

<t:inputCalendar

Sept-07 Java Jazz Up 17


JSF Tags: Tomahawk Tags

4. Tomahawk inputHtml tag: Rendered Output :

This tag is used to create the Kupu text


editor. To know about this you can visit
the web site http://kupu.oscom.org. The
important thing about this tag is that it
supports one editor per page. You can
use multiple editors if they are placed in
different tags but rendered only one at a
time, for example, in many tabbed panes.
You can customize this editor according to
your requirement. You can add different
tool boxes if required. Different look and
style can be given by the use of CSS.

Code Description :

<%@ taglib uri=http://java.sun.com/jsf/


html prefix=h%> 5. Tomahawk popup tag:
<%@ taglib uri=http://java.sun.com/jsf/
core prefix=f%> This tag is used to create the popup
<%@ taglib uri=http:// window when user takes the mouse on
myfaces.apache.org/tomahawk the element. This popup is created on the
prefix=t%> mouse event. It has many attributes that
<f:view> can give it extra functionalities. It has an
<t:document> attribute responsible for displaying the
<t:documentHead> popup window at a certain place i.e. we
<meta http-equiv=Content-Type can set its horizontal distance and
content=text/html; vertical distance from the triggering
charset=iso-8859-1"> element. We can also set when to close this
<title>t:inputHtml example</title> window, either when triggering element is
</t:documentHead> left or the popup window is left.
<t:documentBody >
<h:form> Code Description:
<t:inputHtml style=height:300px;
color:green
addKupuLogo=true <%@ taglib uri=http://java.sun.com/jsf/
showAllToolBoxes=true > html prefix=h%>
</t:inputHtml> <%@ taglib uri=http://java.sun.com/jsf/
</h:form> core prefix=f%>
</t:documentBody> <%@ taglib uri=http://
</t:document> myfaces.apache.org/tomahawk
</f:view> prefix=t%>

<f:view>
<html>
<head>
<meta http-equiv=Content-Type
content=text/html; charset=iso-8859-1">

18 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags

<title>t:popup example</title> UIData component like dataTable, dataList in


<style type=text/css> its for attribute. dataScroller tag renders
<! a component that provides the facility to
.popClass{ navigate through the data by scrolling.
background-color:#F1F1F1;
} Code Description:
>
</style> In the code below, the data scroller
</head> component for a data table has been created
<body > that helps to navigate from one set of data
<h:form> to the other by clicking various navigation
<t:popup styleClass=popClass links. There are three types of links to move
closePopupOnExitingElement=true one by one, fast forward and move to
closePopupOnExitingPopup=true the last directly. In this example, faststep
displayAtDistanceX=0" attribute has been set to the value 2 so fast
displayAtDistanceY=0"> forward link will take you two page ahead
<h:outputText value=JSF tutorials and directly. paginatorMaxPages attribute sets
examples. style=font-weight:bold;/> the number of pages to be shown in the
<f:facet name=popup> component to navigate directly clicking on
<h:panelGrid columns=1" > them.
<h:commandLink value=http://
roseindia.net/jsf /> <%@ taglib uri=http://java.sun.com/jsf/
<h:commandLink value=http:// html prefix=h%>
myfaces.apache.org /> <%@ taglib uri=http://java.sun.com/jsf/
</h:panelGrid> core prefix=f%>
</f:facet> <%@ taglib uri=http://
</t:popup> myfaces.apache.org/tomahawk
</h:form> prefix=t%>
</body> <html>
</html> <head>
</f:view> <meta http-equiv=Content-Type
content=text/html; charset=iso-8859-1">
Rendered Output : <title>t:dataScroller example</title>
<style type=text/css>
<!
body{
margin-top:30;
}
.TableRow1 {
background-color: #D0E6E0;
}

.TableRow2 {
background-color: #E8F7F1;
}
6. Tomahawk dataScroller tag : .TableColumn {
text-align: center
The data scroller component of tomahawk }
is one of the very useful component. This .TableClass {
component can take the reference of the
Sept-07 Java Jazz Up 19
JSF Tags: Tomahawk Tags

font-family : verdana, Geneva, Arial, <f:facet name=header>


Helvetica, sans-serif; <t:outputText value=Capital/>
font-size: 13px; </f:facet>
color: #000000; <t:outputText value=#{item.capital}>
padding: 2; </t:outputText>
border-style: solid; </t:column>
border-width: 2px; </t:dataTable>
} <t:dataScroller id=scroller
.TableHeader { for=dt1" paginator=true
color: #000000; fastStep=2" paginatorMaxPages=5"
background-color: #F1F1F1; paginatorActiveColumnStyle=font-
padding: 3; size:20px;font-weight:bold;
text-align: center; immediate=true>
border: none; <f:facet name=first >
} <t:graphicImage url=images/first.gif
> border=1" />
</style> </f:facet>
</head> <f:facet name=last>
<body ><center> <t:graphicImage url=images/last.gif
<f:view> border=1" />
<h:form id=form1" > </f:facet>
<t:dataTable id=dt1" <f:facet name=previous>
value=#{DataScrollerBean.country_Capital} <t:graphicImage url=images/pre1.gif
var=item bgcolor=#F1F1F1" border=1" />
border=10" cellpadding=5" </f:facet>
cellspacing=3" first=0" rows=2" <f:facet name=next>
width=50% dir=LTR frame=hsides <t:graphicImage url=images/next1.gif
rules=all summary=This is a JSF code border=1" />
to create dataTable. </f:facet>
rowClasses=TableRow1,TableRow2" <f:facet name=fastforward>
columnClasses=TableColumn <t:graphicImage url=images/next2.gif
styleClass=TableClass border=1" />
headerClass=TableHeader> </f:facet>
<f:facet name=header> <f:facet name=fastrewind>
<h:outputText value=Countries and <t:graphicImage url=images/pre2.gif
Capitals /> border=1" />
</f:facet> </f:facet>
<t:column style=color:green; font- </t:dataScroller>
weight:bold headerstyle=background- </h:form>
color:#99CCFF;> </f:view>
<f:facet name=header> </center>
<t:outputText value=Country /> </body>
</f:facet> </html>
<t:outputText
value=#{item.country}></
t:outputText>
</t:column>
<t:column headerstyle=background-
color:#99CCFF;>

20 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags

new CountryCapital(France,Paris),
new CountryCapital(China,Beijing),
new
CountryCapital(Denmark,Copenhagen),
new CountryCapital(Brazil,Brasilia),
new CountryCapital(Bangladesh,Dhaka),
new CountryCapital(Australia,Canberra),
new CountryCapital(Fiji,Suva)

};

public CountryCapital[]
getCountry_Capital() {
return country_Capital;
Rendered Output : }
The figure below shows that when we click
on fast forward element then it moves public class CountryCapital {
ahead by 2 pages because fastStep String country;
String capital;
public CountryCapital(String
country,String capital) {
this.country = country;
this.capital = capital;
}
public String getCountry() {
return country;
}

public String getCapital() {


return capital;
}
attribute has been set to the value 2. }
Backing bean
(DataScrollerBean.java) }

package net.roseindia.web.ui; 7. Tomahawk panelTabbedPane tag :


public class DataScrollerBean {
This tag is used to create a tabbed
private CountryCapital[] country_Capital = pane. Its has the capability of switching
new CountryCapital[]{ the tabs at client side or server side. If
new CountryCapital(India,New Delhi), its serverSideTabSwitch attribute is set
new CountryCapital(United to true then switching is server side
States,Washington D.C.), otherwise it is client side. If we want a
new CountryCapital(Russia,Moscow), specific tab to be opened by default when it
new CountryCapital(United is rendered then we can set its
Kingdom,London), selectIndex attribute to any integer
new CountryCapital(Mexico,Mexico City), value. Here index value starts from 0 i.e.
new CountryCapital(Japan,Tokyo), setting the value to 0 indicates to the first
new CountryCapital(Germany,Berlin), tab and 1 to the second tab and so on. This

Sept-07 Java Jazz Up 21


JSF Tags: Tomahawk Tags

tag offers a lot of attributes to make it <t:inputText id=empAdd size=27" />


according to your need of look and <t:outputText value=Phone
functionality. The panelTab tag is used styleClass=font11bold/>
with panelTabbedPane tag to create <t:inputText id=empPhone size=27" />
tabs for panel. It has label attribute to </t:panelGrid>
give label for the tab </h:form>
</t:panelTab>
Code Description: <t:panelTab label=Exprience Detail
rendered=true>
<%@ taglib uri=http://java.sun.com/jsf/ <h:form id=form2">
html prefix=h%> <t:panelGrid columns=5" border=0">
<%@ taglib uri=http://java.sun.com/jsf/ <t:outputText value=Company Name/>
core prefix=f%> <t:outputText value=Designation/>
<%@ taglib uri=http:// <t:outputText value=Technologies/>
myfaces.apache.org/tomahawk <t:outputText value=From/>
prefix=t%> <t:outputText value=To/>
<html> <t:inputText id=cmpname />
<head> <t:selectOneListbox id=designation
<title>t:panelTab example<title> value= size=1" required=true>
</head> <f:selectItem id=one
<body> itemLabel=Manager itemValue=one />
<center> <f:selectItem id=two itemLabel=Jr.
<f:view> Manager itemValue=two />
<t:panelTabbedPane width=400" <f:selectItem id=three itemLabel=Clerk
bgcolor=#cddcf6" align=center itemValue=three />
serverSideTabSwitch=false <f:selectItem id=four
selectedIndex=0"> itemLabel=Engineer itemValue=four />
<t:panelTab label=personal </t:selectOneListbox>
rendered=true> <t:inputTextarea id=technologies
<h:form id=form1"> rows=1" />
<t:panelGrid columns=2" border=0"> <t:inputCalendar id=fromdate value=
<t:outputText value=Employee Name/> renderAsPopup=true
<t:inputText id=empFn size=27" /> popupDateFormat=MM/dd/yyyy
<t:outputText value=Sex/> helpText=MM/DD/YYYY
<t:selectOneListbox id=empSex forceId=true size=12"/>
value= size=1" required=true > <t:inputCalendar id=todate value=
<f:selectItem id=sex1" itemLabel=Male renderAsPopup=true
itemValue=sex1" /> popupDateFormat=MM/dd/yyyy
<f:selectItem id=sex2" helpText=MM/DD/YYYY
itemLabel=Female itemValue=sex2" /> forceId=true size=12"/>
</t:selectOneListbox> </t:panelGrid>
<t:outputText value=Birth Date </h:form>
styleClass=font11bold/> </t:panelTab>
<t:inputCalendar id=empDOB </t:panelTabbedPane>
value= renderAsPopup=true </f:view>
popupDateFormat=MM/dd/yyyy </center>
helpText=MM/DD/YYYY forceId=true/> </body>
<t:outputText value=Address </html>
styleClass=font11bold/>

22 Java Jazz Up Sept-07


JSF Tags: Tomahawk Tags

Rendered Output:

When we click on the second tab we get


the following image as shown below.

Sept-07 Java Jazz Up 23


Building Projects: Maven2
Learn to Set Up A Maven2 Repository
Maven2 is an Open Source Open Source technologies. information, defines what
build tool that made the People are introduced to use the project consists of and
revolution in the area of maven as the core build system that can share JARs across
building projects. Like the for Java development in one several projects. The result
build systems as "make" and project and a multi-project of all these requirement was
"ant" it is not a language to environment. After a little the maven tool that builds
combine the build knowledge about the maven, and manages the java-
components but it is a build developers are able to setup a based-project.
lifecycle framework. A new project with maven and also
development team does not become aware of the default Maven: Features
require much time to maven project structure.
automate the project's build Developers are easily enabled to 1. Portable: Maven is
infrastructure since maven configure maven and its plugins portable in nature because:
uses a standard directory for a project. Developers enable
layout and a default build common settings for maven and Building configuration
lifecycle. Different its plugins over multiple projects, using maven are
development teams, under a how to generate, distribute and portable to another
common roof can set-up the deploy products and reports with machine, developer and
way to work as standards in maven so that they can use architecture without any
a very short time. This repositories to set up a company effort
results in the automated repository. Developers can also
build infrastructure in more know about the most important Non trivial: Maven is
stable state. On the other plugins and about how to install, non trivial because all
hand, since most of the configure and use them, just to file references need to
setups are simple and look for other plugins to evaluate be relative, environment
reusable immediately in all them so that they can be must be completely
the projects using maven integrated in their work controlled and
therefore many important environment. independent from any
reports, checks, build and specific file system.
test animation are added to Maven is the standard way to
all the projects. Which was build projects and it also provides 2. Technology: Maven is a
not possible without maven various other characters like simple core concept that is
because of the heavy cost of clearing the definition of the activated through IoC
every project setup. project, ways to share jars container (Plexus).
across projects. It also provides Everything is done in maven
Maven 2.0 was first released the easy way to publish project through plugins and every
on 19 October 2005 and it is information (OOS). plugin works in isolation
not backward compatible (ClassLoader). Plugings are
with the plugins and the Originally maven was designed downloaded from a plugin-
projects of maven1. In to simplify the building processes repository on demand.
December 2005, a lot of in the Jakarta Turbine project.
plugins were added to Several projects were there Maven's Objectives: The
maven but not all plugins containing their own slightly primary goal of maven is to
that exists for maven1 has different Ant build files and JARs allow the developers to
been ported yet. Maven 2 is were checked into CVS. An comprehend the complete
expected to be stabilized apache group's tool that can state of a project in the
quickly with most of the build the projects, publish project shortest time by using easy

24 Java Jazz Up Sept-07


Building Projects: Learn to Set Up A Maven2 Repository

build process, uniform synchronous to the maven Use cases for maven
building system, quality repository defined in the repository:
project management settings.xml file that exists in
information (such as change the .m2 directory at its It creates two sub-
Log, cross-reference, mailing standard location i.e. repository inside the
lists, dependencies, unit test C:\Documents and internal repository.
reports, test coverage Settings\Administrator. If
reports and many more), no private internal repository Downloads ibiblio-cache
guidelines for best practices is setup and not listed in the from ibiblio for artifacts
and transparent migration to pom.xml or in the setting.xml and make it available
new features. To achieve to then the local repository exists publically. This
this goal Maven attempts to on the developer's machine is synchronizes with
deal with several areas like: synchronized with the public external repository from
maven repository at ibiblio.
It makes the build ibiblio.org.
process easy internal-maven-
Provides a uniform Advantages of having an repository: used for
building system internal private repository : internal artifacts of an
Provides quality related organization. It contains
Poject information Reduces conflicts among unique artifacts for the
Provides guidelines likelihood versions. organization and is not
related to development To build first time it requires synchronized with any
to meet the best goal. less manual intervention. repository.
Allows transparent Rather than having several
migration to new separate independent Alternatively, another
features. libraries it provides a single sub-repository that is
central reference repository not at ibiblio can be
for all the dependent created for artifacts. This
Maven repository Types: software libraries. does not synchronize
It quickly builds the project with any external
Public remote external while using an internal repository.
repository: This public repository as maven artifacts
external repository exists are retrieved from the Browse the remote
at ibiblio.org and maven intranet server rather than repository by using a
synchronizes with this retrieving from the server on web browser.
repository. internet.
Internal private repository Search the artifacts in
Private remote internal of an organisation: the repository.
repository: We set up
this repository and make Download code from
changes in the maven's version control and
pom.xml or settings.xml make changes in
file to use this repository. settings.xml to point to
the internal repository
Local repository: This and build without any
repository is maintained manual intervention.
by the developer and
stays on the developer's Install new version of the
machine. It is artifacts.

Sept-07 Java Jazz Up 25


Building Projects: Learn to Set Up A Maven2 Repository

Import artifacts into the Getting Hands On Setting Up specific shared library or a
repository in bulk. Internal Private Repository For commercial library).
An Organisation
Export artifacts from Software requirements to set
the repository in bulk. We have set up an internal Maven up the maven repository:
Repository for our organisation
Setup the task to backup so that the developers are not Artifactory: Download
wasting time in searching and and install the artifactory
the repository
downloading the required project from the site http://
automatically.
libraries. This also allows us to www.jfrog.org/sites/
have a single company wide artifactory/latest/.
Criteria for choosing a
repository for project artifacts. Artifactory comes with
maven repository
The setup steps are not too much the application that can
implementation: In
complicated but we didn't run be installed into Tomcat.
ideal condition a maven
into several issues while JDK 1.6: Get the
repository
settingup the local repository information for
implementation should
server (artifactory), for the first downloading and
be:
time. installation from the site
Free and open source http://www.jfrog.org/
When you're using maven at sites /artifactory/latest/
Provide admin tools
your company, you almost install .html.
Easy to setup and use always want to setup local maven Tomcat 6.0
Provide backup facility repository as relying on ibiblio for
Able to create, edit and nightly / production builds is not A Quick glance at the
delete sub repositories. a great idea and it takes time to steps of how we set up
Anonymous read only download the library files if your our local maven
access and also access development team is big. When repository :
control facility. setting up a local repository you
Deployable in any don't want to setup the entire 1 Download the
standard web server ibiblio repository locally as it is appropriate
such as Tomcat or huge and has more libraries than Artifactory.zip file. You
Apache. you'll ever be using for your can get it from http://
Issue tracker, forums project. Maven-repository (in our www.jfrog.org/sites/
and other independent case maven artifactory) is a artifactory/latest/.
source of information. repository server, which acts as Download and unzip the
Active community your internal maven repository file in your directory of
developers make the and downloads jars from ibiblio choice. We have
product enhanced and or other public maven downloaded artifactory-
bugs fixed. repositories on demand and 1.2.1.zip at our end.
Bulk import/export store it for further use in the
facility to move groups project builds. And all this is 2 Lets take the Installation
of artifacts into the transparent to the developer directory as
repository and out of the running a maven build. D:\artifactory-
repository. 1.2.2\artifactory-1.2.2,
Provide a repository The other thing about local Extract the artifactory-
maven-repository is that it allows 1.2.1.zip into the
browser: should be a
you to neatly separate and <artifactory-install-
web browser instead of
organize jars that might not be directory> directory.
the desktop application.
available on ibiblio i.e. the 3rd-
party artifacts (some company

26 Java Jazz Up Sept-07


Building Projects: Learn to Set Up A Maven2 Repository

<url>http://repo1.maven.org/maven2
3 Create repository configuration file </url>
artifactory.config.xml into <artifactory- <proxyRef>proxy1</proxyRef>
install-directory>/etc/ directory and </remoteRepository>
paste the following content in the
artifactory.config.xml file: <remoteRepository>
<key>ibiblio.org</key>
<config xmlns:xsi="http://www.w3.org/ <description>ibiblio.org</description>
2001/XMLSchema-instance" <handleReleases>true</handleReleases>
xmlns="http://artifactory.jfrog.org/xsd/ <handleSnapshots>false</
1.0.0" xsi:schemaLocation="http:// handleSnapshots>
artifactory.jfrog.org/xsd/1.0.0 <excludesPattern>org/artifactory/**</
http://www.jfrog.org/xsd/artifactory- excludesPattern>
v1_0_0.xsd"> <url>http://www.ibiblio.org/maven2</
<!-- Backup every 12 hours --> url>
<!--<backupCronExp>0 0 /12 * * ?</ <proxyRef>proxy1</proxyRef>
backupCronExp>--> </remoteRepository>

<localRepositories> <remoteRepository>
<key>java.net</key>
<localRepository> <description>java.net</description>
<key>private-internal-repository</key> <handleReleases>true</handleReleases>
<description>Private internal repository</ <handleSnapshots>false</
description> handleSnapshots>
<handleReleases>true</handleReleases> <excludesPattern>org/artifactory/**,org/
<handleSnapshots>true</ jfrog/**</excludesPattern>
handleSnapshots> <url>http://download.java.net/maven/
</localRepository> 2</url>
<proxyRef>proxy1</proxyRef>
<localRepository> </remoteRepository>
<key>3rd-party</key>
<description>3rd party jars added </remoteRepositories>
manually</description>
<handleReleases>true</handleReleases> <proxies>
<handleSnapshots>false</ <proxy>
handleSnapshots> <key>proxy1</key>
</localRepository> <host>192.168.10.80</host>
<port>9090</port>
</localRepositories> <username></username>
<password></password>
<remoteRepositories> <domain>192.168.10.80</domain>
</proxy>
<remoteRepository> </proxies>
<key>ibiblio</key>
<handleReleases>true</handleReleases> </config>
<handleSnapshots>false</
handleSnapshots> At our end we are using squid proxy server
<excludesPattern>org/artifactory/**,org/ to connect with the internet. Our
jfrog/**</excludesPattern> artifactory repository server will connect to
internet through squid proxy server

Sept-07 Java Jazz Up 27


Building Projects: Learn to Set Up A Maven2 Repository

running on the machine 192.168.10.80 at bin: batch files are used to run the
port 9090. You can also use artifactory included jetty web server.
server without proxy. We have made two lib: Contains all the jar files required to
local and three remote repositories. run any application.
webapps: Contains the war files of an
4 Install Tomcat 6.0 Download and install application. We can also copy and install
tomcat 6.0 on your machine. it in tomcat.
logs: Includes all the log files.
5 Copy artifactor.war from artifactory-
backup: Backs up the repository. We
1.2.1\webapps to the webapps folder of
can use 'cron' expressions to setup the
your installed tomcat directory.
backup policy and Quartz scheduler to
run the backup at the specified time.
6 Specify the local artifactory installation
The backup interval is specified in the
folder to the tomcat environment.
config.xml file inside the
Go to Start-->Programs --> Apache
ARTIFACTORY_INSTALLATION
Tomcat 6.0--> Configure Tomcat and
_FOLDER>/etc/artifactory folder.
specify the installation folder to the Java
data: Includes the derby database files.
Options. -
artifactory.home=<artifactory-install- If you are interested to clean up the
directory> repository then all the things containing
in this folder are deleted. In case of new
7 Now start the tomcat and configure your installation process this folder is empty.
clients to use maven artifactory etc: Includes the artifactory
repository. configuration files
"artifactory.config.xml", "jetty.xml" and
8 To access the admin control panel type "log4j.properties".
http://<server>:<port>/artifactory and
login as User: admin and Password: II. Deployment in Tomcat 6.0 :
password. Deploy the 'war' file of your application in
<ARTIFACTORY_INSTALLATION
_FOLDER>/webapp to
Let's Dig the things Deeper <TOMCAT_INSTALLATION_FOLDER> /
webapps. There is no need to change the
I. Directory Structure of Artifactory-1.2.2 configuration with jdk1.6 and Tomcat 6.0.
: Here are the folders that are shipped with Tomcat detects the web application and
the Artifactory-1.2.2.zip file. deploy it.

Once the application is deployed


successfully, the web application requires
the following information:

* Database location to store artifacts


* Artifactory config xml file location
* Backup folder location

To specify all the above three information, a


single configuration is used. We only need
to specify the artifactory installation folder
location during Tomcat startup and
artifactory does all the rest of the task by

28 Java Jazz Up Sept-07


Building Projects: Learn to Set Up A Maven2 Repository

itself. There is another approach, that is, the organization, this repository does
setup the connection to the derby database not synchronize with the remote
using jdbc and configure artifactory in the repository with ibiblio.
web application (by including
artifactory.config.xml in the web application). Ibiblio-cache: This repository is the
cache of the artifacts from ibiblio and
We can use the environment variable to synchronized with ibiblio.
specify the location of the artifactory
installation folder. In case of Windows, we 3rd party: Publicly available artifacts
can add it to Tomcat startup options and are contained in this repository but not
Configure Tomcat by specifying the in ibiblio repository. Since ibiblio does
installation folder to the Java Options. not have these jar files therefore this
repository is not synchronized with
-Dartifactory.home=<artifactory-install- ibiblio.
directory>
e.g. -artifactory.home=D:\artifactory- This is configured in the
1.2.2\artifactory-1.2.2 <ARTIFACTORY_INSTALLATION
_FOLDER>/etc/artifactory .config.xml. The
configuration to setup these 3 repositories
is shown below:

<config xmlns:xsi="http://www.w3.org/
2001/XMLSchema-instance"
xmlns="http://artifactory.jfrog.org/xsd/
1.0.0" xsi:schemaLocation="http://
artifactory.jfrog.org/xsd/1.0.0
http://www.jfrog.org/xsd/artifactory-
v1_0_0.xsd">
<!-- Backup every 12 hours -->
<!--<backupCronExp>0 0 /12 * * ?</
backupCronExp>-->

<localRepositories>

<localRepository>
<key>private-internal-repository</key>
<description>Private internal repository</
III. Setting up the maven repositories: description>
First create three repositories or we can <handleReleases>true</handleReleases>
say sub-repositories given in the following <handleSnapshots>true
list in our maven repository. </handleSnapshots>
</localRepository>
Private-internal-repository: The
artifacts which are used only within the <localRepository>
organization are contained in this <key>3rd-party</key>
repository. The developer uploads them <description>3rd party jars added
manually. Since the artifacts in this manually</description>
repository (sub-repository) are private to <handleReleases>true</handleReleases>
<handleSnapshots>false

Sept-07 Java Jazz Up 29


Building Projects: Learn to Set Up A Maven2 Repository

</handleSnapshots> as 'password'. You can view the content of


</localRepository> the repository simply by clicking on the
Repository Browser link.
</localRepositories>

<remoteRepositories>

<remoteRepository>
<key>ibiblio</key>
<handleReleases>true</handleReleases>
<handleSnapshots>false</
handleSnapshots>
<excludesPattern>org/artifactory/**,org/
jfrog/**</excludesPattern>
<url>http://repo1.maven.org/maven2</
url>
</remoteRepository>

</remoteRepositories>
V. Configuring maven to use the new
</config> repository:

IV. Navigate Artifactory: You can use either of the settings.xml or


the pom.xml files to configure maven to
Start Tomcat, open the browser and use the local repository.
navigate http://localhost:8080/
artifactory Configure maven using settings.xml file:
Maven uses the settings.xml file contained in
Here is the artifactory home page shown .m2 folder inside the C\Document and
below: Setting\Administrator to get the location of
the maven repository. In case of no repository
is specified then maven uses the default
repository from ibiblio.org. We will have to
make changes in the settings.xml file to use
the new repository. Here is the settings.xml
shown below:

<profiles>
<profile>
<id>dev</id>
<properties>
<tomcat6x.home>C:/InstalledPrograms/
apache-tomcat-6.0</tomcat6x.home>
</properties>
<repositories>
<repository>
<id>central</id>
<url>http://localhost:8080/artifactory/
Sign in username as 'admin' and password repo</url>

30 Java Jazz Up Sept-07


Building Projects: Learn to Set Up A Maven2 Repository

<snapshots> <packaging>jar</packaging>
<enabled>false</enabled> <version>1.0-SNAPSHOT</version>
</snapshots> <name>test</name>
</repository> <url>http://maven.apache.org</url>
<repository> <repositories>
<id>snapshots</id> <repository>
<url>http://localhost:8080/artifactory/ <id>central</id>
repo</url> <url>http://localhost:8080/artifactory/
<releases> repo</url>
<enabled>false</enabled> <snapshots>
</releases> <enabled>false</enabled>
</repository> </snapshots>
</repositories> </repository>
<pluginRepositories> <repository>
<pluginRepository> <id>snapshots</id>
<id>central</id> <url>http://localhost:8080/artifactory/
<url>http://localhost:8080/artifactory/ repo</url>
repo</url> <releases>
<snapshots> <enabled>false</enabled>
<enabled>false</enabled> </releases>
</snapshots> </repository>
</pluginRepository> </repositories>
<pluginRepository> <pluginRepositories>
<id>snapshots</id> <pluginRepository>
<url>http://localhost:8080/artifactory/ <id>central</id>
repo</url> <url>http://localhost:8080/artifactory/
<releases> repo</url>
<enabled>false</enabled> <snapshots>
</releases> <enabled>false</enabled>
</pluginRepository> </snapshots>
</pluginRepositories> </pluginRepository>
</profile> <pluginRepository>
</profiles> <id>snapshots</id>
<url>http://localhost:8080/artifactory/
Configure maven using project "pom.xml" : repo</url>
We can also set the repository settings <releases>
through the pom.xml file. Simple pom.xml <enabled>false</enabled>
is shown below: </releases>
</pluginRepository>
<project xmlns="http:// </pluginRepositories>
maven.apache.org/POM/4.0.0" <dependencies>
xmlns:xsi="http://www.w3.org/2001/ <dependency>
XMLSchema-instance" <groupId>junit</groupId>
xsi:schemaLocation="http:// <artifactId>junit</artifactId>
maven.apache.org/POM/4.0.0 <version>3.8.1</version>
http://maven.apache.org/maven- <scope>test</scope>
v4_0_0.xsd"> </dependency>
<modelVersion>4.0.0</modelVersion> </dependencies>
<groupId>test</groupId> </project>
<artifactId>test</artifactId>

Sept-07 Java Jazz Up 31


Building Projects: Learn to Set Up A Maven2 Repository

VI. Building using the new maven


repository

While building the maven project, all the


repositories should be downloaded using
the new repository. The console will show
the server maven uses as shown below:

VII. Installing artifacts to the


repository :

We can use the web UI or maven command


line to install the artifacts. Installation
process through the web UI is simpler and
faster and does not require any change in
the configuration. While installation through
the command line requires changes in the
configuration in settings.xml and then we
can use it in other scripts.
Login into your new repository through the Installing artifacts using the web UI: Steps
web browser and you see that the involved in the installation process are
artifactory has downloaded and cached the shown below:
artifacts from ibiblio.
1 Upload artifact (e.g. 'jar' file or 'pom'
file) and deploy using Artifact Deployer.

It provides an advance search facility that 2 If you upload the jar file then the
can be used to search an artifact simply artifactory will create the pom.xml file as
by using the advanced search technique. well as you can also specify which
repository to upload to.

32 Java Jazz Up Sept-07


Building Projects: Learn to Set Up A Maven2 Repository

The command given below is used to install


an artifact to internal maven repository.

mvn deploy:deploy-file -
DrepositoryId=organisation-internal -
Durl=http://localhost:8080/artifactory/
private-internal-repository-DgroupId=
test -DartifactId=test -Dversion=
1.1 -Dpackaging=jar -Dfile=target/test-
1.1.jar

Both the repository id and the server id


defined in the settings.xml should be same.
The url should include the repository name
to which the artifact is to be installed. The
artifactory and the new artifacts appeared
3 Once uploading is complete successfully, in the repository creates the 'pom'
the artifact along with the pom.xml file (pom.xml) file for us automatically.
created by artifactory appears in the
repository.

Installing artifacts from maven command


line:Using the command 'maven clean
install' maven only packages and installs
the artifact to the local repository. We need
to add the additional configuration section
in the settings.xml file to install it to the
local internal repository. Steps involved in
whole of the process are shown below:

settings.xml

<settings>

<servers>
<server>
<id>organisation-internal</id> VIII. Other Artifactory features:
<username>admin</username>
<password>password</password> * Backup the repository: Backup policy
</server> is specified in the
</servers> <ARTIFACTORY_INSTALLATION _FOLDER>/
etc/artifactory .config.xml and 'cron'
</settings> expression specifies the backup
configuration. Backup configuration is
shown below:

Sept-07 Java Jazz Up 33


Building Projects: Learn to Set Up A Maven2 Repository

<config xmlns:xsi="http://www.w3.org/ The directory


2001/XMLSchema-instance" <ARTIFACTORY_INSTALLATION
xmlns="http://artifactory.jfrog.org/xsd/ _FOLDER>/backups contains the backups.
1.0.0" The local repository on the developer's
xsi:schemaLocation="http:// machine and the backups both have the
artifactory.jfrog.org/xsd/1.0.0 same format. It allow us the repository
http://www.jfrog.org/xsd/artifactory- contents to migrate easily to another
v1_0_0.xsd"> implementation of maven repository.
<!-- Backup every 12 hours -->
<backupCronExp>0 0 /12 * * ? Other features:
</backupCronExp>
<localRepositories> Use the web UI to delete the artifacts
<localRepository> Use the web UI to search for artifacts.
<key>private-internal-repository</key> Bulk import/export all artifacts in
<description>Private internal repository repository.
</description> If tomcat is not required then we can
<handleReleases>true</ use the included jetty web server.
handleReleases>
<handleSnapshots>true Conclusion: The overall conclusion is that
</handleSnapshots> an internal maven repository helps us to
</localRepository> avoid conflicts due to different versions of
<localRepository> libraries and it also speeds up the build
<key>3rd-party</key> process. Artifactory seems the better product
<description>3rd party jars added among the 4 common maven repository. It
manually</description> has all the features that a good maven
<handleReleases>true repository should have. The organization will
</handleReleases> not be locked into this tool since migration
<handleSnapshots>false of the repository to another implementation
</handleSnapshots> is rather easy. A web UI simplifies the use of
</localRepository> the repository even for the peoples who don't
</localRepositories> know the working of the repository.
<remoteRepositories>
<remoteRepository>
<key>ibiblio</key>
<handleReleases>true
</handleReleases>
<handleSnapshots>false
</handleSnapshots>
<excludesPattern>org/artifactory/
**,org/jfrog/**</excludesPattern>
<url>http://repo1.maven.org/maven2
</url>
</remoteRepository>
</remoteRepositories>
</config>

34 Java Jazz Up Sept-07


Maven2 with JPA Example

Getting Started with Maven2 : Download Directory Structure of the example: Our
Maven2 from maven.apache.org, unzip application must maintain a directory
the archive into your local directory. Here structure understandable by the maven
we are assuming that the local repository project build tool. It is shown below:
already exists.
Our Application includes: Our application
Set the JAVA_HOME variable to point to the includes the source folder "src" and an
JDK installation directory and pom.xml file. Source folder contains java
MAVEN_HOME to point to the Maven files, here HelloWorld.java and Message.java
directory and add the MAVEN_HOME/bin to files are contained in the hello folder.
the PATH environment variable. Resource folder exists parallel to the java
folder inside the main folder and contains
To test, whether the path has been set log4j.properties file and the META-INF folder.
properly. Type mvn -version on the META-INF folder contains persistence.xml file.
command prompt. "pom.xml" is the main file for the maven build
system that includes information about the
C:\>mvn -versionMaven tools required to build the application.
version: 2.0.7Java version:1.5.0OS name:
windows 2000 version: 5.0 arch:x86

Developing java presistence


example with Maven2

Here I will show, how to build a very


simple example that uses java persistence
API. Maven2 highly simplifies the build
process, all the required libraries are
downloaded automatically only when it
really requires.

1. Create a java class (lets take it


Message.java ), where you map java class/
properties to database table/fields. Java
persistence annotations will do this job for
us:

package hello;
import javax.persistence.*;
@Entity
@Table(name = "MESSAGES")
public class Message {
@Id @GeneratedValue @Column(name =
"MESSAGE_ID")
private Long id;

Sept-07 Java Jazz Up 35


Maven2 with JPA Example

@Column(name = "MESSAGE_TEXT") HelloWorld.java


private String text; package hello;
@ManyToOne(cascade = CascadeType.ALL) import java.util.*;
@JoinColumn(name = import javax.persistence.*;
"NEXT_MESSAGE_ID") public class HelloWorld {
private Message nextMessage; public static void main(String[] args) {
// Start EntityManagerFactory
public Message() {} EntityManagerFactory emf =
Persistence.createEntity
public Message(String text) { ManagerFactory("helloworld");
this.text = text; // First unit of work
} EntityManager em =
emf.createEntityManager();
public Long getId() { EntityTransaction tx =
return id; em.getTransaction();
} tx.begin();

private void setId(Long id) { Message message = new Message("Hello


this.id = id; World with JPA");
} em.persist(message);

public String getText() { message = new Message("This is message


return text; 2");
} em.persist(message);
public void setText(String text) {
this.text = text; message = new Message("This is message
} 3");
em.persist(message);
public Message getNextMessage() { tx.commit();
return nextMessage; em.close();
} // Second unit of work
EntityManager newEm =
public void setNextMessage(Message emf.createEntityManager();
nextMessage) { EntityTransaction newTx =
this.nextMessage = nextMessage; newEm.getTransaction();
} newTx.begin();
}
List messages =
Here "Message" class is mapped to newEm.createQuery("select m from
"MESSAGES" table, "id", "text" and Message m order by m.text
"nextMessage" properties - to asc").getResultList();
"MESSAGE_ID", "MESSAGE_TEXT" and
"NEXT_MESSAGE_ID" fields. System.out.println( messages.size() + "
message(s) found:" );
2. Now create a simple program (
HelloWorld.java ) that uses persistent for (Object m : messages) {
"Message" object: Message loadedMsg = (Message) m;
System.out.println(loadedMsg.getText());
}

36 Java Jazz Up Sept-07


Maven2 with JPA Example

newTx.commit(); <!-- SQL stdout logging -->


newEm.close(); <property name="hibernate.show_sql"
// Shutting down the application value="true"/>
emf.close(); <property name="hibernate.format_sql"
} value="true"/>
} <property name="use_sql_comments"
value="true"/>
This example does not refer to any <property name="hibernate.dialect"
persistent framework directly. Instead, it value="org.hibernate.dialect.HSQLDialect"/>
uses symbolic names to access the <property
framework in indirect way. In the above name="hibernate.connection.driver_class"
mentioned example we have used value="org.hsqldb.jdbcDriver"/>
"helloworld" name to refer to the ORM <property
framework. name="hibernate.connection.url"
value="jdbc:hsqldb:file:persistence-db/
3. In this example we used Hibernate test"/>
(http://hibernate.org) as persistence <property
framework and hsqldb (http://hsqldb.org) name="hibernate.connection.username"
as database. Let's take a look at the value="sa"/>
hibernate configuration file <property
(persistence.xml) where we describe name="hibernate.hbm2ddl.auto"
"helloworld" factory: value="create"/>
<property name="hibernate.c3p0.min_size"
persistence.xml value="5"/>
<persistence xmlns="http://java.sun.com/ <property name="hibernate.c3p0.max_size"
xml/ns/persistence" value="20"/>
xmlns:xsi="http://www.w3.org/2001/ <property name="hibernate.c3p0.timeout"
XMLSchema-instance" value="300"/>
xsi:schemaLocation="http://java.sun.com/ <property
xml/ns/persistence name="hibernate.c3p0.max_statements"
http://java.sun.com/xml/ns/persistence/ value="50"/>
persistence_1_0.xsd" <property
version="1.0"> name="hibernate.c3p0.idle_test_period"
value="3000"/>
<!-- persistence.xml --> </properties>
</persistence-unit>
<persistence-unit name="helloworld"> </persistence>

<!-- The provider only needs to be set if persistence.xml should be located on your
you use several JPA providers --> CLASSPATH within META-INF directory.
<provider> "hibernate.hbm2ddl.auto" property will
org.hibernate.ejb.HibernatePersistence take care of creating database table
</provider> automatically.
<properties>
<!-- Scan for annotated classes and 4. Create a Maven2 file i.e. pom.xml file,
Hibernate mapping XML files --> responsible for downloading all dependent
<property libraries, building correct CLASSPATH for the
name="hibernate.archive.autodetection" project and running the example. POM is the
value="class, hbm"/> fundamental unit of work in Maven. It is an
xml file that contains information about the
Sept-07 Java Jazz Up 37
Maven2 with JPA Example

project and configuration details used by </artifactId>


Maven to build the project. It contains default <version>3.2.1.ga</version>
values for most projects. For example, the </dependency>
build directory, which is target, the source
directory, which is src/main/java the test <dependency>
source directory, which is src/main/test and <groupId>org.hibernate</groupId>
so on. POM also contains the goals and <artifactId>hibernate-entitymanager</
plugins. So, while executing a task or goal, artifactId>
Maven looks for the POM in the current <version>3.2.1.ga</version>
directory. It reads the POM, gets the needed </dependency>
configuration information, and then executes
the goal. Some of the configuration that can <dependency>
be specified in the POM are the project <groupId>org.hibernate</groupId>
dependencies, the plugins or goals that can <artifactId>hibernate-tools</artifactId>
be executed, the build profiles, and so on. <version>3.2.0.beta9a</version>
Other information such as the project version, </dependency>
description, developers, mailing lists and such
can also be specified. <dependency>
<groupId>c3p0</groupId>
pom.xml <artifactId>c3p0</artifactId>
<version>0.9.1</version>
<?xml version="1.0" encoding="UTF-8"?> </dependency>
<project> </dependencies>
<modelVersion>4.0.0</modelVersion>
<groupId>persistence-deps</groupId> <build>
<artifactId>persistence-deps</artifactId> <defaultGoal>compile</defaultGoal>
<version>1.0</version>
<dependencies> <plugins>
<plugin>
<dependency> <groupId>org.apache.maven.plugins</
<groupId>commons-logging</groupId> groupId>
<artifactId>commons-logging</artifactId> <artifactId>maven-compiler-plugin</
<version>1.0.4</version> artifactId>
</dependency> <configuration>
<source>1.5</source>
<dependency> <target>1.5</target>
<groupId>hsqldb</groupId> </configuration>
<artifactId>hsqldb</artifactId> </plugin>
<version>1.8.0.7</version>
</dependency> <plugin>
<groupId>org.codehaus.mojo</groupId>
<dependency> <artifactId>exec-maven-plugin</
<groupId>org.hibernate</groupId> artifactId>
<artifactId>hibernate</artifactId> <executions>
<version>3.2.2.ga</version> <execution>
</dependency> <goals>
<goal>java</goal>
<dependency> </goals>
<groupId>org.hibernate</groupId> </execution>
<artifactId>hibernate-annotations

38 Java Jazz Up Sept-07


Maven2 with JPA Example

</executions> Hibernate:
<configuration> call identity()
<mainClass>hello.HelloWorld</mainClass> Hibernate:
</configuration> insert
</plugin> into
</plugins> MESSAGES
</build> (MESSAGE_ID, MESSAGE_TEXT,
<!-- NEXT_MESSAGE_ID)
<repositories> values
<repository> (null, ?, ?)
<id>scriptlandia-repo</id> Hibernate:
<name>Scriptlandia Maven2 repository</ call identity()
name> Hibernate:
<url>http://scriptlandia- select
repository.googlecode.com/svn/trunk/ message0_.MESSAGE_ID as
tools</url> MESSAGE1_0_,
</repository> message0_.MESSAGE_TEXT as
</repositories> MESSAGE2_0_,
--> message0_.NEXT_MESSAGE_ID as
</project> NEXT3_0_
from
MESSAGES message0_
4. Open the command prompt. Go inside order by
the project directory of your application message0_.MESSAGE_TEXT asc
(MyApplication in this case) and run the 3 message(s) found:
"mvn compile exec:java" command. Hello World with JPA
This is message 2
C:\MyApplication >mvn compile exec:java This is message 3
Aug 21, 2007 3:18:06 AM
After successfully running the command, org.hibernate.impl.SessionFactoryImpl
your command prompt will display the close
output on the console shown below: INFO: closing
Hibernate: [INFO] ---------------------------------------
insert [INFO] BUILD SUCCESSFUL
into [INFO] ---------------------------------------
MESSAGES [INFO] Total time: 34 seconds
(MESSAGE_ID, MESSAGE_TEXT, [INFO] Finished at: Tue Aug 21 03:18:06
NEXT_MESSAGE_ID) GMT+05:30 2007
values [INFO] Final Memory: 6M/11M
(null, ?, ?) [INFO] ---------------------------------------
Hibernate:
call identity() On building successfully, our application
Hibernate: displays the messages given below on the
insert console:
into
MESSAGES Hello World with JPA
(MESSAGE_ID, MESSAGE_TEXT, This is message 2
NEXT_MESSAGE_ID) This is message 3
values
(null, ?, ?)

Sept-07 Java Jazz Up 39


Database Testing with DbUnit
DbUnit : 2 It provides a very simple XML based
mechanism for loading test data.
DbUnit is an open source Framework 3 It provides equally a simple mechanism
created by Manuel Laflamme. This is a to export existing test data into the XML
powerful tool for simplifying Unit Testing of format for subsequent use.
the database operations. 4 It can work with very large datasets.
It extends the popular JUnit test 5 It can help verify your data matches an
framework that puts the database into a expected set of values.
known state while the test executes. This 6 It provides methods for comparing data
strategy helps to avoid the problem that between flat files, queries and database
can occur when one test corrupts the tables.
database and causes subsequent test to
fail. DbUnit provides a very simple XML Setting up the environment :
based mechanism for loading the test data,
in the form of data set in XML file, before a To run the example of DbUnit in Eclipse, we
test runs. Moreover the database can be need jar files of DbUnit, JUnit and Jakarta
placed back into its pre-test state at the Commons IO. DbUnit is available from
completion of the test. DbUnit web site, http://www.dbunit.org.
JUnit is available from http://
Advantages of DbUnit : www.junit.org. commons-io-1.3.2.jar can
The reasons to use this testing tool can be be found from http://mirrors.kahuki.com/
summarized as follows : apache/commons/io/binaries/commons-io-
1 A framework which simplifies operations 1.3.2-bin.zip. Now these jar files are
for each stage in the life cycle of required to be added in the referenced
individual database tests. library of your testing directory.

40 Java Jazz Up Sept-07


Database Testing with DbUnit

DbUnit test Life Cycle : }


protected DatabaseOperation
DbUnit framework follows some steps in its getTearDownOperation() throws Exception{
life cycle : return DatabaseOperation.NONE;
}
1 Removing the old data left in the
database from previous tests. DbUnit can work with default behavior,
2 Loading some data from XML file into however, you can override the methods
the database. according to the s requirement.
3 Running the test.
Getting Started : For the database
DatabaseTestCase class provides two purpose we have used MySQL
methods setUp() and TearDown() which
internally call getSetUpOperation() and 1 Create a table "login" in the database
getTearDownOperation() methods "hrapptest" in MySQL like below :
respectively. setUp() method provides the
setup operation login Table in database:
DatabaseOperation.CLEAN_INSERT or
Field Type Collation Null Key Default
DatabaseOperation.REFRESH. ----- ----- ---------- ----- ---- --------
id bigint(20) (NULL) NO PRI
DatabaseOperation.CLEAN_INSERT empcode varchar(15) latin1_swedish_ci YES (NULL)
operation is the combination of two loginname varchar(30) latin1_swedish_ci NO
password varchar(30) latin1_swedish_ci NO
operations DELETE_ALL and INSERT. So loginenabled varchar(1) latin1_swedish_ci NO
data defined in the XML file is loaded in the
database by this operation. First two steps 2 Create XML file (for example,
of the life cycle are executed when "input.xml") representing the database
executing the setUp() method before tables and the data within it. Put a data
running the test. These steps allow you not set in this file like below. In this file
to waste time in writing code to restore "login" is the table name in the database
state in the database. and "id", "empcode" etc are the columns
in the table. Put values for the fields in
DatabaseOperation.REFRESH updates the this file.
desired database with the data found in the
XML file. The getTearDownOperation() input.xml :
performs a NONE operation which does
nothing. <?xml version='1.0' encoding='UTF-8'?>
<dataset>
protected void setUp() throws Exception{ <!--Login Table -->
super.setUp(); <login id="1" empcode="E005"
executeOperation(getSetUpOperation()); loginname="chandan"
} password="chandan" loginenabled="y"/>
protected void tearDown() throws <login id="2" empcode="E006"
Exception{ loginname="deepak" password="deepak"
super.tearDown(); loginenabled="n"/>
executeOperation(getTearDownOperation()); </dataset>
}
protected DatabaseOperation 3 DbUnit framework provides an abstract
getSetUpOperation() throws Exception{ class named "DatabaseTestCase" which
return is a sub class of JUnit's "TestCase" class.
DatabaseOperation.CLEAN_INSERT; So instead of creating a subclass of

Sept-07 Java Jazz Up 41


Database Testing with DbUnit

TestCase class we need to extend represents database connection created


DatabaseTestCase class. This class using DriverManager class. In the above
provides two abstract methods code, IDatabaseConnection represents
"getConnection()" and "getDataSet()". MySQL database where hrapptest is the
name of database where username and
IDatabaseConnection getConnection() password both are "deepak".
throws Exception getDataSet() method uses the
protected IDataSet getDataSet() throws FlatXmlDataSet class to load "input.xml"
Exception. file and return this loaded data set as an
object implementing IDataSet interface.
Because of its being an abstract class we IDataSet provides many useful methods to
need to implement these two methods: return data sets.

TestDbUnit.java : 4. Writing Test :

........................... Now, write test to check that the data has


........................... been loaded in TestDbUnit.java file:

// Provide a connection to the database ............................


protected IDatabaseConnection ............................
public void testCheckLoginDataLoaded()
getConnection() throws Exception{ throws Exception{
Class driverClass = Class.forName assertNotNull(loadedDataSet);
("com.mysql.jdbc.Driver"); int rowCount = loadedDataSet.getTable
(TABLE_LOGIN).getRowCount();
Connection jdbcConnection = assertEquals(2, rowCount);
DriverManager.getConnection }
("jdbc:mysql://localhost:3306/hrapptest", ............................
"root", "root"); ............................

return new Combining all of the above functionalities


into one TestDbUnit.java file, you will find it
DatabaseConnection(jdbcConnection); as follows :
}
// Load the data which will be inserted for TestDbUnit.java :package test;
the test
import java.sql.Connection;
protected IDataSet getDataSet() throws import java.sql.DriverManager;
Exception{ loadedDataSet = import org.dbunit.DatabaseTestCase;
new FlatXmlDataSet(this.getClass() import
.getClassLoader().getResourceAsStream org.dbunit.database.DatabaseConnection;
("input.xml")); import
return loadedDataSet; org.dbunit.database.IDatabaseConnection;
} import org.dbunit.dataset.IDataSet;
............................ import
............................ org.dbunit.dataset.xml.FlatXmlDataSet;
public class TestDbUnit extends
getConnection() method returns DatabaseTestCase{
IDatabaseConnection object that public static final String TABLE_LOGIN =

42 Java Jazz Up Sept-07


Database Testing with DbUnit

"login"; FlatXmlDataSet(this.getClass().getClassLoader().
getResourceAsStream("input.xml"));
private FlatXmlDataSet loadedDataSet; return loadedDataSet;
}
// Provide a connection to the database // Check that the data has been loaded.
protected IDatabaseConnection public void testCheckLoginDataLoaded()
getConnection() throws Exception{ throws Exception{
Class.forName("com.mysql.jdbc.Driver"); assertNotNull(loadedDataSet);
Connection jdbcConnection = int rowCount =
DriverManager.getConnection("jdbc:mysql:/ loadedDataSet.getTable(TABLE_LOGIN).
/localhost:3306/hrapptest", "root", "root"); getRowCount();
return new assertEquals(2, rowCount);
DatabaseConnection(jdbcConnection); }
} }

// Load the data which will be inserted for Running Test :


the test Now, in Eclipse, go to Run->Run As and
protected IDataSet getDataSet() throws click "JUnit Test" to run tests. If testing is
Exception{ successful then a green strip appears at
loadedDataSet = new the left of the eclipse window. If any of the
test fails then it turns into a red strip
indicating failure of any test.

Sept-07 Java Jazz Up 43


Creational Design Patterns
Singleton Pattern: package singleton;
import org.apache.log4j.Priority;
import java.util.GregorianCalendar;
The singleton design pattern deals with import java.text.SimpleDateFormat;
one and only one instance of an object that import java.io.FileOutputStream;
encapsulates the control of the object from import java.util.Properties;
a common place. There are various ways import java.io.PrintStream;
of achieving this pattern. import java.io.InputStream;
import java.io.IOException;
For example, create an exception that is
thrown by a class if the class is instantiated
more than once. Next declare a boolean public class Logger {
variable and make it static so that it can private String fileName;
be shared among all the instances of a private Properties properties;
class. Initialize this static variable inside private Priority priority;
the constructor of this class. The
constructor would throw an exception if it private Logger() {
is initialized second time. It is the best logger = this;
technique of using the singleton pattern. }
But take care to set the variable whenever
destroying during the finalize method call. public int getRegisteredLevel() {
int i = 0;
Another approach of creating Singleton try {
method includes a static method and InputStream inputstream =
private constructor in a class. Declaring the getClass().getResourceAsStream
constructor as private ensures that the ("Logger.properties");
instance variable can be created only from properties.load(inputstream);
inside the method of the class. The static inputstream.close();
method sets the variable as boolean that i = Integer.parseInt(properties.getProperty
indicates the creation of the instance and ("logger.registeredlevel"));
returns an instance. if(i < 0 || i > 3)
i = 0;
Benefits: Singleton pattern controls }
access to unique instances, reduce name catch(Exception exception) {
space, permits a variable number of System.out.println("Logger: Failed in the
instances, allows refinement of operations getRegisteredLevel method");
and representations, and provides more exception.printStackTrace();
flexibility than class operations. }
return i;
Usage: These are used in those places }
where there is only one instance of a class.
The Singleton pattern is mostly used in private String
multi-threaded applications. Singleton getFileName(GregorianCalendar gc) {
patterns are often used as global variables SimpleDateFormat dateFormat1 = new
because the global variables permit SimpleDateFormat("dd-MMM-yyyy");
allocation and initialization whenever String dateString =
required. They don't permit to pollute the dateFormat1.format(gc.getTime());
global namespace with unnecessary String fileName =
variables. "C:\\prashant\\patterns\\log\\PatternsExceptionLog-
" + dateString + ".txt";

44 Java Jazz Up Sept-07


Creational Design Patterns

return fileName; Example:


}
final class Logger {
public void logMsg(Priority p, String //implementation of a static class of a
message) { Singleton pattern
try { static public void logMessage(String s) {
GregorianCalendar gc = new System.out.println(s);
GregorianCalendar(); }
String fileName = getFileName(gc); }
FileOutputStream fos = new
FileOutputStream(fileName, true); public class StaticLogger {
PrintStream ps = new PrintStream(fos); public static void main(String args[]) {
SimpleDateFormat dateFormat2 = new Logger.logMessage("This is SINGLETON");
SimpleDateFormat("EEE, MMM d, yyyy 'at' }
hh:mm:ss a"); }
ps.println("<"+dateFormat2.format
(gc.getTime())+">["+message+"]"); The advantage of this static approach is
ps.close(); that its easier to use. The disadvantage of
} course is that if in future you do not want
catch (IOException ie) { the class to be static anymore, you will
ie.printStackTrace(); have to do a lot of recoding.
}
} Builder Pattern:

public static void initialize() { This design pattern allows the client to
logger = new Logger(); construct a complex object based on its
} type and content. One can achieve the way
// singleton - pattern of constructing the objects by using the
private static Logger logger; factory pattern. This is similar to the
public static Logger getLogger() { abstract factory pattern as both returns a
return logger; group of related objects. The only
} difference between these two patterns is
} that Builder pattern makes a complex
object step by step on the basis of data
passed to it.
Difference between static class and static
method approaches: One question that Benefits: These types of patterns provide
comes to most of the people's mind is that greater control over construction process,
" Whats the difference between a static separation between the construction and
class and a singleton class?" The answer is representation, and support to change the
static class is one of the approaches that internal representation of objects.
makes a class Singleton.
Usage: Builder is useful in those conditions
We can create and declare a class as final where you need to assemble several
simply by declaring all its methods as different kinds of complex objects at run-
static. In this case, you can call the static time. Once it is created it isolates the
methods directly but cant create any building process of object, from the object
instance of class. itself. Different objects may be constructed
by using similar methods but once the

Sept-07 Java Jazz Up 45


Creational Design Patterns

object is constructed it may exhibit Now the class pizza further extended to
different behavior. Italianpizza, Cheesepizza etc. All these
classes will implement the price() method
First lets create an interface named Item and return a price for each type of pizza.
which contains the two public methods one In this example we are implementing the
for packaging the item and other for Italianpizza class of the Pizza class.
defining the price of each item.
Italianpizza.java
We are putting all the classes in the
package builder. package builder;

package builder; public class Italianpizza extends Pizza {

public interface Item { public int price() {


return 200;
public Packing pack(); }
}
public int price();
Now lets consider the item Ice Cream
}
IceCream.java
package builder;
Now, we define the classes for each of the
item, as pizza, ice cream and cold drink. public class IceCream implements Item {
All these classes will implement the Item
interface. public Packing pack() {
return new Envelop();
Lets start with Pizza. Here we are making }
the pizza.java class as abstract because
we will implement price method according public int price() {
the type of the pizza. A pizza is wrapped return 20;
in the paper and is served. The class }
Wrapper is sub-class of Packing interface. }

Lets consider this class as Pizza.java


Now, lets see the Builder class,
package builder; MealBuilder. This is the class which serves
the meal.
public abstract class Pizza implements
Item { MealBuilder.java
package builder;
public Packing pack() {
return new Wrapper(); public class MealBuilder {
} public Packing additems() {
public abstract int price(); Item[] items = {new Italianpizza(), new
} IceCream(), new Coke()}

return new MealBox().addItems(items);


}

46 Java Jazz Up Sept-07


Creational Design Patterns

public int CalculatePrice() { Usage: These are used when you are not
int totalPrice = new Italianpizza().price() + interested in constructing a class hierarchy
new Coke().price() + new of factories which is parallel to the class
IceCream().price(); hierarchy of products. Instances of a class
can have only one combination of state,
return totalPrice; the classes are instantiated at run-time.
}
} Example: Let's create an interface and
implement it in the various classes.

This class calculates the total meal and its Shape.java


total price. Here, we have extracted the
price calculation and meal package interface Shape {
building activity, that is a meal box. The public void draw();
Builder pattern hides the internal details of }
how the product is built. Since each builder
is independent of others therefore it Square.java
improves modularity and makes the class Square implements Shape {
building of other builders easy. Because, public void draw() {
each builder builds the final product step System.out.println("square");
by step, we have more control on the final }
product. }

The conclusion is that in Builder Pattern, Circle.java


the client instructs the builder class what it class Circle implements Shape {
needed and asks for the result, the client is public void draw() {
not interested how the builder class will System.out.println("circle");
create the objects. }
}
Painting.java
class Painting {
The Prototype Pattern: public static void main(String[] args) {

This pattern enables you to copy or clone Shape s = new Square();


of an existing object instead of creating the Shape c = new Circle();
new one and may also customized as per
the requirement. It copies the existing paint(s);
object to avoid so much overhead. We can paint(c);
also use the clone method by }
implementing the Clonable interface to static void paint(Shape s1) {
create the copy of the existing object. s1.draw();
}
Benefits: It supports for specifying the }
new objects with varying structure and
varying values, adding and removing
products at runtime, dynamically At the runtime, the paint method takes a
configuring the classes for an application variable of Shape type and the draw
and reducing sub-classing. method is called accordingly.

Sept-07 Java Jazz Up 47


Creational Design Patterns

Overloading method is a kind of prototype


pattern too.

Painting.java

class Painting {
public void draw(Point p, int x, int y) {
}
public void draw(Point p, int x) {
}
}

To draw the related shape the draw


method is called on the bases of the
parameters passed to it.

48 Java Jazz Up Sept-07


Web services with Lomboz
Lomboz plug-in
In this article, we will discuss the Lomboz A whole new JSP editor with
plug-in and its usability in developing web
services. o Java Servlet previews
o JSP and HTML code assist with syntax
Lomboz is an open source and free JEE checking and highlighting
development environment used for o Tracking of JSP errors with standard
businesses and individual purposes. Eclipse problem markers
o The ability to edit a JSP file regardless of
With Lomboz , one can develop, test, profile how it is packaged in web modules.
and deploy Web Services, Java, JEE and EJB o Code assists for TLDs and taglibs.
applications. It provides comprehensive
support for most of the JEE standard Application Server support
application server runtimes, and supports
other vendor runtime environments too. o Application server launchers and
stoppers for and almost any J2EE
Lomboz is built on the Eclipse open source compliant server including:
platform and the Web Tools Platform (WTP) JBoss, Resin, Tomcat, JRun,
projects. It is a free Eclipse plug-in for JEE BEA WebLogic Server, new: IBM
developers. Lomboz is integrated with many WebSphere, Oracle 9iAS, Orion, and
popular open source JEE tools such as: -new- JOnAS, the open source
Jasper, XDoclet, Axis and Ant and even more application server of ObjectWeb
naturally with Eclipse and the Eclipse Java o Manage and launch multiple application-
Development Toolkit (JDT). server configurations inside Eclipse in
Run or Debug modes
Lomboz implements an end-to-end JEE o JSP debugging for Tomcat and BEA
application development by providing WebLogic Server
support for the complete development cycle: o Manage multiple Web, EJB and
Code, deploy, test and debug. Application (EAR) modules inside the
same project.
Salient features of Lomboz : o Ability to target multiple application
servers from the same project
Wizards for rapid coding: Containers,
Servlets, JSPs, and EJBs Web Services Support

o Flexibility to manipulate the launching o Web Services wizards


and deployment behaviors by allowing o Web Services code generators
developers to modify corresponding XML
scripts EAR support
o JEE Project Outlining View: Allowing
developers to view and manipulate Create application archives quickly and
containers in projects deploy them on application servers using
o EJB code generators Lomboz actions. A graphical application.xml
o Improved EJB and XDoclet wizards editor allows you to edit the contents of an
application rapidly.

Sept-07 Java Jazz Up 49


Developing web services with Lomboz plug-in

Lets develop web services with Lomboz

Now lets create a simple web service and a


client web application using eclipse IDE
along with Lomboz plug in. We will deploy
and test the web service on Tomcat 5.5.4
web application server.

I. Environment
Jdk1.5.0 gets it at: http://java.sun.com/
Eclipse 3.1 gets it at: http://
www.eclipse.org/
Tomcat 5.5.4 gets it at: http://
tomcat.apache.org/
Lomboz 3.1RC2 gets it at: http://
lomboz.objectweb.org/ 3. Set up the Server view in eclipse
(Windows -> Show View -> Other)
II. Installation
Install JDK (in D:\ jdk1.5.0)
Install Tomcat (in E:\Tomcat5.5)
Install Eclipse (in E:\Eclipse3.1)
Install Lomboz (in E:\Eclipse3.1)

III. Set Ups

1. Set up the installed JRE in eclipse


(Windows -> Preferences -> Java ->
Installed JREs)

4. Set up the Tomcat Server by right


clicking and selecting New -> Server option
from the Server view in eclipse

2. Set up the installed runtime for server in


eclipse (Windows -> Preferences -> Server
-> Installed Runtimes)

50 Java Jazz Up Sept-07


Developing web services with Lomboz plug-in

2. Enter name as WebServiceTutorial,


select project location as E:\Test and
select Apache Tomcat v5.5 as the Target
server.

3. Now create a new Java class from the


Project Explorer (Dynamic Web Projects ->
Java Source -> New -> Class

VI. Creating a Web service

1. Create a new Dynamic Web Project in


eclipse (File -> New -> Other)

Sept-07 Java Jazz Up 51


Developing web services with Lomboz plug-in

4. Enter name as Hello and package as


com.tutorial.

8. Select Generate a proxy.

9. Select Test the Web service.

10. Select Overwrite files without warning.

5. Add a simple method in the Hello


class as shown below.

6. Save and build the project.

7. Create a new Web service in eclipse


(File -> New -> Other)

11. Select or enter the Bean name as


com.tutorial.Hello. This is the java class
that we just now created.

52 Java Jazz Up Sept-07


Developing web services with Lomboz plug-in

15. Verify the Tomcat folder and ensure the


newly created web applications
WebServiceTutorial,
WebServiceTutorialClient.

12. Continue the wizard by clicking next


and finish.

13. On Finish, the Tomcat server starts up


and launches the Test client.

14. Verify the generated contents. Look for


Hello.class and the generated JSPs as
below.

16. We can also run the following url from


the browser to access/test the Web service.
http://localhost:8080/
WebServiceTutorialClient/
sampleHelloProxy/TestClient.jsp
If servlet error
org.eclipse.jst.ws.util.JspUtils cannot be
resolved or is not a type is thrown on the
browser, then copy the webserviceutils.jar
file from the E:\Eclipse3.1\eclipse\plugins\
org.eclipse.jst.ws.consumption_0.7.0 into
the WEB-INF\lib folder of the
WebServiceTutorialClient application and
restart the Tomcat server.

17. The browser displays the methods


available in the web service.

Sept-07 Java Jazz Up 53


Developing web services with Lomboz plug-in

21. Right-click on the WSDL file and


18. Click on the sayHello(..) method, explore the options to test the web service
enter your name (for e.g. Jeeva) in the / publish the WSDL file / generate client /
inputs section and click Invoke. etc.

19. The browser greets using the web


service.

Conclusion

This article provides a good introduction to


Web service development using one of the
Web development tools available.
20. The WSDL for the Hello Web service
can be found in We hope this article would help you create
E:\Test\WebServiceTutorial\ a simple web service and a client web
WebContent\wsdl\Hello.wsdl. On double- application using eclipse IDE along with
click, the WSDL opens in a graphical editor. Lomboz plug in, very convieniently. We
have deployed and tested the web service
on Tomcat 5.5.4 web application server.

54 Java Jazz Up Sept-07


Spring Framework
Spring Core with Data Access Framework

In this article, we will move on to the These properties can be configured in the
main process of any enterprise application: spring configuration file also.
Data Persistence. For this we have to Springs own Data Access Framework
initialize our data access framework, Spring comes with its own data access
manage resources, handle various framework. Spring separates the fixed and
exceptions and if anything goes wrong, we variant parts of data access process into
must roll-back so as to save the existing two distinct classes: template and
data. callback. Template manages the fixed part
of our framework like data connection,
Spring comes with a family of data access managing resources, controlling
frameworks that integrates well will variety transaction etc., while the Callback defines
of data access technologies like JDBC, Java the things that are specific to our
Data Objects and Object Relational application like creating statements,
Mapping (ORM) tools like Hibernate, OJB, binding parameters etc.,
iBatis etc., The template class of Spring is
JdbcTemplate. A dataSource is
Many JEE application servers and even web provided inside JdbcTemplate.
servers provide a dataSource via JNDI 1 An example of database connection
name. To configure the spring bean with using JdbcTemplate is shown below.
the JNDI name of our dataSource and use Here we are using MySql database.
its connection pooling facility, The MySql database can be downloaded
JndiObjectFactoryBean is used. When from http://www.mysql.com.
a DataSource is not present, we need a Download latest MySql version and
connection pooling bean that implements mysql-connector-java-3.1.6-bin.jar.
dataSource. For this purpose we use Install them in the hard disk.
dbcp.BasicDataSource. By using this
we can have a dataSource with Installing MySql:
connection pooling independent of
application server. 1. For Mysql give a username(root) and a
password (root).
To perform unit-tests in our data access
code, spring comes with a very lightweight 2 Then start the My Sql Console Line
dataSource implementation class: Client from programs and type the
DriverManagerDataSource. This class password. The prompt will be changed
can be easily configured for unit tests as to mysql,mysql> show databases; Few
shown: databases will be present by default like
mysql and test. Lets use test for our
purpose.mysql> use test;

DriverManagerDataSource dataSource = 3 We will get a message as Database
new DriverManagerDataSource(); changed.
dataSource.setDriverClassName(driver);
dataSource.setUrl(url); 4 Next create a table in test database as
dataSource.setUsername(username); follows
dataSource.setPassword(password); mysql> create table table1(name text,
place text);

Sept-07 Java Jazz Up 55


Spring Framework: Spring Core with Data Access Framework

You will get the message Query OK, 0 1. D:\springdemo\ datacon.java


rows affected.
import javax.sql.*;
Now we have created a table in mysql public interface datacon{
database with two fields: Name and City. public DataSource dbcon();
}
Setting up the environment variables:
As the entire Spring Framework is included 2. D:\springdemo\ dataconimpl.java
in spring.jar. We use it to run our import
examples.
org.springframework.jdbc.core.*;
1 Copy spring.jar from spring1.2.9\dist import
folder to the working folder org.springframework.jdbc.datasource.*;
(springdemo) , mysql-connector- import org.springframework.jdbc.object.*;
java-3.1.6-bin.jar, also copy import
commons-logging.jar from apache- org.springframework.jdbc.support.*;
tomcat-6.0.10 to the working import javax.sql.*;
directory. public class dataconimpl implements
datacon{
2 Set path for jdk1.4.2 and above private DataSource dataSource;
versions only public void setDataSource(DataSource ds)
{
3. Now set the classpath as shown: dataSource = ds;
}
D:\>springdemo >set public DataSource dbcon() {
classpath=D:\springdemo; return dataSource;
D:\springdemo\spring.jar; }
D:\springdemo\commons-logging.jar; }
D:\springdemo\ mysql-connector-java-
3.1.6-bin.jar; 3. D:\springdemo\datacon.xml

4. For a typical Spring Application we need <? xml version=1.0" encoding=UTF-


the following files: 8"?><!DOCTYPE beans PUBLIC -//
SPRING//DTD BEAN//ENhttp://
i. An interface that defines the www.springframework.org/dtd/spring-
functions. beans.dtd><beans><bean
ii. An Implementation that contains id=dataSource
properties, its setter and getter class=org.springframework.jdbc.datasource.
methods, functions etc., DriverManagerDataSource>
iii. A XML file called Spring <property name=driverClassName>
configuration file. <value>com.mysql.jdbc.Driver</value>
iv. Client program that uses the function. </property>
<property name=url>
Create the following files <value>
jdbc:mysql://localhost:3333/test
1. datacon.java </value>
2. dataconimpl.java </property>
3. datacon.xml <property name=username>
4. helloclient.java <value>root</value>
</property>

56 Java Jazz Up Sept-07


Spring Framework: Spring Core with Data Access Framework

<property name=password> }
<value>root</value> catch(Exception e1) {
</property></bean> System.out.println(+e1);
<bean id=datacon }
class=dataconimpl> }
<property name=dataSource> }
<ref local=dataSource/>
</property> Now, execute the programs:
</bean>
</beans> D:\springdemo>javac datacon.java
D:\springdemo>javac dataconimpl.java
4. D:\springdemo\helloclient.java D:\springdemo>javac helloclient.java
D:\springdemo>java helloclient
import java.io.*;
import javax.sql.*; We will get the output as follows:
import java.sql.*;
import java.util.*; Wait... Please Wait...Aug 27, 2007 4:35:00
import PM
org.springframework.beans.factory.*; org.springframework.core.CollectionFactory
import <clinit>INFO: JDK 1.4+ collections
org.springframework.beans.factory.xml.*; availableAug 27, 2007 4:35:01 PM
import org.springframework.core.io.*; org.springframework.beans.factory.xml.
import XmlBeanDefinitionReader
org.springframework.core.io.ClassPathResource; loadBeanDefinitionINFO: Loading XML bean
import org.springframework.jdbc.core.*; definitions from class path resource
import [datacon.xml]Aug 27, 2007 4:35:01 PM
org.springframework.jdbc.datasource.*; org.springframework.jdbc.datasource.Driver
import org.springframework.jdbc.object.*; ManagerDataSource
import setDriverClassNameINFO: Loaded JDBC
org.springframework.jdbc.support.*; driver: com.mysql.jdbc.DriverRecord
public class helloclient { Added{name=Amit, place=Dehradun}
public static void main(String args[])
throws Exception{ Spring also provides integration for many
try { of the ORM frameworks like Hibernate,
String a=Amit; JDO, Apache OJB and iBATIS SQL
String b=Dehradun; Maps.
System.out.println(Wait...);
Resource res = new For mapping the hibernate resources, an
ClassPathResource(datacon.xml); instance of SessionFactory is needed,
System.out.println(Please Wait...); LocalSessionFactoryBean is used for
BeanFactory factory = new this purpose and its properties
XmlBeanFactory(res); hibernateProperties,
datacon bean1 = mappingResources and
(datacon)factory.getBean(datacon); mappingDirectoryLocation are set.
DataSource ds=bean1.dbcon(); Like springs DAO framework, here we
JdbcTemplate jt = new have HibernateTemplate to create an
JdbcTemplate(ds); object of SessionFactory. To access the
jt.execute(insert into table1 values(+a data with HibernateTemplate
+,+ b+) ); execute(HibernateCallback) method is
System.out.println(Record Added); used.

Sept-07 Java Jazz Up 57


Spring Framework: Spring Core with Data Access Framework

Similar to the SessionFactory of


hibernate, JDO has PersistenceManager
Factory. It can be configured by using
LocalPersistenceManagerFactoryBean.
Also JDOTemplate to create an object of
PersistenceManagerFactory. To access
the data with JDOTemplate
execute(JDOCallback) method is used.
For iBATIS, we have to configure a
SQLMapClient by using
SQLMapClientFactoryBean and its
properties configLocation and
dataSource are set. Here also we have
SQLMapClientTemplate.
To access the data
execute(SQLMapClientCallback)
method is used.
The only property that we need to change
to integrate Spring with OJB is
ConnectionFactoryClass and it is done
by using
LocalDataSourceConnectionFactory.

58 Java Jazz Up Sept-07


Web 3.0
Web 3.0 is a term, which coined with different meanings defined the term Web 3.0 as,
definition is not confirmed or to describe the evolution of web Web 3.0 is highly
defined so far as several usage and interaction among the specialized information
experts have given several several separate paths. These structures, moderated by a
meaning, which do not include transforming the Web group of personality,
match to each other, but into a database, a move towards validated by the community,
sometimes it is referred to making content accessible by and put into context with the
as a Semantic Web. In the multiple non-browser inclusion of meta-data
context of Semantic Web, applications, the leveraging of through widgets.
Web 3.0 is an evolving artificial intelligence
extension of the World technologies, the Semantic web, While Leiki, the Finland
Wide Web in which web or the Geospatial Web. based pioneer company of
content can be expressed Semantic Web describes:
not only in natural According to Wikipedia, an online Web 3.0 makes the
language, bu t also in a encyclopedia, Web 3.0 is a third discovery of content streams
form that can be generation of Internet based Web effortless. It introduces
understood, interpreted services, which emphasize automatic discovery of like-
and used by software machine-facilitated minded users and automatic
agents, thus permitting understanding of information in tagging.
them to find, share and order to provide a more
integrate information productive and intuitive user
more easily. experience.. The third History
generation of Internet services is
Tim Berners-Lee, the collectively consists of semantic The term Web 3.0 was first
inventor of first World Wide web, microformats, natural coined by John Markoff of
Web has coined the term language search, data-mining, the New York Times in 2006,
Semantic Web. But the machine learning, while it first appeared
concept of Web 3.0, first recommendation agents that is prominently in early 2006 in
entered among the public in known as Artificial a Blog article written by
2001, when a story Intelligence technologies or Jeffrey Zeldman in the
appeared in scientific article Intelligent Web. Critical of Web 2.0 and
written by American associated technologies such
Coauthored Berners-Lee that According to some experts, Web as Ajax.
described this term as a 3.0 is characterized and fueled
place where machines can by the successful marriage of The debate originates in
read Web pages as much as artificial intelligence and the summit named Technet
humans read them e.g. web web. While some experts have Summit in November 2006,
connected bathroom summarized the definition in which various software
mirrors, which can read the defining as Web 3.0 is the next tycoons expressed their
news coming through on the step in the progression of the views. e.g.
web. tubes that are the Internets.
Jerry Yang, founder and
Definitions and According to Nova Spivack, the Chief of Yahoo, stated:
Roadmap CEO of Radar Networks, one of
the leading voices of this new- Web 2.0 is well documented
There are several age Internet, Web 3.0 is a set and talked about. The power
definitions of the web, but of standards that turns the Web of the Net reached a critical
usually Web 3.0 is defined as into one big database. mass, with capabilities that
a term, which has been can be done on a network
Steve, a famous Blog author has
Sept-07 Java Jazz Up 59
Web 3.0

level. We are also seeing Web 3.0 is. I think maybe when accessible and linkable as
richer devices over last four youve got an overlay of scalable Web pages. To make
years and richer ways of vector graphics - everything available structured data
interacting with the network, rippling and folding and looking using RDF is primarily
not only in hardware like misty - on Web 2.0 and access focused in Data Web phase.
game consoles and mobile to a semantic Web integrated The full Semantic Web stage
devices, but also in the across a huge space of data, will so expand the scope that
software layer. You dont youll have access to an both structured and semi-
have to be a computer unbelievable data resource. structured or unstructured
scientist to create a content will be widely
program. We are seeing that --Tim Berners-Lee, available in RDF and OWL
manifest in Web 2.0 and 3.0 A more revolutionary Web semantic formats.
will be a great extension of
that, a true communal The term Web 3.0 has became a An evolutionary path
mediumthe distinction subject of interest and debate to artificial
between professional, semi- since late 2006 to till date. But intelligence
professional and consumers no exact definition has been
will get blurred, creating a created that everyone accepts it. Web 3.0 has also been
network effect of business used to describe the trend
and applications. Web 3.0 Debates over of artificial intelligence,
Definition which is being popular in the
-- Jerry Yang web like a quasi-human
Since the origins of the fashion. Some cynic believes
While Reed Hastings, the concept of Web 3.0, the debate that it is an unobtainable
founder and CEO of Netflix, continues goes on about exactly vision. However, this is being
stated a simpler formula for what the term Web 3.0 means, used new technologies on
defining the phases of the and what a suitable definition mass level that yields
Web in the same Technet might be. As emerging the new amazing information like
Summit: technology, a new definition making predictions of hit
emerged: songs from mining
Web 1.0 was dial-up, 50K information on college music
average bandwidth, Web 2.0 Transforming the Web Web sites. There is also
is an average 1 megabit of into a database debate on the driving force
bandwidth and Web 3.0 will behind Web 3.0. Will it be
be 10 megabits of bandwidth Transforming the Web into the intelligent systems, or
all the time, which will be the database is the beginning step whether intelligence will
full video Web, and that will towards transforming definition emerge in a more organic
feel like Web 3.0. of Web 3.0 when the technology fashion and how people
of Data Web emerged as interact with it?
--Reed Hastings structured data records that can
be published to the Web in The realization of the
Before this people were very reusable and remotely queryable Semantic Web and Service
curious about Web 3.0 as formats, such as XML, RDF and Oriented Architecture
they asked to Tim Berener microformats. The Data Web is
about the full-fledged the initial step in the way of full Another debate originates
information of Web 3.0 as Semantic web that enables a new over the artificial intelligence
Tim Berners-Lee stated in level of data integration and direction in which Web 3.0
May 2006: application interoperability, can be extent to Semantic
which makes the data openly web concept. Academic
People keep asking what

60 Java Jazz Up Sept-07


Web 3.0

research is going on to Web 3.0 that indulge in itself the Web 3.0 as Different
develop such reasoning collection of various foremost Formats of Web
software that must be based harmonizing technology
on description logic and developments that are growing The Semantic Web
intelligent agents. These to a new level of maturity
sorts of applications can simultaneously includes: The term Semantic Web
perform logical reasoning refers to Defined Web that
operations through using Ubiquitous Connectivity, is an alliance of World Wide
sets of rules expressing broadband adoption, mobile Web Consortium (W3C) and
logical relationships between Internet access and mobile others to provide a standard
concepts and data on the devices for defining data structures
Web. on the Web. Semantic Web
Network computing, refers to the use of XML-
But some critics are disagree software-as-a-service tagged data that matches
on the viewpoint, which business models, Web services the Resource Description
describes that Semantic Web interoperability, distributed Framework (RDF).
would be the core of the 3rd computing, grid computing
generation of the Internet and cloud computing Sometimes it is refers to
and suggests a formula to Web 3.0, that is a
summarize Web 3.0. Open technologies, Open debatable topic, but in the
APIs and protocols, open data form of Web 3.0, the main
Web 3.0 has also been formats, open-source goal of the Semantic Web
associated to a possible hub software platforms and open becomes to identify exact
of SOA (Service Oriented data (e.g. Creative Commons, required data that matches
Architecture) and Semantic Open Data License) the keywords. e.g. if we
web. search Web 3.0 in Google /
Open identity, OpenID, open yahoo / msn or any advance
Evolution towards 3D reputation, roaming portable search engines using specific
identity and personal data key words, there are millions
The evolution of 3D of web pages appears on the
technology is also being The intelligent web, window in which only very
connected to Web 3.0 as Semantic web technologies few have some information
Web 3.0 may be used on such as RDF, OWL, SWRL, and all other pages are
massive scale due to its SPARQL, Semantic application worthless.
characteristics. In this platforms, and statement-
process Web 3.0 would based datastores Web 3.0 in terms of
transform into a series of 3D Semantic Web is the third
spaces, taking the concept Distributed databases, the generation of World Wide
realized by Second Life World Wide Database Web in which machines can
expansion. This could open (enabled by Semantic Web read sites similar to human
up new ways to connect and technologies) being and also follows your
collaborate using 3D shared instructions. For example if
spaces. you order to check your
Intelligent applications,
natural language processing, schedule against the
Proposed Expanded machine learning, machine schedules of all the dentists
Definitions of Web 3.0 reasoning, and autonomous and doctors within a 10-mile
agents radius if follows tour order
Nova Spivack has proposed and provide the appropriate
the expanded definition of information.

Sept-07 Java Jazz Up 61


Web 3.0

The 3D Web The Media-Centric Web generated from an


approved pseudo-random
3-D refers to the three The terms Media-Centric Web sequence of characters.
dimensional design that refers to the web where users Web 3.0 would have three
represents the virtual looks can find true similar graphics and main objectives:
of any object from three sound on the other media, not
different sides just the keywords. e.g. if users 1- Seeking Information
simultaneously. A user can searches any favorite movie/ 2- Seeking Validation
view the true picture of any graphics/ music in the search 3- Seeking entertainment
building, any location or any engines, can find the exact
object and walk through the desired thing on the other media. Seeking Information
location without leaving the
computer desk on his/her The Pervasive Web Searching information
system. Though these are would be more compact in
the virtual pictures but seem The pervasive web refers the Web 3.0. Till now, the web
to be real. These uses of web in the wide range of uses keywords in order to
technologies are extensively area in which the web has now comprehensive data into
being used in a wide range been reached not only in usable chunks. Search
of services like computer computers and cell phones but engines index the Internet
games, Virtual Reality (VR) also in clothing, appliances, and in proper order and present
models and Multimedia automobiles and much more, it to the end user in order
solutions. e.g. web based bedroom of relevance. The users
windows that checks weather select the information that
Now, 3-D technology has and self open or close it is nearer to their
come on the Internet and according to climate. requirement. Sometimes
has become a new trend of this becomes a very hectic
Web. Now user can go house Web 3.0 in terms of pervasive process. But Web 2.0 goes
hunting across town or take web refers to those websites, one step ahead and
a tour of the world or can which are going to be brought us a change in the
walk through a Second Life transformed into web services basic way of searching. It
style virtual world, surfing and will depict and expand their applies the tags in the
for data and interacting with information to the world. searching data e.g. if
others in 3D. The 3d web is anyone wants to look for
being used massively in Overview car. He/she types the word
online computer games, in the specified space of
virtual world tour, Geospatial As the times goes and the the search engine. The
engineering, online high tech technology enriches, the experts search engine displays
research, online software feels to develop some thing many webs, but if the user
development, online better that can be more fruitful, type BMW cars, it displays
shopping, online advance, user friendly and all the relevant site onlk\y
telecommunication and intelligent. Thus originates the related to BMW cars. So
social networking sites. concept of web 3.0 and now it is BMW works as a tag.
Google Earth, Wiki Earth, taking a handsome shape. Web
MySpace, You Tube are the 3.0 has some more features Web 3.0 will be more
biggest examples of 3D web including the feature of Web 2.0. advance in searching the
users. information for example of
Web 3.0 sites will only allow Cars, Web 3.0 uses the
collaboration of content further research beyond the
engines, it also uses the

62 Java Jazz Up Sept-07


Web 3.0

subsearch engines that displayed with some attached seat to product placements
would provide more compact tags. If would display the total on sites, search results and
information and user can find wiki profile, in which all the data subengines.
the nearest desired data. It would be specified whether the
would go to all major user would have created it or
categories like pictures, anyone else. All the related deeds Web 3.0 Design
videos, blog posts, news would also show in the profile.
articles, commerce etc. Each Then People would be more REST, AJAX, Silverlight,
of these would happed universal rather than now. Widget Enabled, Taggable,
because of RSS feed so that Searchable everything
user can get alerts when The looks and shape of the
something new would added blogging would be also changed; RSS. A Web 3.0 Driver
to his/her search profile. the current weblogs would be
converted in to Microblogging. In the coming ten years
Seeking Validation People will be able to blog from RSS and its related
anywhere, without having to technologies will become the
If the user wants to go the spend hours writing a properly single most important
news not the information, it formatted post. Web 3.0 will see Internet technology because
will work in a different way. a more complete integration of its specific quality to
It would provide the exact between devices like cell phones development of the new web
data what user wants. It and the World Wide Web. Posting as its really very simple. Any
would also search the pictures, videos and text from person who has a little bit
available people on the net. anywhere, anytime would be knowledge of coding can
The user have to type the more tussles free. generate an extensible,
words what he/she wants to standards based database of
access, Web 3.0 would Commerce information that can be
provide the relevant transferred to almost any
information in order of its Here the terms of commerce other modern web site.
proximity, algorithms, means the criteria of earning that
tagging, and validation will be more advance, but the If Web 3.0 is the Semantic
through user voting. whole criteria would not primarily Web, where machine read
change. The product will carry on content like human beings
Seeking to sell online. Conversational then RSS will be its eyes.
Entertainment advertising and Advertainment RSS technology is still in vast
will take the place of stock ads uses especially in the online
Entertainment, the most and promotions. Sect of news portals. The entire
popular trend of Web 2.0 personality and their business models have
would be more advance in sponsorships will also be more already being created
Web 3.0 as it would be based specific as the advertisement around aggregating meta-
around the sect of the companies will be narrower data. IGoogle, MyIndiaTims
personality. People Search because of categorizing of the and Netvibes allow the users
will replace the social people. to create their own personal
networks that are most homepage, drawing much of
popular fashion in this The entire advertising landscape its content from RSS feeds
generation of web. For will change; the ultra specialized that users select.
searching about any person, subengines will search the tightly
just type the name and all focused target audience to selling The trend of RSS tool will be
the information related to the product. Contextual increased in the future in
regarding person would be advertisement will take second which user can include a

Sept-07 Java Jazz Up 63


Web 3.0

host of data-points. Each


blog post, the future
microblogging feed can be
personalize according to
users desire as every
picture, every video clip,
every music will be
searchable, taggable and
XML based collaborate. The
biggest example of its
already exists in a web portal
named MyIndiaTims.com.

The real power of Web 3.0


will be in the used in creating
data and transferring it
effectively.

Candidate Web 3.0


technologies

Web 3.0 would be used


in various technologies of
computer and Internet.
Here is the list of web 3.0
users:

Artificial intelligence
Automated reasoning
Cognitive architecture
Composite applications
Distributed computing
Knowledge
representation
Ontology (computer
science)
Recombinant text
Scalable vector graphics
Semantic Web
Semantic Wiki
Software agents

64 Java Jazz Up Sept-07


Tips n Tricks
1. Download files data from many // openConnection method on a URL.
URLs and save them to the local URLConn = fileUrl.openConnection();
files in the directory of your choice: is = URLConn.getInputStream();
buf = new byte[size];
This Java program lets you download files while ((ByteRead = is.read(buf)) != -1) {
from one or more URLs and save them in the os.write(buf, 0, ByteRead);
directory where you want. This program takes ByteWritten += ByteRead;
destination directory for the files to save as }
first command line argument and URLs for
the files as next command line arguments System.out.println(Downloaded
separated by space. Java provides Successfully.);
URLConnection class that represents a System.out.println(File name
communication link between the application :\+localFileName+ \\nNo of
and a URL. Invoking the openConnection bytes : + ByteWritten);
method on a URL creates URLConnection }
object. Now get InputStream object from that catch (Exception e) {
connection and read the data. Finally write e.printStackTrace();
the data to the local file. }
finally {
FileDataDownload.java: try {
is.close();
os.close();
import java.io.*; }
import java.net.*; catch (IOException e) {
e.printStackTrace();
public class FileDataDownload { }
final static int size=1024; }
public static void }
FileDownload(String fileAddress, String
localFileName, String destinationDir) { public static void fileDownload(String
OutputStream os = null; fileAddress, String destinationDir)
URLConnection URLConn = null; {

// URLConnection class represents a // Find the index of last occurance of


communication link between the character / and ..
// application and a URL.
int lastIndexOfSlash =
InputStream is = null; fileAddress.lastIndexOf(/);
try {
URL fileUrl; int lastIndexOfPeriod =
byte[] buf; fileAddress.lastIndexOf(.);
int ByteRead,ByteWritten=0;
fileUrl= new URL(fileAddress); // Find the name of file to be downloaded
os = new BufferedOutputStream(new from the address.
FileOutputStream(destinationDir+\\+ String fileName=fileAddress.substring
localFileName)); (lastIndexOfSlash + 1);

//The URLConnection object is // Check whether path or file name is given


created by invoking the correctly.

Sept-07 Java Jazz Up 65


Tips n Tricks

if (lastIndexOfPeriod >=1 && Output:


lastIndexOfSlash >= 0 &&
lastIndexOfSlash < fileAddress.length() -
1)
{
FileDownload(fileAddress,fileName,destinationDir); 2. Using Swing Timer:
}
else
A Swing Timer fires an event after a
{
specified delay of time. Swing Timer can be
used to perform a task once, after a delay
System.err.println(Specify correct path or
and to perform a task repeatedly. For
file name.);
example, determining when to display and
hide a tool tip, updating a component that
}
displays the progress. Swing timers are very
}
easy to use. Create actionPerformed()
public static void main(String[] args)
method, which is called when action listener
{
is notified. So write the code for the task to
be performed, in actionPerformed()
// Check whether there are atleast
method. When creating timer by instantiating
two arguments.
the Timer class, we specify the time in
milliseconds which is the time interval of
if(args.length==2)
invoking the actionPerformed() each time.
{
To start the timer, just call its start() method
for (int i = 1; i < args.length; i++) {
and to stop it doing anything, call stop()
fileDownload(args[i],args[0]);
method. To understand how the swing timer
}
can be used with the progress bar component
}
showing its status is given below:
else{System.err.println(Provide
SwingTimer.java:
\Destination directory path\ and \file
names\
import java.awt.*;
separated by space.);
import java.awt.event.*;
}
import javax.swing.*;
}
import javax.swing.text.html.*;
}
public class SwingTimer{
Compile and Run:
final static int interval = 1000;
int i;
In this example, the location for the
JLabel label;
directory where file jsf.htm is to be
JProgressBar pb;
saved is c:\download.
Timer timer;
JButton button;
C:\JavaJazzup>javac
public SwingTimer() {
FileDataDownload.java
JFrame frame = new JFrame(Swing Timer
C:\JavaJazzup>java FileDataDownload
Example);
c:\download http://localhost:8080/
button = new JButton(Start);
tomahawk_tags/pages/jsf.htm
button.addActionListener(new
ButtonListener());

66 Java Jazz Up Sept-07


Tips n Tricks

pb = new JProgressBar(0, 20); color=\#008000\> + <b> +


pb.setValue(0); Downloading is in process....... + </b>
pb.setStringPainted(true); + </font> +</html>;
label = new JLabel(Roseindia.net); label.setText(str);
JPanel panel = new JPanel(); timer.start();
panel.add(button); }
panel.add(pb); }
JPanel panel1 = new JPanel(); public static void main(String[] args) {
panel1.setLayout(new BorderLayout()); SwingTimer spb = new SwingTimer();
panel1.add(panel, BorderLayout.NORTH); }
panel1.add(label, BorderLayout.CENTER); }
panel1.setBorder
(BorderFactory.createEmptyBorder(20, 20, Compile and Run:
20, 20));
frame.setContentPane(panel1); C:\JavaJazzup>javac SwingTimer.java
frame.pack(); C:\JavaJazzup>java SwingTimer
frame.setVisible(true);
frame.setDefaultCloseOperation Output:
(JFrame.EXIT_ON_CLOSE);
The output of the above program appears
//Create a timer. as shown in the figure below.
timer = new Timer(interval, new
ActionListener() {
public void actionPerformed(ActionEvent
evt) {
if (i == 20){
timer.stop();
button.setEnabled(true);
pb.setValue(0);
String str = <html> + <font
color=\#FF0000\> + <b> +
Downloading completed. + </b> + </
font> + </html>; When the start button is clicked, a string
label.setText(str); Downloading is in process. appears at
the bottom as in the figure below.
i = i + 1;
pb.setValue(i);
}
}
);
}

class ButtonListener implements


ActionListener {
public void actionPerformed(ActionEvent
ae) { The above string is replaced by the string
button.setEnabled(false); Downloading completed. when the task is
i = 0; completed.
String str = <html> + <font

Sept-07 Java Jazz Up 67


Tips n Tricks

passing a true boolean value to


setIndeterminate() method.

ipb.setIndeterminate(true);
pane.add(ipb);
setContentPane(pane);
}
public void iterate() {
while (number <= 1000) {
3. Creating Indeterminate Progress ipb.setValue(number);
Bar in Java:
//Sets the progress bars current value to n.
Sometimes, at the time of downloading
or transferring a file, we see a component try {
showing how much the particular task has Thread.sleep(10);
been completed. For this purpose, Java }
provides a Progress Bar component to convey catch (InterruptedException e) { }
the progress of completing a task in a GUI. number++;
One way of showing this progress is in }
percent format. But suppose a situation //To stop the animation make the progress
where extent of the task is unknown and so bar determinate.
we are not able to present it in percent
format. To handle this situation java provides ipb.setIndeterminate(false);
a solution by putting the progress bar in }
indeterminate mode. An indeterminate public static void main(String[] args) {
progress bar animates constantly. By default, IndeterminatePB frame = new
every progress bar is determinate. You may IndeterminatePB();
make any JProgressBar indeterminate pass frame.pack();
a true boolean value to setIndeterminate() frame.setVisible(true);
method. Just have a look on the code below: frame.iterate();
}
IndeterminatePB.java: }

import java.awt.*; Compile and Run:


import java.awt.event.*;
import javax.swing.*; C:\JavaJazzup>javac IndeterminatePB.java
public class IndeterminatePB extends C:\JavaJazzup>java IndeterminatePB
JFrame {
JProgressBar ipb; Output:
int number = 0; The output below appears until the
public IndeterminatePB() { completion of the task. The dark portion
super(Indeterminate Progress Bar waves from one side to the other.
Example);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
ipb = new
JProgressBar(JProgressBar.HORIZONTAL,0,
1000);
//make any JProgressBar indeterminate
When the task ends, progress bar

68 Java Jazz Up Sept-07


Tips n Tricks

appears like this. calendar.set(Calendar.HOUR_OF_DAY, 0);


calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
timeInMillis = alendar.getTime().getTime();
// set the message to be displayed for
greeting.
greetingMessage = Happy New Year +
newYear;
4. Wishing New Year with count }
down in full screen window: public static void main(String[] args) {
JFrame frame = new JFrame();
This program displays Frame in full screen frame.setUndecorated(true);
window in which the remaining number of JLabel label = new JLabel(.);
seconds for the New Year to come is // Set the alignment of the text to be
displayed. Screen is updated every second displayed.
and finally the message Happy New Year label.setHorizontalAlignment
2008 is displayed. (SwingConstants.CENTER);
frame.getContentPane().add(label);
import java.util.*; // Set the size of window to full of the
import java.awt.*; screen.
import java.awt.event.*; GraphicsEnvironment.getLocal
import javax.swing.*; GraphicsEnvironment().
import java.text.NumberFormat; getDefaultScreenDevice().
public class GreetingNewYear setFullScreenWindow(frame);
implements Runnable{ // Set the style, type and size for the
font of the label.
JFrame frame; label.setFont(new
JLabel label; Font(monospaced,Font.BOLD,100));
long timeInMillis; new HappyNewYear(frame, label).run();
String greetingMessage; }
public void run()
static NumberFormat formatter = {
NumberFormat.getInstance(); boolean isNewYear = false;
public GreetingNewYear (JFrame frame, do
JLabel label) {
{ long timeLeft= (timeInMillis -
this.frame = frame; System.currentTimeMillis()) /1000L;
this.label = label; String displayMessage;
// Check for New Year.
// Set values for New Year. if (timeLeft< 1){
isNewYear = true;
Calendar calendar = new displayMessage = greetingMessage;
CregorianCalendar(); }
int newYear = calendar.get(Calendar.YEAR) else
+ 1; {
calendar.set(Calendar.YEAR, newYear); displayMessage =
calendar.set(Calendar.MONTH, formatter.format(timeLeft);
Calendar.JANUARY); // Set the above displayMessage
calendar.set(Calendar.DAY_OF_MONTH, 1); value to the label text.
label.setText(displayMessage);

Sept-07 Java Jazz Up 69


Tips n Tricks

// Make the thread sleep for one 5. Save your documents in the
second. directory of your choice in zipped
try{ form:
Thread.sleep(1000);
} Zip file is a way of packaging a set of files
catch (InterruptedException ie) in the compressed form. When a developer
{ needs to use a set of files together, bundling
ie.printStackTrace(System.err); them together in zipped form is one of the
} most frequently adopted way. When we need
} to download a group of files from the web,
while (!isNewYear); we create a zip file to transport them as a
} single unit. In this section, we will learn
} creating zip file containing two files of your
choice in the specified directory.
Compile and Run:
CreateZip.java:
C:\JavaJazzup>javac
GreetingNewYear.javaC:\JavaJazzup>java import java.io.*;
GreetingNewYear import java.util.zip.*;
public class CreateZip{
Output: public static void main(String args[]){
//Collect file names to be zipped in an
The output shows the remaining number of array by command line arguments.
seconds. This screen gets updated every String[] filesToZip = new String[]{args[0],
second and no of seconds displayed in the args[1]};
screen becomes one less than previous. So // Create a buffer for reading the files
this count down goes on till New Year byte[] buffer = new byte[1024];
comes. try {
// Specify the location of the zipped
file to be stored.
String zip = c:\\MyDocuments\\
MyZippedDocuments.zip;
//Creates a new ZIP output stream.
ZipOutputStream out = new
ZipOutputStream(new
FileOutputStream(zip));
// Compress the files for (int i=0;
i<filesToZip.length; i++) {
FileInputStream in = new
When New Year comes, it wishes for the FileInputStream(filesToZip[i]);
New Year like in the figure below: // Add ZIP entry to output stream.
out.putNextEntry(new
ZipEntry(filesToZip[i]));
//ZipEntry(String name)Creates a
new zip entry with the specified name.
// Transfer bytes from the file to the
ZIP file
int len;
while ((len = in.read(buffer)) > 0) {

70 Java Jazz Up Sept-07


Tips n Tricks

out.write(buffer, 0, len); Exploring the above file shows two files


//Writes an array of bytes to the inside it. You can see this in the figure
current below:
// ZIP entry data. }
out.closeEntry();
//Closes the current ZIP entry and
positions the stream
//for writing the next entry.

in.close();
}
out.close();

// Closes this output stream and


releases any system resource
//associated with the stream.
} 6. Want to scribble on the Applet
catch (Exception e) { window?
e.printStackTrace();
} Do you know how to write with the mouse
} on the applet window? Its an easy task.
} Select and save position (X and Y
coordinates) of the mouse on mouse down
Compile and Run: event and position on mouse drag. Just draw
a line between these two points. This process
C:\JavaJazzup>javac CreateZip.java goes on until mouse is dragged. When the
C:\JavaJazzup>java CreateZip mouse is pressed down again the line is
CreateZip.java CreateZip.class drawn again on the applet window.

Output: MouseScribbling.java:

Running the above program creates a zip import java.awt.*;


file named MyZippedDocuments.zip which import java.applet.*;
contains two files CreateZip.java and public class MouseScribbling extends
CreateZip.class. You can take a look Applet {
below: // Declare variables to store mouse
point location.
int startX,startY;
// This method is called when the
user press down the mouse button.
public boolean mouseDown
(Event e, int startX, int startY)
{
// Store the point location.
this.startX = startX;
this.startY = startY;
return true;
}
// This method is called when the
user drags the pressed mouse.

Sept-07 Java Jazz Up 71


Tips n Tricks

public boolean mouseDrag(Event e, int


endX, int endY)
{
Graphics g = getGraphics();
// Draw a line from start point to the
end point.
g.drawLine(startX, startY, endX, endY);
// Change the start point with the end
point.
startX = endX; startY = endY;
return true;
}
}

MouseScribbling.html:

<HTML>
<BODY>
<APPLET CODE=MouseScribbling
WIDTH=200"
HEIGHT=300">
</APPLET>
</BODY>
</HTML>

Compile and Run:

C:\JavaJazzup>javac
MouseScribbling.javaC:\JavaJazzup>appletviewer
MouseScribbling.html 7. Learn running external programs
(Notepad, Calculator, browser etc.) by
Output: a Java program:

Running the applet creates an applet Opening any sub process like Notepad,
window like below where you can write Calendar, browser etc from a java program
anything by pressing and dragging the feels good for a new java programmer. The
mouse. For instance, in the figure below class Runtime provides a static method
Java word is written in the applet getRuntime(), which helps to work with
window. Java Runtime Environment. This is the only
way to get the reference to the Runtime
object. Now, by invoking its method exec(),
external programs can be invoked. Here is a
simple demonstration for performing this
operation from a Java program.

72 Java Jazz Up Sept-07


Tips n Tricks

CreateSubProcess.java: Output:

public class CreateSubProcess Running the above program prints the


{ message Solve the problem within 1
public static void main(String[] args) { minute. and opens a calculator.
try {
//Get the current runtime to interface
with the environment in
//which the application is running.

Runtime runTime = Runtime.getRuntime();


System.out.println(Solve the problem
within 1 minute.);
Process process = runTime.exec(calc);

//Executes the specified string


// command in a separate process.

try {
Thread.sleep(60*1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
process.destroy();
// Kills the subprocess forcibly.
8. Can you find the name of Operating
int exitValueCalc = process.exitValue(); System you are working on and
environment variables by a Java
//The exit value 0 indicates normal program?
termination.
Environment variables are key/value
System.out.println(Process exitValue: + pairs, which are available to all the programs
exitValueCalc); running within DOS environment or top of it,
} including Windows. Because these can be
catch (Throwable e) { changed so they are called variables. Java
e.printStackTrace(); provides a way to access these variables by
} providing System class. To get the value of a
}} single variable, call its static method
getProperty(property_name). To get
Compile and Run: value of all the variables, use static method
getenv() which returns values as a Map.
C:\JavaJazzup>javac Now using collection methods, keys and
CreateSubProcess.javaC:\JavaJazzup>java values can be displayed.
CreateSubProcessSolve the problem within
1 minute.

Sept-07 Java Jazz Up 73


Tips n Tricks

EnvironmentInformation.java:

import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class EnvironmentInformation{
public static void main(String[] args){
System.out.println(\n+You are working
with
\+System.getProperty(os.name)+\
Operating System );
System.out.println(and using jdk version :
\+System.getProperty(java.version)+\\n);
Map map = System.getenv();
Set keys = map.keySet();
Iterator iterator = keys.iterator();
System.out.println(List of all environment
variable names and their values :+\n);
System.out.println(Variable Name Are you really confident about the execution
Variable Values); flow of a java program?
System.out.println(\t\t Sometimes, even a simple java program, can
); make you confused about the flow of
while (iterator.hasNext()) initialization of variables and flow of program.
{ If you are clear with the concept of static
String key = (String) iterator.next(); keyword and flow of constructor calling
String value = (String) map.get(key); (constructor chainging) then the program
System.out.println(key + + below is simple to understand. The compiler
value); combines multiple static initializer blocks into
} a single initialization procedure (which is
} executed one time only when the class is
} loaded) so the order of execution of program
code will not necessarily be the same as the
order in which the code appears in the
Compile and Run: program i.e. non-static code can separate
multiple static initializer blocks. The static
C:\JavaJazzup>javac initializer blocks are executed in the order in
EnvironmentInformation.javaC:\JavaJazzup>java which they appear in the code, regardless of
EnvironmentInformation the other code that may separate them. This
causes the program to be a little difficult to
Output: understand.

Above program shows environment In the program below first static variables
variables as it is shown in the figure below. are initialized. Then main method is called
which calls the SubClass constructor. Here
constructor chaining is applied in which every
constructor calls its super class constructor.
So before entering into constructor of
SubClass, its instance variables are initialized.
Now, control goes to call the constructor of

74 Java Jazz Up Sept-07


Tips n Tricks

SuperClass without entering into constructor Compile and Run:


of SubClass. Here also the instance variables
of SuperClass are initialized and then super C:\JavaJazzup>javac
classs constructor is called then control SubClass.javaC:\JavaJazzup>java SubClass
comes back to call the constructor of
SubClass. Output:

SubClass.java:

//This example demonstrates the


execution order of a java program.

class SuperClass {
private String supVar1=staticPrintMethod
(\SuperClass.supVar1\ initialized);
public int supVar2;
superClass(){
System.out.println(In \SuperClass\
constructor.);
supVar1=java;
supVar2=10;
System.out.println(supVar1 = + supVar1
+ , supVar2 = + supVar2);
}
private String staticVarInSuperClass =
staticPrintMethod(static
\SuperClass.staticVarInSuperClass\
initialized);
static String staticPrintMethod(String str) {
System.out.println(str);
return success;
}}
public class SubClass extends SuperClass {
private String subVar1 =
staticPrintMethod(\SubClass.subVar1\
initialized);
public SubClass() {
System.out.println(In \SubClass\
constructor.);
System.out.println(subVar1 = +
subVar1);
}
private static String staticVarInSubClass =
staticPrintMethod(static
\SubClass.staticVarInSubClass\
initialized);
public static void main(String[] args) {
System.out.println(In main() method.);
SubClass b = new SubClass();
}}

Sept-07 Java Jazz Up 75


Advertise with JavaJazzUp
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. Our network is getting around
3 million hits per month and its increasing
with a great pace.

For a long time we have endeavored to


provide quality information to our readers.
Furthermore, we have succeeded in the
dissemination of the information on technical
and scientific facets of IT community
providing an added value and returns to the
readers.

We have serious folks that depend on our


site for real solutions to development
problems.

JavaJazzUp Network comprises of :

http://www.roseindia.net
http://www.newstrackindia.com
http://www.javajazzup.com
http://www.allcooljobs.com

Advertisement Options:

Banner Size Page Views Monthly


Top Banner 470*80 5,00,000 USD 2,000
Box Banner 125 * 125 5,00,000 USD 800
Banner 460x60 5,00,000 USD 1,200
Pay Links Un Limited USD 1,000
Pop Up Banners Un Limited USD 4,000

The http://www.roseindia.net network is the


real deal for technical Java professionals.
Contact me today to discuss your customized
sponsorship program. You may also ask
about advertising on other Technology
Network.

Deepak Kumar
deepak@roseindia.net

76 Java Jazz Up Sept-07


Valued Java Jazz Up Readers
Community

We invite you to post Java-technology Hands-on technology demonstrations


oriented stuff. It would be our pleasure
to give space to your posts in some people are Internet experts. Some
JavaJazzup. are barely familiar with the web. If youd like
to show others aroud some familiar sites and
Contribute to Readers Forum tools, that would be great. It would be our
If theres something youre curious about, pleasure to give you a chance to provide your
were confident that your curiosity, combined demonstrations on such issues : How to set
with the knowledge of other participants, will up a blog, how to get your images onto Flickr,
be enough to generate a useful and exciting How to get your videos onto YouTube,
Readers Forum. If theres a topic you feel demonstrations of P2P software, a tour of
needs to be discussed at JavaJazzup, its up MySpace, a tour of Second Life. (Or let us
to you to get it discussed. know if there are other tools or technologies
you think people should know about...)
Convene a discussion on a specific
subject Present a question, problem, or
puzzle
If you have a topic youd like to talk about.
Whether its something you think lots of were inviting people from lots of different
people will be interested in, or a narrow topic worlds. We do not expect everybody at
only a few people may care about, your article Readers Forum to be an expert in some
will attract people interested in talking about areas. Your expertise is a real resource you
it at the Readers Forum. If you like, you can may contribute to the Java Jazzup. We want
prepare a really a good article to explain what your curiosity to be a resource, too. You can
youre interested to tell java technocrates also present a question, problem, or puzzle
about. that revolves around java technologies along
with their solution that you think would get
Sharing Expertise on Java really appreciated by the java readers
Technologies around the globe.

If youre a great expert on a subject in Post resourceful URLs


java, the years you spent developing that
expertise and want to share it with others. If if you think you know such URL links which
theres something youre an expert on that can really help the readers to explore their
you think other technocrates might like to java skills. Even you can post general URLs
know about, wed love to set you up in the that you think would be really appreciated
Readers Forum and let people ask you by the readers community.
questions.
Anything else
Show your innovation
if you have another idea for something
we invite people to demonstrate innovative youd like to do, talk to us. If you want to do
ideas and projects. These can be online or something that we havent thought of, have
technology-related innovations that would a crazy idea, wed really love to hear about
bring you a great appreciations and it. Were open to all sorts of suggestions,
recognition among the java technocrates especially if they promote reader s
around the globe. participation.

Sept-07 Java Jazz Up 77


78 Java Jazz Up Sept-07
Sept-07 Java Jazz Up 79

You might also like