Tuesday, 14 May 2013

RESTFUL Web Service Basic Program using Jersey (JAX-RS)


Hi Friends,
I would like to share a simple Hello World program in Restful web services.

Here to implement JAX-RS am using Jersey, which is well matured and production quality implementated api.

In Restful Web services, the response provided by the service to a class is the Resource class.
These Root Resource classes are the POJO classes which are annotated with @Path.

These resources should contains atleast one resource method designator annotation such as
@Get
@Post
@Put
@Delete

Commonly mostly used among those are @Get and @Post.

@Path annotation's value is a relative URI path.

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.
It can be applied at both class and method levels.
More than one media type may be declared in the same @Produces declaration.

The  @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.
It can be applied at both class and method levels.
More than one media type may be declared in the same @Consumes declaration.


Following is the basic Hello World Program for Restful Web services (JAX-RS)


@Path("/hello")
public class Hello {
    @GET
    @Produces({MediaType.TEXT_HTML,MediaType.TEXT_PLAIN})
    public String sayHello() {
        String resp =  "<html><head><title>Hello World</title></head>"
   + "<body><h1>Hello World!</h1></body></h1></html> ";
return resp;
    }
}

Check the Deployment of RESTFUL WEB SERVICES here.

After successful deployment, check the service.

Sample URL is:
http://ipaddress:port/context-path/jersey-servlet-path/hello
(relative path is /hello)

The Restful service @Produces will choose the most acceptable media type as declared by the client.

For example if the Accept header is:
Accept: text/plain
then the total HTML content will be displayed as Plain Text as

<html><head><title>Hello World</title></head><body><h1>Hello World!</h1></body></h1></html> 

Alternatively if the Accept header is:
Accept: text/plain;q=0.9, text/html
which declares that the client can accept media types of "text/plain" and "text/html" but prefers the latter, then the HTML Page will be rendered as

Hello World!



Deploying Restful Web Services (JAX-RS)


Hi Friends...
I would like to share you some information regarding deploying Restful Webserives.

Here to implement JAX-RS am using Jersey, which is well matured and production quality implementated api.

Deploying Jersey Restful service can be achieved in following ways:

Method1:
JAX-RS provides abstract class Application for declaring root resource classes.
Override getClasses method with all the resource classes which you want to provide as a service.

The code for providing access for the resources is:

package app;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class MyApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> set = new HashSet<Class<?>>();
set.add(com.navin.first.Hello.class);
set.add(com.navin.model.TodoResource.class);
return set;
    }
}

Check web.xml configuration after Method2.

Method2:
Another alternative way is by extending PackagesResourceConfig class.
Here the classes provide in this implementation are automatically added to the set of classes that are returned by getClasses in above method (Method1).

package app;
import com.sun.jersey.api.core.PackagesResourceConfig;

public class MyApplication extends PackagesResourceConfig {
    public MyApplication2(){
super("com.navin.first;com.navin.model");
    }
}


web.xml configurations for above two methods:
We should configure Jersey specific servlet for loading our resources.
Snippet for Jersey specific servlet is given below:

<servlet>
  <servlet-name>Jersey REST Service</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>app.MyApplication</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/rest/*</url-pattern>
</servlet-mapping>


Method3:
This is the simplest approach to let Jersey choose the PackagesResourceConfig implementation automatically by declaring the packages as follows:

<servlet>
  <servlet-name>Jersey REST Service</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>com.navin.first;com.navin.model</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

By doing this you are ready with your settings for deploying your JAX-RS Restful application.

Further, its very easy to develop your Restful Web services applications.

Happy coding... :)

Friday, 10 May 2013

TRIM, LTRIM and RTRIM in Java


In java, we have trim() method to remove trailing and leading spaces.

String s = "         dsafsdafdsa dfasfda asfdasf asdfsaf       ";
System.out.println(s.trim());


But there are no direct methods for L-TRIM or R-TRIM individually.

Below are the some of the implementations of L-TRIM and R-TRIM:

Method1:
Implementing using Regular Expressions

String ltrim = s.replaceAll("^\\s+","");
String rtrim = s.replaceAll("\\s+$","");

very simple right..... :)

Method2:
If you have to do it often, you can create and compile a pattern for better performance

private final static Pattern LTRIM = Pattern.compile("^\\s+");
private final static Pattern RTRIM = Pattern.compile("\\s+$");

public static String ltrim(String s) {
    return LTRIM.matcher(s).replaceAll("");
}

public static String rtrim(String s) {
    return RTRIM.matcher(s).replaceAll("");
}


Method3:
Implemented by removing the white spaces.
This method is least prefered.

public static String ltrim3(String s) {
    int i = 0;
    while (i < s.length() && Character.isWhitespace(s.charAt(i))){
        i++;
    }
    return s.substring(i);
}

public static String rtrim3(String s) {
    int i = s.length()-1;
    while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
        i--;
    }
    return s.substring(0,i+1);
}

ICMP Ping through Java


ICMP Ping through program is often useful in many cases like testing server state, accessibility of the given host, etc.

Below is the code to ping host by executing the Ping command through Java.

public boolean pingHostByCommand(String host){
    try{
        String strCommand = "";
        System.out.println("My OS :" + System.getProperty("os.name"));
        if(System.getProperty("os.name").startsWith("Windows")) {
            // construct command for Windows Operating system
            strCommand = "ping -n 1 " + host;
        } else {
            // construct command for Linux and OSX
            strCommand = "ping -c 1 " + host;
        }
        System.out.println("Command: " + strCommand);
        // Execute the command constructed
        Process myProcess = Runtime.getRuntime().exec(strCommand);
        myProcess.waitFor();
        if(myProcess.exitValue() == 0) {
            return true;
        } else {
            return false;
        }
    } catch( Exception e ) {
        e.printStackTrace();
        return false;
    }
}


Below is the code to ping host without using JNI or NOI. It is very reliable way to Ping the host.

public void pingHostByJavaClass(String host, int timeout){
    try {            
        boolean isreachable = InetAddress.getByName(host).isReachable(timeout);
        System.out.println(isreachable);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Saturday, 4 May 2013

Database Connection Pooling In Tomcat


Software Object pooling is not a new concept. This technique is used to improve the performance of the application.

Creating a new Database connection is a very expensive process. Opening a connection for every request creates massive load on the server.
So, for avoiding the load and to improve performance of the server we use connection pooling concept for creating database connection.

Lets see the steps for creating connection pool in Tomcat:

step1:
Open the server.xml file in 'tomcathome-dir'/conf/server.xml

step2:
Add the resource in 'GlobalNamingResources' tag.

Sample resource:

<Resource name="jdbc/myDB" auth="Container" type="oracle.jdbc.pool.OracleDataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
factory="oracle.jdbc.pool.OracleDataSourceFactory"
url="jdbc:oracle:thin:@localhost:1521:orcl" removeAbandoned="true" logAbandoned="true"
user="username"
password="password"
maxActive="200"
maxIdle="10"
maxWait="-1"/>

step3:
Open the context.xml file in 'tomcathome-dir'/conf/context.xml

step4:
Add the resourceLink in 'context' tag.

Sample ResourceLink:
<ResourceLink global="jdbc/myDB" name="jdbc/myDB" type="oracle.jdbc.pool.OracleDataSource"/>

step5:
Save the above two files and restart the server



The context.xml looks like

<?xml version='1.0' encoding='utf-8'?>
<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
<ResourceLink global="jdbc/myDB" name="jdbc/myDB" type="oracle.jdbc.pool.OracleDataSource"/>
</Context>



The server.xml looks like

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />


    <Resource name="jdbc/myDB" auth="Container" type="oracle.jdbc.pool.OracleDataSource"
     driverClassName="oracle.jdbc.driver.OracleDriver"
     factory="oracle.jdbc.pool.OracleDataSourceFactory"
             url="jdbc:oracle:thin:@localhost:1521:orcl" removeAbandoned="true" logAbandoned="true"
       user="username"
     password="password"
     maxActive="200"
     maxIdle="10"
             maxWait="-1"/>
  </GlobalNamingResources>

  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
      </Host>
    </Engine>
  </Service>
</Server>





  • The JNDI datasource provided at step2 is used as a factory for connections.
  • One of the major advantages of using a configuration like this is that the characteristics of the pool can be changed without affecting the application code.
  • Our application's use of connection pooling is almost transparent.


Now you are done with creation of Connection pooling setting at server side in TOMCAT server.



HOW TO ACCESS TOMCAT DATASOURCE IN JAVA:

Now, we ready with server side settings for database connection pooling.

For accessing the Datasource from the server, we use InitialContext lookup.
The snippet is given below:

Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
javax.sql.DataSource dataSource = (javax.sql.DataSource) envContext.lookup("jdbc/myDB");

After getting the datasource from the server, we can get the database connection from datasource.
The snippet is given below:
java.sql.Connection connection = dataSource.getConnection();



Sample Java Program for Creating Database Connection:


package testapp;
import java.sql.*;
import javax.naming.*;
/**
 * @author naveen.k
 */
public class CreateDBConnection{
    public static void main(String args[])
        throws SQLException{
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            javax.sql.DataSource dataSource = (javax.sql.DataSource) envContext.lookup("jdbc/myDB");
            
            Connection con = dataSource.getConnection();
            Statement stmt = con.createStatement();
            
        } catch (NamingException ne) {
            ne.printStackTrace();
        }

    }
}


Cheers.......!!!!

Saturday, 27 April 2013

JSON To XML Conversion



Hi friends,

I would like to share converting JOSN to XML format.

XML: 

  • XML (Extensible Markup Language) is a mark-up language that defines the set of rules for encoding document in Human &Machine readable format.
  • XML mainly emphasizes on Simplicity, Generality and Usability over the Internet. 
  • XML is a textual data format with strong support for all the languages of the World.
JSON:
  • JSON (JavaScript Object Notation) is a text-based open standard designed for Human-Readable data interchange.
  • Even JSON is javaScript specific, it is language-independent with parsers available for many languages.
  • JSON format is often used over network connection for serializing and transmitting structured data .

On keeping Pros and Cons of them a-part, this is the scenario which is very often needed for developing Applications (Mainly in Web environment).


Pre-Requisites:
I used net.sf.json-lib for JSON support. You can download from here.
Json-lib should contain the below dependencies in classpath:
  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging
  • ezmorph

Below is code for Converting JSON to XML format:

package testapp;
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
/**
 * @author naveen.k
 */
public class JsonToXMLConverter {
    private URL url = null;
    private InputStream inputStream = null;    
    public void getJsonfromXml() {
        try{
            url = JsonToXMLConverter.class.getClassLoader().getResource("sample.txt");
            inputStream = url.openStream();
            String jsonData = IOUtils.toString(inputStream);
            XMLSerializer serializer = new XMLSerializer();
            JSON json = JSONSerializer.toJSON(jsonData);
            String xml = serializer.write(json);
            System.out.println(xml);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
     try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }
    public static void main(String[] args) {
        new JsonToXMLConverter().getJsonfromXml();
    }
}



Place the sample JSON in the specified path

sample.txt
==========

[
{
"@id":"bk01",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications \n with XML."
},
{
"@id":"bk02",
"author":"Ralls, Kim",
"title":"Midnight Rain",
"genre":"Fantasy",
"price":"5.95",
"publish_date":"2000-12-16",
"description":"A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
 


Output XML:
===========

   
  
  
  Gambardella, Matthew 
  An in-depth look at creating applications with XML. 
  Computer 
  44.95 
  2000-10-01 
  XML Developer's Guide 
  
  
  Ralls, Kim 
  A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. 
  Fantasy 
  5.95 
  2000-12-16 
  Midnight Rain 
  
  


For XML to JSON conversion please refer this

XML To JSON Conversion



Hi friends,

I would like to share converting XML into JSON format.

XML: 

  • XML (Extensible Markup Language) is a mark-up language that defines the set of rules for encoding document in Human &Machine readable format.
  • XML mainly emphasizes on Simplicity, Generality and Usability over the Internet. 
  • XML is a textual data format with strong support for all the languages of the World.
JSON:
  • JSON (JavaScript Object Notation) is a text-based open standard designed for Human-Readable data interchange.
  • Even JSON is javaScript specific, it is language-independent with parsers available for many languages.
  • JSON format is often used over network connection for serializing and transmitting structured data .

On keeping Pros and Cons of them a-part, this is the scenario which is very often needed for developing Applications (Mainly in Web environment).


Pre-Requisites:
I used net.sf.json-lib for JSON support. You can download from here.
Json-lib should contain the below dependencies in classpath:
  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging
  • ezmorph

Below is code for Converting XML to JSON format:


package testapp;
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
/**
 * @author naveen.k
 */
public class XMLtoJsonConverter {
    private URL url = null;
    private InputStream inputStream = null;    
    public void getXMLfromJson() {
        try{
            url = XMLtoJsonConverter.class.getClassLoader().getResource("sample.xml");
            inputStream = url.openStream();
            String xml = IOUtils.toString(inputStream);
            JSON objJson = new XMLSerializer().read(xml);
            System.out.println("JSON data : " + objJson);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
     try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {}
        }
    }
    public static void main(String[] args) {
        new XMLtoJsonConverter().getXMLfromJson();
    }
}


Place the sample xml in the specified path

sample.xml
==========



   
      Gambardella, Matthew
      XML Developer's Guide
      Computer
      44.95
      2000-10-01
      An in-depth look at creating applications 
      with XML.
   
   
      Ralls, Kim
      Midnight Rain
      Fantasy
      5.95
      2000-12-16
      A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.
   

 


Output for the above specified xml is given below

OUTPUT:
=========

xml to json: [{"@id":"bk01","author":"Gambardella, Matthew","title":"XML Developer's Guide","genre":"Computer","price":"44.95","publish_date":"2000-10-01","description":"An in-depth look at creating applications \n      with XML."},{"@id":"bk02","author":"Ralls, Kim","title":"Midnight Rain","genre":"Fantasy","price":"5.95","publish_date":"2000-12-16","description":"A former architect battles corporate zombies, \n      an evil sorceress, and her own childhood to become queen \n      of the world."}]
 


Formated JSON data as  per the Output is given below

JSON DATA:
===========
[
{
"@id":"bk01",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications \n with XML."
},
{
"@id":"bk02",
"author":"Ralls, Kim",
"title":"Midnight Rain",
"genre":"Fantasy",
"price":"5.95",
"publish_date":"2000-12-16",
"description":"A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world."
}
]
For JSON To XML Conversion Check here