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

Load Balancer using mod_proxy_balancer on Ubuntu

I am assuming you know where site-enabled and other folders are
enable modules and configuration following below

/etc/init.d/apache2 stop
sudo a2ensite mynewsite
sudo /etc/init.d/apache2 restart
a2dissite utility to disable sites

Go to /etc/apache2 

0.
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_ajp

1. Modify the config file from sites-enabled folder >nano 000-default and add the below configuration change the documentRoot to the location where you have unzipped the Tomcat I unzipped under /home/localadmin

NameVirtualHost *:80
<VirtualHost *:80>
 ServerName ubuntu
 DocumentRoot /home/localadmin/
 ProxyRequests Off

 <Proxy *>
 Order deny,allow
 Allow from all
 </Proxy>

 ProxyPass /balancer-manager !
 ProxyPass / balancer://mycluster/ stickysession=JSESSIONID nofailover=On
 ProxyPassReverse / http://localhost:8081/   ----three tomcat instance will be running on different ports change server.xml of tomcat to make that work also change the below ajp port in server.xml
 ProxyPassReverse / http://localhost:8082/
 ProxyPassReverse / http://localhost:8083/

 <Proxy balancer://mycluster>
# BalancerMember http://localhost:8081  route=a1
# BalancerMember http://localhost:8082  route=a
  BalancerMember ajp://localhost:8109 route=a1
  BalancerMember ajp://localhost:8209 route=a2
  BalancerMember ajp://localhost:8309 route=a3
  ProxySet lbmethod=byrequests
 </Proxy>

 <Location /balancer-manager>
 SetHandler balancer-manager
 Order deny,allow
 Allow from all
 </Location>

</VirtualHost>



2. Enable proxy in proxy.conf in mods-enabled folder

<IfModule mod_proxy.c>
        #turning ProxyRequests on and allowing proxying from all may allow
        #spammers to use your proxy to send email.

        ProxyRequests Off

        <Proxy *>
                AddDefaultCharset off
                Order deny,allow
                Deny from none
                #Allow from .example.com
        </Proxy>

        # Enable/disable the handling of HTTP/1.1 "Via:" headers.
        # ("Full" adds the server version; "Block" removes all outgoing Via: he$
        # Set to one of: Off | On | Full | Block

        ProxyVia On
</IfModule>

From terminal find your >servername this will return your server name
Tip: Restart apache and try the link below
using http://yourservername/balancer-manager

Remote debugging using eclipse and Tomcat

Instead of start.sh start tomcat as follows after the project is deployed
./catalina.sh jpda run

In Eclipse Set the project on build path
Debug Configuration
Remote Java Application Right Click New and start debugging it already set to monitor port 8000

Setting up SSL: Ubuntu and Apache 2

Setting up SSL: Ubuntu and Apache 2


This document requires that you've got a signed server.crt and a server.key file available.  You may have justgone through my page Creating Certificate Authorities and self-signed SSL certificates.If not, go there first and follow the instructions.

The remaining steps involve Apache and other tweaks detailed step-by-step below.  This file was originallywritten for Ubuntu 6.06, but has been kept current and verified with 10.04 Lucid Lynx.  It should work withmost/all releases in between -- and probably Debian-based distros in general, with little or no modification.
(1) Preliminaries and Packages.
If you have a registered DNS name, be sure that you properly set it up.  On the Gnome console:System->Administration->Networking:General.  Your host/domain name here should match the one you'llbe using in later steps.  You can also edit /etc/hosts directly if you're comfortable with that route.

If you haven't done so already, use apt-get, Synaptic or some other tool toget and install Apache 2.  I prefer apache2-mpm-prefork.  You should also have openssl by this point.

(2) Copy the server.crt and server.key files into position.
This step suggests putting certificate-related files in this location: /etc/apache2/ssl.  If the"ssl" directory doesn't already exist there, go ahead and mkdir it now.

Then copy the server.key and server.crt files into position:

cp server.key /etc/apache2/ssl
cp server.crt /etc/apache2/ssl
(3) Enable ssl.
You'll want to run the /usr/sbin/a2enmod script.  If you look at this script, it's simply ageneral purpose utility to establish a symlink between a module in/etc/apache2/mods-available to /etc/apache2/mods-enabled (or give a message to theeffect that a given module doesn't exist or that it's already symlinked for loading).

a2enmod ssl
(4) Create a stub SSL conf. file (if needed) and establish a necessary symlink.
NOTE.  Ubuntu 10.04 already ships with a stub SSL conf file(/etc/apache2/sites-available/default-ssl), so you won't need to copy the 'default'conf as a stub for the 'default-ssl' conf -- but you will STILL need a symlink between it and thesites-enabled directory.

So if using an Ubuntu prior to ~10.04:

cp /etc/apache2/sites-available/default /etc/apache2/sites-available/default-ssl

For all versions of Ubuntu:

Next, establish a symlink from the 'available' default-ssl file to the 'enabled' file.  The symlinking methodology between those two directories is similar in philosophy to mods-available and mods-enabled (previous step).  The general idea is that enabled files exist as symlinks created to their available counterparts.  Ubuntu prefixes '000-' in frontof the default file, so we may as well keep the same convention with default-ssl:

ln -s /etc/apache2/sites-available/default-ssl /etc/apache2/sites-enabled/000-default-ssl
(5) Set up the document roots.
The default location for HTML pages with an initial install of Ubuntu is/var/www and there exists no separate place for ssl files.  I prefer toserve up basic HTML pages in /var/www/html and SSL pages in /var/www-ssl/html.Whatever works for you.  But at this point I create the directories.

cd /var/www
mkdir html
cd /var
mkdir www-ssl
cd www-ssl
mkdir html
(6) Configure virtual hosts.
su to the superuser and make a backup of the original Apache configuration file.Call it whatever you want.  My practice is to add "_original" to any default configurationfile before I make changes -- in case I need to revert.  You should not make a backup of the followingfile in the sites-enabled directory, since both the original and backup will be loaded when you restartApache.  Also note that a symlink exists from /etc/apache2/sites-enabled/000-default to/etc/apache2/sites-available/default.  Back it up in the sites-available directory or some other location outsideof Apache altogether.

sudo su
cd /etc/apache2/sites-available
cp /etc/apache2/sites-available/default default_original

(Note: If using Ubuntu 10.04+ you may want to backup the original SSL conf also):
cp /etc/apache2/sites-available/default-ssl default-ssl_original
Now you need to declare the IP of your box (or FQDN/DNS name) and document roots you created in a previous step.

To configure HTTP over port 80 (edit /etc/apache2/sites-available/default):

NameVirtualHost *:80


(Note: Look down just a bit and make a change to the virtual host settings.)
<VirtualHost *:80>
ServerName localhost
DocumentRoot /var/www/html/
(Note: Use your assigned IP or DNS name followed with ":80" if you have one for ServerName).
Similar procedure for HTTPS over port 443 (edit /etc/apache2/sites-available/default-ssl):

NameVirtualHost *:443


(Note: Look down just a bit and make a change to the virtual host settings.)
<VirtualHost *:443>
ServerName localhost
DocumentRoot /var/www-ssl/html/
(Note: Again, use your assigned IP or a DNS name followed with ":443" if you have one for ServerName.)
(7) Instruct Apache to listen to 443.
Go to this file /etc/apache2/ports.conf and add the following to it:

Listen 443
I noted that starting with Ubuntu 7.10 (or thereabouts), the ports.conf may already have an IfModule clause in it for the SSL portion.  If you see this, you can just leave it as-is:

<IfModule mod_ssl.c>    Listen 443</IfModule>
(8) Turn on the SSL engine.
Make sure the following are in your default-ssl file. The SSLengine should be on, and thecert and key should be properly pathed:

SSLEngine On
SSLCertificateFile /etc/apache2/ssl/server.crt
SSLCertificateKeyFile /etc/apache2/ssl/server.key
(9) Make an /etc/hosts tweak (if need be) -- and restart apache.
When starting and stopping Apache there may be a complaint such as "Could not determine the server's fully qualifieddomain name, using 127.0.1.1 for ServerName".  You may encounter this if you don't have a DNS name for your server, andare just using an IP.  If this applies to you, go into your /etc/hosts file and make the following changes.Basically, we'll be adding "localhost.localdomain" to the 127.0.0.1 IP and whatever system name you chose when youinstalled Ubuntu (assuming you've not changed it).  The final line below should be there if you have a static IP, andcorresponding DNS name registered to it.  If this is the case, earlier steps that wanted ServerName should have a valuewhich corresponds to the DNS name also indicated here.

127.0.0.1 localhost localhost.localdomain {your system name}
127.0.1.1 {your system name}
{static IP if you you have one} {fully qualified DNS host name if you have one}
It may be that I first noticed additional behavior with Ubuntu 8.04 Hardy Heron.  Ifyou don't have a fully qualified domain name (FQDN) for your box, you may need to makean additional tweak.  In your /etc/apache2/apache2.conf file, you may want to add the followingline at the very end of the file if Apache is still complaining about lacking a fullyqualified domain name at startup:

ServerName localhost
Restart Apache.

cd /etc/init.d
./apache2 restart
Done -- test it out!

Forward vs Reverse Proxy


Forward Proxy I send a request with the name of the target server and proxy decides whether to allow or deny (acts like a firewall)
eg

   You --------www.facebook.com---->Forward proxy (companay proxy)
   You -------  denied        <----- 
   You -------www.google.com----> Forward proxy (company proxy)--->granted--->www.google.com
   You <-----------------------------------------------------------------------
Reverse Proxy I send a request with the name of the proxy and proxy re-routes the request to internal server (acts like a loadbalancer)
eg
  You -------www.mycompany.com----Reverse proxy (load balancer)
                                  |    |     |
                                  v    v     v
     <--------------------server  A    B     C

Setting Virtual Host in Apache

Apache2 is installed under /etc/apache2 

sudo apt-get install apache2

/etc/init.d/apache2 stop
sudo a2ensite mynewsite
sudo /etc/init.d/apache2 restart
a2dissite utility to disable sites
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_ajp



NameVirtualHost *:80
<VirtualHost *:80>
    ServerName localhost
    UseCanonicalName On
    ServerAdmin harshal.shah1982@gmail.com
    Alias /healthcheck /var/www
     DocumentRoot /home/localadmin/liferay

    <Directory "/">
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          Allow from all
          ProxyPass ajp://localhost:8009/
     </Directory>
     CustomLog /liferay.log combined
     Options +FollowSymlinks
</VirtualHost>

Check if proxy is loades in mods-enabled

and in proxy.conf change
        <Proxy *>
                AddDefaultCharset off
                Order deny,allow
                Deny from none
                #Allow from .example.com
        </Proxy>

Php alongside Liferay and Tomcat

To get PHP to run alongside Liferay and Tomcat is a simple matter of modifying the liferay.conf file. Here's how you do it:
ssh into the server.
 cd /var/www/
 sudo mkdir directory name
sudo nano (or vim if you prefer) index.php
 Enter this into the text editor.
 <?php        echo "Hello World!";?> cd /etc/apache2/sites-enabled/
 sudo nano (or vim if that's your preference) 000-default
 Make sure the first item on the page looks like this...
 NameVirtualHost *:80 Make sure the <VirtualHost> directive looks like this...
 <VirtualHost *:80> Save and exit the file.
 sudo nano liferay.conf
 Make sure the <VirtualHosts> directive looks like this...
 <VirtualHost *:80> Add an alias inside the <VirtualHost> tag.
 Alias /apps "/var/www/apps" Add a <Directory> directive inside the <VirtualHost> tag. It should look like this...
 <Directory "/apps/">      Options FollowSymLinks      AllowOverride None      Order allow,deny      Allow from all      ProxyPass [http://localhost:80/apps/]
</Directory> Save and exit the file.
 Restart the server
 /etc/init.d/apache2 restart Test to see if it's working by navigating to the root URL of the server. You should be taken to Liferay. Then navigate to the siteurl/apps/ and you should see a blank page that says "Hello World".
 

Tomcat Monitoring

I followed the following steps to set up tomcat monitoring.
1. In tomcat/bin/startup.bat add the following line below all the rem comments on top of the file.
 
set JAVA_OPTS=-Dcom.sun.management.jmxremote.port=7009 -Dcom.sun.management.jmxremote.ssl=false -
Dcom.sun.management.jmxremote.authenticate=false

2. From Jdk/bin> jconsole localhost:7009

It is a basic monitoring with no authentication and ssl.

Tomcat Clustering Pratical and Simple Example for Linux

Tomcat Clustering and Distribution For Ubuntu

1) sudo apt-get install apache2 tomcat6 libapache2-mod-jk
2) sudo vim /etc/apache2/workers.properties
and type/past in:
# Define 1 real worker using ajp13
worker.list=worker1
# Set properties for worker1 (ajp13)
worker.worker1.type=ajp13
worker.worker1.host=localhost
worker.worker1.port=8009
3) sudo vim /etc/apache2/apache2.conf
and type/past in:
# Load mod_jk module
# Update this path to match your modules location
LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
# Declare the module for (remove this line on Apache 2.x)
#AddModule mod_jk.c
# Where to find workers.properties
# Update this path to match your conf directory location (put workers.properties next to httpd.conf)
JkWorkersFile /etc/apache2/workers.properties
# Where to put jk shared memory
# Update this path to match your local state directory or logs directory
JkShmFile /var/log/apache2/mod_jk.shm
# Where to put jk logs
# Update this path to match your logs directory location (put mod_jk.log next to access_log)
JkLogFile /var/log/apache2/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the timestamp log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
6) sudo vim /etc/apache2/sites-enabled/000-default
Delete "DocumentRoot /var/www"
And type in
JkMount / worker1
JkMount /* worker1
note, you can use JkUnMount to define directories you want apache to serve
7) Enable port 8009 on tomcat
sudo vim /etc/tomcat6/server.xml
remove the "" that is a line below

  restart tomcat
sudo /etc/init.d/tomcat6 restart
9) restart apache
sudo /etc/init.d/apache2 restart
10) wget localhost
You should see the default tomcat page

Tomcat Clustering and Distribution on Windows

Download tomcat5.5.zip from apache website instead of executable.
Steps to Make web pages + clustered and distributed.
1. Download tomcat 5.5
2. Make copy as TomcatA and TomcatB.
    Configure Tomcat A by setting the following in server.xml
         <Server port="8105" shutdown="SHUTDOWN">
        Define a non-SSL HTTP/1.1 Connector on port 8080
        -->
        <Connector port="8081" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" />

         <!-- Define an AJP 1.3 Connector on port 8009 -->
        <Connector port="8109" protocol="AJP/1.3" redirectPort="8443" />

        <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
        -->
        <Engine name="Catalina" defaultHost="localhost" jvmRoute="TomcatA">

    Configure Tomcat B by setting the following in server.xml
         <Server port="8205" shutdown="SHUTDOWN">
        Define a non-SSL HTTP/1.1 Connector on port 8080
        -->
        <Connector port="8082" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" />

         <!-- Define an AJP 1.3 Connector on port 8009 -->
        <Connector port="8209" protocol="AJP/1.3" redirectPort="8443" />

        <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
        -->
        <Engine name="Catalina" defaultHost="localhost" jvmRoute="TomcatB">

3. Add <distributable /> tag in web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<distributable />

</web-app>

4. Download apache_2.0.55-win32-x86-no_ssl.msi from http://httpd.apache.org/download.cgi
 Set network and domain address as localhost.
Apache Group\Apache2\conf\httpd.txt file change the listen to Listen 8080
if listen 80 does not work.
5. Create errors.log in log folder.
6. Start Apapche from Apache Group\Apache2\bin\Apache on one command prompt.
7. Download connector from location http://www.apache.org/dist/tomcat/tomcat-connectors/jk/binaries/win32/jk-1.2.28/
  Connector mod_jk-1.2.28-httpd-2.0.52.so
 Rename it to mod_jk.so match it with setting below
 and place it in apache2/module folder.
8. Add following settings to apache -> httpd.conf
LoadModule jk_module modules/mod_jk.so
JkWorkersFile "C:\cluster\Apache\conf\workers.properties"
JkLogFile "logs/mod_jk.log"
JkLogLevel error
JkMount /cluster loadbalancer
JkMount /cluster/* loadbalancer

9. Create workers.properties file at location C:\cluster\Apache\conf
workers.tomcat_home=/tomcatA
workers.java_home=$JAVA_HOME
ps=/
worker.list=tomcatA,tomcatB,tomcatC,loadbalancer
worker.tomcatA.port=8109
worker.tomcatA.host=localhost
worker.tomcatA.type=ajp13
worker.tomcatA.lbfactor=1
worker.tomcatB.port=8209
worker.tomcatB.host=localhost
worker.tomcatB.type=ajp13
worker.tomcatB.lbfactor=1
worker.tomcatC.port=8309--this will remain same for all
worker.tomcatC.host=localhost--change this for horizontal servers
worker.tomcatC.type=ajp13
worker.tomcatC.lbfactor=1
worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcatA,tomcatB,tomcatC
worker.loadbalancer.sticky_session=1

10. Create a cluster folder in TomcatA & Tomcat B/webapps
      Add test.jsp
<%
session.setAttribute("a","a");
%>
<html>
<head>
<title>Test JSP</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#CCCCCC">
<td width="13%">TomcatA Machine</td>
<td width="87%">&nbsp;</td>
</tr>
<tr>
<td>Session ID :</td>
<td><%=session.getId()%></td>
</tr>
</table>
</body>
</html>
11. web.xml would be in WEB-INF and setting would be
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
<distributable />

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
</web-app>

12. Start Apache. TomcatA and Tomcat B.
  Using CATALINA_BASE:   C:\TomcatA
Using CATALINA_HOME:   C:\TomcatA
Using CATALINA_TMPDIR: C:\TomcatA\temp
Using JRE_HOME:        "C:\Java\jre6"
these settings should point to respective folders for each server.

13. Connect using http://localhost:8080/cluster/test.jsp
        where 8080 is the listen port set in apache config file.

Usefull links
1. http://www.easywayserver.com/implementation-tomcat-clustering.htm
2. http://www.apache.org/dist/tomcat/tomcat-connectors/jk/binaries/win32/jk-1.2.28/
3. http://archive.apache.org/dist/tomcat/tomcat-5/v5.5.27/bin/
4. http://easywayserver.com/apache-installation.htm

Logging in Tomcat

Follow the following steps to setup a file named tomcat.log that has internal Tomcat logging output to it:

Create a file called log4j.properties with the following content and save it into common/classes.
            log4j.rootLogger=DEBUG, R
            log4j.appender.R=org.apache.log4j.RollingFileAppender
            log4j.appender.R.File=${catalina.home}/logs/tomcat.log
            log4j.appender.R.MaxFileSize=10MB
            log4j.appender.R.MaxBackupIndex=10
            log4j.appender.R.layout=org.apache.log4j.PatternLayout
            log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
         


Download Log4J (v1.2 or later) and place the log4j jar in $CATALINA_HOME/common/lib.
Download Commons Logging and place the commons-logging-x.y.z.jar (not commons-logging-api-x.y.z.jar) in $CATALINA_HOME/common/lib with the log4j jar.
Start Tomcat
 commons-logging-x.y.z.jarhttp://mirror.its.uidaho.edu/pub/apache/commons/logging/ 

Velociy Pratical Example

Download velocity-tools-2.0-src 
Add the following jars in WEB-INF/lib folder of tomcat
velocity-1.6.2.jar
velocity-tools-view-2.0.jar
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-digester-1.8.jar
commons-lang-2.2.jar
commons-logging-1.1.jar
oro-2.0.8.jar

Create a project simple inside webapps using eclipse
1.Inside simple folder create index.jsp


<%@taglib prefix="velocity" uri="http://velocity.apache.org/velocity-view" %>

<html>
<body>

I'm a JSP file that uses the VelocityViewTag.

<velocity:view>
#if( $XHTML )
  #set( $br = "<br />" )
#else
  #set( $br = "<br>" )
#end

$br
$br

Here we use a custom tool: $toytool.message

$br
$br

Lets count : #foreach($i in [1..5])$i #end

$br
$br

Let's play with a hashmap:$br
first add foo: $map.put("foo",$foo)$br
then add bar: $map.put("bar",$bar)$br
$br
and that gives us $map

$br
$br

Here we get the date from the DateTool:  $date.medium

$br
$br

#if( $isSimple )
This is simple#if( $XHTML ) xhtml#end app version ${version}.
#end

$br
$br

Click <a href="index.vm">here</a> to see this VTL markup as a normal template.

</velocity:view>
</body>
</html>

2. Create index.vm file inside the simple folder


<html>
<body>

I'm a velocity template processed using the VelocityViewServlet.

#if( $XHTML )
  #set( $br = "<br />" )
#else
  #set( $br = "<br>" )
#end

$br
$br

Here we use a custom tool: $toytool.message

$br
$br

Lets count : #foreach($i in [1..5])$i #end

$br
$br

Let's play with a hashmap:$br
first add foo: $map.put("foo",$foo)$br
then add bar: $map.put("bar",$bar)$br
$br
and that gives us $map

$br
$br

Here we get the date from the DateTool:  $date.medium

$br
$br

#if( $isSimple )
This is simple#if( $XHTML ) xhtml#end app version ${version}.
#end

$br
$br

Click <a href="index.jsp">here</a> to see the VelocityViewTag handle the same VTL markup.

</body>
</html>
 
3. In src under WEB-INF folder place class file


public class ToyTool
{
    private String message = "Hello from ToyTool!";

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String m)
    {
        message = m;
    }

    /** To test exception handling in templates. */
    public boolean whine() {
        throw new IllegalArgumentException();
    }

}
4. Web.xml

<web-app>
  <servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.vm</welcome-file>
  </welcome-file-list>
</web-app>

5. Beside web.xml create a file tools.xml

<?xml version="1.0"?>

<tools>
    <data type="boolean" key="xhtml" value="true"/>
    <data type="boolean" key="isSimple" value="true"/>
    <data type="number" key="version" value="2.0"/>
    <data key="foo">this is foo</data>
    <data key="bar">this is bar.</data>
    <toolbox scope="request">
        <tool key="toytool" class="ToyTool" restrictTo="index*"/>
    </toolbox>
    <toolbox scope="session">
        <tool key="map" class="java.util.HashMap"/>
    </toolbox>
</tools>

In lib folder place the jar files mentioned above...start tomcat and try accessing the index.jsp
So the folder structure is


Simple
     |
     |WEB-INF
     |       | src
     |       | lib
     |       | tools.xml
     |       | web.xml
     | index.jsp
     | index.vm

If you want a working example send me a mail at harshal.shah1982@gmail.com

Restful webservice Post Client

Restful webservice Post Client

1. Netbeans 6.9
2. Create a project Helloworld
3. Deploy and test the service
4. Right Click on project properties set relative url as resources/helloworld

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworld;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;
import javax.ws.rs.FormParam;
import javax.ws.rs.QueryParam;
import java.util.ArrayList;
import java.util.List;

/**
 * REST Web Service
 *
 * @author localadmin
 */

@Path("helloworld")
public class HelloWorld {
    @Context
    private UriInfo context;

    /** Creates a new instance of HelloWorld */
    public HelloWorld() {
    }

    /**
     * Retrieves representation of an instance of helloworld.HelloWorld
     * @return an instance of java.lang.String
     */
    @POST
   // @Produces("text/html")
   @Produces("application/xml")
  // @Consumes("application/x-www-form-urlencoded")
 //   public List<userData> getHtml(@QueryParam("name") String user_id) {
      public List<userData> getHtml(@FormParam("test") String user_id) {
           userData toReturn = new userData();
                toReturn.name = user_id;
        List<userData> retUser = new ArrayList<userData>();
        retUser.add(toReturn);
   return retUser;
  }

    /**
     * PUT method for updating or creating an instance of HelloWorld
     * @param content representation for the resource
     * @return an HTTP respons with content of the updated or created resource.
     */
    @PUT
    @Consumes("text/html")
    public void putHtml(String content) {
    }
}


2nd Class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworld;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class userData {
    public String name;
  
}



WebService Post Client

<html>
<head>
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
    //    window.open("/welcome.html",'welcome','width=300,height=200,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');
        alert("hey");
        $.ajax({
            type: "GET",
            url: "http://localhost:8080/HelloWorld/resources/helloworld",
            data: "user_id=" + document.getElementById("user_id").value ,
            success: function(msg){
                            window.alert(msg);
                        },
                error: function(xmlHttpRequest, status, err) {
                    alert('Status ' + status + ', Error ' + err);
                }
    });
        }
    </script>
</head>
<body>
<form action="http://localhost:8080/HelloWorld/resources/helloworld" method="post">
<textarea name="test" rows="8" cols="40" value="tangeo"></textarea>
<input type="text" id="name" name="name" value="harshal"/>
<input type="submit" value="submit"/>
<div id="response">
hello
    </div>
</form>
</body>
</html>


Create the security key and password

1 ./usr/lib/jvm/java-6-sun/bin# keytool -genkey -alias tomcat -keypass changeit -keystore sslkey.bin -storepass changeit
2. Go to glass fish Server http://localhost:4848 Network Config http listener 2 enable ssl and set port number to 8443.
3. Click on tab SSL and put in certificate name as tomcat or the one given above as alias.
4. In Key Store place /usr/lib/jvm/java-6-sun/bin/sslkey.bin
5. Go back to HelloWorld project in netbeans and click on web.xml then click on security tab. Click on Add Web Resource Collection
 put the name as http://localhost:8080/HelloWorld/resources/application.wadl which is displayed when you right click project in netbean and Test WebService on this page the resource name is present.
6. Coming back after web resource collection in url pattern place /helloworld.