Friday, February 27, 2009

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching yourdomain.com found

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching yourdomain.com found

try the following code

HttpsURLConnection con = null;
con = (HttpsURLConnection) server.openConnection();
con.setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session) {
return true;
}
});

for more details try the following link

http://jijo84.blogspot.com/2009/02/http-and-https-tunneling-using-java.html


http://jijo84.blogspot.com/2009/02/http-and-https-tunneling-using-java.html

JMS - Apache ActiveMQ

Java Messaging Service(JMS):Apache ActiveMQ is a goood framework for building JMS applications.

Refer the following sites,

http://activemq.apache.org/
http://activemq.apache.org/examples.html
http://activemq.apache.org/web-samples.html

Thursday, February 26, 2009

ServletContext,User Session and request in DWR

ServletContext context = org.directwebremoting.WebContextFactory.etServletContext();
HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
HttpSession session = WebContextFactory.get().getSession();

for more details
http://directwebremoting.org/dwr/server/javaapi

Wednesday, February 25, 2009

HTTP and HTTPS Tunneling using java

/*
* HttpTunnel.java
* @author Jijo Mathew
*/


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Security;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
public class HttpTunnel {

public HttpTunnel() {
}
/**
*
* This method is used for HTTP tunneling
*/
static public Object transaction(Object data, String url) {

URL server = null;
HttpURLConnection con = null;

try {
server = new URL(url);

} catch(MalformedURLException e) {
System.out.println("URL exception: " + e );
return null;
}


// send request
ObjectInputStream response = null;
Object result = null;
try {

con = (HttpURLConnection) server.openConnection();


con.setDoOutput(true);


con.setUseCaches(false);
con.setConnectTimeout(20000);

con.setRequestProperty("Content-Type", "application/octet-stream");

OutputStream out = con.getOutputStream();
ObjectOutputStream request = new ObjectOutputStream(new BufferedOutputStream(con.getOutputStream()));
request.writeObject(data);
request.flush();
request.close();

// get the result input stream
response = new ObjectInputStream(new BufferedInputStream(con.getInputStream()));

// read response back from the server
result = response.readObject();

} catch(IOException ignored) {
ignored.printStackTrace();
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
finally {
try {

con=null;
server=null;

if( response!=null ) {
response.close();
}
} catch(IOException ex) {}
}



return result;
}

/***
* This method is used for HTTPS tunneling
* @param data (Object to send)
* @param url (domain name)
* @param keyPath(SSL key path)
* @return
*/
static public Object transaction(Object data, String url,String keyPath) {
URL server = null;
HttpsURLConnection con = null;
try {
System.setProperty("javax.net.ssl.trustStore", keyPath);
System.setProperty("java.protocol.handler.pkgs","javax.net.ssl");
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());

server = new URL(url);
} catch(MalformedURLException e) {
System.out.println("URL exception: " + e );
return null;
}
// send request
ObjectInputStream response = null;
Object result = null;
try {
con = (HttpsURLConnection) server.openConnection();
con.setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
con.setDoOutput(true);
con.setUseCaches(false);
con.setConnectTimeout(20000);
con.setRequestProperty("Content-Type", "application/octet-stream");
OutputStream out = con.getOutputStream();
ObjectOutputStream request = new ObjectOutputStream(new BufferedOutputStream(con.getOutputStream()));
request.writeObject(data);
request.flush();
request.close();

// get the result input stream
response = new ObjectInputStream(new BufferedInputStream(con.getInputStream()));

// read response back from the server
result = response.readObject();
//System.out.println(result);
} catch(IOException ignored) {
ignored.printStackTrace();
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
finally {
try {

con=null;
server=null;

if( response!=null ) {
response.close();
}
} catch(IOException ex) {}
}


return result;
}

public static void main(String args[]) {
String object = "helooo";
//HTTP tunneling
transaction(object,"http://yourdomain.com");
//HTTPS tunneling
transaction(object,"https://yourdomain.com","C:/Program Files/Java/jdk1.6.0_10/jre/lib/security/cacerts");

}

}

Tuesday, February 10, 2009

Http Tunneling using Java

/**
*
*/
package jijo;

import com.client. HttpTunnel;

/**
* @author jijo
*
*/
public class Tunnel {
public static void main(String args[]){
Object obj = "grgt";
Object result = HttpTunnel.transaction((Object)obj, "http://192.168.0.123/tunnel/myservlet.do");

}

}

package com.client;

/*
* File: HttpTunnel.java
*/


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

public class HttpTunnel {
static public Object transaction(Object data, String url) {
URL server = null;
URLConnection con=null;
HttpURLConnection con1=null;
try {
server = new URL(url);
} catch(MalformedURLException e) {
System.out.println("URL exception: " + e );
return null;
}

// send request
ObjectInputStream response = null;
Object result = null;
try {

con1 = (HttpURLConnection) server.openConnection();
con1.setDoOutput(true);

con1.setUseCaches(false);
con1.setRequestMethod("POST");
con1.setRequestProperty("Content-Type", "application/octet-stream");
ObjectOutputStream request =
new ObjectOutputStream(
new BufferedOutputStream(con1.getOutputStream()));
request.writeObject(data);
request.flush();
request.close();

// get the result input stream
response = new ObjectInputStream(new BufferedInputStream(con1.getInputStream()));

// read response back from the server
result = response.readObject();

} catch(IOException ignored) {
ignored.printStackTrace();
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
finally {
try {

con1=null;
server=null;

if( response!=null ) {
response.close();
}
} catch(IOException ex) {}
}

return result;
}
}

/************************************/

/**
*
*/
package jijo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author jijo
*
*/
public class MyServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

public void init (ServletConfig c) throws ServletException {
super.init (c);
}

public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException{
try{
ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(request.getInputStream()));
Object o = null;
o = inputStream.readObject();
if( o!=null && (o instanceof Object) ) {
System.out.println("Object : "+o);
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream (response.getOutputStream ()));
response.setStatus(HttpServletResponse.SC_OK);
oos.writeObject ("OK");
oos.flush ();
oos.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/****************************************/

in the web.xml
MyServlet
jijo.MyServlet

MyServlet
/myservlet.do

Condition Checking h:outputText in JSF

<h:outputText value="#{beanname.beanvalue?'checked' : 'not checked'}"/>

Object encryption and decryption using AES algoritham

package jijo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;

import org.apache.log4j.Logger;


public class Encrypter {
static Cipher ecipher = null;
static Cipher dcipher = null;
// private static final byte[] SHARED_KEY = hexstringToByteArray("BAC464B197083EE626273DC4C9EBD8AE82E0897E3D8388EE06CB3EF7BCFFF458");
private static Logger logger = Logger.getLogger(Encrypter.class);
public Encrypter(String path) {
try {
Key key = getSecretKeyFromFile(path);
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");

/*byte[] iv = new byte[16];
System.arraycopy(SHARED_KEY, 0, iv, 0, 16);
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

//String myAES = getSecretKey().toString();
//System.out.println("hello key is"+myAES.toString());

ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);*/

ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);

} catch (javax.crypto.NoSuchPaddingException e) {
e.printStackTrace();

} catch (java.security.NoSuchAlgorithmException e) {
e.printStackTrace();

} catch (java.security.InvalidKeyException e) {
e.printStackTrace();

} catch (Exception e) {
e.printStackTrace();

}
}
/**
encrypt object
*/

public Object encrypt(EncVO encVO) {
SealedObject so = null;
try {
so = new SealedObject(encVO, ecipher);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();

} catch (java.io.IOException e) {
e.printStackTrace();

}
return so;
}
public static void generateKeyFile() {
KeyGenerator kg = null;
ObjectOutputStream out = null;

try {
kg = KeyGenerator.getInstance("AES");
kg.init(128);
// 128 is the keysize. Fixed for AES

// BASE64Decoder bd = new sun.misc.BASE64Decoder();
// SecretKeyFactory desFactory = SecretKeyFactory.getInstance("AES");
// DESKeySpec keyspec = new DESKeySpec(bd.decodeBuffer("JIJO"));
// Key key = new SecretKeySpec(SHARED_KEY, "AES");

// SecretKey key1 = desFactory.generateSecret(keyspec);


SecretKey key = kg.generateKey();
out = new ObjectOutputStream(new FileOutputStream("C:/key/aes.key")); //Storage of AES Key to File
// out.writeObject(key);
out.writeObject(key);
out.close();
} catch (IOException e) {
e.printStackTrace();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();

}
}
private static Key getSecretKeyFromFile(String keyFile) throws Exception
{
ObjectInputStream in = null;
Key key = null;
try{
if(keyFile != null){
in = new ObjectInputStream(new FileInputStream(keyFile));
key = (Key) in.readObject();
in.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
return key;
}

/**
decrypt object
*/

public EncVO decrypt(Object obj) {
EncVO encVO = null;
try {
SealedObject sealedObject = (SealedObject)obj;
encVO = (EncVO)sealedObject.getObject(dcipher);

} catch (javax.crypto.BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return encVO;
}
public static void main(String args[]){
try {
EncVO encVO = new EncVO();
encVO.setStr("jijo");
generateKeyFile(); //generate key file
Encrypter encrypter = new Encrypter("C:/key/aes.key");
Object obj = encrypter.encrypt(encVO); //encrypt
EncVO encVO2 = encrypter.decrypt(obj); //decrypt
System.out.println(encVO2.getStr());
}
catch (Exception e) {
e.printStackTrace();
}
}


}
/*****************************/
/**
*
*/
package jijo;

import java.io.Serializable;

/**
* @author jijo
*
*/
public class EncVO implements Serializable {
private String str;

public String getStr() {
return str;
}

public void setStr(String str) {
this.str = str;
}

}

Start Quartz scheduler manually

package jobs;
import java.sql.SQLException;
import java.text.ParseException;

import org.apache.log4j.Logger;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import com.util.FacesUtils;

/**
*
*/

/**
* @author jijo
*
*/
public class JobScheduler {
/**
* Author Jijo Mathew
* This method is used to start the scheduler.
* @return
* @throws Exception
*/
private static Logger logger = Logger.getLogger(JobScheduler.class);
private String expression = null; //put your expreession
private String cronExpressionSummary = null; //
public void setSchedulerStart() throws SchedulerException, SQLException{

StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = (Scheduler) schedulerFactory.getScheduler();
JobDetail jobDetail = null;
CronTrigger cronTrigger = null;
String expression = null;

jobDetail = new JobDetail("clientJob", "clientJobGroup", Job1.class);
String triggerName = "cronTrigger";
setScheduler(triggerName,expression,jobDetail);



jobDetail =new JobDetail("clientJob1", "clientJobGroup", Job2.class);
triggerName = "cronTrigger1";
setScheduler(triggerName,expression,jobDetail);

//}
scheduler.getContext().put("servletContext", FacesUtils.getServletContext());

// start the scheduler
scheduler.start();
FacesUtils.getServletContext().setAttribute("schedulerFlag", true);

}
/**
* Author Jijo Mathew
* This method will schedule the jobs to the scheduler.
* @return
* @throws Exception
*/
private void setScheduler(String triggerName,String expression,JobDetail jobDetail) throws SchedulerException{
StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();
CronTrigger cronTrigger = new CronTrigger(triggerName, "triggerGroup");
CronExpression cexp = null;
try {
cexp = new CronExpression(expression);
} catch (ParseException e) {
//e.printStackTrace();
logger.error("SchedulerBean:setScheduler():"+e);
}
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);

}
/**
* Author Jijo Mathew
* This method is used to unschedule the jobs from the scheduler.
* @return
* @throws Exception
*/
public void setJobUnschedule(int schId) throws SchedulerException{

if(schId != 0){

String triggerName = null;
if(schId == 1){
triggerName = "cronTrigger";
}
if(schId == 2){
triggerName = "cronTrigger1";
}
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();

String[] triggerGroups;
String[] triggers;

triggerGroups = scheduler.getTriggerGroupNames();
for (int i = 0; i < triggerGroups.length; i++) { triggers = scheduler.getTriggerNames(triggerGroups[i]); for (int j = 0; j < triggers.length; j++) { Trigger tg = scheduler.getTrigger(triggers[j], triggerGroups[i]); if (tg instanceof CronTrigger && tg.getName().equals(triggerName)) { // unschedule the job scheduler.unscheduleJob(triggers[j], triggerGroups[i]); } } } } } /** * Author Jijo Mathew * This method is used to set the jobs to the scheduler. * @return * @throws ParseException * @throws Exception */ public void setJobSchedule(int schId) throws SchedulerException, SQLException, ParseException{ JobDetail jobDetail = null; CronTrigger cronTrigger = null; String expression = null; String triggerName = null; if(CronExpression.isValidExpression(expression)){ /* if(CronExpression.isValidExpression(expression)){ CronExpression cronExpression = new CronExpression(expression); System.out.println(cronExpression.getExpressionSummary()); System.out.println("valid"); } else{ System.out.println("invalid"); } */ if(schId == 1){ triggerName = "cronTrigger"; //jobDetail =new JobDetail("clientJob", "clientJobGroup", ClientJob.class); cronTrigger = new CronTrigger("cronTrigger", "triggerGroup"); cronTrigger.setJobGroup("clientJobGroup"); cronTrigger.setJobName("clientJob"); expression = ""; //ur expression } if(schId == 2){ triggerName = "cronTrigger1"; //jobDetail =new JobDetail("clientJob1", "clientJobGroup", ClientJob1.class); cronTrigger = new CronTrigger("cronTrigger1", "triggerGroup"); cronTrigger.setJobGroup("clientJobGroup"); cronTrigger.setJobName("clientJob1"); expression = "";////ur expression } // Initiate a Schedule Factory StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); // schedulerFactory.initialize(""); // SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); // factoryBean.setApplicationContext((ApplicationContext)FacesUtils.getServletContext()); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler(); String[] triggerGroups; String[] triggers; triggerGroups = scheduler.getTriggerGroupNames(); // Retrieve a scheduler from schedule factory CronExpression cexp = new CronExpression(expression); try { // setup CronExpression // Assign the CronExpression to CronTrigger cronTrigger.setCronExpression(cexp); } catch (Exception e) { //e.printStackTrace(); logger.error("SchedulerBean:setJobSchedule():"+e); } // schedule a job with JobDetail and Trigger for (int i = 0; i < triggerGroups.length; i++) { triggers = scheduler.getTriggerNames(triggerGroups[i]); for (int j = 0; j < triggers.length; j++) { Trigger tg = scheduler.getTrigger(triggers[j], triggerGroups[i]); if (tg instanceof CronTrigger && tg.getName().equals(triggerName)) { // unschedule the job scheduler.rescheduleJob(triggers[j], triggerGroups[i],cronTrigger); } } } this.cronExpressionSummary = cexp.getExpressionSummary(); } } } ////////////////Job1 and Job2..... package jobs; import javax.servlet.ServletContext; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class Job1 implements Job { public void execute(JobExecutionContext ctx)throws JobExecutionException { try{ ServletContext servletContext = (ServletContext) ctx.getScheduler().getContext().get("servletContext"); //TODO } catch (Exception e) { e.printStackTrace(); } } } package jobs; import javax.servlet.ServletContext; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class Job2 implements Job { public void execute(JobExecutionContext ctx)throws JobExecutionException { try{ ServletContext servletContext = (ServletContext) ctx.getScheduler().getContext().get("servletContext"); //TODO } catch (Exception e) { e.printStackTrace(); } } }
also put in the web.xml


<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>start-scheduler-on-load</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


For more details visit
http://www.opensymphony.com/quartz/wikidocs/Tutorial.html

Disable all links using javascript

function DisableEnableLinks(xHow){
objLinks = document.links;
for(i=0;i

objLinks[i].disabled = xHow;
//link with onclick
if(objLinks[i].onclick and xHow){ //replace the and by
&&
objLinks[i].onclick = new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
}
//link without onclick
else if(xHow){
objLinks[i].onclick = function(){return false;}
}
//remove return false with link without onclick
else if(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){
objLinks[i].onclick = null;
}
//remove return false link with onclick
else if(!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1){
strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;","");
objLinks[i].onclick = new Function(strClick);
}


}
}

Hide javascript error using javascript

Inside script tag ,

function handleError()
{
return true;
}
window.onerror = handleError;

Monday, February 9, 2009

Compress and decompreess String object

/**
* This method is used to compress string to byte array
* @author jijo
* @param str
* @return
*/
private static Logger logger = Logger.getLogger(StringUtils.class);
public static byte[] compressString(String str){
byte[] compressedData = null;
if(str != null) {
byte[] input = str.getBytes();

// Create the compressor with highest level of compression
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);

// Give the compressor the data to compress
compressor.setInput(input);
compressor.finish();

// Create an expandable byte array to hold the compressed data.
// You cannot use an array that's the same size as the orginal because
// there is no guarantee that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);

// Compress the data
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}

// Get the compressed data
compressedData = bos.toByteArray();
}
return compressedData;
}
/**
* This method is used to decompress byte array to normal byte array
* @author jijo
* @param str
* @return
*/
public static byte[] decompressByte(byte compressedData[]){
// Create the decompressor and give it the data to compress
byte[] decompressedData = null;
if(compressedData != null && compressedData.length > 0){
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);

// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
try {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
} catch (DataFormatException e) {
e.printStackTrace();
}
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}

// Get the decompressed data
decompressedData = bos.toByteArray();
}
return decompressedData ;
}

/**
* This method is used to convert byte array to string
* @author jijo
* @param str
* @return
*/

public static String byteArrayToString(byte[] decompress){
String str = null;
try{
str = new String(decompress);
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}

Convert XML to String

/**
* This method is used to convert XML file To String using DOMParser
* @author jijo
* @param xMLFile
* @return
*/
public static String convertXMLToString(String xMLFile){
String xmlString = null;
DOMParser parser = new DOMParser();
try{
parser.parse(xMLFile);
Document doc = parser.getDocument();
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
xmlString = writer.toString();
}
catch (Exception e) {
logger.info("StringUtils:convertXMLToString:Filename : "+xMLFile);
logger.error("StringUtils:convertXMLToString:"+e);
}
return xmlString;
}





/**
* This method is used to convert XML file To String using Document
* @author jijo
* @param xMLFile
* @return
*/

public static String xmlToString(String path) throws ParserConfigurationException, SAXException
{
String s = null;
try
{
//String xmlFile = "F://xml//ThuJan2915_10_572009.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(path));
Element root = doc.getDocumentElement();
s = root.toString();
//System.out.println(s);
}
catch(IOException e)
{ e.printStackTrace();
}

return s;
}

Sunday, February 8, 2009

Drop Data Base from oracle and mysql

DROP USER databasename cascade; //Oracle

drop database databasename; //mysql


Saturday, February 7, 2009

DWR - Direct Web Remoting( Ajax)

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.
Look the following url :

http://directwebremoting.org/

examples:
http://directwebremoting.org/dwr/examples

Display tag for pagination in jsp

You can use display tag for pagination in JSP.
The following url gives lot of examples.

http://displaytag.homeip.net/displaytag-examples-1.1/

Convert a serializable object to byte array and vise versa

Convert a serializable object to byte array and vise versa using apache.commons.codec

/**
*
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.BinaryCodec;

/**
* @author jijo
*This class is used to convert object to byte array and wise verse
*/
public class ObjectByteArray {
/**
* This method is used to convert object to Byte array
* @param object
* @return
* @throws IOException
* @throws EncoderException
*/
public static byte[] getBytes(Serializable object) throws IOException, EncoderException {
byte[] data = null ;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytes);
oos.writeObject(object);
oos.flush();
oos.close();
data = bytes.toByteArray();
BinaryCodec binaryCodec = new BinaryCodec();
byte[] byteArr = binaryCodec.encode(data);
return byteArr;
}
/**
* This method is used to convert byte array to object
* @param bytes
* @return
* @throws Exception
*/
public static Object restoreBytes(byte[] bytes) throws Exception {
byte[] data = null;
BinaryCodec binaryCodec =new BinaryCodec();
data = binaryCodec.decode(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
Object object = ois.readObject();
ois.close();
return object;
}
}

Connection Pooling and Transaction implementation using apache commons and JTA

The following is code for creating connection pool using apache commons-dbcp and transaction using java transaction api.
Download commons-dbcp-all-1.3.jar



import java.sql.Connection;
import java.sql.PreparedStatement;


import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.commons.dbcp.managed.BasicManagedDataSource;



public class Main {

public void saveData() throws Exception{
DataSource dataSource = (DataSource)getDataSource();
XADataSource xaDS=(XADataSource) dataSource ;
XAConnection xaCon = (XAConnection) dataSource.getConnection();
XAResource xaRes = xaCon.getXAResource();
Connection connection = xaCon.getConnection();
Xid xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});
String sql ="";//insertion query
int ret;
xaRes.start(xid, XAResource.TMNOFLAGS);
connection.setAutoCommit(false);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
connection.commit();
connection.setAutoCommit(true);
xaRes.end(xid, XAResource.TMSUCCESS);
ret = xaRes.prepare(xid);
if (ret == XAResource.XA_OK) {
xaRes.commit(xid, false);
}
else {
xaRes.rollback(xid);
connection.rollback();
}
}
public BasicManagedDataSource getDataSource(){
BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource();
basicManagedDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicManagedDataSource.setDefaultAutoCommit(false);
basicManagedDataSource.setMaxActive(20);
basicManagedDataSource.setUrl("jdbc:mysql://localhost:3306/pralink");
basicManagedDataSource.setUsername("root");
basicManagedDataSource.setPassword("mysql");
basicManagedDataSource.setMaxIdle(10);
basicManagedDataSource.setXADataSource("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");//oracle.jdbc.xa.client.OracleXADataSource ---- for oracle
return basicManagedDataSource;

}
}


/**
*
*/

import javax.transaction.xa.Xid;

/**
* @author jijo
*
*/

public class MyXid implements Xid
{
protected int formatId;
protected byte gtrid[];
protected byte bqual[];

public MyXid()
{
}

public MyXid(int formatId, byte gtrid[], byte bqual[])
{
this.formatId = formatId;
this.gtrid = gtrid;
this.bqual = bqual;
}


public int getFormatId()
{
return formatId;
}

public byte[] getBranchQualifier()
{
return bqual;
}

public byte[] getGlobalTransactionId()
{
return gtrid;
}
}

Connection pool using apache commons-dbcp

You can create java connection pooling using commons-dbcp-all-1.3.jar or commons-dbcp.jar
The Code is given,

BasicDataSource basicDataSource = new BasicDataSource();
//oracle.jdbc.driver.OracleDriver -- for oracle
//com.mysql.jdbc.Driver -- for mysql
basicDataSource.setDriverClassName(properties.getProperty(driverclassname);//
basicDataSource.setDefaultAutoCommit(false);
basicDataSource.setMaxActive(5);
basicDataSource.setUrl(properties.getProperty(serverurl);
basicDataSource.setUsername(properties.getProperty("username));
basicDataSource.setPassword(properties.getProperty("password));
basicDataSource.setMaxIdle(2);
//basicDataSource.setMaxWait(1000);
basicDataSource.setRemoveAbandoned(true);
basicDataSource.setRemoveAbandonedTimeout(3);

Get All table names from a mysql and oracle schemas using java

ResultSet resultSet = null;
ResultSetMetaData resultSetMetaData = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String sql = "";
Statement statement = null;
String oracleSql = "select object_name from user_objects where object_type = 'TABLE'";

try{

//for mysql
if(properties.getProperty("jdbc.identfier").toString().equalsIgnoreCase("MYSQL")){
DatabaseMetaData dbm = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbm.getTables(null,null,"%",types);
while (rs.next()){
String table = rs.getString(3) ;//table name
sql = "SELECT * FROM `"+table+"` limit 1 " ;
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
for(int i=1 ; i<=metaData.getColumnCount();i++){
System.out.println(metaData.getColumnName(i));//column name
System.out.println((metaData.getColumnTypeName(i)); //column type
System.out.println((metaData.getColumnDisplaySize(i)); //size

}

}
}
//for oracle
else {
preparedStatement = connection.prepareStatement(oracleSql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()){
String table = rs.getString(1) ;
tableVO.setTableName(table);
sql = "SELECT * FROM "+table+" where rownum<=1 " ;
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
for(int i=1 ; i<=metaData.getColumnCount();i++){
System.out.println(metaData.getColumnName(i));//column name
System.out.println((metaData.getColumnTypeName(i)); //column type
System.out.println((metaData.getColumnDisplaySize(i)); //size

}


}
}

}
catch (Exception e) {
logger.error("error:"+e);
}
finally{ //close all objects
closeAll(resultSetMetaData,resultSet,statement,preparedStatement,connection);
}

Get All Tables in a Oracle and MySql Schema

Oracle
In Oracle you can use the following query
select object_name from user_objects where object_type = 'TABLE';

MYSQL
In MySql you can use the follwing query
show tables;

Get All Schema in Oracle and MySql

ORACLE
We can get all oracle schemas using the following query
SELECT username FROM all_users;
or
SELECT * all_users;


MYSQL
We can get all mysql schemas using the following query
SELECT SCHEMA_NAME FROM information_schema.SCHEMATA;
or
SELECT * information_schema.SCHEMATA;
or
show databases