Thursday, 20 November 2014

HOW TO BUILD JSON STRUCTURE IN JAVA EE 7 USING JSON-PROCESSING (JSON-P)


JSON is just like XML. 

JSON-P provides two different programming models to process JSON documents:

* Object Model API            * Streaming API

Object Model API is similar to DOM API for XML. It provides classes to model
JSON objects and arrays in a treelike structure that represent JSON data in memory.

To create this tree structure : we use the Builder classes

* Class JsonObjectBuilder -> used for creating a JSON object & returns  JsonObject object instance.

* JsonArrayBuilder - used for creating a JSON Array (might be inclusive to a JsonObject or a standalone JsonArray)  and returns a JsonArray object instance.

* All the classes :

Json
JsonObject
JsonArray
JsonObjectBuilder
JsonArrayBuilder

are available under the package: javax.json

Lets take an example:

This example is about a student and his skills.
{
  "student" : {
            "id" : "999",
            "name" : "dinesh",
            "address" : {
                "city" : "hyderabad"
                "country" : "india"
              },
             "skills": {
                 "languages": [
                     {
                        "language" :  "english"
                        "reading" : "good"
                        "writing": "average"
                        "speaking" : "excellent"
                    },
                    {

                        "language" :  "telugu"
                        "reading" : "good"
                        "writing": "average"
                        "speaking" : "good"
                    }
                  ]
           }
      }
  }

Note:

JSON structures:

 *Any thing included in { } is considered as a JsonObject


 *Any thing included  in [ ]  is considered as a JsonArray


 * Also, note that a JsonObject may internally can have any number of other 

Json objects and Arrays.

*Even, Json arrays that are included in [ ] brackets are also internally included in
json objects, means array elements must be included in json objects i.e, { }



Now, let us get some hands-on...

//this class has many factory methods useful for object , array creations
import javax.json.Json;

 import javax.json.JsonObject;

 import javax.json,JsonArray;


public class StudentInfoBuilder { public JsonObject buildStudentInfo() {


return Json.createObjectBuilder().add("student", Json.createObjectBuilder()
                 .add("id", "999")
                 .add("name", "dinesh")
                 .add("address", Json.createObjectBuilder()
                                                   .add("city", "hyderabad")
                                                   .add("country", "india"))
                 .add("skills", Json.createObjectBuilder()
                                             .add("languages", Json.createArrayBuilder()
                                                                  .add(Json.createObjectBuilder()
                                                                                    .add("language", "english")
                                                                                    .add("reading", "good")
                                                                                    .add("writing", "average")
                                                                                    .add("speaking", "excellent"))
                                                                  .add(Json.createObjectBuilder()
                                                                                    .add("language", "telugu")
                                                                                    .add("reading", "good")
                                                                                    .add("writing", "average")

                                                                                    .add("speaking", "good"))
                                          )
                 )).build();
          }

 }
 

Json.createObjectBuilder() method is used to build a JsonObject

Json.createArrayBuilder() method is used to build a JsonArray

.add() method for adding  the respective elements for either an object  / array.


Hope this is helpful....


Thursday, 16 October 2014

DEFAULT HIBERNATE CONNECTION DETAILS FOR MYSQL & POSTGRESQL

mysql
-------

driver:  com.mysql.jdbc.Driver
diaelect: org.hibernate.dialect.MySQLDialect
database: mysql
username: root
password: ''
url: jdbc:mysql://localhost:3306/mysql

postgres
------------

driver: org.postgresql.Driver
dialect: org.hibernate.dialect.PostgreSQLDialect
database: hibernatedb
username: postgres
password: password
url: jdbc:postgresql://localhost:5432/postgres

JAXB Marshalling -TRANSFORMING OBJECT TO AN XML FILE



Classes used here:

Customer.java
Address.java
JAXBMarshall.java

Customer and Address are just plain old java objects(POJO).

Annotation used in Customer.java:

@javax.xml.bind.annotation.XmlRootElement;
@javax.xml.bind.annotation.XmlAttribute;
@javax.xml.bind.annotation.XmlElement;

We have to annotate either Getter methods or instance fields with the above annotation.

JAXBMarshall is the main class the transforms the Object into an XML file.

Here, First we need to get an instance of JAXBContext using its static method newInstance();

newInstane() has an argument - class name. In our example, it is Customer.

By using the instance of JAXBContext we have to create a Marshaller.

marshaller instance's marshall() method - marshalls the object state.




Customer.java


package com.marshal.example;


import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author dinesh
 */

@XmlRootElement
public class Customer {
    
    private int id;
    
    private String name;
    
    private String mobileNumber;
    
    private List<Address> address;
    public Customer() {
    }

    public Customer(int id, String name, String mobileNumber, List<Address>) {
        this.id = id;
        this.name = name;
        this.mobileNumber = mobileNumber;
        this.address = address;
    }

    @XmlAttribute
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

   @XmlElement
    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }

    @XmlElement
    public List<Address> getAddress()
        return address;
    }

    public void setAddress(List<Address> address) {
        this.address = address;
    }
      
}

Address.java
package com.marshal.example;

/**
 *
 * @author dinesh
 */
public class Address {
 
     private int streetNumber;
     private String city;
     private String state;
     private String country;
     private Long zipcode;

    public Address() {
    }

    public Address(int streetNumber, String city, String state, 
        String country, Long zipcode) {
        this.streetNumber = streetNumber;
        this.city = city;
        this.state = state;
        this.country = country;
        this.zipcode = zipcode;
    }

    public int getStreetNumber() {
        return streetNumber;
    }

    public void setStreetNumber(int streetNumber) {
        this.streetNumber = streetNumber;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public Long getZipcode() {
        return zipcode;
    }

    public void setZipcode(Long zipcode) {
        this.zipcode = zipcode;
    }
          
}
JAXBMarshall.java
package com.marshal.example;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 *
 * @author dinesh
 */
public class JAXBMarshal {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)  throws JAXBException{
        // TODO code application logic here
        
        JAXBContext context = JAXBContext.newInstance(Customer.class);
        
        Marshaller m=context.createMarshaller();
        
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        
        Address homeaddr =new Address(1,"Warangal","Telangana","India",506002L);
        Address offaddr =new Address(1,"Hyderabad","Telangana","India",500044L);
        
        ArrayList list = new ArrayList<>()<address>
        
        list.add(offaddr);
        list.add(homeaddr);
        
        Customer customer = new Customer(1,"Dinesh","9999111199",list);
        
        try {
            m.marshal(customer, new FileOutputStream("/home/dinesh/customer.xml"));
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
    
}

Output -XML file


<?xml version="1.0" encoding="UTF-8"?>
<customer id="1">
    <address>
        <city>Hyderabad<city>
         <city>Telangana<city>
         <city>Warangal<city>
         <city>1<city>
         <city>500044<city>
    </address>
      <address>
        <city>Hyderabad<city>
         <city>Telangana<city>
         <city>Warangal<city>
         <city>1<city>
         <city>500044<city>
    </address>
    <mobileNumber>9999111199<mobileNumber>
    <name>Dinesh<name>
<customer>



Sunday, 21 September 2014

MOST USEFUL COMMON EXPRESSIONS IN ENGLISH

You can use these expressions in your daily life:


1. Twenty Four Seven (24X7) - (24X7-365)

Meaning: Every Minute Every Day

Example: 

> I have been working 24/7 on my short film.
          (A kind of an Exaggeration)

> You can access our website 24/7

2. Get the ball rolling

Meaning: Lets start now

> If you don't get the ball rolling on the application soon, you'll miss soon. 

3. Sleep on it

Meaning: THINK ABOUT SOME THING

> Before taking a decision, you must sleep on it.

> I will get back to you tomorrow. I will sleep on it.

(means -I will say my decision soon i have think about it once).

4. I am broke

Meaning: I have no Money

5. Like the back of my hand

Meaning: Knows much about something

> I know paris like the back of my hand.

6.  Give me a hand

Meaning: Helping

> would you give me a hand
  (can you help me)

7. In ages

Meaning: for a long time

> I haven't seen him in ages.
  (I haven't seen him for long time)

8. SICK & TIRED

Meaning: don't want to do any more

> I am sick & tired of doing assignments.


Saturday, 20 September 2014

PRIVATE CONSTRUCTORS IN JAVA

Usage: - How to make a class whose instance cannot be created by any other class but except itself-(Singleton Design Pattern)

We generally know that constructors in java uses public access modifier. But in fact, constructors can use other modifiers like private

Eg:

 package com.sample;

 public class MyClass {

   // a zero-argument constructor

    public MyClass(){}

     ...
     ...


The above MyClass class can be used by other classes by importing it and can get an instance of that class.


What if the constructor uses the a private access modifier like

Eg:

 public class MyClass {

   // a zero-argument constructor

    private MyClass(){}

     ...
     ...

In the above case, no other classes can get an instance of the above classes since it is implementing a private constructor.


Let's see one more example:

public class ClientService {

    private static ClientService clientService = new ClientService();

  //private constructor 

    private ClientService() {}

    public static ClientService createInstance() {

        return clientService;
    }


}

The above example uses a private constructor, where its object is created within itself and used, this scenario restrict others to get an instance.


Private constructors are mainly used in Singleton Design Pattern, where a class can be instantiated only once. In such cases, we can use private constructors.

Tuesday, 16 September 2014

WHAT IS MAVEN ? A PROJECT MANAGEMENT TOOL (UPDATED)

MAVEN is a Java Dependency Management tool. You wonder what is a dependency management tool.

Its Simple...

For instance, if your working on a project which uses many external jar files, which you generally download from the web and then you configure them in the classpath- which is a conventional way of doing.

But if you use maven tool which is basically command line tool(can also be integrated with popular IDEs like NET BEANS & ECLIPSE), you can create a project without this overhead 
How?

Behind the scenes, maven actually works for us a lot to get the required jars from a central repository(collections of jars),  but as a developer only need to do is to supply it the information specifically related to the project you want to create.

We can supply our project information(required jars-simply called as dependencies) through a simple XML file which is called pom.xml

Let us take an example, consider I am developing a JMS application which uses JMS
(Java Messaging Service) API jar file, here for your application this is a dependency, without which you can't create your app. 

And also consider, you are using logging API(requires log4j jar file) in your project for logging purposes, so this is also considered as another dependency.

so we need JMS jar and log4j jar for my project to be completed,so specify them in pom.xml file

Example:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                          http://maven.apache.org/xsd/maven-4.0.0.xsd">

        <groupId>....your groupid or your company name..</groupId>
       <artifactId>..your project name...</artifactId>
    <version>..your project build version number---</version>
       <modelVersion>4.0.0</modelVersion>

<!-- Here are your project dependencies-->

    <dependencies>
        <dependency>
                       <groupId>javax.jms</groupId>
                      <artifactId>javax.jms-api</artifactId>
                      <version>2.0</version>
        </dependency>
        <dependency>
                      <groupId>log4j</groupId>
                      <artifactId>log4j</artifactId>
                      <version>1.2.17</version>
        </dependency>
  </dependencies>
  <build>
           <!-- I can use various maven plugins for different use cases- like reporting
                 ,  mailing, packaging(such jar, war) -->
          <!-- Here I am using a reporting plugin - Maven-Surefire-Report-Plugin
            .This plugin generates a html report showing all my test case failures  
           passed cases & skipped test cases--> 
         <!-- you have use plugins & dependencies according to your project needs--> 
      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                    </dependency>
 
          </plugin> 
      </plugins>    
  </build>
</project>


JMS jar details are

                   <groupId>javax.jms</groupId>
                  <artifactId>javax.jms-api</artifactId>      
                    <version>2.0</version>

log4j jar details are

                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                 <version>1.2.17</version>


Terminology :

groupId
artifactId
version

are tags that maven generally uses to specify the project structure.

groupId is generally a name which represents a company the project belongs to.

artifactId is name of your project

version is the build release version

Plugins are placed under build tag. As aforementioned, you can use any plugins such as war plugin creates a war file for a web application, jar plugin creates a jar file. In the above example, I have defined a surefire-report plug-in , this creates an HTML report for your tests if there are any tests in your project.

Sample Surefire Report 

You can configure your plugins using a <configuration> tag under <plugin> tag.

Let us, you want your surefire-reports, i.e HTML file, you this file to be stored in an outtput directory called newsite. you can configure like this


      <plugins>
          <plugin>                     
                     <dependency>
                              <groupId>org.apache.maven.plugins</groupId>
                              <artifactId>maven-surefire-report-plugin</artifactId>
                              <version>2.16</version>

                              <scope>test</scope>
                              <configuration>                                      
                     <outputDirectory>${basedir}/target/newsite</outputDirectory>
                              </configuration>
          
          </dependency>
 
          </plugin> 
      </plugins>    

${basedir}  is the default variable represents the path of your project.

say your project is at c:/documents/MyProject  

so ${basedir} points to this path.

By default, Surefire-report plugin stores its reports in site folder under target.


Maven  has build life cycle phases. During this life cycle phases, it performs various operations. Mostly the build phase names are self-explanatory.

Maven's default build life cycle phases : validate, compile, test, package, integration-test-process, verify, install and deploy.

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test - process and deploy the package if necessary into an environment where integration tests can be run
  • verify - run any checks to verify the package is valid and meets quality criteria
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.


Complete list of Build Phases

<scope> represents this plugin is going to be used in only test phase of the build life cycle.

One of Maven plug in's : maven-compiler-plugin. Its scope is only up to compile build phase. Because it is going to be used only in compiling the classes of your project. so you can specify the <scope>compile</scope> for compiler-plugin.
  

Important Note: Once maven builds a project - you are able to see a new target folder, where all distributions(war, jar) , surefire reports , and compiled classes are placed in that target folder.

 Until you have pom.xml file in your project folder, you cannot execute your maven goals.

Oh! what are Maven goals? How to execute maven using command line?

Each and every maven build phases binds to some goals:

say:

assume this format for explanation - Build Phase: Goals

>>>>>>>>>>>>>>>>
compile phase : compiler:compile
>>>>>>>>>>>>>>>

During compile phase, a compiler plugin uses these goals to perform its executions.

For example, Maven-compiler-plugin as another goa

compiler: testCompile (here, compiler represents plugin & testCompile is the goal)

Whats the difference between two goals?

Here, the plugin used is same - maven-compiler-plugin. But these two goals: compile & testCompile are executed in two different build phases

Execute maven compile goal  like this
(on command line)


< proj path>$ mvn compiler:compile 

Note: In proj path - you must have pom.xml file.

This only compiles your main source files. (Exclusdes test source files)

Whereas, testCompile goal is bound to test-compile phase 

As I mentioned, test is also a build phase. test-compile is executed just before test build phase. These test classes are excluded during compilation of normal source files.

>>>>>>>>>
test phase: surefire-report:report
 >>>>>>>>>

Here, Build phase is test.  Plugin used here is maven-surefire-report-plugin.

surefire-report:report

surefire-report represents plugin

report represents goal

Note: This is one of the reporting plugin I have used in test phase. There can be n number of maven reporting plugins. you have decide which to one to choose.
This post will be updated in future also. 
An Updated on 25-Feb-2015