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

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

Monday, 22 April 2013

Compare Dates In Java


This is one of the way for comparing Dates in Java using Date.compareTo() method.

Date.compareTo():
If return value is 0 - argument Date is equal to this Date
If return value is less than 0 (-ve) - this Date is before the Date argument
If return value is greater than 0 (+ve) - this Date is after the Date argument





Following is the example:

package testapp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author naveen.k
 */
public class CompareDates {
    public static void main(String[] args) {
        try{
            // Take SimpleDateFormat for choosing the format you need
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // Parse the dates accordingly
        Date objDate1 = sdf.parse("2013-01-23");
        Date objDate2 = sdf.parse("2013-04-23");

            // Its nothing doing with comparing the dates....
            // It is provided only to show the Date in string format
        String firstDate = sdf.format(objDate1);
        String secondDate = sdf.format(objDate2);

            /*
             * the value 0 if the argument Date is equal to this Date;
             * a value less than 0 if this Date is before the Date argument;
             * and a value greater than 0 if this Date is after the Date argument.
             */
        if(objDate1.compareTo(objDate2)>0)
        System.out.println(firstDate + " is after to " + secondDate);
        else if(objDate1.compareTo(objDate2)<0)
        System.out.println(firstDate + " is before to " + secondDate);
        else
        System.out.println("Both Dates are equal");        

    }catch(ParseException ex){
    ex.printStackTrace();
    }
    }
}

Monday, 15 April 2013

URL, URI and URN


The specifications of URI and URL are defined by World Wide Web Consortium.

The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web (abbreviated WWW or W3).
Founded by Tim Berners-Lee at MIT and currently headed by him.

Tim Berners-Lee is one of the greatest Computer Scientists. He created the world’s first web page http://info.cern.ch/.

URI:

In computing, a uniform resource identifier (URI) provides a simple and extensible means for identifying a resource.
Best described at RFC 3986

Syntax as per RFC 3986 is:

The generic URI syntax consists of a hierarchical sequence of components referred to as the scheme, authority, path, query, and fragment.

      URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

      hier-part   = "//" authority path-abempty
                  / path-absolute
                  / path-rootless
                  / path-empty

The following is an example URI and their component parts:

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment


URL:
A uniform resource locator, abbreviated URL is the subset of URI.
In addition to identification of resource, URL provides the means of locating the resource.
That is, basically physical addresses of objects which are retrievable using protocols already deployed on the net.
Example:
http://en.example.org/navn/url


URN:
Uniform Resource Names (URNs) are the subset of URI.
URNs are intended to serve as persistent, location-independent, resource identifiers.

Syntax as per RFC 2141 is:

<URN> ::= "urn:" <NID> ":" <NSS>

where <NID> is the Namespace Identifier, and <NSS> is the Namespace Specific String.  The leading "urn:" sequence is case-insensitive.

Example:
urn:ietf:rfc:2141
The IETF's RFC 2141.


Summary:

A URI is super set of URL and URN.
URL identifies a resource using one of the URI schemes.
URN identifies a resource independent of its location.

Wednesday, 10 April 2013

Running Another Application Independently from Java Application


Hi Friends,

I would like to share you some notes regarding ProcessBuilder, which helps in execution of seperate Java application.

We can run the Java application not only from console or bat/sh file, but even from another Java application also.

We can make use of Runtime class and ProcessBuilder classes for running the java application.

Now i would like to share you the process of executing java application individually from another java application using ProcessBuilder class.

Below is the snippet for Running java application as independent process.

package test;
import java.io.File;
import java.io.IOException;
/**
 * @author naveen.k
 */
public class ProcessBuilderDemo {

    public int runProcess(){
        try {
            String javaHome = System.getProperty("java.home");
            String javaBin = javaHome +
                    File.separator + "bin" +
                    File.separator + "java";
            ProcessBuilder probuilder = new ProcessBuilder(javaBin, "-cp", "d:\\", "TestProcess", "Naveen", "Naresh");
            Process process = probuilder.start();
            System.out.println("Process started successfully");
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    public static void main(String[] args) {
            new ProcessBuilderDemo().runProcess();
    }
}

With the above execution of code, you can observe a new Java.exe task in Task Manager, with executes independently.

Below is the given TestProcess.java file which is provide as argument for above ProcessBuilder constructor:


import java.io.FileOutputStream;
import java.io.PrintWriter;
/**
 * @author naveen.k
 */
class TestProcess {

    public static void main(String[] args) {
        try {
            int i = 0;
            for (i = 0; i < args.length; i++) {
                System.out.println("Hello " + args[i] + "!");
            }
            FileOutputStream fos = new FileOutputStream("D:\\Test\\output.txt");
            PrintWriter bos = new PrintWriter(fos);
            int count = 0;
            while (count++ <= 100) {
                bos.write(" ******* " + count + " ******* ");
                bos.write("\n");
                for (i = 0; i < args.length; i++) {
                    bos.write("Hello " + args[i] + "!");
                    bos.write("\n");
                }
            }
            bos.flush();
            fos.flush();
            bos.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


After executing the ProcessBuilderDemo class, even if you closes/terminates the ProcessBuilderDemo class, the TestProcess execution will be continued.

Let's assume, we are calling the TestProcess class from the Web-application. Even, if we shut-down the server also the TestProcess execution will be continued.

For more details regarding ProcessBuilder you can check this space.

Monday, 8 April 2013

Inserting Text at cursor position in Textarea


We can insert simple text in Text area at cursor position using javascript

Below is the snippet.

var myTextArea = document.getElementById("mymessage");
var textInArea = myTextArea.value;
var textToInsert = '$Simple Text$';
var caretPosition = myTextArea.selectionStart;
myTextArea.value = textInArea.substring(0, caretPosition)
    + textToInsert  + textInArea.substring(caretPosition);


'selectionStart' property provides the cursor position in Textarea.

Simillarly getting cursor position in JQuery

$('#mymessage').prop("selectionStart")


Try Example:

Saturday, 6 April 2013

Compress Files into Zip Format


The java.util.zip package provides direct functionality to access zip files.

Below are the steps to follow for compressing files into zip file

1. create FileOutputStream
2. create ZipOutputStream using FileOutputStream
3. create a ZipEntry
4. add ZipEntry (individual files or directories) to ZipOutputStream
5. create a FileInputStream
6. write inputstream into zipoutputsteam (i.e. zipentry)
7. close inputstream
8. close zipentry
9. For multiple files continue from step 3
10. close outputstreams


The code for compressing the files into Zip file is provided below:

package testapp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author naveen.k
 */
public class ZipUtilityTest {

    public static void main(String[] args) {
        compressToZipFile();
    }

    public static void compressToZipFile(){
        int len = 0;
        byte[] buffer = new byte[1024];
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try{
            fos = new FileOutputStream("D:\\Test\\TestZip.zip");    // Not a good standard of providing name like this...
            zos = new ZipOutputStream(fos);

            ZipEntry entry1 = new ZipEntry("test1.log");
            zos.putNextEntry(entry1);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message1.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            ZipEntry entry2 = new ZipEntry("test2.log");
            zos.putNextEntry(entry2);

            fis = new FileInputStream("D:\\Test\\TestZipContent\\Message2.log");
            while((len = fis.read(buffer)) > 0){
                zos.write(buffer, 0, len);
            }
            fis.close();
            zos.closeEntry();

            zos.flush();
            zos.close();
            System.out.println("Done");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(fos != null)fos.close();
                if(zos != null)zos.close();
                if(fis != null)fis.close();
            }catch(Exception e){
            }
        }
    }
}

SomeNotes Regarding Favicon


How to find favicon for any website?

We can find favicon.ico for any website in any of the following ways:

Method 1:

Finding favicon.ico at the root of the desired domain.

Enter the URL in below format:
www.domain.com/favicon.ico

Example:
www.google.com/favicon.ico

www.twitter.com/favicon.ico

www.facebook.com/favicon.ico





Method 2:

By looking for <link> tag in the head part of the website source

a. search for <link> tag having rel="icon" attribute
<link rel="icon" href="/favicon.png" />

b. search for <link> tag having rel="shortcut icon" attribute
<link rel="shortcut icon" href="/favicon.ico" />


The Method 2 will provide the favicon with higher image quality.




Monday, 1 April 2013

CSS MENU

Menu in CSS

Vertical menu Using CSS
HTML Code :

 <ul class="navigation">
          <li>
<a href="#">Home</a>
</li>
         <li>
<a href="#">Blogger For Java</a>
</li>
         <li>
<a href="#">About</a>
         </li>
  </ul>

CSS :

.navigation{margin: 0; padding: 0;}

.navigation {
background: #fff;
overflow: hidden;
width: 500px;
box-shadow: 0 2px 10px 2px rgba(0, 0, 0, 0.2);
}

.navigation li {
width: 136px; border-left: 5px solid #666;
float: left;
cursor: pointer;
list-style-type: none;

padding: 10px 10px 10px 15px;

-webkit-transition: all 0.5s ease-in;
-moz-transition: all 0.5s ease-in;
-o-transition: all 0.5s ease-in;
}

.navigation li a {
font-family: georgia;
font-weight: normal;
font-style: italic;
font-size: 14px;
margin-bottom: 5px;
line-height: 16px;
text-decoration: none;
}

.navigation li:hover {
background: #333;
border-left: 5px solid #000;
}

.navigation li:hover a {
font-weight: bold;
color: #fff;
}

see the DEMO here

OUTPUT :


Saturday, 9 March 2013

Doubleton Class in JAVA


Hi Friends....!!
Hi Friends....!!!                             





I would like to share some of my views about Doubleton Class in JAVA.


It’s very similar concept to Singleton Design Pattern.

For any java class if we are allowed to create at-most two objects, such type of class is called as ‘Doubleton class’.

Before going forward, please look into the concepts and implementation of SingletonClass.


Example implementation for the Doubleton class is:

public class Doubleton{
    private static Doubleton objDoubleton1;
    private static Doubleton objDoubleton2;
    private Doubleton(){
    }
    
    // Factory Method
    public  static Doubleton getInstance(){
        if(objDoubleton1 == null){
            objDoubleton1 = new Doubleton();
      return objDoubleton1;
        }
        else if(objDoubleton2 == null){
            objDoubleton2 = new Doubleton();
      return objDoubleton2;
        }
        else{
           if(Math.random() < 0.5)
          return objDoubleton1;
           else
          return objDoubleton2;
        }
    }
    // override clone method
    public  Object clone(){
        return this;
    }
}

Similarly, you can design Tripleton,...., xxxton classes.

Factory Method in JAVA


Factory Methods are static methods that return a same (native) class object.

Example:
Sample Factory Class:

Below is the sample Factory method from Example of Singleton Design Pattern.

public class Singleton{
    private static Singleton objSingleton;
    private Singleton(){
    }
    
    // Factory Method
    public  static Singleton getInstance(){
        if(objSingleton == null)
            objSingleton = new Singleton();
        return objSingleton;
    }
}