Thursday, January 27, 2011

Java And Tibco Practical Example

Tibco Standard Class example

package com.tibco;
/*
 * Copyright 2001-2006 TIBCO Software Inc.
 * All rights reserved.
 * For more information, please contact:
 * TIBCO Software Inc., Palo Alto, California, USA
 *
 * $Id: tibjmsQueueRequestor.java 21731 2006-05-01 21:41:34Z $
 *
 */

/*
 * This is a simple sample of basic QueueRequestor.
 *
 * This sample publishes specified message(s) on a specified
 * queue and quits.
 *
 * Notice that specified queue should exist in your configuration
 * or your queues configuration file should allow
 * creation of the specified queue.
 *
 * This sample can send into dynamic queues thus it is
 * using the QueueSession.createQueue() method
 * to obtain the Queue object.
 *
 * Usage:  java tibjmsQueueRequestor  [options]
 *                                  <message-text1>
 *                                  ...
 *                                  <message-textN>
 *
 *
 *    where options are:
 *
 *      -server     Server URL.
 *                  If not specified this sample assumes a
 *                  serverUrl of "tcp://localhost:7222"
 *
 *      -user       User name. Default is null.
 *      -password   User password. Default is null.
 *      -queue      Queue name. Default is "queue.sample"
 *
 *
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.codec.DecoderException;


public class TibjmsQueueCompositeForMDN
{
    /*
    String      serverUrl       = null;
    String      userName        = null;
    String      password        = null;

    String      queueName       = "queue.sample";

    Vector      data            = new Vector();
    Calendar calendar = Calendar.getInstance();
    Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance()
            .getTime().getTime());

    String TimeStamp = currentTimestamp.toString();
   
   
   

   
    static public String getContents(String args) {
        StringBuilder contents = new StringBuilder();
        try {
            BufferedReader input = new BufferedReader(new FileReader(args));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }

            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return contents.toString();
    }

    public TibjmsQueueCompositeForMDN(String[] args) {

        parseArgs(args);

        /* print parameters
        System.out.println("\n------------------------------------------------------------------------");
        System.out.println("------------------------------------------------------------------------");
        System.out.println("Server....................... "+(serverUrl!=null?serverUrl:"localhost"));
        System.out.println("User......................... "+(userName!=null?userName:"(null)"));
        System.out.println("Queue........................ "+queueName);
        System.out.println("------------------------------------------------------------------------\n");
       
       

        try
        {
            TibjmsUtilities.initSSLParams(serverUrl,args);
        }
        catch (JMSSecurityException e)
        {
            System.err.println("JMSSecurityException: "+e.getMessage()+", provider="+e.getErrorCode());
            e.printStackTrace();
            System.exit(0);
        }

        if (queueName == null)
        {
            System.err.println("Error: must specify queue name");
            usage();
        }

        if (data.size() == 0)
        {
            System.err.println("Error: must specify at least one message text");
            usage();
        }

        System.err.println("Publishing into queue: '"+queueName+"'\n");

        try
        {
            QueueConnectionFactory factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(serverUrl);

            QueueConnection connection = factory.createQueueConnection(userName,password);

            QueueSession session = connection.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);

            /*
             * Use createQueue() to enable sending into dynamic queues.
            
            javax.jms.Queue queue = session.createQueue(queueName);

            javax.jms.TemporaryQueue tempqueue = session.createTemporaryQueue();

            QueueSender sender = session.createSender(queue);

            QueueReceiver receiver = session.createReceiver(tempqueue);
            System.out.println(tempqueue.getQueueName());

            connection.start();
            sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            /* publish messages
            for (int i=0; i<data.size(); i++)
            {
                javax.jms.TextMessage message = session.createTextMessage();
                String text = (String) data.elementAt(i);
                  //    message.setJMSReplyTo(getMDNResponseTempQueue);
                message.setJMSReplyTo(tempqueue);
                message.setText(getContents(text));
                sender.send(message);
                System.out.println("Sent Message:"+message.toString());
                File sentXmlFile = new File(text);
            //    System.err.println("Sent message: " + message);
                //logger.info(message.toString());
                if(sentXmlFile!=null)
            //    WriteFileToDisk.writeDisk(sentXmlFile,getContents(text),storeLocation);
                com.sax.parser.SaxXmlParser.logSentFile(sentXmlFile);
            }
            javax.jms.Message replymsg=null;
            replymsg = receiver.receive(20000);
            System.out.println("Received Reply: "+replymsg);
            receiver.close();
            session.close();
            tempqueue.delete();
            connection.close();
        }
        catch(JMSException e)
        {
            e.printStackTrace();
            System.exit(0);
        }
        catch(Exception e1){}
    }
*/
   
    static public String getContents(String args) {
        StringBuilder contents = new StringBuilder();
        try {
            BufferedReader input = new BufferedReader(new FileReader(args));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }

            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return contents.toString();
    }

    public static void main(String args[])
    {
        //TibjmsQueueCompositeForMDN t = new TibjmsQueueCompositeForMDN(args);
        String url = args[0];
        String strXMLFilename = args[1];
        System.out.println("Sent File\n"+getContents(strXMLFilename).toString());
        File input = new File(strXMLFilename);
        PostMethod post = new PostMethod(url);
        try{
        post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
        }catch(IOException e){
            e.printStackTrace();
        }
        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance()
                .getTime().getTime());

        String TimeStamp = currentTimestamp.toString();
       
       
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.addRequestHeader("Service", "OGO");
        post.addRequestHeader("Method", "dfg");
        post.addRequestHeader("Version", "1.1");
        post.addRequestHeader("Culture", "en-US");
        post.addRequestHeader("TimeStamp", TimeStamp);
        post.addRequestHeader("SystemUsername", "DemoUsername");
        post.addRequestHeader("SystemPassword", "DemoPassword");
        post.addRequestHeader("LineOfBusiness", "IRO");
        post.addRequestHeader("Application", "ADB");
        post.addRequestHeader("Client", "ABC");
        post.addRequestHeader("Channel", "WEB");
        post.addRequestHeader("QueueName","sfsdf.fsdfs.PolicyAdministration.ProcessEnrollments.Request");
       
       
        HttpClient httpclient = new HttpClient();
        try{
            int result = httpclient.executeMethod(post);
               System.out.println("Response status code: " + result);
               System.out.println("Resquest Header: " + result);
               Header[] ha = post.getRequestHeaders();
               for(int i=0;i<ha.length;i++){
                   System.out.println(ha[i]);
               }
              
            System.out.println("Response body: "+post.getResponseBodyAsString());
            System.out.println("Response body: "+post.getStatusText());
        } catch(Exception e){
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
    }
/*
    void usage()
    {
        System.err.println("\nUsage: java tibjmsQueueRequestor [options]");
        System.err.println("                                <message-text1 ... message-textN>");
        System.err.println("");
        System.err.println("   where options are:");
        System.err.println("");
        System.err.println(" -server    <server URL> - EMS server URL, default is local server");
        System.err.println(" -user      <user name>  - user name, default is null");
        System.err.println(" -password  <password>   - password, default is null");
        System.err.println(" -queue     <queue-name> - queue name, default is \"queue.sample\"");
        System.err.println(" -help-ssl               - help on ssl parameters\n");
        System.exit(0);
    }

    void parseArgs(String[] args)
    {
        int i=0;

        while(i < args.length)
        {
            if (args[i].compareTo("-server")==0)
            {
                if ((i+1) >= args.length) usage();
                serverUrl = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-queue")==0)
            {
                if ((i+1) >= args.length) usage();
                queueName = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-user")==0)
            {
                if ((i+1) >= args.length) usage();
                userName = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-password")==0)
            {
                if ((i+1) >= args.length) usage();
                password = args[i+1];
                i += 2;
            }
            else
            if (args[i].compareTo("-help")==0)
            {
                usage();
            }
            else
            if (args[i].compareTo("-help-ssl")==0)
            {
                TibjmsUtilities.sslUsage();
            }
            else
            if(args[i].startsWith("-ssl"))
            {
                i += 2;
            }
            else
            {
                data.addElement(args[i]);
                i++;
            }
        }
    }
*/
}

TibcoUtilities.java

package com.tibco;


/*
 * This sample uses JNDI to retrieve administered objects.
 *
 * Optionally all parameters hardcoded in this sample can be
 * read from the jndi.properties file.
 *
 * This file also contains an SSL parameter helper class to enable
 * an SSL connection to a TIBCO Enterprise Message Service server.
 *
 */

import javax.jms.*;
import javax.naming.*;
import java.util.Hashtable;
import java.util.Vector;
import java.security.*;


public class TibjmsUtilities
{
    static Context jndiContext = null;

    static final String  providerContextFactory =
                            "com.tibco.tibjms.naming.TibjmsInitialContextFactory";

    static final String  defaultProtocol = "tibjmsnaming";

    static final String  defaultProviderURL =
                            defaultProtocol + "://localhost:7222";

    public static void initJNDI(String providerURL) throws NamingException
    {
        initJNDI(providerURL,null,null);
    }

    public static void initJNDI(String providerURL, String userName, String password) throws NamingException
    {
        if (jndiContext != null)
            return;

        if (providerURL == null || (providerURL.length() == 0))
            providerURL = defaultProviderURL;

        try
        {
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY,providerContextFactory);
                env.put(Context.PROVIDER_URL,providerURL);

                if (userName != null) {

                    env.put(Context.SECURITY_PRINCIPAL,userName);

                    if (password != null)
                        env.put(Context.SECURITY_CREDENTIALS,password);
                }

                jndiContext = new InitialContext(env);
        }
        catch (NamingException e)
        {
                System.out.println("Failed to create JNDI InitialContext with provider URL set to "+
                                providerURL+", error = "+e.toString());
                throw e;
        }
    }

    public static Object lookup(String objectName) throws NamingException
    {
        if (objectName == null)
            throw new IllegalArgumentException("null object name not legal");

        if (objectName.length() == 0)
            throw new IllegalArgumentException("empty object name not legal");

        /*
         * check if not initialized, then initialize
         * with default parameters
         */
        initJNDI(null);

        /*
         * do the lookup
         */
        return jndiContext.lookup(objectName);
    }


    /**
     * This method creates a java.Security.SecureRandom object seeded with
     * the current time.  It allows the samples that use SSL to initialize
     * the SSL environment much faster than if they had to generate a truly
     * random seed.
     *
     * NOTE: THIS SHOULD NOT BE USED IN A PRODUCTION ENVIRONMENT AS IT IS
     *       NOT SECURE.
     */
     public static SecureRandom createUnsecureRandom()
             throws JMSSecurityException {

        try {
             SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
             sr.setSeed(System.currentTimeMillis());

            return sr;

        } catch(NoSuchAlgorithmException e) {
          JMSSecurityException jmse =
                new JMSSecurityException("Error creating SecureRandom object: " + e.getMessage());
          jmse.setLinkedException(e);
          throw jmse;
        }
    }


    public static void initSSLParams(String serverUrl,String[] args) throws JMSSecurityException{
        if (serverUrl != null && serverUrl.indexOf("ssl://") >= 0) {
           SSLParams ssl = new SSLParams(args);

           ssl.init();
        }
    }

    public static void sslUsage()
    {
        System.err.println("\nSSL options:");
        System.err.println("");
        System.err.println(" -ssl_vendor               <name>      - SSL vendor: 'j2se' or 'entrust6'");
        System.err.println(" -ssl_trace                            - trace SSL initialization");
        System.err.println(" -ssl_vendor_trace                     - trace SSL handshake and related");
        System.err.println(" -ssl_trusted[n]           <file-name> - file with trusted certificates,");
        System.err.println("                                         this parameter may repeat if more");
        System.err.println("                                         than one file required");
        System.err.println(" -ssl_verify_hostname                  - do not verify certificate name.");
        System.err.println("                                         (this disabled by default)");
        System.err.println(" -ssl_expected_hostname    <string>    - expected name in the certificate");
        System.err.println(" -ssl_custom                           - use custom verifier (it shows names");
        System.err.println("                                         always approves them).");
        System.err.println(" -ssl_identity             <file-name> - client identity file");
        System.err.println(" -ssl_issuer[n]            <file-name> - client issuer file");
        System.err.println(" -ssl_private_key          <file-name> - client key file (optional)");
        System.err.println(" -ssl_password             <string>    - password to decrypt client identity");
        System.err.println("                                         or key file");
        System.err.println(" -ssl_ciphers              <suite-name(s)> - cipher suite names, colon separated");
        System.exit(0);
    }

private static class SSLParams implements com.tibco.tibjms.TibjmsSSLHostNameVerifier {
        String          ssl_vendor                  = null;
        boolean         ssl_trace                   = false;
        boolean         ssl_debug_trace             = false;
        boolean         ssl_verify_hostname         = false;
        String          ssl_expected_hostname       = null;
        Vector          ssl_trusted                 = null;
        Vector          ssl_issuers                 = null;
        String          ssl_identity                = null;
        String          ssl_private_key             = null;
        String          ssl_password                = null;
        boolean         ssl_custom                  = false;
        String            ssl_ciphers             = null;

        public SSLParams(String[] args) {
            int     trusted_pi      = 0;
            String  trusted_suffix  = "";
            int     issuer_pi      = 0;
            String  issuer_suffix  = "";

            int i=0;
            while(i < args.length)
            {
                if (args[i].compareTo("-ssl_vendor")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_vendor = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_trace")==0)
                {
                    ssl_trace = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_debug_trace")==0)
                {
                    ssl_debug_trace = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_expected_hostname")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_expected_hostname = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_verify_hostname")==0)
                {
                    ssl_verify_hostname = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_custom")==0)
                {
                    ssl_custom = true;
                    i += 1;
                }
                else
                if (args[i].compareTo("-ssl_ciphers")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_ciphers = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_identity")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_identity = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_private_key")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_private_key = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_password")==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    ssl_password = args[i+1];
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_trusted"+trusted_suffix)==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    String cert = args[i+1];
                    if (cert == null) continue;
                    if (ssl_trusted == null)
                        ssl_trusted = new Vector();
                    ssl_trusted.addElement(cert);
                    trusted_pi++;
                    trusted_suffix = String.valueOf(trusted_pi);
                    i += 2;
                }
                else
                if (args[i].compareTo("-ssl_issuer"+issuer_suffix)==0)
                {
                    if ((i+1) >= args.length) sslUsage();
                    String cert = args[i+1];
                    if (cert == null) continue;
                    if (ssl_issuers == null)
                        ssl_issuers = new Vector();
                    ssl_issuers.addElement(cert);
                    issuer_pi++;
                    issuer_suffix = String.valueOf(issuer_pi);
                    i += 2;
                }
                else
                {
                    i++;
                }
            }
        }

        public void init() throws JMSSecurityException {
            if (ssl_trace)
                com.tibco.tibjms.TibjmsSSL.setClientTracer(System.err);

            if (ssl_debug_trace)
                com.tibco.tibjms.TibjmsSSL.setDebugTraceEnabled(true);

            if (ssl_vendor != null)
                com.tibco.tibjms.TibjmsSSL.setVendor(ssl_vendor);

            if (ssl_expected_hostname != null)
                com.tibco.tibjms.TibjmsSSL.setExpectedHostName(ssl_expected_hostname);

            if (ssl_custom)
                com.tibco.tibjms.TibjmsSSL.setHostNameVerifier(this);

            if (!ssl_verify_hostname)
                com.tibco.tibjms.TibjmsSSL.setVerifyHostName(false);

            if (ssl_trusted != null) {
                for (int i=0; i<ssl_trusted.size(); i++) {
                    String certfile = (String)ssl_trusted.elementAt(i);
                    com.tibco.tibjms.TibjmsSSL.addTrustedCerts(certfile);
                }
            }
            else {
                com.tibco.tibjms.TibjmsSSL.setVerifyHost(false);
            }

            if (ssl_issuers != null) {
                for (int i=0; i<ssl_issuers.size(); i++) {
                    String certfile = (String)ssl_issuers.elementAt(i);
                    com.tibco.tibjms.TibjmsSSL.addIssuerCerts(certfile);
                }
            }
            if (ssl_identity != null)
                com.tibco.tibjms.TibjmsSSL.setIdentity(
                        ssl_identity,ssl_private_key,ssl_password.toCharArray());

            if (ssl_ciphers != null)
                com.tibco.tibjms.TibjmsSSL.setCipherSuites(ssl_ciphers);

            /*
             * Install our own random number generator which is fast but not secure!
             */
            com.tibco.tibjms.TibjmsSSL.setSecureRandom(createUnsecureRandom());
        }

        public void verifyHostName(String connectedHostName,
                                   String expectedHostName,
                                   String certificateCN,
                                   java.security.cert.X509Certificate server_certificate)
                    throws JMSSecurityException
        {
            System.err.println("HostNameVerifier: "+
                    "    connected = ["+connectedHostName+"]\n"+
                    "    expected  = ["+expectedHostName+"]\n"+
                    "    certCN    = ["+certificateCN+"]");

            return;
        }
    }
}



In the lib folder or class path add the jar files

commons-codec-1.4.jar
jms.jar
slf4j-api-1.4.2.jar
slf4j-simple-1.4.2.jar
tibcrypt.jar
tibemsd_sec.jar
tibjms.jar
tibjmsadmin.jar
tibjmsapps.jar
tibrvjms.jar



Pass the arguments to the class file from the command prompt

3 comments:

  1. all the time i used to read smaller articles or reviews which as well clear their motive, and
    that is also happening with this article which I am reading
    at this place.

    Here is my blog :: diet plans that work

    ReplyDelete
  2. I was suggested this website by my cousin.

    I am not sure whether this post is written by him as no
    one else know such detailed about my problem.

    You're incredible! Thanks!

    My homepage :: all inclusive vacation packages

    ReplyDelete
  3. Ηi are usіng Wοrdpress fοr youг
    site ρlatform? I'm new to the blog world but I'm
    trying to get ѕtaгted and сreate my own.

    Do you need any html coding expertise to mаkе
    yоur own blоg? Any help wοuld be really
    appreciatеd!

    Feel free tο ѵisіt my web раgе .
    .. debt consolidation loans for bad credit

    ReplyDelete