Monday 6 January 2014

Generating java thread dump in Linux or Unix

If your server got hang, before restarting your server you can take the thread dump of the server for identifying the issue.
In Linux or Unix machine you can identify the running processes by below command
ps -ef
By this command you will get list of all the processes running. From those list, to filter the processes list which are of java processes use the below command
ps -ef | grep java
Identify the required process which you want to kill and provide the corresponding process in below command
Kill -3 java-process Id
This command will kill the corresponding process and generates the thread dump at the server location
If you want to get the thread dump without killing the process, below command generates the thread dump at provided location
jstack java-process Id > jstack.out

Friday 20 December 2013

Program 1: Logical Sequecial numbers in a Traigular form

This is the program for printing the numbers in the below format:

1
3*2
4*5*6
10*9*8*7
11*12*13*14*15


Method 1:

public void printFormat1(){
        int num = 10;
        for(int i = 1; i <= num; i++){
            System.out.println(formString("",getStartNum(i),i,(i%2 == 0 ? -1 : 1)));
        }
    }
    
    public int getStartNum(int num){
        int incrRdecr = num%2 == 0 ? -1 : 1;
        int sum = (num * (num+1))/2;        
        if(incrRdecr == 1){
            return sum - num + 1;
        }else{
            return sum;
        }        
    }
    
    public String formString(String str, int startNum, 
            int countNum, int incrCount){
        String resp;
        if(countNum == 0){
            str = (str + startNum);
            resp = str.substring(0, str.lastIndexOf("*"));
            return resp;
        }else{
            resp = formString(str + startNum + "*",(startNum + incrCount),--countNum, incrCount);
            return resp;
        }        
    }

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