Thursday, 29 September 2016

Itext: Working with List object

List is a collection of ListItem objects. As you see the implementation of ListItem class, it extends Paragraph class. So List is a collection of paragraph objects.

public class ListItem extends Paragraph {
         ....
         ....
}

ListItem
A ListItem is a Paragraph that can be added to a List.

List
List is a collection of ListItem objects. There are two kinds of lists.
a.   Ordered Lists
b.   Unordered lists

How to create Ordered List?
List list = new List(List.ORDERED);

How to create Unordered List?
List list = new List(List.UNORDERED);

Following application displays list of countries in Asia using ordered list.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.List;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ListEx {
  private static java.util.List<String> countries = Arrays.asList("Afghanistan", "Armenia", "Azerbaijan", "Bahrain",
      "Bangladesh", "Bhutan", "Brunei", "Cambodia", "China", "Cyprus", "Georgia", "India", "Indonesia", "Iran",
      "Iraq", "Israel", "Japan", "Jordan", "Kazakhstan", "Kuwait", "Kyrgyzstan", "Laos", "Lebanon", "Malaysia",
      "Maldives", "Mongolia", "Myanmar (Burma)", "Nepal", "North Korea", "Oman", "Pakistan", "Palestine",
      "Philippines", "Qatar", "Russia", "Saudi Arabia", "Singapore", "South Korea", "Sri Lanka", "Syria",
      "Taiwan", "Tajikistan", "Thailand", "Timor-Leste", "Turkey", "Turkmenistan", "United Arab Emirates (UAE)",
      "Uzbekistan", "Vietnam", "Yemen");

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

    PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));

    List list = new List(List.ORDERED);

    Paragraph paragraph = new Paragraph("List Of Countries in Asia");

    for (String country : countries) {
      list.add(country);
    }

    document.open();
    document.add(paragraph);
    document.add(list);
    document.close();

  }
}


As you see by default it displays list items using numbers.


Following application displays list of countries in Asia using unordered list.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.List;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ListEx {
  private static java.util.List<String> countries = Arrays.asList("Afghanistan", "Armenia", "Azerbaijan", "Bahrain",
      "Bangladesh", "Bhutan", "Brunei", "Cambodia", "China", "Cyprus", "Georgia", "India", "Indonesia", "Iran",
      "Iraq", "Israel", "Japan", "Jordan", "Kazakhstan", "Kuwait", "Kyrgyzstan", "Laos", "Lebanon", "Malaysia",
      "Maldives", "Mongolia", "Myanmar (Burma)", "Nepal", "North Korea", "Oman", "Pakistan", "Palestine",
      "Philippines", "Qatar", "Russia", "Saudi Arabia", "Singapore", "South Korea", "Sri Lanka", "Syria",
      "Taiwan", "Tajikistan", "Thailand", "Timor-Leste", "Turkey", "Turkmenistan", "United Arab Emirates (UAE)",
      "Uzbekistan", "Vietnam", "Yemen");

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

    PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));

    List list = new List(List.UNORDERED);

    Paragraph paragraph = new Paragraph("List Of Countries in Asia");

    for (String country : countries) {
      list.add(country);
    }

    document.open();
    document.add(paragraph);
    document.add(list);
    document.close();

  }
}


By default, unordered list uses – (hyphen) for each list item.







Previous                                                 Next                                                 Home

Wednesday, 28 September 2016

Itext: Set space between two paragraphs

It is always good to provide space between two paragraphs. Paragraph class provides following method to provide space between two paragraphs.
public void setSpacingBefore(float spacing)
public void setSpacingAfter(float spacing)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ParagraphEx {
 private static Font fontNormal = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLACK);

 private static String data = "We Are Living In An Environment, Where Multiple Hardware Architectures And Multiple Platforms Presents. So It Is Very Difficult To Write, Compile And Link The Same Application, For Each Platform And Each Architecture Separately. The Java Programming Language Solves All The Above Problems. The Java Programming Language Platform Provides A Portable, Interpreted, High-Performance, Simple, Object-Oriented Programming Language And Supporting Run-Time Environment. Java Design And Architecture Decisions Drew From A Variety Of Languages Such As Eiffel, SmallTalk, Objective C, And Cedar/Mesa. Closely Observed The Problems In The Other Languages Like Platform Dependent, Pointers Complexity, Manual Garbage De Allocation Etc., Java Removes The Basic Problems In Other Languages. ";

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

  PdfWriter.getInstance(document, new FileOutputStream("java_features.pdf"));

  document.open();

  Paragraph paragraph = new Paragraph();
  paragraph.setSpacingAfter(18);

  paragraph.setFirstLineIndent(72);
  paragraph.setAlignment(Element.ALIGN_JUSTIFIED);

  Chunk chunk = new Chunk(data, fontNormal);
  paragraph.add(chunk);

  document.add(paragraph);
  document.add(paragraph);

  document.close();
 }
}


Previous                                                 Next                                                 Home

Tuesday, 27 September 2016

Itext: Changing the indentation

Paragraph class provides following methods to change the indentation.

public void setIndentationLeft(float indentation)
Changes the indentation to left.

public void setIndentationRight(float indentation)
Changes the indentation to right.

public void setFirstLineIndent(float firstLineIndent)

Changes the indentation of first line.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ParagraphEx {
 private static Font fontNormal = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLACK);

 private static String data = "We Are Living In An Environment, Where Multiple Hardware Architectures And Multiple Platforms Presents. So It Is Very Difficult To Write, Compile And Link The Same Application, For Each Platform And Each Architecture Separately. The Java Programming Language Solves All The Above Problems. The Java Programming Language Platform Provides A Portable, Interpreted, High-Performance, Simple, Object-Oriented Programming Language And Supporting Run-Time Environment. Java Design And Architecture Decisions Drew From A Variety Of Languages Such As Eiffel, SmallTalk, Objective C, And Cedar/Mesa. Closely Observed The Problems In The Other Languages Like Platform Dependent, Pointers Complexity, Manual Garbage De Allocation Etc., Java Removes The Basic Problems In Other Languages. ";

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

  PdfWriter.getInstance(document, new FileOutputStream("java_features.pdf"));

  document.open();

  Paragraph paragraph = new Paragraph();

  paragraph.setFirstLineIndent(72);
  paragraph.setAlignment(Element.ALIGN_JUSTIFIED);

  Chunk chunk = new Chunk(data, fontNormal);
  paragraph.add(chunk);

  document.add(paragraph);

  document.close();
 }
}



Previous                                                 Next                                                 Home

Itext: Set alignment to paragraph

Paragraph class provides ‘setAlignment’ method to set the alignment of a paragraph.

Syntax
public void setAlignment(int alignment)

Example
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);

Following is the complete working application.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfWriter;

public class ParagraphEx {
  private static Font fontNormal = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLACK);
  private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
      new BaseColor(255, 0, 0));

  private static String data = "We Are Living In An Environment, Where Multiple Hardware Architectures And Multiple Platforms Presents. So It Is Very Difficult To Write, Compile And Link The Same Application, For Each Platform And Each Architecture Separately. The Java Programming Language Solves All The Above Problems. The Java Programming Language Platform Provides A Portable, Interpreted, High-Performance, Simple, Object-Oriented Programming Language And Supporting Run-Time Environment. Java Design And Architecture Decisions Drew From A Variety Of Languages Such As Eiffel, SmallTalk, Objective C, And Cedar/Mesa. Closely Observed The Problems In The Other Languages Like Platform Dependent, Pointers Complexity, Manual Garbage De Allocation Etc., Java Removes The Basic Problems In Other Languages. ";

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

    PdfWriter.getInstance(document, new FileOutputStream("java_features.pdf"));

    document.open();

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
    Phrase heading = new Phrase("Features Of Java", fontHeading);
    Chunk chunk = new Chunk(data, fontNormal);

    paragraph.add(heading);
    paragraph.add(Chunk.NEWLINE);
    paragraph.add(chunk);

    document.add(paragraph);

    document.close();
  }
}

What is the default alignment?

Default is left alignment.




Previous                                                 Next                                                 Home

Sunday, 25 September 2016

Java Socket Programming Tutorial

What is Socket Programming?
By using socket programming, you can establish a communication between two computers. By using Java Socket programming, you can establish communication between, two java applications running on different machines.

There are two ways to establish communication between two computers.
a.   Connection-Oriented Programming
b.   Connection-less programming

By using Socket and ServerSocket classes, you can perform Connection-Orietned programming. By using DatagramSocket and DatagramPacket classes, you can perform Connection-less programming. In this post, I am going to explain connection oriented programming.

Connection-Oriented Programming
Java provides Socket and ServerSocket classes to support connection oriented programming. Following are the sequence of steps happened in connection-oriented programming.
a.   Establish the connection between two entities
b.   Perform data transmission
c.    Close the connection

Data transmission in connection oriented programming is reliable. It can guarantee that data will arrive in the same order.

Socket Class
By using Socket class, you can create a socket. A socket must know information about the server socket. For example, we should provide server IP address and port (where the server is listening).

Socket class provides following constructors to connect to server socket.

public Socket()
public Socket(Proxy proxy)
protected Socket(SocketImpl impl)throws SocketException
public Socket(String host, int port) throws UnknownHostException,IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException

Following are the important methods, you should know while working with socket.

Method
Description
public InputStream getInputStream() throws IOException
Returns an InputStream for this socket.
public OutputStream getOutputStream() throws IOException
Returns an output stream for this socket.
public void close() throws IOException
Close the socket
public boolean isConnected()
Returns true if the socket was successfuly connected to a server
public boolean isClosed()
Returns true if the socket has been closed

ServerSocket class
ServerSocket class is used to create server socket, it accepts the connections from client sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

ServerSocket class provides following constructors.

ServerSocket()
ServerSocket(int port)
ServerSocket(int port, int backlog)
ServerSocket(int port, int backlog, InetAddress bindAddr)

‘backlog’ specifies the maximum queue length for incoming connection indications. If a connection indication arrives when the queue is full, the connection is refused.

Following are the important methods, you should know while working with ServerSocket.

Method
Description
public Socket accept() throws IOException
Returns the socket and establish a connection between server and client.
public void close() throws IOException
Close the socket
public boolean isClosed()
Returns true if the socket has been closed


In the below example, StringServer class is the server socket, it receives data from client sockets and convert the data to upper case and send back to client.
/**
 * Accept connections from client sockets and convert the string to uppercase.
 * 
 * @author Hari krishna
 */

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

public class StringServer {

 private int port;
 private int backlog;

 public StringServer(int port, int backlog) {
  this.port = port;
  this.backlog = backlog;
 }

 public void startService() {
  ServerSocket serverSocket = null;
  try {
   serverSocket = new ServerSocket(port, backlog);

   System.out.println("Started Listening for clients");
   while (true) {
    Socket socket = serverSocket.accept();

    DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
    String str = (String) dataInputStream.readUTF();
    System.out.println("Received string : " + str);
    String upper = str.toUpperCase();

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    out.writeUTF(upper);
    socket.close();

   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (!Objects.isNull(serverSocket)) {
    try {
     serverSocket.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }

}

Following is the client implementation.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Objects;

public class StringServerClient {
 private String hostName;
 private int port;

 public StringServerClient(String hostName, int port) {
  this.hostName = hostName;
  this.port = port;
 }

 public String processData(String message) {
  Socket client = null;

  try {
   client = new Socket(hostName, port);
   OutputStream outToServer = client.getOutputStream();
   DataOutputStream out = new DataOutputStream(outToServer);

   out.writeUTF(message);

   InputStream inFromServer = client.getInputStream();
   DataInputStream in = new DataInputStream(inFromServer);

   String result = in.readUTF();

   return result;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   if (!Objects.isNull(client)) {
    try {
     client.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
  return null;
 }
}


Following are the test classes.
public class StringServerTest {
 public static void main(String args[]) {
  StringServer server = new StringServer(12345, 10);
  server.startService();
 }
}

public class StringServerClientTest {
 public static void main(String args[]) {
  StringServerClient client = new StringServerClient("localhost", 12345);
  String data = "Hello Good Morning";
  System.out.println("Sending \'" + data + "\' to server");

  String result = client.processData(data);
  System.out.println("Result : " + result);
 }
}


Open command prompt and run StringServerTest class.
C:>javac StringServerTest.java

C:>java StringServerTest
Started Listening for clients


Open other command prompt and run StringServerClientTest class.
C:>javac StringServerClientTest.java

C:>java StringServerClientTest
Sending 'Hello Good Morning' to server
Result : HELLO GOOD MORNING





Previous                                                 Next                                                 Home

Saturday, 24 September 2016

Itext: Adding chunks, phrases to a paragraph

Paragraph class provides add method, by using this you can add any Element to it. Following is the signature of add method.

public boolean add(Element o)
Return true if add is successful, else false. You can add any number of elements (chunks, phrases etc.,) to a paragraph element.

Following is the complete working application.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfWriter;

public class ParagraphEx {
 private static Font fontNormal = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLACK);
 private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
   new BaseColor(255, 0, 0));

 private static String data = "We Are Living In An Environment, Where Multiple Hardware Architectures And Multiple Platforms Presents. So It Is Very Difficult To Write, Compile And Link The Same Application, For Each Platform And Each Architecture Separately. The Java Programming Language Solves All The Above Problems. The Java Programming Language Platform Provides A Portable, Interpreted, High-Performance, Simple, Object-Oriented Programming Language And Supporting Run-Time Environment. Java Design And Architecture Decisions Drew From A Variety Of Languages Such As Eiffel, SmallTalk, Objective C, And Cedar/Mesa. Closely Observed The Problems In The Other Languages Like Platform Dependent, Pointers Complexity, Manual Garbage De Allocation Etc., Java Removes The Basic Problems In Other Languages. ";

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

  PdfWriter.getInstance(document, new FileOutputStream("java_features.pdf"));

  document.open();

  Paragraph paragraph = new Paragraph();
  Phrase heading = new Phrase("Features Of Java", fontHeading);
  Chunk chunk = new Chunk(data, fontNormal);

  paragraph.add(heading);
  paragraph.add(Chunk.NEWLINE);
  paragraph.add(chunk);

  document.add(paragraph);

  document.close();
 }
}



Previous                                                 Next                                                 Home