Thursday, July 2, 2009

startsWith and endsWith functions in Javascript

inside script tag,

var data = "Helloo Good Morning";
startsWith
String.prototype.startsWith = function(data)
{
return (this.match("^"+data)==data)
}

eg:
data.startsWith("Helloo");
returns true
-----------------------------------------------------------------------
endsWith
String.prototype.endsWith = function(data)
{
return (this.match(data+"$")==data)
}
eg:
data.endsWith("Helloo");
returns false;

----------------------------------------------------------
trim
String.prototype.trim = function()
{
return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}
eg:
var tm = data.trim();


for more ...
http://www.tek-tips.com

Date showing wrong in JSF outputText or with dataTable

Some times in , h:outputText with dataTable or without , java.util.Date showing wrong, means one date before the actual date is showing.
We can solve this problem using Converter.
One example :

DateConverter.java

package com.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
/**
* This class is is used to convert a date to dd-MMM-yyyy format
* @author jijo
*
*/
public class DateConverter implements Converter {
public String getAsString(FacesContext context, UIComponent c, Object object)
throws ConverterException {
if(object!=null && !object.toString().equals("")){
final Date date = (Date) object;
String dt=null;
if(date!=null){
SimpleDateFormat formatter=new SimpleDateFormat("dd-MMM-yyyy");
dt=formatter.format(date);
return dt;
}}
return null;
}
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
throws ConverterException {
return null;
}
}

In
faces-config.xml
<converter>
<converter-id>dateConvert<converter-id>
<converter-class>com.converter.DateConverter</converter-class>
</converter>



In your jsp page

<h:outputText value="#{item.onDate}" converter="dateConvert" />

Tuesday, June 23, 2009

Stream has already been closed; nested exception is java.sql.SQLException

Stream has already been closed; nested exception is java.sql.SQLException in Oracle.
Java - Oracle connectivity some times this exception will happen.
One of the reason of this exception is , the table contains a long(datatype) field.
eg: 'users' table contains a field 'age' long datatype.
To solve this problem , replace the 'long' field to 'number' datatype.

Tuesday, June 16, 2009

Check and Uncheck checkboxes using javascript

inside script tag

//this will mark all the checkboxes inside a form are checked.

//form1 is the form name
function checkAll() {

for(var i=0;i

if(document.forms['form1'].elements[i].type=='checkbox') {

document.forms['form1'].elements[i].checked=true; } } }
//this will mark all the checkboxes inside a form are unchecked.

//form1 is the form name

function uncheckAll() {

for(var i=0;i

if(document.forms['form1'].elements[i].type=='checkbox') {

document.forms['form1'].elements[i].checked=false; } } }
//form1 is the form name

----------------------------------------------------------------------
//this will mark the specified checkboxes inside a form are checked

//form1 -- formname

//checkboxname-- checkbox name

function selectAllFields()

{

var chk = document.form1.checkboxname;

for (i = 0; i < checked =" true">

var chk = document.form1.checkboxname;

for (i = 0; i

}

Monday, June 15, 2009

Drag and drop using using Javascript

You can drag and drop for an html component using Yahoo Ui -javascript library.
More details check the following link,

http://developer.yahoo.com/yui/dragdrop/

Saturday, June 13, 2009

Deploy axis webservice in Jboss server

Download the axis.war from
http://ws.apache.org/axis/java/install.html
Put the axis.war in jboss\server\default\deploy folder.
Then deploy the webservice in the axis.war and deploy the webservice using the command,
java org.apache.axis.client.AdminClient ..\src\com\jijo\stubs\deploy.wsdd
then copy the server-config.wsdd file from axis.war/WEB-INF folder and put the file in your WEB-INF folder.

In short first deploy in axis.war and copy the server-config.wsdd file and put into your project/WEB-INF folder.

WebService using Apache axis

Download the following jar

axis.jar,axis-ant.jar,commons-discovery-0.2.jar,commons-logging-1.0.4.jar,jaxrpc.jar,
log4j-1.2.8.jar,saaj.jar,wsdl4j-1.5.1.jar.
Create one project eg: CalcTest and set classpath to theses jars.

Download the axis.war file from http://ws.apache.org/axis/java/install.html and put into your tomcat(webapps) or jboss(deploy) folder.

Create one interface

package com.jijo;
/**
* @author jijo
*
*/
public interface Calculator {
public int add(int x,int y);
public int subtract(int x, int y);
}

Create one class and implemet the Calculator interface
package com.jijo;
public class CalculatorImpl implements Calculator {
public int add(int x, int y) {
return x+y;
}
public int subtract(int x, int y) {
return x-y;
}
}
Compile the classes, and in command prompt:
java org.apache.axis.wsdl.Java2WSDL -o calculator.wsdl -n urn:com.jijo.Calculator -l http://localhost:8080/axis/services/calcservice com.jijo.Calculator
[This is for creating the WSDL(Java to WSDL)].

After this a wsdl file is created in you folder.
Then Create the Stubs based on this WSDL(WSDL to Java)
java org.apache.axis.wsdl.WSDL2Java -o ..\src -p com.jijo.stubs -s calculator.wsdl
Then the stubs is created .

Replace the
CalcserviceSoapBindingImpl.java to the following


/** * CalcserviceSoapBindingImpl.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */
package com.jijo.stubs;
import com.jijo.CalculatorImpl;

public class CalcserviceSoapBindingImpl implements com.jijo.stubs.Calculator{ com.jijo.Calculator calculator = new CalculatorImpl(); public int add(int in0, int in1) throws java.rmi.RemoteException { return calculator.add(in0, in1); }
public int subtract(int in0, int in1) throws java.rmi.RemoteException { return calculator.subtract(in0, in1); }
}


create a jar eg: cal.jar based on the classes and put into axis.war/WEB-INF/lib folder
start the tomcat/jboss server.Then
Deploy into axis.war using ,
java org.apache.axis.client.AdminClient ..\src\com\jijo\stubs\deploy.wsdd

One server-config.wsdd file is created in the axis.war folder.
Then restart the server.
Check the wsdl file getting using,in browser
http://localhost:8080/axis/services/calcservice?wsdl

Create a client class

import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import com.jijo.stubs.CalculatorService;
import com.jijo.stubs.CalculatorServiceLocator;

public class CalcClient {
public static void main(String[] args) {
CalculatorService service = new CalculatorServiceLocator();
try {
int result = service.getcalcservice().add(10, 20);
System.out.println("Result :"+result);
result = service.getcalcservice().subtract(10, 20);
System.out.println("Result:"+result);
} catch (RemoteException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}

Wednesday, May 27, 2009

JBoss -- Memory configuration

In the jboss server , if out of memory exception ,then configure the following in
jboss/bin/run.conf file,

if [ "x$JAVA_OPTS" = "x" ]; then
JAVA_OPTS="-Xms512m -Xmx1024m -XX:PermSize=512m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000"
fi

Friday, May 22, 2009

String array to java.util.List

Convert a String array to list,

String array[] = {"jijo","mathew"};
List list = Arrays.asList(array);

Thursday, May 21, 2009

Convert String to Blob and Blob to String

Convert String to Blob

String data = "hello world";
java.sql.Blob blob = org.hibernate.Hibernate.createBlob(data.getBytes());

Convert Blob to String

byte[] bdata = blob.getBytes(1, (int)blob.length());
String data1 = new String(bdata);

Thursday, May 7, 2009

Access JBoss application using IP address

Take the command prompt and change the the control to the joboss/bin directory
then,
run -b yourip

eg:
run -b 192.168.0.109

Then u can access the jboss applications using the ip.
eg: http://192.168.0.109:8080/applicationname

Monday, March 30, 2009

Assign style class using javascript

document.getElementById("change1").className='styleclassname';//style class name
//change1 is the control id name

Numbers only in javascript

function checkIsNaN(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8){
if (unicode<48||unicode>57)
return false //disable key press
}
}

call this method in
onkeypress="return checkIsNaN(event)"

ltrim,rtrim,trim in javascript

//for left trim
function ltrim(str) {
for(var k = 0; k < str.length && checkSpace(str.charAt(k)); k++);
return str.substring(k, str.length);
}
//for right trim
function rtrim(str) {
for(var j=str.length-1; j>=0 && checkSpace(str.charAt(j)) ; j--) ;
return str.substring(0,j+1);
}
//for trim
function trim(str) {
return ltrim(rtrim(str));
}
function checkSpace(ch) {
var spaceChars = " \t\n\r\f";
return (spaceChars.indexOf(ch) != -1);
}

Remove the selected options from an html select tag

//remove a selected item from list
function removeKeyword()
{
var elSel = document.getElementById("words");//words is the html select tag id
var i = 0;
for (i = elSel.length-1; i>-1; i--) {
if (elSel.options[i].selected) { //check the selected options
elSel.remove(i);//remove the selected options
}
}
}

Append a data at the end of html select tag

//append at the end of select

function addKeyword()
{
var k = document.getElementById("word").value;//get the data from a text filed
var elOptNew = document.createElement('option');
elOptNew.text = k ;
elOptNew.value = k ;
var elSel = document.getElementById("words");//words is the html select control id
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew, elSel.selectedIndex); // IE only
}
}

hide and display html controls

document.getElementById('div1').style.display="block";
document.getElementById('div2').style.display="none";
//you can use the following also
//document.getElementById("div1").style.visibility = 'visible';
//document.getElementById("div2").style.visibility = 'hidden';

Tuesday, March 10, 2009

Upload file using java

/**
*
*/
package com.jijo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
* @author jijo mathew
*
*/
public class Util {
public static void main(String args[]) {
try{
String outPath = "C:/images/jijo.jpg";
String inputPath = "C:/jijo.jpg";
File f=new File(inputPath);
InputStream inputStream= new FileInputStream(f);
String uploadPath = "C:/images/123.jpg";
uploadFile(uploadPath,inputStream); // for file upload
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void uploadFile(String filename,InputStream stream)
{
try {
OutputStream bos = new FileOutputStream(filename);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
}catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}catch (Exception ioe) {
ioe.printStackTrace();
}
}

}

Image water marking using java

/**
*
*/
package com.jijo;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

/**
* @author jijo mathew
*
*/
public class Util {

public static void imageWaterMarking(InputStream input,String outPath){

try
{

BufferedImage bufferedImage = ImageIO.read(input);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
Image image= bufferedImage.getScaledInstance(bufferedImage.getWidth(),
bufferedImage.getHeight(),Image.SCALE_DEFAULT);
g2d.drawImage(image, 0, 0, null);

//Create an alpha composite of 50%
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.5f);
g2d.setComposite(alpha);

g2d.setColor(Color.white);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

g2d.setFont(new Font("Arial", Font.BOLD, 30));

String watermark = "Copyright © jijo84.blogspot.com";

FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

g2d.drawString(watermark,
(bufferedImage.getWidth() - (int) rect.getWidth()) / 2,
(bufferedImage.getHeight() - (int) rect.getHeight()) / 2);

//Free graphic resources
g2d.dispose();

//Set the mime type of the image


//Write the image as a jpg
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outPath));


ImageIO.write(bufferedImage, "jpg", out);
out.close();
}
catch (Exception ioe)
{
ioe.printStackTrace();
}


}
public static void main(String args[]) {
try{
String outPath = "C:/images/jijo.jpg";
String inputPath = "C:/jijo.jpg";
File f=new File(inputPath);
InputStream inputStream= new FileInputStream(f);
imageWaterMarking(inputStream,outPath);//for water mark image

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

}

Jijo

http://www.blogger.com/profile/02424428361688712489

Jijo Mathew

http://www.blogger.com/profile/02424428361688712489

Thursday, March 5, 2009

JMS using Apache ActiveMQ

1)First download apache ActiveMQ latest from http://activemq.apache.org/download.html.
then unzip the file and in that bin start the activemq server using /bin/activemq.bat.

2)Compile the following classes ,and in one command prompt execute the Publisher class and in the other command prompt execute Consumer class.(execute the publisher class many times , that message will get in the consumer class console).


The Consumer class is given below:

package jmsclient;
import java.io.IOException;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import dto.MessageVO;

/**
* This class is used to Receive message
* @author jijo mathew
*
*/


public class Consumer implements MessageListener, ExceptionListener {

private boolean running;

private Session session;
private Destination destination;
private MessageProducer replyProducer;
private boolean pauseBeforeShutdown;
private boolean verbose = true;
private int maxiumMessages;
//private String subject = "TOOL.DEFAULT";
private String subject = "TESTMSG"; //TOPIC name -- consumers focus this TOPIC
private boolean topic=true; //true means TOPIC false means QUEUE
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private boolean transacted=false; //transaction enabled or not
private boolean durable=true; //enable persistance
private String clientId="jijomathew"; //this should be unique
private int ackMode = Session.AUTO_ACKNOWLEDGE;
private String consumerName = "jijomathew";
private long sleepTime;
private long receiveTimeOut; // keep messages for this time period
public static void main(String[] args) {
Consumer consumer = new Consumer();
consumer.run();

}
public void run() {
try {
running = true;
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
Connection connection = connectionFactory.createConnection("system","manager");
if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
connection.setClientID(clientId);
}
connection.setExceptionListener(this);
connection.start();
System.out.println("Connected");

session = connection.createSession(transacted, ackMode);
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}

replyProducer = session.createProducer(null);
replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

MessageConsumer consumer = null;
if (durable && topic) {
consumer = session.createDurableSubscriber((Topic)destination, consumerName);
} else {
consumer = session.createConsumer(destination);
}

if (maxiumMessages > 0) {
consumeMessagesAndClose(connection, session, consumer);
} else {
if (receiveTimeOut == 0) {
consumer.setMessageListener(this);
} else {
consumeMessagesAndClose(connection, session, consumer, receiveTimeOut);
}
}

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

public void onMessage(Message message) {
try {

if (message instanceof TextMessage) {
//TextMessage txtMsg = (TextMessage)message;
ObjectMessage objMsg = (ObjectMessage)message;
if (verbose) {
MessageVO messageVO = (MessageVO)objMsg.getObject();
String msg = messageVO.getMessage();
System.out.println(msg);
}
} else {
ObjectMessage objMsg = (ObjectMessage)message;
if (verbose) {
MessageVO messageVO = (MessageVO)objMsg.getObject();
String msg = messageVO.getMessage();
System.out.println("Received: " + msg);
}
}

if (message.getJMSReplyTo() != null) {
replyProducer.send(message.getJMSReplyTo(), session.createTextMessage("Reply: " + message.getJMSMessageID()));
}

if (transacted) {
session.commit();
} else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
message.acknowledge();
}

} catch (JMSException e) {
e.printStackTrace();
} finally {
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
}

public synchronized void onException(JMSException ex) {
System.out.println("JMS Exception occured."+ex);
running = false;
}

synchronized boolean isRunning() {
return running;
}

protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer) throws JMSException, IOException {
for (int i = 0; i < maxiumMessages && isRunning();) {
Message message = consumer.receive(1000);
if (message != null) {
i++;
onMessage(message);
}
}
System.out.println("connection is closing");
consumer.close();
session.close();
connection.close();
}

protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer, long timeout) throws JMSException, IOException {
Message message;
while ((message = consumer.receive(timeout)) != null) {
onMessage(message);
}

System.out.println("connection is closing");
consumer.close();
session.close();
connection.close();
}

public void setAckMode(String ackMode) {
if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
this.ackMode = Session.CLIENT_ACKNOWLEDGE;
}
if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
this.ackMode = Session.AUTO_ACKNOWLEDGE;
}
if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
}
if ("SESSION_TRANSACTED".equals(ackMode)) {
this.ackMode = Session.SESSION_TRANSACTED;
}
}

public void setClientId(String clientID) {
this.clientId = clientID;
}

public void setConsumerName(String consumerName) {
this.consumerName = consumerName;
}

public void setDurable(boolean durable) {
this.durable = durable;
}

public void setMaxiumMessages(int maxiumMessages) {
this.maxiumMessages = maxiumMessages;
}

public void setPauseBeforeShutdown(boolean pauseBeforeShutdown) {
this.pauseBeforeShutdown = pauseBeforeShutdown;
}

public void setPassword(String pwd) {
this.password = pwd;
}

public void setReceiveTimeOut(long receiveTimeOut) {
this.receiveTimeOut = receiveTimeOut;
}

public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}

public void setSubject(String subject) {
this.subject = subject;
}

public void setTopic(boolean topic) {
this.topic = topic;
}

public void setQueue(boolean queue) {
this.topic = !queue;
}

public void setTransacted(boolean transacted) {
this.transacted = transacted;
}

public void setUrl(String url) {
this.url = url;
}

public void setUser(String user) {
this.user = user;
}

public void setVerbose(boolean verbose) {
this.verbose = verbose;
}

}

The Message class is given:
package dto;


import java.io.Serializable;
/**
* @author jijo mathew
*
*/
public class MessageVO implements Serializable{

private static final long serialVersionUID = 1L;
/**
*
*/
private String message="";

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}







The publisher class is given below:
package publisher;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.util.IndentPrinter;

import dto.MessageVO;

/**
* This class is used to send message
* @author jijo mathew
*
*/

public class Publisher {

private Destination destination;
private int messageCount = 10;
private long sleepTime;
private boolean verbose = true;
private int messageSize = 255;
private long timeToLive;
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private String subject = "TESTMSG";
private boolean topic=true;
private boolean transacted;
private boolean persistent=true;
public static void main(String[] args) {
Publisher publisher = new Publisher();
publisher.start();
}
public void start() {
Connection connection = null;

try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection("system","manager");
connection.start();
Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}
MessageProducer producer = session.createProducer(destination);
if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0) {
producer.setTimeToLive(timeToLive);
}
sendMessage(session, producer);
System.out.println("Messages sent.");
ActiveMQConnection c = (ActiveMQConnection)connection;
c.getConnectionStats().dump(new IndentPrinter());

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}

protected void sendMessage(Session session, MessageProducer producer) throws Exception {
for (int i = 0; i < messageCount || messageCount == 0; i++) {
String message = "Message from jijo:"+messageCount;
MessageVO messageVO = new MessageVO();
messageVO.setMessage(message);
ObjectMessage objmessage = session.createObjectMessage(messageVO);
producer.send(objmessage);
if (transacted) {
session.commit();
}

Thread.sleep(sleepTime);

}

}

public void setPersistent(boolean durable) {
this.persistent = durable;
}

public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}

public void setMessageSize(int messageSize) {
this.messageSize = messageSize;
}

public void setPassword(String pwd) {
this.password = pwd;
}

public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}

public void setSubject(String subject) {
this.subject = subject;
}

public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}

public void setTopic(boolean topic) {
this.topic = topic;
}

public void setQueue(boolean queue) {
this.topic = !queue;
}

public void setTransacted(boolean transacted) {
this.transacted = transacted;
}

public void setUrl(String url) {
this.url = url;
}

public void setUser(String user) {
this.user = user;
}

public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
}


The following jar files is needed to build these classes:



activation-1.1.jar
activeio-core-3.1.0.jar
activemq-camel-5.2.0.jar
activemq-console-5.2.0.jar
activemq-core-5.2.0.jar
activemq-jaas-5.2.0.jar
activemq-jmdns_1.0-5.2.0.jar
activemq-optional-5.2.0.jar
activemq-pool-5.2.0.jar
activemq-web-5.2.0.jar
activemq-xmpp-5.2.0.jar
ant-1.6.2.jar
axis.jar
axis-ant.jar
camel-core-1.5.0.jar
camel-jetty-1.5.0.jar
camel-jms-1.5.0.jar
camel-spring-1.5.0.jar
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-dbcp-all-1.3.jar
commons-digester-1.6.jar
commons-discovery-0.4.jar
commons-el-1.0.jar
commons-httpclient-3.0.1.jar
commons-io-1.3.2.jar
commons-lang-2.1.jar
commons-logging-1.1.jar
commons-pool-1.4.jar
crimson.jar
geronimo-j2ee-management_1.0_spec-1.0.jar
geronimo-jms_1.1_spec-1.1.1.jar
geronimo-jta_1.0.1B_spec-1.0.1.jar
jaxb-api-2.0.jar
jaxb-impl-2.0.3.jar
jetty-util-6.1.0.jar
jms.jar
jstl.jar
log4j-1.2.15.jar
quartz-all-1.5.2.jar
spring.jar
spring-aop-2.5.5.jar
spring-beans-2.5.5.jar
spring-context-2.5.5.jar
spring-core-2.5.5.jar
spring-jms-2.5.5.jar
spring-tx-2.5.5.jar
spring-web-2.5.5.jar
spring-webmvc-2.5.5.jar
standard.jar
stax-1.2.0.jar
stax-api-1.0.jar
transaction-api-1.1.jar
xalan.jar
xerces-J_1.4.0.jar
xstream-1.3.jar

You can get the jar from the activemq folder /lib directory.Also download the jms.jar .


For more details try the following links:
http://activemq.apache.org/version-5-getting-started.html
http://activemq.apache.org/web-samples.html
http://activemq.apache.org/version-5-examples.html

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