Thursday, February 19, 2009

HTTP Post Request and XML Parsing


Below is a sample code which demonstrate sending HTTP POSt request using java
It also assumes that , if you are getting the putput in XML format, the parseMe() will help you to parse the XML file correctly.



import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;

public class HTTPPostTest{

public static void main(String args[]){
try {
// Construct data
String data = URLEncoder.encode("<Key1>", "UTF-8") + "=" + URLEncoder.encode("
<Value1>", "UTF-8");
data += "&" + URLEncoder.encode("
<Key2>", "UTF-8") + "=" + URLEncoder.encode("<Value2>", "UTF-8");

// Send data
URL url = new URL("
<URL>");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String finalLine="";
while ((line = rd.readLine()) != null) {
// Print the output text as it is
System.out.println(line);
finalLine += line;
}
wr.close();
rd.close();

parseME(finalLine); //calling the function to parse the XML file

} catch (Exception e) {
}

}

/*
*Suppose the XML structure is like this
//
// <xml>
//<person>
//<name>TEST</name>
//
<age> 23</age>
//
<ph>23456</ph>
//
<ph> 6789</ph>
//
</person>
//
</xml>


This code will parse multiple entires with the same tag like 'ph'


*/

public static void parseME(String xmlRecords) {


try {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));

Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("person");
NodeList name = null;
// iterate the entries
for (int i = 0; i <>
Node node = nodes.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;

NodeList nameNode = element.getElementsByTagName("name");
for(int iIndex=0; iIndex<>
{
if (nameNode.item(iIndex).getNodeType() ==Node.ELEMENT_NODE)
{
Element nameElement = (Element) nameNode.item(iIndex);
System.out.println("Name = " +nameElement.getFirstChild().getNodeValue().trim());
}
}
nameNode = element.getElementsByTagName("ph");
for(int iIndex=0; iIndex<>
{
if (nameNode.item(iIndex).getNodeType() ==Node.ELEMENT_NODE)
{
Element nameElement = (Element) nameNode.item(iIndex);
System.out.println("Date = " +nameElement.getFirstChild().getNodeValue().trim());
}
}

}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}

}

Tuesday, February 10, 2009

Elijah went up by a whirlwind into heaven.

As told in TPM CHURCH, ROYAPETTA 08-FEB-2009 SUNDAY SERVICE

2 Kings 2: 11 "And it came to pass, as they still went on, and talked, that, behold, there appeared a chariot of fire, and horses of fire, and parted them both asunder; and Elijah went up by a whirlwind into heaven."

Before Elijah had been taken to heaven he had to go/visit four places; according to the scriptures. These four places reveals the four important phases in our spiritual lives that we have to undergo before we caught up in the soon coming of Jesus Christ.
2 Kings 2:1 "And it came about when the LORD was about to take up Elijah by a whirlwind to heaven, that Elijah went with Elisha from Gilgal". Gilgal is the place where God removed reproaches of Egypt from the people of Israel. This shows our repentance. The Lord Jesus had shown his unconditional love towards us and saved us from the dung of sin.
2 Kings 2:2 "“Stay here please, for the LORD has sent me as far as Bethel."
Meaning of the word Bethel is the House of God. The next thing we have to do is to come to the House of God. What does it shows? It shows our savings in the Christ Jesus.All the love of the world is based on some 'give and take' condition. But the love Jesus showed up on to us is unconditional.
Here the place Bethel shows our savings in the name of Jesus Christ and accepting him us the LORD. Bethel also shows anointing up on a child of GOD.
2 Kings 2:4 Elijah said to him, “Elisha, please stay here, for the LORD has sent me to Jericho". At the time of the ministry of JESUS, while he was crossing through Jericho, there was a man who was blind itself from the womb of his mother. On hearing that JESUS is passing thru the street, he cried aloud and said "O, SON OF DAVID ! HAVE MERCY ON ME". He is a blind man, he had never seen JESUS, HE never seen the miracles did by JESUS, but how he came to know that JESUS is the son of DAVID and only he can help him from his blindness. He had a very sharp ear and he heard from others about the miracle work done by jesus.
In our life we should always have a very eager to know who JESUS and and let him be MERCY ON YOU
2 Kings 2:6 Then Elijah said to him, “Please stay here, for the LORD has sent me to the Jordan”. Jordan is a river which is always be violent throughout the year.In our life also there are situations where we will face problems like Jordan. But he still on LORD and know that he is able to work for you and deliver you from all your trouble. For that what you have to do? You should be still and silent. Let allow the LORD to work / fight for you.
After crossing the JORDAN only , the ELIAJ was caught up in the whirlwind.

Dear child of GOD, these four places shows the four path a child of GOD have to travel in his life. After successfully passing thru all these ways only you can caught up with JESUS.
Let the GOD help us in our ways.
PRAISE THE LORD.

Tuesday, January 6, 2009

Convert a jpg image to base64 encoding

Below is a snippet of code in java for converting a jpg image to base64.

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.imageio.ImageIO;


public class ImageEncode {

/**
* @param args
*/
public static String image;

public static void main(String[] args) {
try {
File f = new File("c:\\temp\\index.jpg");
BufferedImage _image = ImageIO.read(f);

if (_image != null) {
try {
java.io.ByteArrayOutputStream os= new java.io.ByteArrayOutputStream();
ImageIO.write(_image, "jpg", os);
byte[] data= os.toByteArray();
image = new sun.misc.BASE64Encoder().encode(data);

//write to file the encoded character
FileOutputStream fout=null;
OutputStreamWriter out = null;
OutputStream bout = null;
fout = new FileOutputStream ("c:\\temp\\encodedImage.txt");
bout= new BufferedOutputStream(fout);
out = new OutputStreamWriter(bout, "utf-8");
out.write(image);
out.close();

} catch (java.lang.Exception ex2) {
System.out.println("Exception: " + ex2);
ex2.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



}

Converting a base64 encoded image back to jpg file

Below is a small snippet of java code for converting a base64 encoded image back to jpg format. For the smooth running of the program I assume that the base64 encoded image is stored in a .txt file and the program will read the file and create jpg image from it.

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;


public class ImageDecode {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {

StringBuffer Line= new StringBuffer();

FileInputStream fstream = new FileInputStream("c:\\temp\\test2.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Line.append(strLine);
}
//Close the input stream
in.close();


String base64 = Line.toString();
System.out.println(base64);
byte decoded[] = new sun.misc.BASE64Decoder().decodeBuffer(base64);
FileOutputStream fos = null;
fos = new FileOutputStream("c:\\temp\\test212.jpg");
fos.write(decoded);
fos.close();

} catch (java.lang.Exception ex2) {
System.out.println("Exception: " + ex2);
ex2.printStackTrace();
}

}

}

Note: create the respective folders before you test the program

Good Blog

Visit a good Blog

Handling unicode characters while opening a csv file in MS Excel

Eventhough if we write the unicode characters using utf-8 in csv file , the unicode characters will write properly in .csv file and it will display properly when we open the file using notepad.

The problem will occur when we open the .csv file using Excel. The problem is unicode characters will not appear properly and the values will get strangled when openeing in Excel.The reason is excel will support only unicode charactesr using UNICODE endocing and not using UTF-8. For doing this please follow the below given steps.

This will help when writing Chinese , Japanese characters in csv file and opening it using Excel.

First when writing entries to the file, use TAB '\t' to separate entities instead of the default COMMA ',' separation.
The file encodng should be UNICODE instead of UTF-8

Sample code snippets in Java. (The same concept can be used for other programming languages also)

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:\\temp" +"\\"+"test.csv"), "UNICODE"));
;
;
//writing the values to csv file
strTextToWrite = "value1" + "\t";
for (int j=0;j<10;> j++)
{
strTextToWrite += "value"+j +"\t";
}
;
;
out.write(strTextToWrite + "\n");
;
;
out.close();

Tuesday, June 17, 2008

After a long time , i am blogging.