Friday, May 31, 2013

Validate XML and Write to a File

Use below code snippet to validate XML payload and write payload content to a file in local system.

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;

public class WriteXMLToFile {

    public static void main(String[] args) {

        String localFileName = "<file path and file name to Store XML payload>";
        boolean xmlValidated = false;
        String xmlPayload = "<XML Payload>";

        try {
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xmlPayload.getBytes()));
            xmlValidated = true;
        } catch (Exception ex) {
            System.out.println("Error while validating XML " + ex);
        }
        if (xmlValidated) {
            try {
                FileOutputStream fileOutputStream =  new FileOutputStream(new File(localFileName));
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                bufferedOutputStream.write(xmlPayload.getBytes());
            }
            catch (FileNotFoundException fnfe) {
                System.out.println("Specified file not found " + fnfe);
            } catch (IOException ioe) {
                System.out.println("Error while writing file " + ioe);
            } finally {
                if (bufferedOutputStream != null) {
                    try {
                        bufferedOutputStream.flush();
                        bufferedOutputStream.close();
                    } catch (Exception e) {
   System.out.println("Error while closing stream " + e);
                    }
                }
            }
        } else {
            System.out.println("XML payload is not valid");
        }
    }
}

Posting message to weblogic JMS

Use following code snippet to post message to Weblogic JMS:

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class MsgProducer {
  public MsgProducer() {
    super();
  }

  public static void main(String[] args) {
    MsgProducer msgProducer = new MsgProducer();
    String str = "Testing JMS connectivity. Posting sample JMS message";
    Context ctx;
    ConnectionFactory cf;
    Destination queue;
    Connection conn = null;
    Session session = null;
    MessageProducer msgProd = null;
    TextMessage msg =  null;
       
    try {
      ctx = msgProducer.getInitialContext();
      cf = (ConnectionFactory)ctx.lookup("<Connection Factory JNDI Name>");
      conn = cf.createConnection();
      session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      queue = (Destination)ctx.lookup("<JMS Queue JNDI Name>");
      msgProd = session.createProducer(queue);
      msg = session.createTextMessage(str);
      msgProd.send(msg);

    } catch (NamingException e){
        e.printStackTrace();
    } catch (JMSException e) {
        e.printStackTrace();
    } catch(Exception e){
        e.printStackTrace();
    }
  }
 
  private Context getInitialContext() throws NamingException {
    Hashtable env = new Hashtable();
   
    env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    env.put(Context.PROVIDER_URL, "t3://serverhost:port(8001)");
   
    return new InitialContext(env);
  }
}  

Tuesday, May 14, 2013

Calling remote Shell Script using Java

Using following code snippet, we can execute shell script hosted in remote Unix machine. To compile following program, we need to add Jsch JAR file available from http://www.jcraft.com/jsch/.

Code snippet:
package client;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class execJSch {
    public execJSch() {
        super();
    }

    /**
     * Comments by lkakarla
     * Following code snippet calls shell script resides in remote Unix machine. 
     * Note: For reusability, set host pwd command variables as parameters
     * @param args
     */
    public static void main(String[] args) {
        try {
            JSch jsch = new JSch();
            
            String host = "user@host";
            String pwd  = "password";
            String command = "/usr/bin/lkakarla/TestSH.sh";
            
            String user = host.substring(0, host.indexOf('@'));
            host = host.substring(host.indexOf('@') + 1);
            Session sessionJSH = jsch.getSession(user, host, 22);
            sessionJSH.setPassword(pwd);
            java.util.Hashtable configJSH = new java.util.Hashtable();
            configJSH.put("StrictHostKeyChecking", "no");
            sessionJSH.setConfig(configJSH);
            sessionJSH.connect();

            Channel channel = sessionJSH.openChannel("exec");
            ((ChannelExec)channel).setCommand(command);

            channel.connect();
            channel.disconnect();
            sessionJSH.disconnect();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}