Sunday, 1 February 2015

HOW TO INSTALL TESTNG FRAMEWORK AS A PLUGIN IN ECLIPSE

Testng framework is available on Eclipse IDE as a plugin.

Steps to Install:

Step1:

go to "Help" Menu -> click on "install new software"



Step2:

Click Add.... button 

This opens a pop up - Add Repository

For Name Field - enter any name for the installation location

Location Filed:

In location field enter url as per eclipse IDE version


Step3:

After adding respository location

select the checkbox "TestNG"



Step4:

Click next -  be patient it takes some time - then


click - "I accept the terms ...."



Step5:

Click install- you can also choose to run in background

- now this starts installation



NOTE:

To install any new plugin you follow this way of adding the respective software location as a repository.

Thank You
Hope you like it...

Monday, 5 January 2015

TRY-WITH-RESOURCES Statement in Java 7

In java 7, try statement has been enhanced.

Whenever if some resource is used it must be closed once its use is completed.

So, conventionally a developer must need to close the resources -say a database resource, a file handler and any such resource.

generally, this is done in "finally" 

Example:

using try statement - before java 7

...

static String readMe( String path) {

    BufferedReader br = new BufferedReader ( new FileReader(path) );

    try{
             return br.readLine();

    }
   finally
   {
          if( br != null ) 
                br.close();
   }


}

...

With java 7, you as a developer no need to close the resources. But you must use try-with-resources statement instead of normal try statement.

A try-with-resource statements has an open bracket '(' and a closed bracket ')' and in between these brackets you must declare the resource.

Example:

...

static String readMe( String path) {

   try ( BufferedReader br = new BufferedReader( new FileReader(path) ) ){

            return br.readLine();
   }

}

...

Note:


You can close the resources using try-with-resources statement in java 7 for any class that implements either AutoCloseable interface or Closeable interface.

Classes that implements AutoCloseable interface - Click Here

Classes that implements Closeable interface - Click Here


Here, the BufferedReader class implements AutoCloseable interface.

Regardless of whether the try statment executes nomally or Abruptly , the resource will be closed.

Note:

You can declare as many resources separating them with semi-colon.

Example:

....

try ( java.util.jar.JarFile jr = 
                        new java.util.jar.JarFile(jarFileName) ;
        java.util.zip.ZipFile zp =
                       new java.util.zip.ZipFile(zipFileName)
   ) 
{


 ...// create a jar file logic & zip file logic



// once the execution completes - resources jar and zip file handler are also
closed automatically since they implement AutoCloseable interface.


Hope this gives a brief intro.
Please share this.     

Monday, 22 December 2014

STATIC METHODS & DEFAULT METHODS IN AN INTERFACE - JAVA 8 EXICITING FEATURES

Static Methods in interfaces

Prior to Java 8, we have many utility classes with static methods which are commonly used.

For Example, for Collection interface, we have utility class Collections


likewise,

path - Paths

Executor - Executors

So, To reduce the utility classes, java designers introduced static methods
in interfaces.

Note:

. A static method contains a static modifier.

. They are implicitly public.

. Have implementation logic within the interface.

 
Example:
public interface Blog {
int followers_count = 0;
void comment();
//A static convenience method
public static void subscribe(){
//implementation logic
System.out.println("you have successfully subscribed");
}
}

DEFAULT METHODS in an interface 

From Java 8,  you can also declare DEFAULT methods in interface.


DEFAULT METHODS is new feature added in Java 8.


To understand the concept of default methods and its purpose, lets consider that
I have designed a library which is having the above declared interface Blog.

Lets take an assumption that, those who want to make blog must implement my interface Blog.

So I have distributed the interface to all the interested people who want to blog.

 Now, the many of my bloggers are satisfied with the methods available in the 
interface.

But, If one of the bloggers wants to add his/her own methods to the interface, like say adding a new method share().

So They would have to request me to add the method share() method and again I would distribute the library to all the bloggers.

Now, If the bloggers try to use the this new library - the old code breaks because 
share() method must be implemented by all the bloggers.

In java 8, this problem is alleviated by introducing DEFAULT methods in the interface.

default methods have a default modifier and an implementation logic in the interface itself.

So, If I make share() as a default method in the interface - old code breaking problem will be solved.

Thanks to Default methods.

Note:

. Must have a default modifier

. have an implementation logic within the interface.


Example:


public interface Blog {
int followers_count = 0;
void comment();

//A static convenience method
public static void subscribe(){
System.out.println("you have successfully subscribed");
}

default String share(){
System.out.println("You have shared your blog");
return "Success";
}
}



 Hope this is helpful.                                                     
   
 If you like this, please share.

Sunday, 21 December 2014

USING UNDERSCORES IN NUMERIC LITERALS -JAVA 7 FEATURE

Since Java 7, you can use underscores in the numeric literals.

Example:

// declaring a float value

float acc_balance = 5_000L;

Here, the value of the variable is 5000.0

 
Underscores in numeric literals are mainly used to separate the
significant parts of number.


For instance, lets consider 10-digit mobile number in india.


In a 10-digit mobile number, we have two significant parts:

. First four numbers XXXX represents the network operator.

. the last numbers NNNNNN represents the subscriber number.

XXXX-NNNNN

Example:

int phoneNumber = 9849_751031;

This new feature is intended to improve the code readability.


Some examples where you need this feature- to represent:

 . Debit Card Number
 . Credit Card Number
 . Social Security Number


This feature is only a developer convenience.

Note: Compiler will ignore underscores in number literals.  

Example:

 public class Java7Literals {

    public static void main(String args[]){

        long debitCard = 5555_3333_7777_9999L;

        System.out.println("debit card number: "+ debitCard);
      
        }

   }


output:

 debit card number: 5555333377779999

 Here compiler ignored the underscores.

As I said it is a developer convenience.


Some example declarations:

long ssNumber = 999_89_9999L;

printed as: 999899999

float pi = 3.14_15F;

printed as: 3.1415


Rules:
---------

places where not to place the underscores in numeric literals.


. At the beginning and at the end of the numbers


ILLEGAL

 long x3 = _77L;

int x5 = 55_;


. Adjacent to decimal point in a floating point literal

ILLEGAL

float pi =  3._14_15F;


LEGAL

float pi = 3.14_15F;


 .Prior to D or L or F suffix

ILLEGAL

float pi  = 3.14_5_F;

.In positions where strings of digits is exepcted

ILLEGAL

int x5 =  0_x52

// cannot put underscore in the 0x radix prefix

int x6 = 0x_52

//cannot put the underscore at the beginning of the number


LEGAL


int x7  = 0x5_2;


Note: 

For illegal usage of the underscores as described above may yield an error

error: illegal underscore.

This feature can be applied to primitive data types in any supported 
base - octal, hexadecimal, binary  or decimal. 


the underscores in hexadecimal and binary are used in identifying the
parts of commands

Example:

int commandInHex = 0xE_25D5_8C_7;
int commandInBinary = 0b1110_0011111111010101_10001100_0111;


  Hope this is helpful

 If you like this, please share.

Thursday, 4 December 2014

FunctionalInterface ANNOTATION TYPE - USAGE OF @FunctionalInterface

FunctionalInterface

An interface with one abstract method declaration is known as Functional Interface.

eg:

public interface ExampleIfc {

    void showExample();

}

An interface with more than one abstract methods are not considered as functional
interfaces.

eg:

Not a functional interface

public interface ExampleIfc {

 void showExample();

 boolean executeExample();

}

. FunctionalInterface Annotation type:

FunctionalInterface annotation type (@FunctionalInterface) is a marker interface.

Note: A marker interface is one which indicates or hints the compiler.

using this annotation type on an interface makes the compiler verify whether
the declared interface contains one and only one abstract method.

Note:  you must not use this annotation type on

CLASSES 

ANNOTATION TYPES

ENUMS

If used, yields a compile-time error.

. Can be used only on the interfaces with one abstract method.


LEGAL :


@FunctionalInterface
public interface Runner {
          void run();
}

This compiles fine.


ILLEGAL:


@FunctionalInterface
public interface ExampleIfc {

     void showExample();

     boolean executeExample();

}

Compile-time error : because two abstract methods.


ILLEGAL

 @FunctionalInterface
public class XyzClass {
    public void xyzMethod() {
           ....
     }
}

 Compile-time error : because annotation type cannot be applied on classes.



Note: The concept of the Functional interface is very important to learn about the Java 8 lambda expressions.

 Hope this is helpful

 If you like this, please share.

Wednesday, 3 December 2014

GLASSFISH APPLICATION SERVER - COMMAND LINE INTERFACE (CLI) COMMANDS


Glassfish Application Server is a Java EE 7 compliant Application Server.


We can deploy the Java Application archives (jar, war, ear) manually two ways:

. Using  Glassfish Admin Console using its URL

Default URL: http://localhost:4848

The other new way is 

. Using Command Line Interface (CLI) - "asadmin"

"asadmin" - is a command line tool available in the glassfish server installation folder
under the domain directory

Example:

In Windows

c:/glassfish/domain/domain1/

In Linux

/home/dinesh/glassfish/domain/domain1/

Functions of asadmin:

. we can perform all the functions that are available through a glassfish server admin
console

. Inorder to do operations on application server, first we need to start the domain
 using the command  ----> start-domain

asadmin> start-domain

We will see the following message if the domain is started successfully:

 Waiting for domain1 to start .............................................
 Successfully started the domain : domain1
domain  Location: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1
Log File: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.





Some of useful commands of asadmin:

To start and stop the glassfish application server  domain:

. <start-domain>
. <stop-domain>

To deploy and undeploy an application archive - jar, war, ear.
 
. <deploy>
. <undeploy>

eg:
         asadmin> deploy /home/dinesh/example.jar

         asadmin> undeploy /home/dinesh/example.war


To see the list of the already deployed applications.

. <list-components>

eg:

        asadmin> list-components



To create jdbc connection pool

. <create-jdbc-connection-pool>

eg:

asadmin> create-jdbc-connection-pool 
--datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlDataSource  
--restype javax.sql.DataSource
 --property portNumber=3306:user=root:password=root:
serverName=localhost:databaseName=mydatabase   sample_mysql_pool

Command create-jdbc-connection-pool executed successfully.

 To test the created jdbc connection pool use:
 

. <ping-connection-pool>

eg:

asadmin> ping-connection-pool sample_mysql_pool

Command ping-connection-pool executed successfully.

To create jdbc resource using the above created jdbc connection pool.

. <create-jdbc-resource>

 eg:

asadmin> create-jdbc-resource --connectionpoolid sample_mysql_pool jdbc/SampleDS 

Command create-jdbc-resource executed successfully.

 asadmin is also used to create jms resources, java mail resources and many more commands are used in real-time.

. <create-jms-host>
. <create-jms-resource>
. <create-jmsdest>
. <create-jndi-resource>

Note:

Glassfish is a reference implementation, created by JCP Team.
 Please refer to glassfish reference manual for more concepts:

useful links: glassfish reference - > asadmin commands

VARIABLE ARGUMENTS - VARARGS -JAVA 5 FEATURE

VARIABLE ARGUMENTS:

It is a feature introduced in Java version 5. It is very handy feature in some situation where you don't know the exact number of arguments for methods.


It is generally known as VARARGS. It is represented by a symbol
ellipsis(...)

Example:
class CountMarks{

//create a static method inorder to access in the main method

static void add(int... params){
          int result=0;
          for(int i:params){
             result=result+i;
          }
          System.out.println("sum of marks: "+result);
      }
    public static void main(String args[]){
        m(10);
        m(10,20,30,23,23,23,23,23);
    }
    }


Output:

sum of numbers: 10
sum of numbers: 175



Rules for varargs:


  1.  There should be only one variable argument in a method.
  2.  The variable argument must be the last argument.
Violating these rules leads to COMPILE TIME ERRORS;

Examples: 

Legal:

void sumUp(int... x) {}
//expects from 0 to many ints as parameters

void sumUp(char chr,int... x) {}
//expects first a char, then 0 to many ints

void sumUp(Salary... sal) {}
//expects 0 to many salary objects

ILLEGAL:

void sumUp(int x...) { }
 //Bad syntax

void sumUp(int... x,char... y) {}
 //too many varargs - rule 1 violated

void sumUp(String... s,char b){} 
// var-arg must be last argument-rule 2 
//violated


Note:  In the above example, We can pass as many numbers as we need, to do the same thing earlier we used to do method overloading. 


ENUM TYPE - DECLARATION ERROR

ENUM is a data type - using which can create a fixed set of constants.

Example:

package enum.example;

class EnumExample { 

  public static void main(String args[]){
     

     //Declaring ENUM here yields compile time error

     public enum Days { MON, TUE, SAT}
     

     for(Days d:Days.values()){
         System.out.println(d);
     }
  }

}


Output:

Compile time error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The member enum Days can only be defined inside a top-level class or interface
    Days cannot be resolved to a type
    Days cannot be resolved

 
Because we should include enum declaration inside a method

It's declaration should be inside a top-level class or interface.

so move the enum declaration to class level


package enum.example;

class EnumExample {  


    //Class-level declaration is correct

    public enum Days { MON, TUE, SAT}

    public static void main(String args[]){


     for(Days d:Days.values()){


         System.out.println(d);


     }


 }


}


Output:

MON
TUE
SAT

JAVA STATIC IMPORT - JAVA5 Feature

JAVA STATIC IMPORT

static import is used to access static members of a class without which you have to access static members using the class name.


Example:(without static import)


public class A {

public static void main(String[] args){

System.out.println("one");
System.out.println("two");
System.out.println("three");
System.out.println("four");
System.out.println("five");
System.out.println("six");


}


Example:(with static import)

import static java.lang.System.out; 

public class A {

public static void main(String[] args){

out.println("one");

out.println("two");

out.println("three");

out.println("four");

out.println("five");

out.println("six");

}
}



Output:

one
two
three
four
five
six

Here, output remains same but, we are accessing and printing Strings with preceding class name for static variable out


ADV: Reduces amount of code

CONDITIONAL OPERATOR IN JAVA - TERNARY OPERATOR - JAVA5 Feature

TERNARY OPERATOR

The conditional operator is a ternary operator (it has 3 operands) & used to evaluate Boolean expressions, much like an if statement.

Based on its condition -  it assigns a value to a variable.


Syntax:

X= (Boolean Expression)  ?   value1  :  value2

It assigns value1 if the Expressions evaluates to true, otherwise assigns value2.

Example:
public class Salary{

public static void main(String[] args){

int age=45;

String pension=(age>=50)?"Eligible for pension":"Not eligible for Pension";

System.out.println("Your are: "+pension);

}

}




Output:

Your are: Not eligible for Pension


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>