Saturday, 28 February 2015

CREATE PDF FILES USING iTextPdf Jar LIBRARY - BASIC EXAMPLE

iText is an API for creating and manipulating PDF files in java.

Note: you must add itextpdf jar file to your build path in order to use itext pdf API.

Download Link:

itextpdf-5.5.5.jar

(or)

Using Maven:

If you are interested to use a maven dependency - add the following to your dependencies list:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.5</version>
</dependency>

Note: you can continue reading this post even if you don't no maven.

If you are new to maven - click here ---> What is Maven & how to use it?

This post explains the creation of PDF with a specifed format like this:

Example PDF :  CWCReport.pdf

Important Classes:

Mostly all the classes I am using here are from same package:
com.itextpdf.text package


>>Document - Objects of this classes resembles the real world PDF document.

//creating an instance of Document
Document document = new Document();

Document class has different overloaded constructors. I am using one which specifies the page size of A4.

//creating an instance of Document
Document document = new Document(PageSize.A4.rotate());

Here,
>>PageSize  - class having all standard page formats like A1-A10 , B1-B10

rotate() method - creates a landscape PDF.

>>PdfWriter

* After defining a Document object - define PdfWriter object

//creating PdfWriter instance using a static method getInstance

//You can specify the path for PDF file creating using FileOutputStream
 OutputStream file=new FileOutputStream(new File("/home/dinesh/CWCReport.pdf"));

For File pass you pdf path where you want to create on your file system.

Note: On windows, you may have you give \\ (double slashes) for file's path.
Like: c:\\home\\pdfs\\create.pdf

//Parameters document & FileOutStream file
PdfWriter.getInstance(document, file);

Defining Document Information using document object:

using document object - we can define the pdf author, subject, title, & creation date.

                 //defining an author
                document.addAuthor("Dinesh Dontha");

                 //defining a subject
                document.addSubject("CWC Matches List");
   
                // title on the document-window
                document.addTitle("CWC - Schedule");

                // creation date
                document.addCreationDate();

Opening a Document:

Note: Inorder to write content into the pdf document - you must open it first

//open a document
document.open();

Adding a Paragraph:

>> Paragraph

Objects of this classes resembles real-object Paragraphs - so to create a paragraph use an object of it.

Paragraph class extends a Phrase class.

Phrase is like a sentence.

Defining Paragraphs :

//create a paragraph - using a String argument
Paragraph para2 = new Paragraph("para1....");

//create a paragraph -using a Phrase

>>Phrase
 
Phrase is a series of chunks

Here, we also have Chunk class

Chunk is the smallest significant part of the text that can be added to
document.

//creating a phrase with no parameters
Phrase phrase = new Phrase();

//Phrase with a specified font
Phrase title =new Phrase("phrase1",new Font(FontFamily.HELVETICA, 32));

Note:

>>Font  class 

 FontFamily  is an ENUM defined inside Font class

//creating Paragraph by passing Phrase instance
Paragraph para2 = new Paragraph(phrase);

//creating Paragraph with specified Font
Paragraph para2 = new Paragraph("Paragraph Text", new Font(FontFamily.HELVETICA, 16));

 Adding New Blank Lines between Paragraphs:

Using Chunk class

>>Chunk

//adds a blank line
document.add(Chunk.NEWLINE);

Creating a table:

Use  PdfPTable class instance

>>PdfPTable

While creating the instance of PdfPTable - we can define the number of columns in that table

//create a table with 2 columns
PdfPTable table = new PdfPTable(2);

Using this instance, you can set some global properties for this table elements

//setting the table width in the document
table.setWidthPercentage(100);

Here, table extends complete width of page.

 //setting a padding for all cells
table.getDefaultCell().setPadding(10);

//setting an align of cell data      
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

Defining Table Cells:

we can add table cells using  addCell() method of PdfPTable class

//adding a basic cell using addCell() method

table.addCell("Match Date");
table.addCell("Between");

(or)

you can define table cells using PdfPCell class

>>PdfPCell
PdfPCell class has many overloaded constructors

//with no parameters
PdfPCell cell1 = new PdfPCell();

//with a Phrase paramter -defines the cell content with Phrase
Phrase p1 =new Phrase("Cell Content");

//defining cell with phrase as content
PdfPCell cell = new PdfPCell(p1);

Once defined a cell instance - we can override the properties that are
globally defined- defined on table i.e, PdfPTable object.

//overrides padding defined on table object
cellHeader2.setPadding(20);

**Note:
 //setting properties on PdfPTable object-"table" are not applicable for this particular cell defined using PdfPCell class

i.e,       table.getDefaultCell().setPadding(10);

Here, padding for all cells is 10. But, for this cell - it is 20.

//similarly this overrides - alignment property set on table(PdfPTable) object
cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);

Example:

All the data in this example are stored in a Map object.

Note: finally close the document object and file stream object.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/* GeneratePdf.java
 * Created on 26-Sep-2014
 */

public class CreatePdf {

 public static void main(String[] args) {

try {

 // creating a file stream object
 OutputStream file = new FileOutputStream(new File(
   "/home/dinesh/CWCReport.pdf"));

 // creating a document object - with A4 size
 // please see the effect of rotate() method -with and without it

 // rotate() method -creates a pdf in landscape format
 Document document = new Document(PageSize.A4.rotate());

 // must create a PdfWriter object -pass document and file output
 // stream
 PdfWriter.getInstance(document, file);

 // creating document info
 document.addAuthor("Dinesh Dontha");
 document.addSubject("CWC Matches List");
 document.addTitle("CWC - Schedule");
 document.addCreationDate();

 // must open a document -to put content
 document.open();

 // creating a Phrase
 Phrase title = new Phrase("Cricket World Cup-2015- Schedule",
   new Font(FontFamily.HELVETICA, 32));

 // creating a Paragrapgh with Phrase as parameter
 Paragraph para1 = new Paragraph(title);
 para1.setAlignment(Element.ALIGN_CENTER);

 // adding paragraph to document -this main heading for document.
 document.add(para1);

 // adding a blank line after - heading/title
 document.add(Chunk.NEWLINE);

 // creating a paragraph
 Paragraph para2 = new Paragraph(
   "Next upcoming league matches of Team India in the "
     + "giagantic Cricket World Cup-2015", new Font(
     FontFamily.HELVETICA, 16));
 para2.setAlignment(Element.ALIGN_LEFT);

 // adding a paragraph - this is infact the first paragraph in this
 // exxample
 document.add(para2);

 // adding a blank line after - first paragraph
 document.add(Chunk.NEWLINE);

 // adding all cell data to a Map object
 Map indiaMatches = new HashMap<>();

 indiaMatches.put("Sunday, March 6th 2015", "INDIA VS WEST INDIES");
 indiaMatches.put("Sunday, March 10th 2015", "INDIA VS IRELAND");
 indiaMatches.put("Sunday, March 14th 2015", "INDIA Vs ZIMBABWE");

 // Define a PDF table with 2 columns - Match Date & Between column
 // Names
 PdfPTable table = new PdfPTable(2);

 // Setting global table cell properties
 table.setWidthPercentage(100);
 table.getDefaultCell().setPadding(10);
 table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

 // table header creation -using PdfPCell class

 // creating table header -cell -first column - Match Date
 Phrase matchDate = new Phrase("Match Date", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader1 = new PdfPCell(matchDate);
 cellHeader1.setBackgroundColor(BaseColor.ORANGE);
 cellHeader1.setPadding(10);
 cellHeader1.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader1);

 // creating table header -cell -second column - Between
 Phrase matchBetween = new Phrase("Match Between", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader2 = new PdfPCell(matchBetween);
 cellHeader2.setBackgroundColor(BaseColor.ORANGE);
 cellHeader2.setPadding(10);
 cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader2);

 // creating cell data -other than table column headers- using
 // addCell()
 // method of PdfPTable object
 for (Map.Entry entry : indiaMatches.entrySet()) {
  table.addCell(entry.getKey());
  table.addCell(entry.getValue());
 }

 // adding table to Pdf document
 document.add(table);

 // finally close - document & file stream
 document.close();
 file.close();

} catch (DocumentException | IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
}

}

Source Code: Download
Note: To run it successfully change the file path.

Saturday, 14 February 2015

PROGRAM FOR PRINTING ALL PERMUTATIONS OF A STRING - JAVA

Let us say -

String str = "abc"

As the length of the str is 3,  it should have 3! (factorial - 3*2*1) permutations - 6

[abc acb bca bac cab cba]


Example:

It builds all permutations recursively looping through all the characters - char by char

Here I have defined 3 custom methods - All 3 methods are looped after every character.

appendBefore -
appendAfter
appendMiddle

Go Over the code - it is commented properly

If not understood - just try to execute it once
package testing;

import java.util.ArrayList;
import java.util.List;

public class Permutations {

 /*
  * You will get n! (factorial) - permutations from this
  * 
  * Just like this Example: abc (3! = 6 permutations) 
  * [abc acb bac bca cab cbc]
  * 
  */
 static String str = "abcd";
 static char[] ch = str.toCharArray();
 static List s1 = new ArrayList<>();
 static List s2 = new ArrayList<>();

 public static void main(String[] args) {

  // s1 - list stores initial character from the string
  s1.add(String.valueOf(ch[0]));

  // recursive loop - char by char
  for (int k = 1; k < ch.length; k++) {

   // adds char at index 0 for all elements of previous iteration
   appendBefore(s1, ch[k]);
   
   // adds char at last index for all elements of previous iteration
   appendAfter(s1, ch[k]);
   
   /*adds char middle positions like a^b^C - if prev list stores
    * elements whose size() is 3 - then it would have 2 positions fill
    * say d is next char - d should be filled in _^_^_ _ positions are
    * previous permutations for 3 chars a,b,c(i.e 6 permutations
    */
   appendMiddle(s1, ch[k], k);
   
   /*for every iteration first clear s1 - to copy s2, which contains
   previous permutations*/
   s1.clear();
   
   /* now copy s2 to s1- then clear s2
   - this way finally s2 contains all the permutations*/
   for (int x = 0; x < s2.size(); x++) {
    s1.add(s2.get(x));
   }
   //shows how it is building - all iterations
   System.out.println(s1);
   s2.clear();
  }
  System.out.println("Total Permutations for given string "+str+" are "+s1.size());
 }

 private static void appendMiddle(List str, char ch, int positions) {
  for (int pos = 1; pos <= positions - 1; pos++) {
   for (int i = 0; i < str.size(); i++) {
    s2.add(str.get(i).toString().substring(0, pos) 
    + String.valueOf(ch)
    + str.get(i).toString().substring(pos, str.get(i).toString().length()));

   }
  }
 }

 private static void appendBefore(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(String.valueOf(ch) + str.get(i));
  }
 }

 private static void appendAfter(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(str.get(i) + String.valueOf(ch));
  }
 }

} 

Wednesday, 11 February 2015

READING EXCEL FILES USNG APACHE POI API

With Apache POI API, you can access various Microsoft Documents like MS Excel, MS Powerpoint,  and MS Word.

In this post, I am going to discuss - How to access Excel File using Apache POI API?

To Access excel files with different versions like 2003(xls) and 2007(xlsx) - we use POI-HSSF and POI-XSSF APIs respectively. HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 (.xlsx) file format.

Note: You must include APACHE POI jar in you build path to access and manipulate excel files.This jar file contains all the required classes for various versions of excel files.

Download Link:  Apache POI jar


Important Classes(For Excel- 2007 & above):

XSSFWorkbook

XSSFSheet

XSSFRow

XSSFCell

 All these classes are in same package : org.apache.poi.xssf.usermodel


Important Classes(For Excel- 97-2003):

HSSFWorkbook

HSSFSheet

HSSFRow

HSSFCell

 All these classes are in same package : org.apache.poi.hssf.usermodel

Examples:

In examples, reading excel file -Sheet1 - row wise and printing on console

Sample Data- In Sheet1

Test Case Name Username Password Results IsExecute
APACHE_POI_TC testuser_1 Test@123 Pass Yes
APACHE_POI_TC testuser_2 Test@124 Pass No
APACHE_POI_TC testuser_3 Test@125 Pass Yes
APACHE_POI_TC testuser_4 Test@126 Pass Yes
APACHE_POI_TC testuser_5 Test@127 Pass No
APACHE_POI_TC testuser_6 Test@128 Pass Yes

Example : with Excel file (2007) - .xlsx

Use  org.apache.poi.xssf.usermodel package - all class names starts with XSSF

 Here,   

XSSFWorkbook represents the whole excel file

XSSFSheet represents the instance of a single sheet

XSSFRow represents a single row of  the current sheet you are working on

XSSFCell represents a tiny element cell in the sheet

 
package com.sample;

import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/*
 * For Excel - From 2007 version
 * File Extension - .xlsx
 * All class from Apache POI API -should start with XSSF
 * 
 */

public class ReadWriteWorkbook {
 private static XSSFWorkbook xlWBook;
 private static XSSFSheet xlSheet;
 private static XSSFRow xlRow; 
 private static String filePath = "/home/dinesh/";
 private static String fileName = "xtest.xlsx";

 public static void main(String[] args) {

  try {

   FileInputStream xlFile = new FileInputStream(filePath + fileName);

   // Access the required test data sheet
   xlWBook = new XSSFWorkbook(xlFile);

   // Assuming your data is in Sheet1
   xlSheet = xlWBook.getSheet("Sheet1");

   // gives row count in sheet
   int noOfRows = xlSheet.getPhysicalNumberOfRows();

   // gives number of rows
   xlRow = xlSheet.getRow(0);
   
   int noOfColumns = xlRow.getLastCellNum();
   
   // Storing all the excel data into an array excelData (Sheet1 only)
   String[][] excelData = new String[noOfRows][noOfColumns];

   // r - row c- column
   for (int r = 1; r < noOfRows; r++) {
    for (int c = 0; c < noOfColumns; c++) {
     xlRow = xlSheet.getRow(r);
     
     // Here we have complete excel data excelData
     // if there are any cells with no data - as treated as blanks
     Cell cell = xlRow.getCell(c, Row.CREATE_NULL_AS_BLANK);

     excelData[r][c] = cell.toString();

     System.out.println("row: " + r + " column: " + c
       + " cell data: " + excelData[r][c]);
    }
    System.out.println("*****************************************");
   }
  } catch (Exception e) {
   e.printStackTrace();

  }
 }
}
Example : with Excel file (2003) - .xls Use  org.apache.poi.hssf.usermodel package - all class names starts with HSSF
package com.sample;

import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;


/*
 * For Excel - Upto 2003 version
 * File Extension - .xls
 * All class from Apache POI -should start with HSSF
 */

public class ReadWriteExcelUpto2003 {
 
 private static HSSFWorkbook xlWBook;
 private static HSSFSheet xlSheet;
 private static HSSFRow xlRow;
 private static String filePath = "/home/dinesh/";
 // file extension - .xls
 private static String fileName = "xtest.xls";

 public static void main(String[] args) throws InterruptedException {

  try {

   FileInputStream xlFile 
   = new FileInputStream(filePath + fileName);

   // Access the required test data sheet
   xlWBook = new HSSFWorkbook(xlFile);

   // Assuming your data is in Sheet1
   xlSheet = xlWBook.getSheet("Sheet1");

   // gives row count in sheet
   int noOfRows = xlSheet.getPhysicalNumberOfRows();
   
   //gives number of rows 
   xlRow = xlSheet.getRow(0);
   int noOfColumns = xlRow.getLastCellNum();

   //Storing all the excel data into an array excelData (Sheet1 only)
   String[][] excelData = new String[noOfRows][noOfColumns];

   // r - row c- column
   for (int r = 1; r < noOfRows; r++) {
    for (int c = 0; c < noOfColumns; c++) {
  xlRow = xlSheet.getRow(r);
  
  // Here we have complete excel data excelData
  // if there are any cells with no data - as treated as blanks
  Cell cell = xlRow.getCell(c, Row.CREATE_NULL_AS_BLANK);

  excelData[r][c] = cell.toString();

     System.out.println("row: " + r + " column: " + c 
       + " cell data: "+excelData[r][c]);     
    }
    System.out.println("*****************************************");
   }
  } catch(Exception e){
   e.printStackTrace();
   
  }
 }
} 
Output:
row: 1 column: 0 cell data: APACHE_POI_TC
row: 1 column: 1 cell data: testuser_1
row: 1 column: 2 cell data: Test@123
row: 1 column: 3 cell data: Pass
row: 1 column: 4 cell data: Yes
*****************************************
row: 2 column: 0 cell data: APACHE_POI_TC
row: 2 column: 1 cell data: testuser_2
row: 2 column: 2 cell data: Test@124
row: 2 column: 3 cell data: Pass
row: 2 column: 4 cell data: No
*****************************************
row: 3 column: 0 cell data: APACHE_POI_TC
row: 3 column: 1 cell data: testuser_3
row: 3 column: 2 cell data: Test@125
row: 3 column: 3 cell data: Pass
row: 3 column: 4 cell data: Yes
*****************************************
row: 4 column: 0 cell data: APACHE_POI_TC
row: 4 column: 1 cell data: testuser_4
row: 4 column: 2 cell data: Test@126
row: 4 column: 3 cell data: Pass
row: 4 column: 4 cell data: Yes
*****************************************
row: 5 column: 0 cell data: APACHE_POI_TC
row: 5 column: 1 cell data: testuser_5
row: 5 column: 2 cell data: Test@127
row: 5 column: 3 cell data: Pass
row: 5 column: 4 cell data: No
*****************************************
row: 6 column: 0 cell data: APACHE_POI_TC
row: 6 column: 1 cell data: testuser_6
row: 6 column: 2 cell data: Test@128
row: 6 column: 3 cell data: Pass
row: 6 column: 4 cell data: Yes
*****************************************
Note: All examples are properly commented - please feel free to post your doubts/comments - Hope you like the content  please share this - thank u

Monday, 2 February 2015

FORMATING NUMBERS USING DecimalFormat

 DecimalFormat


Using java.text.DecimalFormat class  you can control the display of leading and trailing zeros, prefixes and suffixes, thousand separators, and the decimal   separator.


Example:
package com.selenium;

import java.text.DecimalFormat;

public class DecimalFormatEx {

 public static void main(String[] args) {
  
  /* first parameter - pattern  second parameter - value
   * According to the given pattern 
   */
  
  //acts as a thousand separator - 12,345.343
  formatByPattern("###,###.###",12345.34343);
  
  //here the decimal value is rounding - 123456.79
  formatByPattern("###.##",123456.789);
  
  //adding trailing and leading zeros - 000898.780
  formatByPattern("000000.000",898.78);
  
  //adding prefix $  - $12,345.34
  formatByPattern("$###,###.###",12345.34);  
  
 }

 //a custom method - you can name this method as you wish
 
 private static void formatByPattern(String pattern,double value){
  
  DecimalFormat formater = new DecimalFormat(pattern);
  
  String output = formater.format(value);
  
  System.out.println(output);
 }

}


Sunday, 1 February 2015

HOW TO USE TESTNG FRAMEWORK - SAMPLES-I

Just like Junit, TestNG provides very good testing strategies.

This post gives an overview of TestNG - a sample test case.

To you TestNG framework in your project you must use TestNG.jar

Ways To Download:

Official Download Link:  TestNG.jar

or

use git clone
git clone git://github.com/cbeust/testng.git  
or

If your using eclipse IDE, you can install TestNG as an eclipse plugin:
Read More...

After downloading TestNG jar file - add that jar to the project build path:

Now you are ready to use TestNG framework.

TestNG test cases  uses some important annotations:


All annotations are placed in the package:

org.testng.annotations.*;

@Test 

To write a test case - use @Test annotation.

Example:

package examples.testng;

import org.testng.annotations.Test;

public class MyFirstTest {

//First Test Case
@Test
public void validUser() {
// write your validation logic
System.out.println("Checking authorization");
}

//Second Test Case
@Test
public void checkBalance() {
// write a business logic to check the balance
System.out.println("Must check balance - before transactions");
}
} 


 How to run it?

It is very easy to run a test case in TestNG if your are using an IDE like eclipse

Right Click on Test Case Class->select "Run as"  -> TestNG test


More Concepts on TestNG ..coming soon

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