Tuesday, December 16, 2008

JBOSS Portal vs Liferay Portal

Feature Comparison

Feature Liferay(5.1+) JBoss Portal(2.7)
Out of the box Tools Has rich set of out of the box portlets Not too much out of the box portlets
Single Click configuration (altering a page layout, adding new applications and content, and changing look and feel can all be done in a couple of clicks) Supported Supported
Dynamic Drag and Drop(move different elements around in the portal by) Supported Supported
SSO Supported Supported
Role Based Authorization support Supported Supported
Communities and Organizations Liferay users can be intuitively grouped into a hierarchy of "organizations" or cross-organizational "communities," providing flexibility and ease of administration. Not Supported
Personal User Pages All users get a personal space that can be made public (published as a website with a unique friendly URL) or kept private. You can customize how the space looks, what tools and applications are included Not provided
Internationalization support Out of the box internationalization support provided for 22 languages. No out of the box internationalization support available
Wikis Provides robust wiki support Provided
Activity tracking Display most recent activity Not provided
Message Boards Supported (Can be very easily created) Supported
Instant Message Support A friends list automatically displays the names of all other logged-in portal users. If you have something to say, just IM them. Not provided
Alerts and Announcements Broadcast messages to different group of users whether they are simple announcements or "newsletter"-like in purpose Not provided
Blog Support Provided Not Provided
Calendar Rich calendar support(Can add events) Support
Password Policies Liferay provides flexible password policy through Enterprise Admin Portlet. you can apply different rule sets to different sets of portal users. Not Provided


•Both are JSR-168 compliant.
•Both are open source.

•JBoss Portal can only be installed on Jboss application server whereas Liferay works in any J2EE container or servlet container.
•Liferay has been around longer than JBoss Portal.
•The CMS features are very minimal in JBoss Portal because all that one can do is create html pages using a rich text editor and do some file manipulation activities (create directory, move and copy files and so on.
•The CMS portlet in Liferay is more feature rich than that of JBoss in the sense that one can create custom content types and own templates. This helps separate content form its presentation. It is also very easy to create new pages and add them automatically to the navigation bar.
•Liferay has a larger portal community.
•Liferay has more enterprise clients that have run the portal for many years with hundreds of thousands of users.
•Liferay comes with many useful portlets so you don't have to configure much. But, it also has many external portlets and themes available. JBoss has fewer portlets.
•Though Liferay works with almost any application server, I have found users complaining about setup with any other AS take longer time. Whereas setting up JBoss Portal is a straightforward, three-step process of editing some configuration files, creating the database, and starting the portal. Reference
•Also people felt Liferay portal to be bit slow but stable.
•Liferay is under the MIT (similar to Apache/BSD) style license. JBoss is LGPL.

Liferay Vs JBoss
Portal Polls Survey
JBoss to Liferay Migration Reason
Liferay User Experience Customization
Liferay Technical Spec

•Out of the box: A ready-made software, hardware, or combination package that meets a need that would otherwise require a special development effort.

Tuesday, September 23, 2008

Eclipse PlugIns

1)Fast Code Eclipse Plugin

Fast Code is a free eclipse plugin designed to help write code faster in a spring based applications. But it can be configured to work with many other kinds of applications as well.
It is free eclipse plugin for faster java development. It can help you code faster in a spring based application. It is capable of :

* Automatically create DAO to Service and Service to Action, e.g. FooDAO to FooService and FooService to FooAction.
* Automatically create one DAO to another with different name, e.g. FooDAO (with methods getFoo, saveFoo) to BarDAO (with methods getBar, saveBar).
* Also create spring based configurations.
* Easily navigate from DAO to Service and Service to DAO.
* Easily navigate from hibernate pojos to .hbm files.
* Easily create List, ArrayList, Map, HashMap initializers or fields in a class.
* Easily copy a field, just highlight and right click, go inside Fast Code pop up menu and click 'Copy Field'
* You can highlight part of the field name also.
* Some of the features can be turned off/on or configured in Windows->Preference->Fast Code Preference.

Reference: http://fast-code.sourceforge.net


UCDetector (Unnecessary Code Detector) is a eclipse PlugIn tool to find unnecessary (dead) public java code. For example classes, methods or fields which have no references. UCDetector creates markers for the following problems, which appear in the eclipse problem view.
* Unnecessary (dead) code
* Code where the visibility could be changed to protected, default or private
* Methods of fields, which can be final
UCDetector also finds cyclic dependencies between classes in your code. This cycle classes are shown in s special cycle view.

Reference: http://www.ucdetector.org

Friday, July 11, 2008

Eclipse 3.4 - New Features

Here are descriptions of some of the more interesting or significant changes made to the Java development tools for the 3.4 release of Eclipse.

Java Editor Breadcrumb
The Java editor now offers a breadcrumb which shows the path to the element at the cursor position. The breadcrumb can be enabled via the Toggle Breadcrumb tool bar button or by pressing Alt+Shift+B. Each element in the breadcrumb can be selected and actions can be invoked through a context menu or keyboard short cuts.Furthermore the breadcrumb lets you navigate to other elements via drop-downs.

Rich Javadoc Hover
The Javadoc hover can now be used to navigate Javadoc.
Follow links in Javadoc
Go forward and backward in the navigation history
Show the current content in the Javadoc view
Open the declaration of the current element
Open the current content in an external browser
Resize the hover
Move the hover (start dragging in the toolbar area)

Rich Java problem hover
The problem hover now offers all available quick fixes for a problem and shows a tool bar on F2 or when you move the mouse into it. Quick fixes can be executed by clicking on the links. The actions in the tool bar let you configure the annotation preferences and the problem severity.

Content assist improvements
Content Assist (Ctrl+Space) has been improved in several areas.
Content assist can now use the type of the enclosing instanceof condition to offer more field and method access proposals. The required cast will be inserted when such a proposal is selected.
Content assist for static members also work if the type has not been imported yet. The required import will be added when such a proposal is selected.
Content assist can now propose methods with unknown types.
Content assist on method invocations shows the guessed arguments.

Quick assists
New quick assists (Ctrl+1) have been added in this release.

Highlighting numbers in Java code
The Java editor can now show numbers with their own custom color.

Mark read and write occurrences
Mark Occurrences (Alt+Shift+O) now marks read and write accesses with different colors.

Occurrences in File improvements

Several improvements have been added to Search > Occurrences in File:

The quick menu (Ctrl+Shift+U) now only shows the searches applicable for the current selection. If only one search kind is possible, the shortcut will directly invoke the search.
The menu now offers all searches available by Mark Occurrences.
Matches are now highlighted with different colors for read and write accesses in the search view.
The search view offers a Link with Editor mode where the view input is connected to the current editor selection.

Java compiler on multi-CPU machines
The Eclipse Compiler for Java is now taking advantage of the multi-threading capability of multi-CPU machines. Our measurements show improvements up to 30%. Results depend on the JRE and platform used.

Support for external class folders
Class folders located outside the workspace (external) can now be added to the build path. To add an external class folder use the Java Build Path page of the project properties, select the Libraries tab and push the Add External Class Folder button.

Flexible ZIP archive extensions
It is now possible to add ZIP archives to the build path with file extensions other than .zip or .jar. It is now, for example, possible to add a .rar file on the build path.

Call Hierarchy view works with fields and types
The Call Hierarchy view in caller mode now works with more kinds of elements:
The children of a field are all members that access the field (read and write accesses).
The children of a type or an instance initializer are all constructors of the type

Runnable JAR export wizard
The Runnable JAR File Export wizard can create a JAR file based on a launch configuration. The generated JAR file contains all class files from the project including class files from required JARs and projects.
The generated JAR can be executed with the command: java -jar generated_file.jar
or, on most operating systems, by double-clicking the file.

More Java search options
Type reference search can now be limited to specific match locations in the code. For example, you can find references in cast expressions, or in field and local variable types.
The following example shows how to search for all catch clauses in your code (search for references to '*' and limit to catch clauses):

Paste creates snippet for members and statements
Paste (Ctrl+V) in the Package Explorer view now supports members and statements. Eclipse creates the required enclosing elements for you.

Enhanced debug hover
When debugging, hovers for variables have been enhanced to display an object inspector. The inspector will display logical structures according to the toggle setting in the visible Variables or Expressions view.

Saturday, July 5, 2008

SpringSource Application server

SpringSource announced a new application server that it claims will "liberate" Java users from "antiquated legacy Java technologies."
SpringSource Application Platform is a completely module-based Java application server that is designed to run enterprise Java applications and Spring-powered applications with a new degree of flexibility and reliability. The SpringSource Application Platform is based on the new SpringSource Dynamic Module Kernel™ (dm-Kernel). The dm-Kernel provides a module-based backbone for the server, which also harnesses the power of Spring, Apache Tomcat and OSGi-based technologies.
The product is now in beta at SpringSource's Web site.

Production Benefits
* Real time application and server updates
* Better resource utilization
* Side by side resource versioning
* Longer server uptime
* Run new and old web applications

Development Benefits
* Faster iterative development
* Small server footprint
* More manageable applications
* Greater code reuse

Reference http://www.springsource.com

OSGi technology - Dynamic module system for Java

OSGi technology is Universal Middleware. OSGi technology provides a service-oriented, component-based environment for developers and offers standardized ways to manage the software lifecycle. These capabilities greatly increase the value of a wide range of computers and devices that use the Java platform.OSGi technology adopters benefit from improved time-to-market and reduced development costs because OSGi technology provides for the integration of pre-built and pre-tested component subsystems. The technology also reduces maintenance costs and advances unique new aftermarket opportunities because networks can be utilized to dynamically update or deliver services and applications in the field.

The OSGi framework can be divided in two main elements:

* Services Platform

A services platform is defined as a software platform that supports the service orientation interaction. This interaction involves three main actors: service providers, service requesters and a service registry, although only the service registry belongs to the services platform. In the service orientation interaction, service providers publish service descriptions, and service requesters discover services and bind to the service providers. Publication and discovery are based on a service description.
In the context of OSGi, a service is described as a Java class or interface, the service interface, along with a variable number of attributes, the service properties, that are name and value pairs. Service properties allow different service providers that provide services with the same service interface to be differentiated. The service registry allows service providers to be discovered through queries formulated in an LDAP syntax. Additionnaly, notification mechanisms allow service requesters to receive events signalling changes in the service registry; these changes include the publication or retrieval of a particular service.
In OSGi, service providers and requesters are part of an entity called a bundle that is both a logical as well as physical entity. Service interfaces are implemented by objects created by the bundle. In standard OSGi, the bundle is responsible for run-time service dependency management activities which include publication, discovery and binding as well as adapting to changes resulting from dynamic availability (arrival or departure) of services that are bound to the bundle.

* Deployment infrastructure

Physically, a bundle correspond to a delivery and deployment unit that is materialized by a JAR file that contains code and resources (i.e., images, libraries, etc.) along with a file that contains information about the bundle, the manifest file. The OSGi framework provides mechanisms to support continuous deployment activities (for example a local console or an administration web page). These deployment activities include installation, removal, update, starting (activation) and stopping (de-activation) of a physical bundle. Once a bundle is installed in the platform, it can be activated if deployment dependencies that are associated to the bundle are fulfilled (these dependencies are described in the next section).

Friday, July 4, 2008

Compile a Java source from inside a Java program

Here is sample program which shows how to compile Java source file from inside a Java program using JDK 6.

Sample Java Code

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompilerTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompilerTool.CompilationTask;

public class Compiler {

public static void main (String[] args) {
String sourceFile = "c:/Sample.Java";
JavaCompilerTool compiler = ToolProvider.getSystemJavaCompilerTool ();
StandardJavaFileManager fileManager =
compiler.getStandardFileManager (null);

// prepare the source file(s) to compile
List sourceFileList = new ArrayList ();
sourceFileList.add (new File (sourceFile));
Iterable compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
CompilationTask task = compiler.getTask (null,fileManager, null, null, null, compilationUnits);
task.run ();
boolean result = task.getResult ();
if (result) {
System.out.println ("Compilation was successful");
} else {
System.out.println ("Compilation failed");
try {
fileManager.close ();
} catch (IOException e) {


Monday, June 30, 2008

The Hotswap target for Ant for Java

The Hotswap (hotswap.jar) is Ant task which replaces classes on a running JVM. This task can take the following arguments.

Replaces classes on a running JVM. This task can take the following arguments:
* verbose - prints class names as they are being swapped
* failonerror - causes task to exit if any error occurs
* host - the host of the JVM to be attached to (defaults to localhost)
* port - the port number to be used to attach to the JVM
* name - if not using a socket connection, this name is the share memory label

Of these arguments, the host and port are required. Or, the name can be used instead to indicate a shared mem connection.
See the JPDA documentation for details on the JVM runtime options. http://java.sun.com/j2se/1.4.2/docs/guide/jpda/conninv.html
These are the options that work with the example below: -Xdebug -Xrunjdwp:transport=dt_socket,address=9000,server=y,suspend=n

Add this line to your build.xml
<taskdef name="hotswap" classname="dak.ant.taskdefs.Hotswap"/>

This is an example of how to hotswap with a JVM on port 9000 on your local machine
<target name="hotswap">
<format property="class.tstamp" pattern="MM/dd/yyyy kk:mm:ss" />

<javac destdir="${build.classes.dir}>
<fileset dir="${dev.src.dir}" includes="**/*.java"/>

<hotswap verbose="true" port="9000">
<fileset dir="${build.classes.dir}" includes="**/*.class">
<date datetime="${class.tstamp}" pattern="MM/dd/yyyy kk:mm:ss" when="after" granularity="0"/>


Thursday, June 26, 2008

Calculate CheckSum using Java

Some times we need to calculte checksum of specified file. In java, We can use MessageDigest class to get checksum of specified file.

Sample Java Code

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CheckSum {
public static void main(String args[]){
StringBuffer checksum;
try {
File file = new File("C:\\Test.zip");
FileInputStream is = new FileInputStream(file);
byte buffer[] = new byte[(int)file.length()];
MessageDigest md = MessageDigest.getInstance("MD5");
byte digest[] = md.digest();
checksum = new StringBuffer();
for(int i = 0; i <>
String digit = Integer.toHexString(0xff & digest[i]);
if(digit.length() == 1)
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block

Wednesday, June 25, 2008

Idenfiy Java Compiler Version used to compile a class

Some times we need to identify what compiler version and vendor was used for a given Java class file. We can use Jakarta BCEL to idenfiy compiler version.
Sample Java Code
import org.apache.bcel.classfile.*;
public class JDKIdentifier
public static void main(String[] args) throws Exception
printClassVersion("c:\\foo.jar", "com/foo/Bar.class");
public static void printClassVersion(String jarfile, String classfile) throws Exception
ClassParser cp = new ClassParser(jarfile, classfile);
JavaClass clazz1 = cp.parse();
System.out.println("Major: " + clazz1.getMajor());
System.out.println("Minor: " + clazz1.getMinor());

Sunday, June 22, 2008

Convert plain HTML to XHTML

Tidy reads HTML, XHTML and XML files and writes cleaned up markup. For HTML variants, it detects and corrects many common coding errors and strives to produce visually equivalent markup that is both W3C compliant and works on most browsers. A common use of Tidy is to convert plain HTML to XHTML. For generic XML files, Tidy is limited to correcting basic well-formedness errors and pretty printing.


JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM parser for real-world HTML.

References http://jtidy.sourceforge.net/

DataGrid In Java

Display tag library

We can use Display tag library to display Datagrid in JSP.

The display tag library is an open source suite of custom tags that provide high-level web presentation patterns which will work in an MVC model. The library provides a significant amount of functionality while still being easy to use.

Display tag gives list of objects and it will handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table in a customizable XHTML style.

When you set the Table Tag's export attribute to "true", a footer will appear below the table which will allow you to export the data being shown in various formats like CSV, Excel, XML, PDF.

References http://displaytag.sourceforge.net

Data Grid for JSP

An Asp.Net style grid control for JSP with ability to fetch data from java.sql.Connection or java.util.List or java.sql.ResultSet

Features at a glance

At present the control implements following things.

* Data pagination.
* Sorting by a specified column.
* Automatic row number display.
* Image based hyperlink columns.
* Hyperlink columns.
* Custom data formatting.
* Value decoding.
* Ability to bind to a List.
* Ability to bind to a ResultSet.
* Ability to bind to a RowSet.

References http://www.codeproject.com/KB/grid/DBGrid.aspx

Saturday, June 21, 2008

Java PathFinder

The Java PathFinder, JPF, is a translator from Java to Promela, the programming language of the SPIN model checker. The purpose is to establish a framework for verification and debugging of Java programs using model checking. The system detects deadlocks and violations of assertions stated by the programmer.

Java PathFinder (JPF) is a system to verify executable Java bytecode programs. In its basic form, it is a Java Virtual Machine (JVM) that is used as an explicit state software model checker, systematically exploring all potential execution paths of a program to find violations of properties like deadlocks or unhandled exceptions. Unlike traditional debuggers, JPF reports the entire execution path that leads to a defect. JPF is especially well-suited to finding hard-to-test concurrency defects in multithreaded programs.

JPF is a pure Java application that can be run either as a standalone command line tool, or embedded into systems like development environments. It was mostly developed - and is still used - at the NASA Ames Research Center. Started in 1999 as a feasibility study for software model checking, JPF has found its way into academia and industry, and has even helped detect defects in real spacecraft.



Friday, June 20, 2008

Splash screens using Java

Almost all modern applications have a splash screen. Typically splash screens are used for the following purposes:

* Advertising a product
* Indicating to the user that the application is launching during long startup times
* Providing information that is only needed once per visit

Fortunately, Java™ SE 6 provides a solution that allows the application to display the splash screen much earlier, even before the virtual machine starts. A Java application launcher is able to decode an image and display it in a simple non-decorated window.

Here is sample java code available to display splash Screen.

Sample Java Code

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SplashScreen extends Frame{
static void renderFrame(Graphics2D g, int frame) {
final String[] comps = { "foo", "bar", "baz" };
g.fillRect(130, 250, 280, 40);
g.drawString("Loading " + comps[(frame / 5) % 3] + "...", 130, 260);
g.fillRect(130, 270, (frame * 10) % 280, 20);

public SplashScreen() {
super("SplashScreen demo");
setSize(500, 300);
setLayout(new BorderLayout());
Menu menu = new Menu("File");
MenuItem menuItem = new MenuItem("Exit");
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){


MenuBar mb = new MenuBar();
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
Graphics2D g = (Graphics2D) splash.createGraphics();
if (g == null) {
for (int i = 0; i <>
renderFrame(g, i);
try {
} catch (InterruptedException e) {

public static void main(String args[]) {
SplashScreen screen = new SplashScreen();



Tuesday, June 17, 2008

Conversion between Array and List types

In some scenario, we may need to convert an array to a list or vice versa. We can use asList() method available in the Arrays class, and the toArray() method in List and set classes serve this purpose.

The Arrays.asList() method converts an array into a list and the size of the list is fixed.

The toArray() method converts a set or list to an array. This method has two forms of invocation. One form of the toArray() method returns a Object array, and another form returns the array of the type that is passed as the argument.

Passing properties from command line

We can pass property from command line. The syntax to pass properties from command line is as follows.

java -D<name>=
<value> .....

The getProperty() method in System class is used to get the value of a property by specifying the property name as key.

Sample Java Code

public class Properties {

public static void main(String[] args) {

String name = System.getProperty("name");
System.out.println("name is " name);
String address = System.getProperty("address");
System.out.println("address is " +address);
String age = System.getProperty("age");
System.out.println("age is " +age);

Monday, June 16, 2008

Copy File using Java

FileChannel is class used for reading, writing, mapping, and manipulating a file. File Channels are part of Java New I/O Packages. A file can be viewed as a sequence of bytes. The various Buffer classes in New I/O Packages serve as a container for manipulating the primitive byte contents. It is also possible to allocate a new Buffer object, read and write byte data into the existing Buffer using the Buffer classes. The File Channel objects are tightly associated with the Buffer class, and now File objects are coupled with File Channel object which means that it is now possible to perform read and write data on the files using the File Channel objects.

Sample Java Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class CopyFile {

public static void main(String[] args) throws Exception{

String file = "input.txt";
FileInputStream source = new FileInputStream(file);
FileOutputStream destination = new FileOutputStream("Output.txt");

FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();

long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);

Dynamic Forms with Adobe LiveCycle

PDF and Flash® technologies come together to more effectively engage customers, constituents, partners, and employees in key business processes.

Adobe® LiveCycle® ES (Enterprise Suite) software is an integrated J2EE server solution that blends electronic forms, process management, document security, and document generation to help you create and deliver rich and engaging applications that reduce paperwork, accelerate decision-making, and help ensure regulatory compliance.

Adobe LiveCycle ES can help you:

* Build more engaging experiences that scale from paper forms to rich and interactive online applications
* Reduce development time with intuitive and integrated developer resources
* Protect sensitive information to inspire confidence on both ends of a transaction
* Extend your enterprise with new applications that span data capture, process orchestration, and document generation — inside and outside the firewall.

Using Adobe LiveCycle Forms ES we can create interactive XML based forms as HTML,PDF or SWF.

* Empower users to complete and submit dynamic forms online or offline and across the firewall.
* Create interactive forms and form guides to improve data accuracy and reduce transaction cycle times.
* Comply with government accessibility requirements for online forms, including Section 508 and W3C WCAG 1.0 Level AA guidelines.
* Automate form data exchange and validation with core business systems.
* Reduce training costs and increase user adoption by using PDF to maintain the look and feel of paper forms.
* Smoothly integrate RIAs with existing applications, back-end data, and LiveCycle ES services.

Reference: http://www.adobe.com/products/livecycle/

Sunday, June 15, 2008

PDF Renderer: Open Source Java Project

PDF Renderer is Open source Java Project to render PDF document using java2D. iText is very powerful java library for pdf creation. PDFRenderer does not generate PDF doucments, but it view PDF document.

You can use PDF renderer for achieving following goals:

* view PDFs documents using java PDF Renderer
* print-preview before exporting PDF files
* render PDFs to PNGs in a server-side web application
* view PDFs in a 3D scene
* draw on top of PDFs and annotate them in a networked viewer

You can find sample java code for rendering PDF document on following reference site.



Saturday, June 14, 2008

Java CSS

Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents. Java CSS is Java implementation of CSS which differs in some aspects, but overall concept is same.


Java CSS documents look much like their HTML CSS.

Component {
font-family: "SansSerif";
font-size: 14;
font-weight: normal;

JLabel#title {
font-size: 24;
font-weight: bold;
foreground: #0099ff;
border: etchedBorder;

JButton:mouseover {
font-weight: bold;

JButton.toolbar {
text: null;

The :mouseover in JButton:mouseover is known as a pseudoclass, and it means "only when the mouse is over the component". So JButtons will normally have font-weight: normal (because of the Component rule), but will switch to bold text when the mouse is over them. JButtons with the "toolbar" style class (according to getClientProperty("styleClass")) will additionally have their text set to null.

Using Stylesheets

You can create a stylesheet using one of its constructors and then apply it to the appropriate components using applyTo():

FileReader in = new FileReader("example.css");
Stylesheet stylesheet = new Stylesheet(in);

You can also set a stylesheet as the global stylesheet with Stylesheet.setGlobalStylesheet(). The global stylesheet is automatically applied to all windows as they are displayed.

Differences from HTML

Many readers will be familiar with CSS as it applies to HTML documents. The Java CSS implementation has some important differences relative to HTML CSS:

* Java property names are used throughout. A label's color, for example, is controlled with "foreground" after its Java property name instead of the HTML CSS property "color".
* The set of available properties is different. JPanel, for example, has no equivalent to HTML's "background-image" property. On the other hand HTML has no equivalent to the JSlider property "majorTickSpacing" -- in fact it doesn't even offer sliders to begin with!
* Not all CSS selectors are supported. For example, there is currently no way to specify "all JLabels which are children of a JPanel".
* Java CSS's pseudoclasses are more powerful and useful. HTML has no equivalent to Java's programmatic pseudoclasses.

There are many other minor differences, but these are by far the most significant.



Thursday, June 12, 2008

Mysql - Associate a username with Mupltiple hosts

Mysql stores user account information in user table of mysql database.
In Mysql, same username can be assoicated with Multiple hosts. You can create multiple accounts with same username. you can use differnt password, and previlages for each account.

e.g we can create following two accounts with same username maulin

maulin@localhost - This account can be used only when connecting with localhost.
maulin@% - This account can be used only when connecting from any other host.

To determine which account applies, the server uses the username value in conjunction with the name of the host from which you connect. This means that there can be different accounts with the same username, which can be used for connections from different hosts. So make sure you are using correct combination of username & hosts for connecting database, otherwise you will get connection error.

Sunday, June 8, 2008

Java Performance Tuning

Best Practices to improve performance in Servlets

1. Use init() method to cache static data
2. Use StringBuffer/StringBuilder rather than using + operator when you concatenate multiple strings
3. Use print() method rather than println() method
4. Use ServletOutputStream rather than PrintWriter to send binary data
5. Initialize the PrintWriter with proper size
6. Flush the data partly
7. Minimize code in the synchronized block
8. Set the content length
9. Release resources in destroy() method.
10. Implement getLastModified() method to use browser cache and server cache
11. Use application server caching facility
12. Use Mixed session mechanisms such as HttpSession with hidden fields
13. Remove HttpSession objects explicitly in your program whenever you finish the task
14. Reduce session time out value as much as possible
15. Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
16. Disable servlet auto reloading feature.
17. Use thread pool for your servlet engine and define the size as per application requirement.

Best Practices to improve Performance in JSP

1. Use jspInit() method to cache static data
2. Use StringBuffer rather than using + operator when you concatenate multiple strings
3. Use print() method rather than println() method
4. Use ServletOutputStream instead of JSPWriter to send binary data
5. Initialize the 'out' object (implicit object) with proper size in the page directive.
6. Flush the data partly
7. Minimize code in the synchronized block
8. Set the content length
9. Release resources in jspDestroy() method.
10. Give 'false' value to the session in the page directive to avoid session object creation.
11. Use include directive instead of include action when you want to include the child page content in the translation phase.
12. Avoid giving unnecessary scope in the 'useBean' action.
13. Do not use custom tags if you do not have reusability.
14. Use application server caching facility
15. Use Mixed session mechanisms such as 'session' with hidden fields
16. Use 'session' and 'application' as cache.
17. Use caching tags provided by different organizations like openSymphony.com
18. Remove 'session' objects explicitly in your program whenever you finish the task
19. Reduce session time out value as much as possible
20. Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
21. Disable JSP auto reloading feature.
22. Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

Best practices to improve performance in JDBC

1. Get database connection from connection pool rather than getting it directly
2. Use batch transactions.
3. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
4. Your database server may not support all isolation levels, be aware of your database server features.
5. Use PreparedStatement when you execute the same statement more than once.
6. Use CallableStatement when you want result from multiple and complex statements for a single request.
7. Use batch update facility available in Statements.
8. Use batch retrieval facility available in Statements or ResultSet.
9. Set up proper direction for processing rows.
10. Use proper getXXX () methods.
11. Close ResultSet, Statement and Connection whenever you finish your work with them.
12. Write precise SQL queries.
13. Cache read-only and read-mostly tables data.

Performance improvement techniques in Object creation

1. Avoid creating objects in a loop.
2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
3. Whenever you are done with an object make that reference null so that it is eligible for garbage collection.
4. Never keep inheriting chains long since it involves calling all the parent constructors all along the chain until the constructor for java.lang.Object is reached.
5. Use primitive data types rather than using wrapper classes.
6. Whenever possible avoid using class variables, use local variables since accessing local variables is faster than accessing class variables.
7. Another technique is Lazy object creation: i.e. delaying the memory allocation to an object till it is not being put into use. This way a lot of memory is saved till the object is actually put in to use.
Performance improvement techniques in Exceptions
1. In a catch block avoid using the generic class Exception. For each try block use specific catch blocks based on what can go wrong in your code.
2. Whenever you are using a throws clause always use the specific subclass of Exception like FileNotFoundException rather than using throws Exception.
3. Always use the finally block to release the resources like a database connection, closing a file or socket connection etc. This prevents resource leaks even if an exception occurs.
4. Do not use Exception handling in loops. It is better to place loops inside try/catch blocks than vice versa. Here is an code snippet that gives bench mark.

Performance improvement techniques in loops

1. Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
2. When using arrays it is always efficient to copy arrays using System.arraycopy() than using a loop.
3. Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions.
4. Method calls are very costly and you only make it worse by putting them in a loop. So as far as possible avoid method calls in a loop.
5. It is better to avoid accessing array elements in a loop the better option would be to use a temporary variables inside the loop and modify the array values out of the loop. It is fast to use a variable in a loop than accessing an array element.
6. Try to compare the terminating condition with zero if you use non-JIT or HotSpot virtual machine, here is an example to prove the point. JIT or HotSpot virtual machines are optimized for general loops so you do not have to bother about the terminating condition.

Reference: www.precisejava.com

Saturday, June 7, 2008

Encrypt user password before storing it to database

It is important to encrypt user password before storing it in the database. Password must be interpreted only by your java application.
Here is the sample java code to encrypt a plain password text. Before comparing password, encrypt it using following java code.

Sample Java Code

public synchronized String encrypt(String plainpassword) throws SystemUnavailableException {
MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
catch(NoSuchAlgorithmException e)
throw new SystemUnavailableException(e.getMessage());
catch(UnsupportedEncodingException e)
throw new SystemUnavailableException(e.getMessage());

byte data[] = md.digest();
String encryptedPassword = (new BASE64Encoder()).encode(data);
return encryptedPassword;

Sunday, May 11, 2008

Executing anonymous servlet in Tomcat - Jboss

If you want to run anonymous servlet classes in Tomcat or Jboss that have not been defined in a web.xml file, you need to change configure it in web.xml.

Open web.xml and uncomment following lines.



Traditionally, this servlet is mapped to the URL pattern "/servlet/*", but you can map it to other patterns as well.

Wednesday, May 7, 2008

Jython - Python with Power of Java

Jython, formerly known as JPython, is an implementation of the Python programming language written in Java.

Java and Python, each have their advantages and disadvantages. Java is a very powerful language. Python is a very easy and very efficient language. Jython is a technology capable of merging Python and Java together to create efficient and powerful applications. Jython combines the advantages of Python and the Java virtual machine and library and serves as a handy complement to the Java platform. Jython allows programmers to use the syntax and most of the features of the Python programming language.

Jython programs can easily import and use any Java class. Except for some standard modules, Jython programs use Java classes instead of Python modules. Jython includes almost all of the modules in the standard Python programming language distribution, lacking only some of the modules implemented originally in C. For example, a user interface in Jython would be written with Swing, AWT or SWT. Jython compiles to Java bytecode either on demand or statically. Jython also includes jythonc, a compiler that converts Python source code into Java bytecode (intermediate language). This allows Python programmers to write classes which can be fully utilized by a Java program.

Jython is interesting to Java programmers for several reasons:

* Jython's version of the Python interpreter shell allows convenient experimentation and exploration of ideas and APIs without having to go through the usual Java compile/run cycle.

* Python is dynamic and generic by design, so you don't have to add these features by using complex libraries (such as those for Java reflection and introspection). This makes some sorts of development easier and is especially useful in automated testing frameworks.

* Many developers like Python's syntax and the feel of the language; they find it a much more productive way to develop and maintain Java applications.

Visit following link for more details.


Visit following link to find out Jython users.


Tuesday, May 6, 2008

Web Developer Tools

Different Tools are available in order to analyase and debug web application and help to improve website. Web developer tools makes development easier and faster.

Here is some of useful tools available for different web browsers.

1) Firebug - For Firefox Browser

Firebug integrates with Firefox to put a wealth of development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.


-Inspect and edit HTML
-Tweak CSS to perfection
-Visualize CSS metrics
-Monitor network activity
-Debug and profile JavaScript
-Quickly find errors
-Explore the DOM
-Execute JavaScript on the fly
-Logging for JavaScript
-Timing and profiling
-Stack traces
-Nested grouping
-Object inspection

Visit the Firebug website for documentation, screen shots, and discussion forums:


2) IE Developer Toolbar

The Microsoft Internet Explorer Developer Toolbar provides a variety of tools for quickly creating, understanding, and troubleshooting Web pages.


-Explore and modify the document object model (DOM) of a Web page.
-Locate and select specific elements on a Web page through a variety of techniques.
-Selectively disable Internet Explorer settings.
-View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
-Outline tables, table cells, images, or selected tags.
-Validate HTML, CSS, WAI, and RSS web feed links.
-Display image dimensions, file sizes, path information, and alternate (ALT) text.
-Immediately resize the browser window to a new resolution.
-Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
-Display a fully featured design ruler to help accurately align and measure objects on your pages.
-Find the style rules used to set specific style values on an element.
-View the formatted and syntax colored source of HTML and CSS.

For more information please visit.


3) Opera Dragonfly -Opera Browser

Opera Dragonfly makes developing using Opera easier than ever. It allows Debug JavaScript, inspect CSS and the DOM, and view any errors.

-Redefine your style
-Reach breaking point step by step
-Debug the DOM
-Spot your errors
-Debug your phone or TV

For more information please visit.


Tips For Measuring Application Performance

Here are some of important points which should be considered while measuring application performance.

- Test systems should match production as closely as possible. Same hardware, OS, and software.
- Populate databases with the number of records expected in production.
An application may perform well with a small number of records in the database. Performance could degrade a great deal as the number of records in the table(s) increases
- Test HTTP requests with different request parameters.
Test with the extremes. A page which performs a search may perform well when the search criteria returns a small result set, but perform poorly when the search criteria returns a large result set.
- Simulate expected traffic over time including short term spikes.
A page which performs well with low request volume can cause the server to fail under higher request volume.
- Use Server load testing tools (like Apache Jakarta JMeter) to simulate heavy load.

Tomcat - Jboss Performance Tuning Tips

Apache Tomcat is an implmentation of the Java Servlet and JavaServer Pages technologies.
In production Enviroment, number of resources which can all impact application overall performance. Here are some important point which can help to improve Tomcat Performance.

Performance Tuning - Tomcat Configuration

Configure server.xml parameters as following.

-Set reloadable to false

When reloadable is true Tomcat tries to detect web application class changes and automatically reload any classes which change. Setting this to false removes a lot of unnecessary overhead in production.

-Set liveDeploy to false

liveDeploy controls whether your webapps directory is periodically checked for new web application directories and war files. This is done using a background thread. Set this to false and use the manager application or ant deploy tasks instead.

-Set debug to 0

Disable all debug output, unnecessary logging just adds overhead.

-Set swallowOutput to true

This makes sure all output to stdout or stderr for a web application gets directed to the web application log rather than the console or catalina.out. This makes it easier to troubleshoot web application problems.

Performance Tuning - Jasper 2 Configuration

Configure web.xml parameters as following.

-Set development to false

Disables JSP page out of date checks on each request and enables JSP background recompiles. development is set to true by default.

-Use JSP custom tag pooling

Object pooling of classes which implement custom tags significantly improves performance of JSP pages which use custom tag libraries. JSP custom tag pooling is enabled by default.

-Configure Jasper to fork javac compiles. (Do not set fork to true on MS Windows)

The JVM compiler javac has known memory leaks. Eliminates JVM memory usage and GC overhead of javac by configuring Jasper to fork javac when compiling JSP pages.