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">
<tstamp>
<format property="class.tstamp" pattern="MM/dd/yyyy kk:mm:ss" />
</tstamp>

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

<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"/>
</fileset>
</hotswap>
</target>

Reference
https://hotswap.dev.java.net

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()];
is.read(buffer);
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(buffer);
byte digest[] = md.digest();
checksum = new StringBuffer();
for(int i = 0; i <>
{
String digit = Integer.toHexString(0xff & digest[i]);
if(digit.length() == 1)
checksum.append('0');
checksum.append(digit);
}
System.out.println("checksum::"+checksum.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

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(jarfile);
System.out.println("Major: " + clazz1.getMajor());
System.out.println("Minor: " + clazz1.getMinor());
}
}
Reference
http://forum.java.sun.com/thread.jspa?threadID=577007&messageID=3791497

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.

References
http://tidy.sourceforge.net

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.

References

http://javapathfinder.sourceforge.net/

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.setComposite(AlphaComposite.Clear);
g.fillRect(130, 250, 280, 40);
g.setPaintMode();
g.setColor(Color.BLACK);
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");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}

});

MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(menu);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
return;
}
Graphics2D g = (Graphics2D) splash.createGraphics();
if (g == null) {
return;
}
for (int i = 0; i <>
renderFrame(g, i);
splash.update();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
splash.close();
setVisible(true);
toFront();
}

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

References

http://java.sun.com/docs/books/tutorial/uiswing/misc/splashscreen.html

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.

Reference:

https://pdf-renderer.dev.java.net/

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.

Example


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);
in.close();
stylesheet.applyTo(mainFrame);

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.

Reference:

https://javacss.dev.java.net/docs/overview.html

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;
try
{
md = MessageDigest.getInstance("SHA");
}
catch(NoSuchAlgorithmException e)
{
throw new SystemUnavailableException(e.getMessage());
}
try
{
md.update(plainpassword.getBytes("UTF-8"));
}
catch(UnsupportedEncodingException e)
{
throw new SystemUnavailableException(e.getMessage());
}

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

ORM Framework for Kotlin

In Kotlin, ORM (Object-Relational Mapping) libraries provide a convenient way to interact with databases using object-oriented programming p...