Wednesday, 22 May 2013

How to create PDF with Java and iText Example

How to create PDF with Java and iText Example
iText is a Java library originally created by Bruno Lowagie which allows to create PDF, read PDF and manipulate them. I will show you a example here.

iText has a hierarchical structure. The smallest text unit is a "Chunk" which is a String with a pre-defined font. A "Phrase" combines several Chunks and allows to define line spacing. "Paragraph" is a subclass of "Phrase" and allows to define more layout attributes, e.g. margins. The class "Anchor" is a subclass of "Paragraph" and serves as the basis for hyperlinks in the generated PDF.

for How to create PDF with Java and iText Example

Installation
Download the iText core binary from here link. Download iText Jar

Creating PDF


package itext.test;
import java.io.FileOutputStream;
import java.util.Date;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GeneratePDFTest {
public static void main(String[] args) {
try {
 //create a document
     Document document = new Document();
     PdfWriter.getInstance(document, new FileOutputStream(FILE));
     document.open();
     //adding metadata about pdf file
     addMetaData(document);
     //adding title of pdf file
     addTitlePage(document);
     //adding contents into pdf file.
     addContent(document);
     document.close();
   } catch (Exception e) {
     e.printStackTrace();
   }

}
 private static String FILE = "D:/test/TestPdf.pdf";
 private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
 private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.NORMAL, BaseColor.RED);
 private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,Font.BOLD);
 private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD);

 //iText allows to add metadata to the PDF which can be viewed in your Adobe Reader
 // You can view under File -> Properties
 private static void addMetaData(Document document) {
   document.addTitle("My Test PDF");
   document.addSubject("Using iText");
   document.addKeywords("Java, PDF, iText");
   document.addAuthor("Wakil Ahmad");
   document.addCreator("Wakil");
}

 private static void addTitlePage(Document document) throws DocumentException {
   Paragraph preface = new Paragraph();
   // We add one empty line
   addEmptyLine(preface, 1);
   // Writing a big header
   preface.add(new Paragraph("Title of the document as pdf file", catFont));
   addEmptyLine(preface, 1);
   // Will create: Report generated by: _name, _date
   preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),smallBold));
   addEmptyLine(preface, 3);
   preface.add(new Paragraph("Describes about document ",smallBold));
   addEmptyLine(preface, 8);
   preface.add(new Paragraph("This document is a preliminary version", redFont));
   document.add(preface);
   // Start a new page
   document.newPage();
 }
    private static void addEmptyLine(Paragraph paragraph, int number) {
   for (int i = 0; i < number; i++) {
     paragraph.add(new Paragraph(" "));
   }
 }
 
    private static void addContent(Document document) throws DocumentException {
       Anchor anchor = new Anchor("Testing page 1", catFont);
       anchor.setName("Test Chapter 1");

       // Second parameter is the number of the chapter
       Chapter catPart = new Chapter(new Paragraph(anchor), 1);

       Paragraph subPara = new Paragraph("Subcategory 1", subFont);
       Section subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("How are you"));

       subPara = new Paragraph("Subcategory 2", subFont);
       subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("Paragraph 1"));
       subCatPart.add(new Paragraph("Paragraph 2"));
       subCatPart.add(new Paragraph("Paragraph 3"));
       subCatPart.add(new Paragraph("Paragraph 4"));
       // Add a list
       createList(subCatPart);
       Paragraph paragraph = new Paragraph();
       addEmptyLine(paragraph, 5);
       subCatPart.add(paragraph);

       // Adding a table
       createTable(subCatPart);

       // Now add all this to the document
       document.add(catPart);

       // Next section
       anchor = new Anchor("Second Chapter", catFont);
       anchor.setName("Second Chapter");

       // Second parameter is the number of the chapter
       catPart = new Chapter(new Paragraph(anchor), 1);

       subPara = new Paragraph("Subcategory", subFont);
       subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("This is a very important message"));

       // Now add all this to the document
       document.add(catPart);

     }
 
        private static void createList(Section subCatPart) {
       List list = new List(true, false, 10);
       list.add(new ListItem("First point"));
       list.add(new ListItem("Second point"));
       list.add(new ListItem("Third point"));
       subCatPart.add(list);
     }
 
    private static void createTable(Section subCatPart) throws BadElementException {
       PdfPTable table = new PdfPTable(3);
       PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);

       c1 = new PdfPCell(new Phrase("Table Header 2"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);
       c1 = new PdfPCell(new Phrase("Table Header 3"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);
       table.setHeaderRows(1);
       table.addCell("1.0");
       table.addCell("1.1");
       table.addCell("1.2");
       table.addCell("2.1");
       table.addCell("2.2");
       table.addCell("2.3");
       subCatPart.add(table);
     }
}

After Running the above java program, the output file below here.







Read an existing PDF :

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class ReadUsePDFTest {
  private static String INPUTFILE = "D:/test/testPdf.pdf";
  private static String OUTPUTFILE = "D:/test/ReadPdf.pdf";

  public static void main(String[] args) throws DocumentException,
      IOException {
    Document document = new Document();

    PdfWriter writer = PdfWriter.getInstance(document,
        new FileOutputStream(OUTPUTFILE));
    document.open();
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages();
    PdfImportedPage page;
    // Go through all pages
    for (int i = 1; i <= n; i++) {
      // Only page number 2 will be included
      if (i == 2) {
        page = writer.getImportedPage(reader, i);
        Image instance = Image.getInstance(page);
        document.add(instance);
      }
    }
    document.close();

  }

} 


Thursday, 16 May 2013

JAX-RS @Path URI Matching Example - RESTful web service

JAX-RS @Path URI Matching Example - RESTful web service

JAX-RS @Path URI Matching Example - RESTful web service


In JAX-RS you can use the @Path annotation to bind the URI pattern to java method
First We see the simple URL Pattern matching with @Path annotation
Simple URI Matching Pattern

URI Matching and Request Parameter
The value within open brace "{" and close brace "}" represent a parameter and can be
acessed using @PathParam annotation for example.

URI Matching and Regular Expression
@Path support complex URI matching with regular expression, via following expression
{" variable-name [ ":" regular-expression ] "}

@PathParam with multiple parameters
This example show how to inject multiple parameters into a java method

Wednesday, 15 May 2013

JAX-RS RESTful web service using Jersey

JAX-RS RESTful web service using Jersey

JAX-RS RESTful web service using Jersey

JAX-RS provides the functionality for Representational State Transfer (RESTful) web services.
RESTful web services often better integrated with HTTP than SOAP based service. Which does not require
XML message or wsdl service.
There are two most important implementation of JAX-RS Java API are Jersey and Resteasy
What Are RESTful Web Services?
RESTful web services are built to work best on the Web. Representational State Transfer (REST) is a
architectural style that specifies constraints, such as the uniform interface, that if applied to a
web service induce desirable properties, such as performance, scalability, and modifiability, that
enable services to work best on the Web. In the REST architectural style, data and functionality are
considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.
The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style
constrains an architecture to a client/server architecture and is designed to use a stateless communication
protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of
resources by using a standardized interface and protocol.
The following principles encourage RESTful applications to be simple, lightweight, and fast:

Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets
of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space
for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations:
PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves
the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding
to HTTP Methods and Requests for more information.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed
in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource
is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate
representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests
and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages
are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques
exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response
messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and
Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

There are some annotations implemented by Jersy and Resteasy
@Path : The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted:
for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example,
you could ask for the name of a user and pass it to the application as a variable in the
URI: /helloworld/{username}.
@GET :The @GET annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@POST :The @POST annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@PUT : The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of
a resource is determined by the HTTP method to which the resource is responding.
@DELETE : The @DELETE annotation is a request method designator and corresponds to the similarly named
HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests.
The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD : The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@PathParam : The @PathParam annotation is a type of parameter that you can extract for use in your resource class.
URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template
variable names specified in the @Path class-level annotation.
@QueryParam : The @QueryParam annotation is a type of parameter that you can extract for use in your resource
class. Query parameters are extracted from the request URI query parameters.
@Consumes : The @Consumes annotation is used to specify the MIME media types of representations a resource can
consume that were sent by the client.
@Produces : The @Produces annotation is used to specify the MIME media types of representations a resource can
produce and send back to the client: for example, "text/plain".
@Provider : The @Provider annotation is used for anything that is of interest to the JAX-RS runtime,
such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an
HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP
response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata,
such as HTTP headers or a different status code, a method can return a Response that wraps the entity and
that can be built using Response.ResponseBuilder.

JAX-RS RESTful web service using Jersey Hello World Example

Where Jersy is reference implementation of JAX-RS Java API. Jersy is used to build RESTful web service.
Dependency of application are :
Jersey 1.8
JDK 1.6
Tomcat 6.0
Eclipse 3.6
Step 1 : Create REST Service

Step 2 : web.xml
In web.xml, register com.sun.jersey.spi.container.servlet.ServletContainer, and puts your Jersey
service folder under init-param, com.sun.jersey.config.property.packages.

In this example, web request from appname/rest/hello/ will match to HelloWorldService, via @Path("/hello").
And the {any values} from appname/rest/hello/{any values} will match to parameter annotated with @PathParam.
URL : http://localhost:8080/appname/rest/hello/wakil

When Run the above url in your browser, the output will come as
Jersey say wakil


Tuesday, 14 May 2013

Convert Java Object To/From JSON (Gson)

How To Convert Java Object To/From JSON (Gson)


Gson is google library for internal use, but now you can use publically.
It is a lightweight data-interchange format.
Gson is easy to learn and implement, We need to know two methods given below.
1 : toJson() – Convert Java object to JSON format.
2 : fromJson() – Convert JSON into Java object.
A pojo, with initialized values, Later use Gson to convert this object to/from JSON formatted string.

toJson() Example:
Convert object to JSON string, and save it as test.json

fromJson() Example: Read data from test.json , convert back to object.

Monday, 13 May 2013

JSON.simple Example

JSON.simple Example


JSON simple is a simple Java toolkit for JSON . You can use JSON simple to encode or
decode JSON text.
Features :
1 : Full compliance with JSON specification (RFC4627) and reliable.
2 : Provides multiple functionalities such as encode, decode/parse and escape
JSON text while keeping the library lightweight.
3 : Flexible, simple and easy to use by reusing Map and List interfaces.
4 : Supports streaming output of JSON text.
5 : Heap based parser.
6 : High performance.
7 : No dependency at all.

You need to download the JSON.simple library here and include it in java classpath.
1 : Write JSON to File
Write JSON data via JSONObject and JSONArray, and save it into a file named test.json


2 : Read JSON from File
Use JSONParser to read above generated JSON file test.json, and display each of the values.

Encode a JSON object - Streaming

Encode a JSON object - Using Map

Encode a JSON object - Using Map and streaming

Jackson data binding –Map & JSON

Jackson data binding –Map & JSON


We show you how to convert user define Map to/from JSON data. Map is more suitable
and easy and short JSON processing.
We will show you how to use Map to construct the JSON data, write it to file, how to read JSON from file,
and display each value via Map.
Step 1: Write JSON to File:

Step 2: Read JSON from a File:

In Jackson, you can use Tree Model to represent JSON, and perform the read and write operations via
JsonNode, it is similar to DOM tree for XML.
ObjectMapper mapper = new ObjectMapper();
BufferedReader fileReader = new BufferedReader(new FileReader("d:\\test\\person.json"));
JsonNode rootNode = mapper.readTree(fileReader);
/*** read value from key "name" ***/
JsonNode nameNode = rootNode.path("name");
System.out.println(nameNode.getTextValue());

Java JSON Data Binding Example ( jackson processor)

Java JSON data Binding

JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. In this tutorial
we focus three opensource java library which process the json data, which are Jackson, Google Gson and JSON.simple.

Jackson


It is a high performance JSON processor. There are some examples given here.

Jackson data binding example-Object & JSON :

In this example we are showing how to convert java object to/from JSON.
before starting with jackson, you have to download the library and include in your java classpath from Here
Create a POJO:
Person object, initialized with some values

Java Object to JSON:
Convert an Person object into JSON formatted string, and save it into a file person.json.

Output will be
{"name":"Wakil","age":29,"messages":["Message 1","Message 2","Message 3"]}

JSON to Java Object:
Read JSON string from file person.json, and convert it back to Java object.

Output will be Person [age=29, name=Wakil, messages=[Message 1, Message 2, Message 3]]