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

itext: Paragraph object

A paragraph is a series of chunks (or) Phrase object. Whenever you add a paragraph, a new line is added by default.

Paragraph paragraph = new Paragraph("This is a paragraph",FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));
document.add(paragraph);

Paragraph class provides following constructors to define Paragraph instance.

public Paragraph()
public Paragraph(float leading)
public Paragraph(Chunk chunk)
public Paragraph(float leading, Chunk chunk)
public Paragraph(String string)
public Paragraph(String string, Font font)
public Paragraph(float leading, String string)
public Paragraph(float leading, String string, Font font)
public Paragraph(Phrase phrase)

When you see the Paragraph class, it extends the functionality of Phrase class.

public class Paragraph extends Phrase implements Indentable, Spaceable, IAccessibleElement{
         .....
         .....
}

In simple terms, Paragraph has same behavior as Phrase with some extra features like the indentation, the alignment of the text.


Following application uses Paragraph instances to add content to a document.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
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.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"));

  Paragraph heading = new Paragraph("Features Of Java", fontHeading);
  Paragraph features = new Paragraph(data, fontNormal);
  document.open();

  document.add(heading);
  document.add(features);

  document.close();
 }
}



Previous                                                 Next                                                 Home

Friday, 23 September 2016

Internationalization using ResourceBundle

Internationalization is the process of developing products (or) services, so they can support different languages like English, Japanese, Chinese, Hindi etc.,

For example, you are developing an Enterprise application, where your application is going to be used by number of people across various countries. Since this is an Enterprise level application, people expect the application labels, messages etc., in their own locale.

How to make the messages Locale specific?
Here ResourceBundle comes into picture, By using ResourceBundle, you can point to the specific properties file, based on the locale.

Example1
ResourceBundle defaultPropertyFile = ResourceBundle.getBundle("app");

Above statement points to ‘app.properties’ file.

Example 2
ResourceBundle germanBundle = ResourceBundle.getBundle("app", Locale.GERMAN);

static public final Locale GERMAN = createConstant("de", "");

As you see the source code of Local.GERMAN, it looks like above. ‘createConstant’ function takes two arguments like lang, country. Based on locale selected by you, it points to specific property file.

The syntax is like below.
baseName_languageCode_countryCode.properties

In case of Example 2, baseName is “app”, languageCode is “de”, and country code is empty, so it points to app_de.properties.

Example 3
ResourceBundle canadaFrenceBundle = ResourceBundle.getBundle("app", Locale.CANADA_FRENCH);

static public final Locale CANADA_FRENCH = createConstant("fr", "CA");

As you see the source code of Locale.CANADA_FRENCH, it looks like above. As per the syntax specified in Example 2, canadaFrenceBundle  points to app_fr_CA.properties (baseName_laguageCode_countryCode.properties).

Example
app.properties
welcomeMessage = Good Morning
signoffMessage = Have a Good Day
version = 10.1


app_de.properties
welcomeMessage = Guten Morgen
signoffMessage = Haben Sie einen guten Tag

app_fr_CA.properties
welcomeMessage = Bonjour
signoffMessage = Bonne journée


Following is the screen shot of the maven project.

Following is the complete working application.
package resource_bundle.resource_bundle;

import java.util.Locale;
import java.util.ResourceBundle;

public class App {
 public static void main(String[] args) {
  ResourceBundle defaultPropertyFile = ResourceBundle.getBundle("app");
  ResourceBundle germanBundle = ResourceBundle.getBundle("app", Locale.GERMAN);
  ResourceBundle canadaFrenceBundle = ResourceBundle.getBundle("app", Locale.CANADA_FRENCH);

  /* Data from Default Property file information */
  System.out.println("defaultPropertyFile Values");
  System.out.println("welcomeMessage : " + defaultPropertyFile.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + defaultPropertyFile.getString("signoffMessage"));
  System.out.println("version : " + defaultPropertyFile.getString("version"));

  /* Data from German Property file */
  System.out.println("\ngermanBundle Values");
  System.out.println("welcomeMessage : " + germanBundle.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + germanBundle.getString("signoffMessage"));
  System.out.println("version : " + germanBundle.getString("version"));

  /* Data from Canada French property file */
  System.out.println("\ncanadaFrenceBundle Values");
  System.out.println("welcomeMessage : " + canadaFrenceBundle.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + canadaFrenceBundle.getString("signoffMessage"));
  System.out.println("version : " + canadaFrenceBundle.getString("version"));

 }
}

Output
defaultPropertyFile Values
welcomeMessage : Good Morning
signoffMessage : Have a Good Day
version : 10.1

germanBundle Values
welcomeMessage : Guten Morgen
signoffMessage : Haben Sie einen guten Tag
version : 10.1

canadaFrenceBundle Values
welcomeMessage : Bonjour
signoffMessage : Bonne journée
version : 10.1

As you see the output, defaultPropertyFile instance return the values from app.properties file, germanBundle instance return the values from app_de.properties file and canadaFrenceBundle instance return the values from app_fr_CA.properties file.

One Key thing to note
As you see the property file, app_fr_CA.properties, app_de.properties, the property "version" is not present. But as you see the output the version is printing as '10.1'.

From where this version10.1 came?
If a ResourceBundle class for the specified Locale does not exist, getBundle tries to find the closest match. For example, if ButtonLabel_fr_CA_UNIX is the desired class and the default Locale is en_US, getBundle will look for classes in the following order:

ButtonLabel_fr_CA_UNIX
ButtonLabel_fr_CA
ButtonLabel_fr
ButtonLabel_en_US
ButtonLabel_en
ButtonLabel

So in our case the property version is not present in the files ‘app_de.properties’, ‘app_fr_CA.properties’, So ResourceBundle class tries to get the property from the nearest match, which is app.properties.

What if the property files are in some folder, not in src/main/resources?

If the property files are in folder "lang", you should use the baseName as "lang/app".

Ex:
String baseName = "lang/app";
                
ResourceBundle defaultPropertyFile = ResourceBundle.getBundle(baseName);
ResourceBundle germanBundle = ResourceBundle.getBundle(baseName, Locale.GERMAN);

ResourceBundle canadaFrenceBundle = ResourceBundle.getBundle(baseName, Locale.CANADA_FRENCH);

Following is the complete working application.
package resource_bundle.resource_bundle;

import java.util.Locale;
import java.util.ResourceBundle;

public class App {
 public static void main(String[] args) {
  String baseName = "lang/app";

  ResourceBundle defaultPropertyFile = ResourceBundle.getBundle(baseName);
  ResourceBundle germanBundle = ResourceBundle.getBundle(baseName, Locale.GERMAN);
  ResourceBundle canadaFrenceBundle = ResourceBundle.getBundle(baseName, Locale.CANADA_FRENCH);

  /* Data from Default Property file information */
  System.out.println("defaultPropertyFile Values");
  System.out.println("welcomeMessage : " + defaultPropertyFile.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + defaultPropertyFile.getString("signoffMessage"));
  System.out.println("version : " + defaultPropertyFile.getString("version"));

  /* Data from German Property file */
  System.out.println("\ngermanBundle Values");
  System.out.println("welcomeMessage : " + germanBundle.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + germanBundle.getString("signoffMessage"));
  System.out.println("version : " + germanBundle.getString("version"));

  /* Data from Canada French property file */
  System.out.println("\ncanadaFrenceBundle Values");
  System.out.println("welcomeMessage : " + canadaFrenceBundle.getString("welcomeMessage"));
  System.out.println("signoffMessage : " + canadaFrenceBundle.getString("signoffMessage"));
  System.out.println("version : " + canadaFrenceBundle.getString("version"));

 }
}







Runtime.addShutdownHook(): Run code at JVM exit

By using addShutdownHook method, we can attach a piece of code to JVM. This piece of code executes when the Java Virtual Machine starts its shutdown sequence.

When the JVM Shutdown?
JVM shutdown in following two scenarios.

Scenario 1
The program exits normally, when the last non-daemon thread exits or when the System.exit method is invoked,

Scenario 2
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Syntax
public void addShutdownHook(Thread hook)

Example
Runtime.getRuntime().addShutdownHook(new Thread() {

 @Override
 public void run() {
  System.out.println("Application exited successfully without any unhandled error. ");
 }
});

public class ShutDownHookEx {
 public static void main(String args[]) {
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("Application exited successfully without any unhandled error. ");
   }
  });

  System.out.println("About to Exit the Application");
  System.exit(0);
  System.out.println("Application Exited");
 }

}

Run above application, you can able to see following messages in the console.

About to Exit the Application
Application exited successfully without any unhandled error.

Can I add multiple shutdown hooks to JVM?
Yes, you can add multiple shutdown hooks to JVM. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
public class ShutDownHookEx {
 public static void main(String args[]) {
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook1");
   }
  });
  
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook2");
   }
  });
  
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook3");
   }
  });

  System.out.println("About to Exit the Application");
  System.exit(0);
  System.out.println("Application Exited");
 }

}

Sample Output
About to Exit the Application
ShutDown Hook1
ShutDown Hook3
ShutDown Hook2


Is there any way that I can skip these shutdown hooks?
By using the halt method of Runtime class, you can skip the shutdown hooks. ‘halt’ method forcibly terminates the currently running Java virtual machine.

public class ShutDownHookEx {
 public static void main(String args[]) {
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook1");
   }
  });

  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook2");
   }
  });

  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("ShutDown Hook3");
   }
  });

  System.out.println("About to Exit the Application");
  Runtime.getRuntime().halt(0);
  System.out.println("Application Exited");
 }

}


Output
About to Exit the Application

Can I stop the shutdown sequence in middle of processing?
Yes any time by calling the halt method.

Can I register (or) deregister shutdown hooks,after shutdown sequence begun?
No, once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook. Attempting either of these operations will cause an IllegalStateException to be thrown.

Can I perform long-running tasks in shutdown hook?
Ideally no, you are not supposed to perform long running operationg in shutdown hook, it is because when the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.

Is there any cases, where shutdown hook processes will not execute?
Yes, following are the cases.
a. When you call halt method
b. When JVM is terminated with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.
c. If JVM aborts, due to some internal errors.

How to deregister shutdown hook?
By calling 'removeShutdownHook' method, you can deregister shutdown hook.
public boolean removeShutdownHook(Thread hook)






Itext: Phrase object

Phrase is list of chunk objects. Assume it is like list of Chunk objects, you can add any number of Chunk objects to it. Once you added all the chunk objects to the phrase, you can add this phrase object to the document.

For example, following function adds list of chunk objects to a phrase and return.
public static Phrase getPhrase() {
 Phrase phrase = new Phrase();
 int counter = 0;
 for (String country : countries) {

  Chunk chunk = new Chunk(country, font);
  phrase.add(chunk);

  String code = "(" + countryCodes.get(counter) + ")";
  counter++;
  Chunk superScript = new Chunk(code, superScriptFont);
  superScript.setTextRise(6);
  phrase.add(superScript);

  phrase.add(Chunk.NEWLINE);
  phrase.add(Chunk.NEWLINE);
 }

 return phrase;
}

Following statement adds the Phrase instance to the document.
document.add(getPhrase());


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

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

public class HelloWorld {
 private static List<String> countries = Arrays.asList("India - Assamese", "India - Bengali", "India - English",
   "India - Gujarati", "India - Hindi", "India - Kannada", "India - Konkani", "India - Malayalam",
   "India - Marathi", "India - Oriya", "India - Punjabi", "India - Sanskrit", "India - Tamil",
   "India - Telugu");

 private static List<String> countryCodes = Arrays.asList("as-IN", "bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN",
   "kok-IN", "ml-IN", "mr-IN", "or-IN", "pa-IN", "sa-IN", "ta-IN", "te-IN");

 private static Font font = FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, BaseColor.BLACK);
 private static Font superScriptFont = FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC, BaseColor.BLACK);
 private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
   new BaseColor(255, 0, 0));

 public static Phrase getPhrase() {
  Phrase phrase = new Phrase();
  int counter = 0;
  for (String country : countries) {

   Chunk chunk = new Chunk(country, font);
   phrase.add(chunk);

   String code = "(" + countryCodes.get(counter) + ")";
   counter++;
   Chunk superScript = new Chunk(code, superScriptFont);
   superScript.setTextRise(6);
   phrase.add(superScript);

   phrase.add(Chunk.NEWLINE);
   phrase.add(Chunk.NEWLINE);
  }

  return phrase;
 }

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

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

  document.open();

  document.add(new Chunk("Langauage codes in India", fontHeading));
  document.add(Chunk.NEWLINE);

  document.add(getPhrase());

  document.close();

 }

}

As you see the code, I don’t mention the statement for leading.


PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));
writer.setInitialLeading(16);

It is because, when you create Phrase object, it creates default leading of 16.

public Phrase(final float leading) {
         this.leading = leading;
    font = new Font();
}

public Phrase() {
         this(16);

}


Previous                                                 Next                                                 Home