Wednesday, December 29, 2010

Tomcat load balancer using mod_proxy_balancer

/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.shah@asurion.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>
Enable modules  and configuration in the 

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/
 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>

using http://ubuntu/balancer-manager

Enable proxy in proxy.conf in mods enabled.

<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>
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".

Restful webservices with Eclipse

Java file place it in the same package

package name.brucephillips.hellows.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

/**
 * Defines a RESTful web service
 * that can be called by using
 * the URI /hello
 *
 * @author Bruce Phillips
 *
 */
@Path("/hello")
public class HelloResource {

    /**
     * Processes HTTP get requests
     * that have no parameters
     * for example /hello
     * @return "Hello"
     */
    @GET
    @Produces("text/plain")
    public String getMessage() {
       
        // Return plain text
        return "Hello";
       
    }//end method getMessage
   
    /**
     * Processes HTTP get requests
     * that have a username parameter
     * for example /hello/Bruce
     * @param userName
     * @return "Hello {userName}"
     */
    @GET
    @Path("{username}")
    @Produces("text/plain")
    public String getMessage(@PathParam("username") String userName) {
       
        return "Hello " + userName;
       
    }//end overloaded method getMessage
   
    /**
     * Processes HTTP post requests
     * that have sent a form parameter
     * named name
     * @param name
     * @return "Hello {name}"
     */
    @POST
    @Consumes("application/x-www-form-urlencoded")
    @Produces("text/plain")
    public String postMessage(@FormParam("name") String name) {
        System.out.println("In here");
        return "Hello " + name;
       
    }//end method postMessage
  
   
   
}//end class HelloResource




web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 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">
    <display-name>helloWS</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>name.brucephillips.hellows.resources</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Hello Home Page</title>
</head>
<body>
<h3>Example RESTful Web Service</h3>

<p>Click on a link to call one of the helloWS methods and view the response.</p>

<p><a href="services/hello">Plain Hello</a></p>

<p><a href="services/hello/Bruce">Hello Bruce</a></p>

<p>Enter your name and click the button to get a personal hello.</p>

<form method="post" action="services/hello">

<p>Name: <input type="text" name="name" /></p>

<p><input type="submit" name="submit" value="Submit" /></p>

</form>

<h3>References</h3>

<ol>
<li><a href="http://wikis.sun.com/display/Jersey/Main" target="_blank">Jersey: RESTful Web services made easy</a></li>
<li><a href="http://docs.sun.com/app/docs/doc/820-4867/6nga7f5mk?l=en&a=view" target="_blank">RESTful Web Services Developer's Guide</a></li>
<li><a href="https://jsr311.dev.java.net/nonav/releases/1.0/index.html?overview-summary.html" target="_blank">jsr311-api 1.0 API</a></li>
<li><a href="http://lqd.hybird.org/journal/?p=123" target="_blank">Hacking Jersey/JAX-RS to run RESTful web services on Google AppEngine/Java</a></li>
<li><a href="http://www.brucephillips.name/restful/helloWS.zip" target="_blank">Zipped Eclipse Maven Project</a></li>
</ol>


</body>
</html>


Add the jar files

asm-3.1.jar
jersey-core-1.1.0-ea.jar
jersey-server-1.1.0-ea.jar
jsr311-api-1.1.jar

Make sure the jar version are the same....



In this article I would like to describe how to get your RESTful webservice to output XML. RESTful doesnt output as much detail as the SOAP specification, but it gives you enough data to work with, assuming you know what the data types are.
Firstly, create a class that represents your output. Remember the import!
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class userData {
    public String firstname;
    public String lastname;
    public String idnumber;
    public String pin;
    public int status;
}
Then we can start coding the webservice. I’m not going to go into detail, but am just going to put in the specifics that are relevant for this article
import java.util.ArrayList;
import java.util.List;
 
@Path("airtime_functions")
public class airtime {
    @GET
    @Path("get_users")
    @Produces("application/xml")
    public List<userData> get_users(@QueryParam("user_id") String user_id)
    {
        List<userData> retUser = new ArrayList<userData>();
        try
        {
            errorMsg = "";
            con = getJNDIConnection();
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            String sql = "SELECT * from users where user_id = ?";
            PreparedStatement prest = con.prepareStatement(sql);
            prest.setString(1, user_id);
            prest.execute();
            rs = prest.getResultSet();
            while (rs.next())
            {
                userData toReturn = new userData();
                toReturn.firstname = rs.getString("firstname");
                toReturn.idnumber = rs.getString("idnumber");
                toReturn.lastname = rs.getString("surname");
                toReturn.pin = rs.getString("pin");
                toReturn.status = rs.getInt("status");
                retUser.add(toReturn);
            }
            con.close();
            return retUser;
        } catch (Exception e)
        {
            userData toReturn = new userData();
            toReturn.firstname = "Error: " + e;
            toReturn.idnumber = "";
            toReturn.lastname = "";
            toReturn.pin = "";
            toReturn.status = 0;
            retUser.add(toReturn);
            return retUser;
        }
    }

Restful webservices with Netbeans

1. Netbeans 6.9
2. Create a project Helloworld
3. Right Click the project and choose the option create Restful webservice.
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;
   
}

And the post html
 <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.