jQuery Tutorials :- Part 1

All web applications these days have become Ajax Enabled and are becoming richer day by day with Increasing Browser Capabilities. JQuery one of the best Javascript Framework which provides Developers with lots of base features similar to Java SDK in java world. Many guys find it very hard to get good Integrated examples in Javascript. After exhaustive search even i couldn’t find good examples in with Java as backend and JQuery as frontend. I would like post series of articles which has JQuery as frontend and J2ee as backend.

Apart from that there are some services which are provided by default in framework like Theming support. I have downloaded all freely available JQuery themes and modified/created themeswitcher tool to point to local themes rahter than pointing to JQuery website for this so as to enable application in Intranet mode too rahter than relying on internet

This Application is also Integrated with JQuery-Layout which provides very elegant look and feel.

Application is designed in same lines as other Demo’s (EXT, JQGrid..etc) so it it looks easy for developors to Understand the Code and see examples
Will be hosting application in couple of days till then will attach screenshots and code base is there in google code.

GoogleCode

My Code base is mavenized to make it easy for developers to build and deploy.
Lets start with Integration with JQuery

Layout And Themerollder
Layout And Themerollder

Creating tabs
Creatign tabs

Cntd……

Generating barcode from Java using Maven

Barcode has become a standardway to identify articles throughout the world. Every day millions of barcodes are generated around the world. Here i would describe some basics of barcode standards and generation of barcode from java

Below are list of various barcode symbologies

1D barcode implementations
Interleaved 2 of 5
Code 39
Code 128
EAN-128, GS1-128 (based on Code 128)
Codabar
UPC-A and UPC-E (with supplementals)
EAN-13 and EAN-8 (with supplementals)
POSTNET
Royal Mail Customer Barcode (Four State)
USPS Intelligent Mail (4-State Customer Barcode)

2D barcode implementations
PDF 417 (ISO/IEC 15438:2001(E))
DataMatrix (ISO/IEC 16022:2000(E))

All the specifications surround around basic concepts of

  • Quiet Zone
  • Start Character
  • Encoded Data
  • Check Character
  • Stop Character
  • Quiet Zone

Read more about barcode generation technologies on wiki. I’ll explain more about generation of barcode in Java Using various open source Libraries and Integration with Maven

Barcode4j

/**
*
*/
package com.linkwithweb.barcode.barcode4j;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

/**
* @author kumara
*
*/
public class HelloWorld {

/**
* @param args
*/
public static void main(String[] args) {
try {
// Create the barcode bean
Code39Bean bean = new Code39Bean();

final int dpi = 150;

// Configure the barcode generator
bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); // makes the narrow
// bar
// width exactly
// one pixel
bean.setWideFactor(3);
bean.doQuietZone(false);

// Open output file
File outputFile = new File("out.jpg");
OutputStream out = new FileOutputStream(outputFile);
try {
// Set up the canvas provider for monochrome JPEG output
BitmapCanvasProvider canvas = new BitmapCanvasProvider(out,
"image/jpeg", dpi, BufferedImage.TYPE_BYTE_BINARY,
false, 0);

// Generate the barcode
bean.generateBarcode(canvas, "123456");

// Signal end of generation
canvas.finish();
} finally {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

Using barbecue

/**
*
*/
package com.linkwithweb.barcode.barbeque;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import net.sourceforge.barbecue.output.OutputException;

/**
* @author kumara
*
*/
public class HelloWorld {

/**
* @param args
*/
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
try {
helloWorld.outputtingBarcodeAsPNG();
} catch (BarcodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void usingBarbecueAsSwingComponent() {
// Always get a Barcode from the BarcodeFactory
Barcode barcode = null;
try {
barcode = BarcodeFactory.createCode128B("My Barcode");
} catch (BarcodeException e) {
// Error handling
}
}

public void drawingBarcodeDirectToGraphics() throws BarcodeException,
OutputException {
// Always get a Barcode from the BarcodeFactory
Barcode barcode = BarcodeFactory.createCode128B("My Barcode");

// We are created an image from scratch here, but for printing in Java,
// your
// print renderer should have a Graphics internally anyway
BufferedImage image = new BufferedImage(500, 500,
BufferedImage.TYPE_BYTE_GRAY);
// We need to cast the Graphics from the Image to a Graphics2D - this is
// OK
Graphics2D g = (Graphics2D) image.getGraphics();

// Barcode supports a direct draw method to Graphics2D that lets you
// position the
// barcode on the canvas
barcode.draw(g, 10, 56);
}

public void outputtingBarcodeAsPNG() throws BarcodeException {
// get a Barcode from the BarcodeFactory
Barcode barcode = BarcodeFactory.createCode128B("My Barcode");

try {
File f = new File("mybarcode.png");

// Let the barcode image handler do the hard work
BarcodeImageHandler.savePNG(barcode, f);
} catch (Exception e) {
// Error handling here
}
}
}

and below is sample pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BarcodeGenerator</groupId>
<artifactId>com.linkwithweb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BarcodeGenerator</name>
<description>BarcodeGenerator</description>
<dependencies>
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
</project>

Attached are sample images generated by code

Generated by Barbeque
Generated By Barbeque

Generated By barcode4j
Generated By barcode4j

Below is link for the sample working maven project
barcode

Rename .doc to .rar extract and njoy!!!!!!

DBUnit / Apache POI / Log4j / Slf4j

I’m going to write about some of the Latest compatibility configuration that can be used so that they dont get into conflict with each other.
For example DBUnit is only updated till apache poi 3.2-FINAL but POI had removed some of old methods in new versions.

<!-- Log4J -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.9</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.5.5</version>
</dependency>

<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.6.2.1</version>
</dependency>

<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.4.8</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

Create Installer using Installshield for newbie

I had a requirement to create an installer using install shield. Having created installer using several opensource tool i wanted to venture into the Installshield world to see hwo easy it is and how it looks like. Wonder what after downloading trail version of Installer from Installshield website i was able to create a installer for tomcat within 1/2 an hour and here a Kind of helloworld and newbie view towards installshied

SelectProject Type
SelectProject Type

Select Project Assistant
SelectProject Type

Define Project Parameters
Define Project Parameters

Add Folder to Project
Add Folder to Project

Create Shortcuts/ On Startup things
Create Shortcuts/ On Startup things

Finally Build the image
Finally Build the image

This is how it looks after installation
This is how it looks after installation

Derby Tutorial Mavenized with Unit Test and Loading Data from Excel

Many applications requirement where they want to store some data at runtime and able to query using SQL. We wouldn’t like to install a full fledged database in such scenarios.
Apache has come up with a light weight database named Derby which suits the purpose. I would like to publish usage of Apache derby in java and how to use it. This tutorial is targetted to any one who understands java

This example rotates around a simple table person

ID NAME FIRST_NAME BIRTH_DATE
1 Jim Hammond 12/12/1974
2 Robert Grass 2/6/1968
3 John Kazyncksy 5/3/2000

This data is loaded by program from an excel file to Derby Database

As i’m using maven i’ll first define my pom here

4.0.0
com.ashwin.test.derby
derby
Derby Example
1.0.0

org.apache.maven.plugins
maven-compiler-plugin

1.5
1.5

org.apache.maven.plugins
maven-surefire-plugin

<!--

Be sure that JAVA_HOME points to a JDK6 installation
${env.JAVA_HOME}/db/lib/derby.jar

-->

org.apache.maven.plugins
maven-source-plugin

attach-sources
verify

jar

org.dbunit
dbunit
2.2.2
test

org.apache.derby
derby
10.6.2.1

Now as we defined our POM. Now lets try to load some data into derby. As derby is inmemory database we dont need to start any db server before hand. I created a base class which return DB Connection url and driver class

package com.linkwithweb.test.derby.dao;

import org.dbunit.JdbcBasedDBTestCase;
import org.dbunit.dataset.IDataSet;

/**
* An abstract Jdbc test case that factorizes the common methods.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public abstract class AbstractDaoTest extends JdbcBasedDBTestCase {

/**
* @see org.dbunit.JdbcBasedDBTestCase#getConnectionUrl()
*/
@Override
protected String getConnectionUrl() {
return "jdbc:derby:myDB;create=true";
}

/**
* @see org.dbunit.JdbcBasedDBTestCase#getDriverClass()
*/
@Override
protected String getDriverClass() {
return "org.apache.derby.jdbc.EmbeddedDriver";
}

/**
* @see org.dbunit.DatabaseTestCase#getDataSet()
*/
@Override
protected IDataSet getDataSet() throws Exception {
return getConnection().createDataSet();
}
}

Now let me create a class Table Creator which loads Data into the Database

package com.linkwithweb.test.derby.dao;

import java.sql.Statement;

/**
* Run once in order to create the tables.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class TableCreator extends AbstractDaoTest {

/**
* Initializes the DB. Must be run once and only once to create structure.
*
* @throws Exception
*/
public void initialize() throws Exception {

Statement lStatement = getConnection().getConnection()
.createStatement();

lStatement
.executeUpdate("CREATE TABLE PERSON (ID INT, NAME VARCHAR(60), FIRST_NAME VARCHAR(60), BIRTH_DATE DATE)");
}

/**
* Calls the {@link #initialize()} method on a new instance.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {

new TableCreator().initialize();
}
}

In the above code we have create a table person in our testDB

Now letme create a GenericDAO which define any generic DAO contract

package com.linkwithweb.test.derby.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;

/**
* A DAO interface with common methods.
*
* @param
* Object type of the DAO
* @param
* Object type of the unique key
* @author Ashwin
* @since 16th Nov 2010
*/
public interface IDao {

/**
* Returns the object denoted by this unique identifier in the back-end
* system.
*
* @param pId
* Unique identifier
* @return Object
* @throws SQLException
* If an error occurs
*/
T findById(K pId) throws SQLException;

/**
* Removes the object denoted by this unique identifier from the back-end
* system.
*
* @param pId
* Unique identifier
* @throws SQLException
* If an error occurs
*/
void removeById(K pId) throws SQLException;

/**
* Returns all the object in the back-end system.
*
* @return Collection of objects
* @throws SQLException
* If an error occurs
*/
Collection getAll() throws SQLException;
}

Now let me create Person DAO which acts on Person Table


package com.linkwithweb.test.derby.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
* An abstract DAO that knows how to get a connection to the db.
*
* @param
* Object type of the DAO
* @param
* Object type of the unique key
* @author Ashwin
* @since 16th Nov 2010
*/
public abstract class AbstractDao implements
IDao {

/** Connection URL . */
private static final String CONNECTION_URL;

/** Connection login to the DB. */
private static final String CONNECTION_LOGIN;

/** Connection password to the DB. */
private static final String CONNECTION_PWD;

static {
CONNECTION_URL = System.getProperty("com.linkwithweb.url");
CONNECTION_LOGIN = System.getProperty("com.linkwithweb.login");
CONNECTION_PWD = System.getProperty("com.linkwithweb.pwd");
}

/**
* Gets a connection to the database.
*
*
* @return Connection
* @throws SQLException
* If the DB can't be connected to
*/
protected Connection createConnection() throws SQLException {

return DriverManager.getConnection(CONNECTION_URL, CONNECTION_LOGIN,
CONNECTION_PWD);
}
}

package com.linkwithweb.test.derby.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import com.linkwithweb.test.derby.model.Person;

/**
* DAO for accessing the datas of a person.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class PersonDao extends AbstractDao {

/**
* @throws SQLException
* @see com.linkwithweb.test.derby.dao.IDao#findById(java.lang.Object)
*/
public Person findById(Integer pId) throws SQLException {

Connection lConnection = null;

try {

lConnection = createConnection();

PreparedStatement lStatement = lConnection
.prepareStatement("SELECT * FROM PERSON WHERE ID = ?");

lStatement.setInt(1, pId);

ResultSet lRs = lStatement.executeQuery();

if (lRs.next()) {

Person lPerson = new Person();

lPerson.setId(lRs.getLong("ID"));
lPerson.setName(lRs.getString("NAME"));
lPerson.setFirstName(lRs.getString("FIRST_NAME"));
lPerson.setBirthDate(lRs.getDate("BIRTH_DATE"));

return lPerson;
}

} finally {

if (lConnection == null) {

lConnection.close();
}
}

return null;
}

/**
* @see com.linkwithweb.test.derby.dao.IDao#getAll()
*/
public Collection getAll() {
// TODO Auto-generated method stub
return null;
}

/**
* @see com.linkwithweb.test.derby.dao.IDao#removeById(java.lang.Object)
*/
public void removeById(Integer pId) {
// TODO Auto-generated method stub

}
}

Now as we have all the classes defined now. Let us create a PersonDAOTest which loads data into our person table and Does simple unit test

package com.linkwithweb.test.derby.dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;

import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.operation.DatabaseOperation;

import com.linkwithweb.test.derby.model.Person;

/**
* A test case for {@link PersonDao}.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class PersonDaoTest extends AbstractDaoTest {

/** The DAO to be tested. */
private PersonDao personDao;

/**
* @see org.dbunit.DatabaseTestCase#setUp()
*/
@Override
protected void setUp() throws Exception {

super.setUp();

// Creates the DAO to be tested
personDao = new PersonDao() {

/**
* @see com.linkwithweb.test.derby.dao.AbstractDao#createConnection()
*/
@Override
protected Connection createConnection() throws SQLException {

try {

return getConnection().getConnection();

} catch (Exception e) {

throw new SQLException(e);
}
}
};

InputStream lStream = PersonDaoTest.class.getClassLoader()
.getResourceAsStream("com/ashwin/test/derby/dao/person.xls");

// Creates the initialization data
IDataSet lDataSet = new XlsDataSet(lStream);

DatabaseOperation.CLEAN_INSERT.execute(getConnection(), lDataSet);
}

/**
* Test method for
* {@link com.linkwithweb.test.derby.dao.PersonDao#findById(java.lang.Integer)}.
*
* @throws SQLException
*/
public void testFindById() throws SQLException {

Person lPerson = personDao.findById(1);

assertNotNull(lPerson);
}
}

Below is the project structure which will give you an overview of how it is

C:\software\derby\src>tree /f
C:.
├───main
│ └───java
│ └───com
│ └───linkwithweb
│ └───test
│ └───derby
│ ├───dao
│ │ AbstractDao.java
│ │ IDao.java
│ │ PersonDao.java
│ │
│ └───model
│ Person.java
│
└───test
├───java
│ └───com
│ └───linkwithweb
│ └───test
│ └───derby
│ └───dao
│ AbstractDaoTest.java
│ PersonDaoTest.java
│ TableCreator.java
│
└───resources
└───com
└───linkwithweb
└───test
└───derby
└───dao
person.xls

DerbyHelloWorld
Rename to .rar

SQL Pagination In Java using spring-jdbc

Conventional and Most Proven of Doing Pagination is Adding Limits in SQL Query based on RowNum/Limit / RowOver() functions based on differrent databases.

Pagination is a required feature in any Reporting framework and where we need to make the solution work across variety of datasource , say from age old ingres, Microsoft access to Latest High End Oracle,Sql Server ,Db2

But there is a new way we can do it and it did work well for me without any problems in production enviroments

Here is how i did
I created a class called BatchResultSetExtractor and overriden extractData method


public class BatchResultSetExtractor implements ResultSetExtractor {
private static final transient Log logger = LogFactory
.getLog(BatchResultSetExtractor.class);

public Object extractData(ResultSet rs) throws SQLException {
List results = (this.rowsExpected > 0 ? new ArrayList(this.rowsExpected)
: new ArrayList());
int rowNum = 0;
.......................
while (rs != null && rs.next()) {
if(rowNum offset + batchSize){
continue;
}
Object returnObject = this.rowMapper.mapRow(rs, rowNum++);
// If splitting output is disabled
if (!queryContext.isSpitOutput()) {
continue;
}

if (returnObject != null) {
totalRowsProcessed = totalRowsProcessed + 1;
// Get Batch Update Statement Here and Add Errored Out sql
// to Log
results.add(returnObject);
}

if (results.size() >= batchSize) {
// Perform Operation
results.clear();
}
}// End of result set while loop
} // End of method

}// End of class

Upload File to Server from Java Client without any library

Here is example code which can upload files to any server without using any third party library in java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import com.linkwithweb.callback.ResponseHandler;

/**
* @author kumara
*
*/
public class HttpPost {
URL u;
private static CookieManager cm = new CookieManager();

/**
* @param args
*/
public static void main(String args[]) {
// post();
new HttpPost().sendFile("http://localhost:8080/Server/LoginServlet",
"serverxml/login.xml");
}

/**
*
*/
private void post() {

String s = URLEncoder.encode("A Test string to send to a servlet");

try {
HttpPost post = new HttpPost();
post.u = new URL("http://myhost/servlet");

// Open the connection and prepare to POST
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setAllowUserInteraction(false);

DataOutputStream dstream = new DataOutputStream(
uc.getOutputStream());

// The POST line
dstream.writeBytes(s);
dstream.close();

// Read Response
InputStream in = uc.getInputStream();
int x;
while ((x = in.read()) != -1) {
System.out.write(x);
}
in.close();

BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine()) != null) {
buf.append(line);
}

} catch (IOException e) {
e.printStackTrace(); // should do real exception handling
}
}

/**
* @param url
* Url to send data to
* @param file1
* path to local file to upload
* @return int if 0 then all ok else see value and look in code!
*/
public int sendFile(String surl, String file1) {

int rtn = 1;

HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = file1;
File fFile2Snd = new File(exsistingFileName);

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "***232404jkg4220957934FW**";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1 * 1024 * 1024;

String responseFromServer = "";

String urlString = surl;// "http://localhost:81/FileUpload/requestupload";
// urlString =
// "http://a.com/sel2in/prjs/php/p12/skewmypic/v1/getBytes.php";

try {
// ------------------ CLIENT REQUEST

FileInputStream fileInputStream = new FileInputStream(new File(
exsistingFileName));
rtn++;

// open a URL connection to the Servlet

URL url = new URL(urlString);
rtn++;

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";"
+ " filename=\"" + fFile2Snd.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);

rtn++;

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ex);
}

catch (IOException ioe) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ioe);
}

// ------------------ read the SERVER RESPONSE

try {
System.out.println("Server response is: \n");
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
System.out.println(str);
System.out.println("");
}
inStream.close();
System.out.println("\nEND Server response ");

} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);

}
rtn = 0;
return rtn;

}

/**
* @param fileContent
* content of file
* @param contextParams
* TODO
* @param url
* Url to send data to
* @return int if 0 then all ok else see value and look in code!
*/
public int uploadStringAsFile(String surl, String fileContent,
String requestIdentifier, ResponseHandler responseHandler,
Map contextParams) {
fileContent = fileContent.trim();
int rtn = 1;
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "***232404jkg4220957934FW**";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1 * 1024 * 1024;

String responseFromServer = "";

String urlString = surl;// "http://localhost:81/FileUpload/requestupload";
// urlString =
// "http://a.com/sel2in/prjs/php/p12/skewmypic/v1/getBytes.php";

try {
// ------------------ CLIENT REQUEST

rtn++;

// open a URL connection to the Servlet

URL url = new URL(urlString);
rtn++;

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();
cm.setCookies(conn);

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";"
+ " filename=\"file\"" + lineEnd);
dos.writeBytes(lineEnd);

rtn++;

// create a buffer of maximum size

bytesAvailable = fileContent.getBytes("UTF-8").length;
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

dos.write(fileContent.getBytes("UTF-8"), 0, bufferSize);

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

dos.flush();
dos.close();

} catch (MalformedURLException ex) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ex);
}

catch (IOException ioe) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ioe);
}

// ------------------ read the SERVER RESPONSE

StringBuffer returnString = new StringBuffer();

try {
// System.out.println("Server response is: \n");
cm.storeCookies(conn);

inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
returnString.append(str + "\r\n");
}
inStream.close();
// System.out.println("\nEND Server response ");

} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);

} finally {
if (responseHandler != null) {
responseHandler.hadleResponse(requestIdentifier,
returnString.toString(), contextParams);
}
}
rtn = 0;
return rtn;

}

/**
* @param urlString
*/
public void storeAndGetCookies(String urlString) {
CookieManager cm = new CookieManager();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
cm.storeCookies(conn);
System.out.println(cm);
cm.setCookies(url.openConnection());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

}

Building Tree From SQL Database with Java5 Generics

There are multiple ways of storing Tree structure in database. The most prominent and not so efficient way is

key parentkey
1 0
2 1
3 2
4 3

Lots of people generally have requirement where in they have to build tree given any node in the whole chain. The above tree as you is a multidimentional tree as in there can be 0-n parents and 0-n children for any given node. If we have build it in C or C++ we would have taken an approach of Multi-Linked List.

It Has become much simpler in java with advent of Generic in Java 5. I ‘m going to show you a very generic version of buildign tree which can be used any where

Basic element of any tree is the Node


import java.util.ArrayList;
import java.util.List;

/**
 * Represents a node of the Tree class. The Node is also a container, and
 * can be thought of as instrumentation to determine the location of the type T
 * in the Tree.
 * 
 * @author kumara
 */
public class Node {

	public T data;
	public List<Node> children;
	public List<Node> parents;

	/**
	 * Default ctor.
	 */
	public Node() {
		super();
	}

	/**
	 * Convenience ctor to create a Node with an instance of T.
	 * 
	 * @param data
	 *            an instance of T.
	 */
	public Node(T data) {
		this();
		setData(data);
	}

	/**
	 * Return the children of Node. The Tree is represented by a single
	 * root Node whose children are represented by a List<Node>. Each of
	 * these Node elements in the List can have children. The getChildren()
	 * method will return the children of a Node.
	 * 
	 * @return the children of Node
	 */
	public List<Node> getChildren() {
		if (this.children == null) {
			return new ArrayList<Node>();
		}
		return this.children;
	}

	/**
	 * Sets the children of a Node object. See docs for getChildren() for
	 * more information.
	 * 
	 * @param children
	 *            the List<Node> to set.
	 */
	public void setChildren(List<Node> children) {
		this.children = children;
	}

	/**
	 * Returns the number of immediate children of this Node.
	 * 
	 * @return the number of immediate children.
	 */
	public int getNumberOfChildren() {
		if (children == null) {
			return 0;
		}
		return children.size();
	}

	/**
	 * Adds a child to the list of children for this Node. The addition of
	 * the first child will create a new List<Node>.
	 * 
	 * @param child
	 *            a Node object to set.
	 */
	public void addChild(Node child) {
		if (children == null) {
			children = new ArrayList<Node>();
		}
		children.add(child);
	}

	/**
	 * Inserts a Node at the specified position in the child list. Will *
	 * throw an ArrayIndexOutOfBoundsException if the index does not exist.
	 * 
	 * @param index
	 *            the position to insert at.
	 * @param child
	 *            the Node object to insert.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void insertChildAt(int index, Node child)
			throws IndexOutOfBoundsException {
		if (index == getNumberOfChildren()) {
			// this is really an append
			addChild(child);
			return;
		} else {
			children.get(index); // just to throw the exception, and stop here
			children.add(index, child);
		}
	}

	/**
	 * Remove the Node element at index index of the List<Node>.
	 * 
	 * @param index
	 *            the index of the element to delete.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void removeChildAt(int index) throws IndexOutOfBoundsException {
		children.remove(index);
	}
	
	
	
	/**
	 * Return the parents of Node. The Tree is represented by a single
	 * root Node whose parents are represented by a List<Node>. Each of
	 * these Node elements in the List can have parents. The getparent()
	 * method will return the parents of a Node.
	 * 
	 * @return the children of Node
	 */
	public List<Node> getParents() {
		if (this.parents == null) {
			return new ArrayList<Node>();
		}
		return this.parents;
	}

	/**
	 * Sets the parents of a Node object. See docs for getparent() for
	 * more information.
	 * 
	 * @param parents
	 *            the List<Node> to set.
	 */
	public void setParents(List<Node> parent) {
		this.parents = parent;
	}

	/**
	 * Returns the number of immediate parents of this Node.
	 * 
	 * @return the number of immediate parents.
	 */
	public int getNumberOfParents() {
		if (parents == null) {
			return 0;
		}
		return parents.size();
	}

	/**
	 * Adds a child to the list of children for this Node. The addition of
	 * the first child will create a new List<Node>.
	 * 
	 * @param child
	 *            a Node object to set.
	 */
	public void addParent(Node parent) {
		if (parents == null) {
			parents = new ArrayList<Node>();
		}
		parents.add(parent);
	}

	/**
	 * Inserts a Node at the specified position in the child list. Will *
	 * throw an ArrayIndexOutOfBoundsException if the index does not exist.
	 * 
	 * @param index
	 *            the position to insert at.
	 * @param child
	 *            the Node object to insert.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void insertParentAt(int index, Node parent)
			throws IndexOutOfBoundsException {
		if (index == getNumberOfChildren()) {
			// this is really an append
			addParent(parent);
			return;
		} else {
			parents.get(index); // just to throw the exception, and stop here
			parents.add(index, parent);
		}
	}

	/**
	 * Remove the Node element at index index of the List<Node>.
	 * 
	 * @param index
	 *            the index of the element to delete.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void removeParentAt(int index) throws IndexOutOfBoundsException {
		parents.remove(index);
	}	
	
	
	/**
	 * @return
	 */
	public T getData() {
		return this.data;
	}

	/**
	 * @param data
	 */
	public void setData(T data) {
		this.data = data;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(this.data.toString());
/*		sb.append("{").append(getData().toString()).append(",[");
		int i = 0;
		boolean addComma = false;
		for (Node e : getParents()) {
			if (i > 0) {
				addComma = true;
				sb.append(",");
			}
			sb.append(e.getData().toString());
			i++;
		}
		
		i = 0;
		for (Node e : getChildren()) {
			if (addComma || i > 0) {
				sb.append(",");
			}
			sb.append(e.getData().toString());
			i++;
		}
		
		sb.append("]").append("}");*/
		return sb.toString();
	}
}

And tree is List of Node’s

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Represents a Tree of Objects of generic type T. The Tree is represented as a
 * single rootElement which points to a List<Node> of children. There is no
 * restriction on the number of children that a particular node may have. This
 * Tree provides a method to serialize the Tree into a List by doing a pre-order
 * traversal. It has several methods to allow easy updation of Nodes in the
 * Tree.
 * 
 * @author kumara
 */
public class Tree {

	private Node rootElement;

	/**
	 * Default ctor.
	 */
	public Tree() {
		super();
	}

	/**
	 * Return the root Node of the tree.
	 * 
	 * @return the root element.
	 */
	public Node getRootElement() {
		return this.rootElement;
	}

	/**
	 * Set the root Element for the tree.
	 * 
	 * @param rootElement
	 *            the root element to set.
	 */
	public void setRootElement(Node rootElement) {
		this.rootElement = rootElement;
	}

	/**
	 * Returns the Tree as a List of Node objects. The elements of the
	 * List are generated from a pre-order traversal of the tree.
	 * 
	 * @return a List<Node>.
	 */
	public List<Node> toList() {
		List<Node> list = new ArrayList<Node>();
		walk(rootElement, list);
		return list;
	}

	/**
	 * Returns a String representation of the Tree. The elements are generated
	 * from a pre-order traversal of the Tree.
	 * 
	 * @return the String representation of the Tree.
	 */
	public String toString() {
		return toList().toString();
	}

	/**
	 * Walks the Tree in pre-order style. This is a recursive method, and is
	 * called from the toList() method with the root element as the first
	 * argument. It appends to the second argument, which is passed by reference
	 * * as it recurses down the tree.
	 * 
	 * @param element
	 *            the starting element.
	 * @param list
	 *            the output of the walk.
	 */
	private void walk(Node element, List<Node> list) {
		for (Node data : element.getParents()) {
			walk(data, list);
		}
		list.add(element);
		for (Node data : element.getChildren()) {
			walk(data, list);
		}
	}

	public String toBranch(List branches) {
		return toBranches(branches).toString();
	}

	public List<Node> toBranches(List branches) {
		List<Node> list = new ArrayList<Node>();
		List pathList = new ArrayList();
		branch(rootElement, list,pathList,branches);
		return list;
	}

	private void branch(Node element, List<Node> list,List pathList,List branches) {
		for (Node data : element.getParents()) {
			parentBranch(data, list,pathList);
		}
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);
		
		for (Node data : element.getChildren()) {
			childBranch(data, list,pathList,branches);
			pathList.remove(pathList.size()-1);
		}

		if(element.getChildren().isEmpty()){
			printArray(pathList,branches);
		}
		//System.out.println(path);
	}
	
	
	/**
	 * @param element
	 * @param list
	 * @param pathList
	 */
	private void childBranch(Node element, List<Node> list,List pathList,List branches) {
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);
		for (Node data : element.getChildren()) {
			childBranch(data, list,pathList,branches);
			pathList.remove(pathList.size()-1);
		}
		
		if(element.getChildren().isEmpty()){
			printArray(pathList,branches);
		}
	}
	
	
	/**
	 * @param element
	 * @param list
	 * @param pathList
	 */
	private void parentBranch(Node element, List<Node> list,List pathList) {
		for (Node data : element.getParents()) {
			parentBranch(data, list,pathList);
		}
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);

	}
	
	
	/**
	 * @param array
	 */
	private void printArray(Collection array,List branches){
		StringBuffer sb = new StringBuffer();
		for(String pathElement :array){
			sb.append(pathElement).append(",");
		}
		branches.add(sb.toString());
		//System.out.println(sb.toString());
	}
}

Lets create a Task class for which we will build a tree


import java.io.Serializable;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * @author kumara
 * 
 */
public class GenericTask implements Serializable {
	private Long id = 0L;
	private Long parentId = 0L;
	
	public GenericTask() {
        super();
    }

	public GenericTask(Long taskId) {
		this();
		setId(taskId);
	}

	public GenericTask(Long taskId,Long parentTaskId) {
		this();
		setId(taskId);
		setParentId(parentTaskId);
	}
	
	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the parentId
	 */
	public Long getParentId() {
		return parentId;
	}

	/**
	 * @param parentId
	 *            the parentId to set
	 */
	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		/*return ReflectionToStringBuilder.reflectionToString(this,
				ToStringStyle.DEFAULT_STYLE);*/
		//return "["+id+","+parentId+"]";
		return id+"";
	}
}


Above code is Generic code which can be implemented any where. For example let us assume we have some tasks for which we have to build this tree. We will just implement Tree and Node for that task like this



/**
 * Non-generic subclass of Tree
 * 
 * @author kumara
 */
public class TaskTree extends Tree {
	public TaskTree() {
		super();
	}
}


/**
 * Non-generic subclass of Node
 * 
 * @author kumara
 */
public class TaskNode extends Node {
	public TaskNode() {
		super();
	}
}

Now the task is to load data from Database to javaObjects. We shall use TaskDAO to do that


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.jdbc.support.rowset.SqlRowSet;

/**
 * Dao for the Task POJO.
 * 
 * @author kumara
 */
public class TaskDAO extends AbstractDAO {

	private String childColumnName = "";
	private String parentColumnName = "";
	private String tableName = "";

	private final static Logger log = Logger
			.getLogger(TaskDAO.class.toString());

	public TaskDAO() {
	}

	/**
	 * @return the childColumnName
	 */
	public String getChildColumnName() {
		return childColumnName;
	}

	/**
	 * @param childColumnName
	 *            the childColumnName to set
	 */
	public void setChildColumnName(String childColumnName) {
		this.childColumnName = childColumnName;
	}

	/**
	 * @return the parentColumnName
	 */
	public String getParentColumnName() {
		return parentColumnName;
	}

	/**
	 * @param parentColumnName
	 *            the parentColumnName to set
	 */
	public void setParentColumnName(String parentColumnName) {
		this.parentColumnName = parentColumnName;
	}

	/**
	 * @return the tableName
	 */
	public String getTableName() {
		return tableName;
	}

	/**
	 * @param tableName
	 *            the tableName to set
	 */
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	/**
	 * Remove a Task object from the database.
	 * 
	 * @param task
	 *            the Task to remove.
	 */
	public void remove(GenericTask task) {
	}

	/**
	 * Saves a Task to the database if it is a new one, else updates it.
	 * 
	 * @param task
	 *            the Task to insert or update.
	 * @return the task id.
	 */
	public Long saveOrUpdate(GenericTask task) {
		return 1L;
	}

	/**
	 * Returns the Task pointed to by the task id. Returns a NULL if the Task is
	 * not found in the database.
	 * 
	 * @param taskId
	 *            the task id to look up.
	 * @return the Task object corresponding to the id.
	 */
	public GenericTask get(Long taskId) {
		return new GenericTask(taskId);
	}

	/**
	 * Returns all the children of the Task which has the specified parents id.
	 * 
	 * @param parentId
	 *            the id of the parents Task.
	 * @return a List of Tasks which are children of the Task specified.
	 */
	@SuppressWarnings("unchecked")
	public List findByParentId(Long parentId) {
		if(parentId == null){
			return Collections.EMPTY_LIST;
		}
		
		try {
			getJdbcTemplate().execute(
					"set lockmode session where readlock = nolock");
		} catch (Exception e) {
			
		}
		
		String sql = "SELECT * FROM " + getTableName() + " WHERE "
				+ getParentColumnName() + " = " + parentId;
		SqlRowSet resultSet = (SqlRowSet) getJdbcTemplate().queryForRowSet(sql);

		List returnList = new ArrayList();
		while (resultSet.next()) {
			GenericTask genericTask = new GenericTask(
					resultSet.getLong(getChildColumnName()));
			genericTask.setParentId(resultSet.getLong(getParentColumnName()));
			returnList.add(genericTask);
		}

		return returnList;
	}

	/**
	 * Returns all the Parents of the Task which has the specified child id.
	 * 
	 * @param childId
	 *            the id of the child Task.
	 * @return a List of Tasks which are parent of the Task specified.
	 */
	@SuppressWarnings("unchecked")
	public List findByChildId(Long childId) {
		if(childId == null){
			return Collections.EMPTY_LIST;
		}
		
		try {
			getJdbcTemplate().execute(
					"set lockmode session where readlock = nolock");
		} catch (Exception e) {
			
		}
		
		String sql = "SELECT * FROM " + getTableName() + " WHERE "
				+ getChildColumnName() + " = " + childId;
		SqlRowSet resultSet = (SqlRowSet) getJdbcTemplate().queryForRowSet(sql);

		List returnList = new ArrayList();
		while (resultSet.next()) {
			GenericTask genericTask = new GenericTask(
					resultSet.getLong(getChildColumnName()));
			genericTask.setParentId(resultSet.getLong(getParentColumnName()));
			returnList.add(genericTask);
		}

		return returnList;
	}

}


Now Lets build Tree using TaskTreeDAO


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author kumara
 *
 * Data Access Object for the TaskTree object. This is not a true Dao, since it
 * delegates to the TaskDao object for any database operations.
 */
public class TaskTreeDAO {

	private static final Logger log = Logger.getLogger(TaskTreeDAO.class
			.toString());

	public TaskTreeDAO() {
		super();
	}

	private TaskDAO taskDao;

	public void setTaskDao(TaskDAO taskDao) {
		this.taskDao = taskDao;
	}

	/**
	 * Saves a TaskTree object.
	 * 
	 * @param taskTree
	 *            a TaskTree object.
	 */
	public void saveOrUpdate(TaskTree taskTree) {
		List<Node> tasks = taskTree.toList();
		// save the tree in reverse order, starting from the leaf nodes
		// and going up to the root of the tree.
		int numberOfNodes = tasks.size();
		for (int i = numberOfNodes - 1; i >= 0; i--) {
			Node taskElement = tasks.get(i);
			GenericTask task = taskElement.getData();
			// taskDao.saveOrUpdate(task);
			Long parentId = task.getId();
			for (Iterator<Node> it = taskElement.getChildren()
					.iterator(); it.hasNext();) {
				Node childElement = it.next();
				GenericTask childTask = childElement.getData();
				childTask.setParentId(parentId);
				// taskDao.saveOrUpdate(childTask);
			}
		}
	}

	/**
	 * Gets a single TaskTree by id. This is the head of a recursive method call
	 * to getRecursive().
	 * 
	 * @param id
	 *            the id of the TaskTree.
	 * @return a TaskTree for that id.
	 */
	public TaskTree get(Long id) {
		TaskTree taskTree = new TaskTree();
		Node rootElement = new Node(new GenericTask(id,id));
		getRecursiveChildren(rootElement, taskTree);
		getRecursiveParents(rootElement, taskTree);
		taskTree.setRootElement(rootElement);
		
		return taskTree;
	}

	/**
	 * Recursively descends the Tree and populates the TaskTree object.
	 * 
	 * @param taskElement
	 *            the root Node.
	 * @param tree
	 *            the TaskTree object to populate.
	 */
	private void getRecursiveChildren(Node taskElement, TaskTree tree) {
		List children = taskDao.findByParentId(taskElement
				.getData().getId());
		List<Node> childElements = new ArrayList<Node>();
		for (Iterator it = children.iterator(); it.hasNext();) {
			GenericTask childTask = it.next();
			Node childElement = new Node(childTask);
			childElements.add(childElement);
			childElement.addParent(taskElement);
			getRecursiveChildren(childElement, tree);
		}
		taskElement.setChildren(childElements);
	}

	
	/**
	 * Recursively descends the Tree and populates the TaskTree object.
	 * 
	 * @param taskElement
	 *            the root Node.
	 * @param tree
	 *            the TaskTree object to populate.
	 */
	private void getRecursiveParents(Node taskElement, TaskTree tree) {
		List parents = taskDao.findByChildId(taskElement
				.getData().getParentId());
		List<Node> parentElements = new ArrayList<Node>();
		for (Iterator it = parents.iterator(); it.hasNext();) {
			GenericTask parentTask = it.next();
			Node parentElement = new Node(parentTask);
			parentElements.add(parentElement);
			parentElement.addChild(taskElement);
			getRecursiveParents(parentElement, tree);
		}
		taskElement.setParents(parentElements);
	}	
	
	/**
	 * @param id
	 * @return
	 */
	public TaskTree buildTree(Long id) {
		TaskTree taskTree = new TaskTree();
		Node rootElement = new Node(taskDao.get(id));
		getRecursiveChildren(rootElement, taskTree);
		getRecursiveParents(rootElement, taskTree);
		taskTree.setRootElement(rootElement);
		return taskTree;
	}
}


And some Utility Classes as i use Spring-JDBC here


import org.springframework.jdbc.core.JdbcTemplate;

import endoworks.dwutility.framework.util.ServiceLocator;
import endoworks.dwutility.framework.util.spring.SpringInitilizer;

/**
 * @author kumara
 * 
 */
public class AbstractDAO {
	private static SpringInitilizer springInitilizer = null;

	static {
		springInitilizer = new SpringInitilizer();
	}
	private JdbcTemplate jdbcTemplate;

	/**
	 * @return the jdbcTemplate
	 */
	public JdbcTemplate getJdbcTemplate() {
		if (jdbcTemplate == null) {
			jdbcTemplate = (JdbcTemplate) ServiceLocator
					.getService("jdbcTemplate");
		}
		return jdbcTemplate;
	}
}

A class to load/Initialize spring beans


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Ashwin
 * 
 */
public class SpringInitilizer {

	private static ApplicationContext context = null;

	static {
		context = new ClassPathXmlApplicationContext(
				new String[] { "applicationContext-dbMigrate.xml" });
	}
}

And finally data base table can be of form

create table test (key integer,parentkey integer);

Njoy creating any tree easily