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) {
}
}
}

Reference
http://www.java2s.com

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);
}
}

ORM Framework for Kotlin

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