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……

Advertisements

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

}