Professional Documents
Culture Documents
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.
Editor
Deepak Kumar
Java Jazz up
Register with JavaJazzUp
Free*
24 Building Project : Maven2 | Maven2 is an Open Source build tool that made the
revolution in the area of building projects.
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.
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.
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
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.*;
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
Rendered Output:
<t:inputCalendar
Code Description :
<f:view>
<html>
<head>
<meta http-equiv=Content-Type
content=text/html; charset=iso-8859-1">
.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
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;
}
Rendered Output:
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.
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
<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
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.
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
<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:
<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>
<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>
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.
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
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:
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
package hello;
import javax.persistence.*;
@Entity
@Table(name = "MESSAGES")
public class Message {
@Id @GeneratedValue @Column(name =
"MESSAGE_ID")
private Long id;
<!-- 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
</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, ?, ?)
"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); }
} }
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
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;
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.
Painting.java
class Painting {
public void draw(Point p, int x, int y) {
}
public void draw(Point p, int x) {
}
}
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)
Conclusion
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);
<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.
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
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.
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
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
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: }
// 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) {
in.close();
}
out.close();
Output: MouseScribbling.java:
MouseScribbling.html:
<HTML>
<BODY>
<APPLET CODE=MouseScribbling
WIDTH=200"
HEIGHT=300">
</APPLET>
</BODY>
</HTML>
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.
CreateSubProcess.java: Output:
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.
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
SubClass.java:
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();
}}
http://www.roseindia.net
http://www.newstrackindia.com
http://www.javajazzup.com
http://www.allcooljobs.com
Advertisement Options:
Deepak Kumar
deepak@roseindia.net