Tuesday, December 22, 2015

Why to have a private constructor?

In Java, it is possible to have a private constructor. When and why should we use private constructor is explained in detail below. Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so.

There are two possible reasons why one would want to use a private constructor
a. You don’t want any objects of your class to be created at all
b. You only want objects to be created internally –as in only created in your class.

Private constructors can be used in the singleton design pattern
A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

Private constructors can prevent creation of objects
The other possible reason for using a private constructor is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn’t make sense – and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name – no instance of the class needs to be created.

Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the usage of that default constructor, thereby preventing a caller from creating an instance of the class. Note that the private constructor may even be empty.

Thursday, December 10, 2015

difference between classpath and buildpath

The classpath is a Java terminology and buildpath is a means to construct java classpath from artifacts in elcipse like IDE's. In java world, both mean the same.
 
The classpath is a Java thing. It's a list of either folders or jar files to consider (in order) when resolving classes to be loaded. It's used by the Java JVM. It can be specified by the CLASSPATH environment variable or java -classpath. It's a list of either Jar files or folders separated by a ":" on Linux/OSX systems or ";" on Windows.
The Eclipse build path is a means to construct this Java classpath from artifacts in the Eclipse environment. The Configure Build Path dialog is used to manipulate a file in your project called .classpath (normally hidden). This dialog allows you to form the Java classpath from Jar files, files you have built, folders, external Jar files and other things. It also controls where the Java Development Tooling (JDT) will locate your compiled files, and other things related to class files. The Eclipse help has pretty good documentation on this.
 

The build path is used for building your application. It contains all of your source files and all Java libraries that are required to compile the application. These are typically required during building the build. (mostly required even during the runtime)
Buildpath is not standard Java terminology. It is the term for the richer way that a typical IDE specifies the relationship between the "modules" or "projects" that make up an application. The IDE uses this to figure out the classpath and sourcepath for compiling the Java code, and the classpath for running it. The IDE also uses the build path to figure out how to package up your code and its dependencies as (for example) a WAR file.



The classpath is used for executing the application. This includes all java classes and libraries that are needed to run the java application. A Classpath is mandatory, the default path is . which is used if the java virtual machine can't find a user defined path. (CLASSPATH environment variable, -cp flag or Class-Path: attribute in a jar manifest)
The classpath is the conventional way to tell the Java compiler and the Java runtime where to find compiled classes. It is typically a sequence of JAR file names and directory names. The classpath used by the compiler and the runtime system don't have to be the same, but they typically "should be*, especially for a small project.

 
For example, an Eclipse build path for a project includes the other projects that it depends on, and lists any additional library JARs that the project contains / relies on. It also lists the packages in the current project that downstream projects can depend on.

(If you are using Maven for your project, the IDE buildpath mechanism is secondary to the dependencies declared in the POM files. For example, using Eclipse with the m2eclipse, the buildpath is synthesized from the POM files.)

Developing Restful Web services Using IBM JAX-RS

Java™ API for RESTful Web Services (JAX-RS) is a programming model that provides a mechanism for developing services that follow Representational State Transfer (REST) principles. Using JAX-RS, development of RESTful services is simplified.

The IBM® implementation of JAX-RS provides an implementation of the JAX-RS specification.

IBM JAX-RS includes the following features:
  • JAX-RS server runtime
  • Standalone client API with the option to use Apache HttpClient 4.0 as the underlying client
  • Built-in entity provider support for JSON4J
  • An Atom JAXB model in addition to Apache Abdera support
  • Multipart content support
  • A handler system to integrate user handlers into the processing of requests and responses
Required Jars:
  • jsr311-api.jar
  • commons-lang.jar
  • slf4j-api.jar
  • slf4j-jdk14.jar
  • ibm-wink-jaxrs.jar
Step 1 - Creating the Root Resource
As defined in the JAX-RS specification, by default, resource instances are created per request.  For the JAX-RS runtime environment to create a resource instance, you must have either a constructor with no argument or a constructor with only JAX-RS annotated parameters(@Context,@HeaderParam,@CookieParam,@MatrixParam,@QueryParam,@PathParam). present.
I created a class with no constructor.
public class HelloWorld {

}
Step 2 – Adding path to resource
Add a @javax.ws.rs.Path annotation to HelloWorld class.  For each @javax.ws.rs.Path annotation, set the value as the part of the URL after the base URL of the application.

@Path("/home")
public class HelloWorld {
..
}

Step 3 – Adding method to resource
 I have created a method called welcomeMessage and annotate the method as GET
@Path("/home")
public class HelloWorld {

      @GET
      public String welcomeMessage(){
            return "Welcome to Our Websphere Portal JAX-RS";
      }    
}
Whenever an HTTP GET request is received by this class, the welcomeMessage method will be invoked.


Step 4 – Creating a javax.ws.rs.core.Application sub-class
For non-JAX-RS aware web container environments (most environments are currently non JAX-RS aware), a javax.ws.rs.core.Application sub-class needs to be created which returns sets of JAX-RS root resources and providers. In the following example, there is only one root resource that will need to be returned.
public class RestConfig extends  Application{
      public Set<Class<?>> getClasses() {
            Set<Class<?>> classes = new HashSet<Class<?>>();
            classes.add(HelloWorld.class);
            return classes;
      }
}
Step 5 – Configure the web.xml file for the JAX-RS application
We need to modify the web.xml so that the servlet container knows that the web application is JAX-RS supported and what are the JAX-RS classes by specifying the application configuration sub class as a parameter.
<web-app id="WebApp_ID" version="2.5" 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">
      <display-name>RestExample</display-name>
      <servlet>
                  <servlet-name>REST</servlet-name>
                  <servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
                  <init-param>
                        <param-name>javax.ws.rs.Application</param-name>
                        <param-value>com.ourwebsphereportal.jaxrs.RestConfig</param-value>
                  </init-param>
                  <load-on-startup>1</load-on-startup>
            </servlet>
            <servlet-mapping>
                  <servlet-name>REST</servlet-name>
                  <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>


on accessing,

where RestExample is context root

Wednesday, December 2, 2015

Converting Java object to or from JSON using Jackson

1. Quick Reference for conversion from Java to JSON or vice-versa..

we will show you how to use Jackson 2.x to convert Java object to / from JSON
 a. Convert Java object to JSON -  writeValue(...)


ObjectMapper mapper = new ObjectMapper(); Staff obj = new Staff(); //Object to JSON in file mapper.writeValue(new File("c:\\file.json"), obj); //Object to JSON in String String jsonInString = mapper.writeValueAsString(obj);
 

b. Convert JSON to Java object, readValue(...)

 
ObjectMapper mapper = new ObjectMapper(); String jsonInString = "{'name' : 'santhosh'}"; //JSON from file to Object Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class); //JSON from URL to Object Staff obj = mapper.readValue(new URL("http://test.com/api/staff.json"),
Staff.class); //JSON from String to Object Staff obj = mapper.readValue(jsonInString, Staff.class);
 
 
 

2. Jackson 2 Dependency

pom.xml
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.6.3</version>
 </dependency>


3. POJO (Plain Old Java Object)

Convert a Staff object into a JSON formatted string.

Jackson2Example.java
 package com.santhosh.json;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

 public static void main(String[] args) {
  Jackson2Example obj = new Jackson2Example();
  obj.run();
 }

 private void run() {
  ObjectMapper mapper = new ObjectMapper();

  Staff staff = createDummyObject();

  try {
   // Convert object to JSON string and save into a file directly
   mapper.writeValue(new File("D:\\staff.json"), staff);

   // Convert object to JSON string
   String jsonInString = mapper.writeValueAsString(staff);
   System.out.println(jsonInString);

   // Convert object to JSON string and pretty print
   jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
   System.out.println(jsonInString);

  } catch (JsonGenerationException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 private Staff createDummyObject() {

  Staff staff = new Staff();

  staff.setName("mkyong");
  staff.setAge(33);
  staff.setPosition("Developer");
  staff.setSalary(new BigDecimal("7500"));

  List<String> skills = new ArrayList<>();
  skills.add("java");
  skills.add("python");

  staff.setSkills(skills);

  return staff;

 }

}


Output
//new json file is created in D:\\staff.json"

{"name":"santhosh","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}

{
  "name" : "santhosh",
  "age" : 33,
  "position" : "Developer",
  "salary" : 7500,
  "skills" : [ "java", "python" ]
}

5. JSON to Java Object

Read JSON string and convert it back to a Java object.
 
Jackson2Example.java
package com.santhosh.json;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

 public static void main(String[] args) {
  Jackson2Example obj = new Jackson2Example();
  obj.run();
 }

 private void run() {
  ObjectMapper mapper = new ObjectMapper();

  try {

   // Convert JSON string from file to Object
   Staff staff = mapper.readValue(new File("D:\\staff.json"), Staff.class);
   System.out.println(staff);

   // Convert JSON string to Object
   String jsonInString = "{\"name\":\"santhosh\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
   Staff staff1 = mapper.readValue(jsonInString, Staff.class);
   System.out.println(staff1);

   //Pretty print
   String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff1);
   System.out.println(prettyStaff1);
   
  } catch (JsonGenerationException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}
 
 
Output
Staff [name=santhosh, age=33, position=Developer, salary=7500, skills=[java, python]]

Staff [name=santhosh, age=0, position=null, salary=7500, skills=[java, python]]

{
  "name" : "santhosh",
  "age" : 0,
  "position" : null,
  "salary" : 7500,
  "skills" : [ "java", "python" ]
}