Thursday, July 2, 2020

Creating PDF in Java Using iText

In this post we’ll see how to create PDF in Java using iText library. Version of iText used here is 7.x.x which has different API from iText 5.x.x versions. We’ll see various examples of PDF creation using iText showing the use of classes in iText like PdfDocument, Document, PdfWriter, Paragraph, Table, PdfFont, PDFReader.

Note that iText is open source but the open source version is AGPL licensed which means you must distribute all source code, including your own product and web-based applications.

Maven dependecy

For using iText library you must add the following dependencies to your pom.xml file.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <itext.version>7.1.3</itext.version>
</properties>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>kernel</artifactId>
  <version>${itext.version}</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>io</artifactId>
  <version>${itext.version}</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>layout</artifactId>
  <version>${itext.version}</version>
</dependency>
<!-- Java logging used-->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-jdk14</artifactId>
  <version>1.7.13</version>
</dependency>

This adds the following jars to the project’s class path.

kernel-7.1.3.jar
io-7.1.3.jar
layout-7.1.3.jar
slf4j-api-1.7.13.jar
slf4j-jdk14-1.7.13.jar

Following examples are listed in this post for generating PDF in Java using iText.

Creating PDF in Java using iText – Hello World

First lets see a simple iText PDF creation example where “Hello world” is written to the PDF using a Java program. Also the font and color for the text is specified before writing it to the PDF.

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class PDFCreation {
 public static final String DEST = "G://Test//hello_world.pdf";
 public static void main(String[] args) {
  PdfWriter writer;
  try {
   writer = new PdfWriter(new FileOutputStream(DEST));
   PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
   PdfDocument pdf = new PdfDocument(writer);
   Document document = new Document(pdf);
   Text text = new Text("Hello World with font and color")
         .setFont(font)
         .setFontColor(ColorConstants.BLUE);
   //Add paragraph to the document
   document.add(new Paragraph(text));
   document.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }   
 }
}

Creating PDF in Java using iText – Content in a Table

In this example we’ll see how to present content as a table in PDF using iText from your Java program. Example uses a bean class User, fields of object of type User are displayed in the table.

User.java

public class User {
  private String firstName;
  private String lastName;
  private String email;
  public User() {
   
  }
  public User(String firstName, String lastName, String email) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.email = email;
  }
  
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName(String firstName) {
   this.firstName = firstName;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName(String lastName) {
   this.lastName = lastName;
  }
  public String getEmail() {
   return email;
  }
  public void setEmail(String email) {
   this.email = email;
  }
}

Class used for creating PDF showing data in a table.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.netjs.Model.User;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;

public class PDFTableCreation {
  public static void main(String[] args) {
    new PDFTableCreation().createTablePDF("G://Test//table.pdf");
  }
    
  private void createTablePDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdf = new PdfDocument(writer);
      Document document = new Document(pdf, new PageSize(PageSize.A4));
      PdfFont headerFont = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
      PdfFont cellFont = PdfFontFactory.createFont(StandardFonts.COURIER);
      // Create table with 3 columns of similar length
      Table table = new Table(new float[]{4, 4, 4});
      table.setWidth(UnitValue.createPercentValue(100));
      // adding header
      table.addHeaderCell(new Cell().add(new Paragraph(
              "First Name").setFont(headerFont)));
      table.addHeaderCell(new Cell().add(new Paragraph(
              "Last Name").setFont(headerFont)));
      table.addHeaderCell(new Cell().add(new Paragraph(
              "Email").setFont(headerFont)));
      List<User> users = getListOfUsers();
      // adding rows
      for(User user : users) {
        table.addCell(new Cell().add(new Paragraph(
             user.getFirstName()).setFont(cellFont)));
        table.addCell(new Cell().add(new Paragraph(
             user.getLastName()).setFont(cellFont)));
        table.addCell(new Cell().add(new Paragraph(
             user.getEmail()).setFont(cellFont)));
      }
      document.add(table);
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }    
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "abc@xyz.com"));
    users.add(new User("Remington", "Steele", "rs@cbd.com"));
    users.add(new User("Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}

Created PDF

Creating table in PDF Using iText- Java

Generating PDF in Java using iText – Adding background image to PDF

public class PDFCreation {
  public static final String DEST = "G://Test//image.pdf";
  public static void main(String[] args) {
    new PDFCreation().addImageToPDF(DEST);
  }
 
  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);
      PageSize pageSize = new PageSize(PageSize.A4).rotate();
   
      PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
      // creating image data instance by passing the path to image
      ImageData img = ImageDataFactory.create("resources//netjs.png");
      canvas.saveState();
      // graphic state
      PdfExtGState state = new PdfExtGState();
      state.setFillOpacity(0.2f);
      canvas.setExtGState(state);
      canvas.addImage(img, 20, 650, pageSize.getWidth()/2, false);
      canvas.restoreState();
      document.add(new Paragraph("Adding image to PDF Example"));      
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Created PDF

adding image to PDF in Java

Creating PDF in Java using iText – Adding image to PDF

If you want to add image to PDF.

public class PDFCreation {
  public static final String DEST = "G://Test//image.pdf";

  public static void main(String[] args) {
    new PDFCreation().addImageToPDF(DEST);
  }
 
  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      // creating image data instance by passing the path to image
      Image image = new Image(ImageDataFactory.create("resources//netjs.png"));
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);       
      document.add(new Paragraph("Adding image to PDF Example"));
      document.add(image);      
      document.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Creating PDF in Java using iText – Adding List to PDF

If you want to show a list of items in PDF then you can create a List and add ListItems to it. Symbol used for marking ListItems can be passed using setListSymbol() method. There is an Enum ListNumberingType that holds possible values for list item prefix. You can also pass a unicode character.

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.ListNumberingType;

public class PDFCreation {
  public static void main(String[] args) {
    new PDFCreation().addImageToPDF("G://Test//list.pdf");
  }

  private void addImageToPDF(String PDFPath){
    PdfWriter writer;
    try {
      writer = new PdfWriter(new FileOutputStream(PDFPath));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc);       
      document.add(new Paragraph("Choices Are (Using English Letters)"));
            // for offset (space from the left)
      List list = new List().setSymbolIndent(14) 
                            .setListSymbol(ListNumberingType.ENGLISH_LOWER);
       
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);
      
      document.add(new Paragraph("Choices Are (Using Roman upper)"));
      list = new List()
           .setSymbolIndent(14)
           .setListSymbol(ListNumberingType.ROMAN_UPPER);
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);
      
      document.add(new Paragraph("Choices Are (Using bullet symbol)"));
      list = new List()
           .setSymbolIndent(14) 
           .setListSymbol("\u2022"); // Passing unicode for bullet
      // Add ListItem objects
      list.add(new ListItem("Aerobic"))
          .add(new ListItem("Anaerobic"))
          .add(new ListItem("Flexibility Training"));
      // Add the list
      document.add(list);            
      document.close();         
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Created PDF

creating PDF with list items using Java

Creating PDF in Java using iText – Rendered to browser as web response

If you want to render PDF to the browser in your web project using the HTTPResponse, then you can do it as follows. PDFWriter constructor also accepts an OutputStream as parameter. If you want to write a web application, then you can create a ServletOutputStream.

PdfWriter writer;
try{
  response.setContentType("application/pdf");
  writer = new PdfWriter(response.getOutputStream());
  PdfDocument pdfDoc = new PdfDocument(writer);
  Document document = new Document(pdfDoc); 
  PdfFont titleFont = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
  PdfFont textFont = PdfFontFactory.createFont(StandardFonts.COURIER);
  document.add(new Paragraph("PDF generated in Web")
          .setFont(titleFont).setFontColor(ColorConstants.RED)
          .setTextAlignment(TextAlignment.CENTER));
  Paragraph p = new Paragraph("This is the text of the PDF created using iText library and 
               rendered to the browser using a Servlet.");
  document.add(p.setFont(textFont).setFontColor(ColorConstants.ORANGE));
  document.close();
}catch(Exception e){
  e.printStackTrace();
}

Created PDF

rendering PDF in web application

Creating PDF in Java using iText – Password protected PDF with user permissions

You can encrypt the created PDF, there are two types of passwords you can set-

  • User password
  • Owner password

The userPassword and the ownerPassword can be null or have zero length.

You can also set user permissions (operation permitted when the PDF document is opened with the user password). Available user permissions are defined in the EncryptionConstants class.

  • EncryptionConstants.ALLOW_PRINTING
  • EncryptionConstants.ALLOW_MODIFY_CONTENTS
  • EncryptionConstants.ALLOW_COPY
  • EncryptionConstants.ALLOW_MODIFY_ANNOTATIONS
  • EncryptionConstants.ALLOW_FILL_IN
  • EncryptionConstants.ALLOW_SCREENREADERS
  • EncryptionConstants.ALLOW_ASSEMBLY
  • EncryptionConstants.ALLOW_DEGRADED_PRINTING

The permissions can be combined by ORing them, as example (EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_MODIFY_CONTENTS)

Example code

For this code to run you will need bouncycastle jar. Maven dependency for it is as follows-

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
</dependency>

which adds the following jar-

  • bcprov-jdk15on-1.60.jar
public class PDFWithPwd {

  public static void main(String[] args) {
    new PDFWithPwd().changePermissions("G://Test//Permissions.pdf");
  }
 
  private void changePermissions(String pdfPath) {
    final String USER_PWD="user";
    final String OWNER_PWD="owner";
    try {
      PdfWriter writer = new PdfWriter(pdfPath, new WriterProperties()
                  .setStandardEncryption(USER_PWD.getBytes(), OWNER_PWD.getBytes(), 
                   EncryptionConstants.ALLOW_PRINTING, 
                   EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA));
      PdfDocument pdfDoc = new PdfDocument(writer);
      Document document = new Document(pdfDoc); 
      document.add(new Paragraph("This PDF is password protected and its content can’t be copied by user."));
      document.close();
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

If you open the created PDF it will ask for the password. If you open it using the user password then you won’t be able to copy the content as per the user permission settings.

password protected PDF in Java using iText

That's all for this topic Creating PDF in Java Using iText. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Create PDF From XML Using Apache FOP
  2. Spring MVC PDF Generation Example
  3. How to Create Password Protected Zip File in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify - Java Program
  5. Converting double to int - Java Program

You may also like-

  1. How to Count Lines in a File - Java Program
  2. Creating Tar File And GZipping Multiple Files - Java Program
  3. Comparing Enum to String - Java Program
  4. How to Remove Duplicate Elements From an Array - Java Program
  5. Difference Between Comparable and Comparator in Java
  6. SerialVersionUID And Versioning in Java Serialization
  7. Difference Between Abstract Class And Interface in Java
  8. Dependency Injection in Spring Framework

Wednesday, July 1, 2020

Python String replace() Method

Python String replace() method is used to replace occurrences of the specified substring with the new substring.

Syntax of replace() method

Syntax of replace() method is-

str.replace(old, new, count)

old- Specifies a substring that has to be replaced.

new- Specifies a substring that replaces the old substring.

count- count argument is optional if it is given, only the first count occurrences are replaced. If count is not specified then all the occurrences are replaced.

Return values of the method is a copy of the string with all occurrences of substring old replaced by new.

Replace() method Python examples

1. Replacing specified substring with new value.

def replace_sub(text):
    text = text.replace('30', 'thirty')
    print(text)

replace_sub('His age is 30')

Output

His age is thirty

2. replace() method with count parameter to replace only specified occurrences.

def replace_sub(text):
    text = text.replace('is', 'was')
    print(text)
    # replacing only one occurrence
    print(text.replace('was', 'is', 1))

replace_sub('His age is 30')

Output

Hwas age was 30
His age was 30

3. Replacing character with space.

def replace_sub(text):
    text = text.replace('H', '')
    print(text)

replace_sub('His age is 30')

Output

is age is 30

That's all for this topic Python String replace() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. String Slicing in Python
  3. Python String isdigit() Method
  4. Python String isnumeric() Method
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Installing Anaconda Distribution On Windows
  3. Python while Loop With Examples
  4. Multiple Inheritance in Python
  5. BigDecimal in Java
  6. Java Stream API Tutorial
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Tuesday, June 30, 2020

Executor and ExecutorService in Java Concurrency

This post gives an overview of Java Executors framework which comprises-

  1. Executor interfaces- Executor, ExecutorService and ScheduledExecutorService interfaces which define the three executor object types.
  2. Thread pools- Executor implementation classes like ThreadPoolExecutor and ScheduledThreadPoolExecutor which use thread pools.
  3. Fork/Join- A framework (from JDK 7) for taking advantage of multiple processors.

Thread management through executors in Java

In large-scale applications, its good to separate thread management and creation from the rest of the application. The concurrent API in Java has a feature called executors that provides an alternative to managing threads through the Thread class.

Executor interface in Java

At the core of the Java executors framework is the Executor interface, which also has two sub interfaces ExecutorService and ScheduledExecutorService.

An object of type Executor can execute runnable tasks. An Executor is normally used instead of explicitly creating threads. For example If r is a Runnable object, and e is an Executor object you can replace

(new Thread(r)).start();
with
e.execute(r);

Methods in Java Executor interface

The Executor interface in Java provides a single method execute().

void execute(Runnable command)- Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

Java ExecutorService interface

ExecutorService interface in Java extends Executor interface and provides methods to manage termination (through shutdown() method) and methods that can produce a Future (using submit() with a Callable) for tracking progress of one or more asynchronous tasks.

ExecutorService interface has more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allows the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks.

ExecutorService Implementing classes

In the Java concurrency there are three pre defined executor classes that implement the Executor and ExecutorService interfaces.

  1. ThreadPoolExecutor- Implements the Executor and ExecutorService interfaces and executes the submitted task using one of the pooled thread.
  2. ScheduledThreadPoolExecutor- It extends ThreadPoolExecutor and also implements the ScheduledExecutorService interface. This class schedule commands to run after a given delay, or to execute periodically.
  3. ForkJoinPool implements the Executor and ExecutorService interfaces and is used by the Fork/Join Framework.

Before writing any examples for Executor or ExecutorService, two things are worth knowing Executors class and ThreadPools.

ThreadPools in Java

In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management overhead.

Thread pool as the name suggests provides a set of threads, any task which has to be executed get a thread from this pool.

Executors class in Java

Executors class provides factory and utility methods for Executors framework classes like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.

Though you can use ThreadPoolExecutor and ScheduledThreadPoolExecutor directly, but the best way to get an executor is to use one of the static factory methods provided by the Executors utility class.

Some of the factory methods provided by Java Executors class are-

  1. static ExecutorService newCachedThreadPool()- Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
  2. static ExecutorService newFixedThreadPool(int numThreads)- Creates a thread pool that reuses a fixed number of threads.
  3. static ScheduledExecutorService newScheduledThreadPool(int numThreads)- Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
  4. newSingleThreadExecutor()- Creates an Executor that uses a single worker thread operating off an unbounded queue.

Java ExecutorService Examples

As already mentioned apart from execute() method, ExecutorService also has submit() method which is overloaded to take either Runnable or Callable as parameter. So let's see examples for these methods.

Using execute method

In this ExecutorService example a thread pool of two threads is created, and 6 runnable tasks are executed using execute() method. These 6 tasks will be executed using only these 2 threads from the thread pool, new thread won't be created for each of the 6 tasks. It can be verified from the thread name in the output.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {
 public static void main(String args[]) {
  // creating executor with pool of 2 threads
  ExecutorService ex = Executors.newFixedThreadPool(2);
  // running 6 tasks
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  //shutting down the executor service
  ex.shutdown();
 }
}
 
/**
 *
 */
class Task implements Runnable{

 @Override
 public void run() {
  System.out.println("in run task for thread - " + Thread.currentThread().getName());
  // Introducing some delay for switching
  try {
   Thread.sleep(500);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

Output

in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1
in run task for thread - pool-1-thread-1
in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1

Submit with Runnable parameter example

In this ExecutorService Java example submit method is used to submit a runnable task for execution which returns a Future representing that task. The Future's get() method will return null upon successful completion of a runnable task.

In the example 2 runnable tasks are submitted which return future objects, in case of Runnable, Future's get method will return null.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceDemo {
 public static void main(String args[]) {
  // creating executor with pool of 2 threads
  ExecutorService ex = Executors.newFixedThreadPool(2);
  // running tasks
  Future f1 = ex.submit(new Task());
  Future f2 = ex.submit(new Task());
  try {
   // getting the future value
   System.out.println("Future f1 " + f1.get());
   System.out.println("Future f1 " + f1.get());
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ExecutionException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  ex.shutdown();
  
 }
}

/**
 * Runnable 
 */
class Task implements Runnable{

 @Override
 public void run(){
  System.out.println("in run task for thread - " + Thread.currentThread().getName());
  // Introducing some delay for switching
  try {
   Thread.sleep(500);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   
   e.printStackTrace();
      
  }
 }
}

Output

in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1
Future f1 null
Future f1 null

Submit with Callable as parameter example

In this ExecutorService Java example callable task is submitted using submit() method.

Callable interface has call method which can return value too, so in this case when Future's get method is called it'll return a value. Note that here callable is implemented as a lambda expression.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceDemo {
  public static void main(String args[]) {
    // creating executor with pool of 2 threads
    ExecutorService ex = Executors.newFixedThreadPool(2);
    // Callable implemented as lambda
    Callable<String> c = ()->"Callable lambda is called";
    // running tasks with callable as param
    Future f1 = ex.submit(c);
    try {
      // getting the future value
      System.out.println("Future f1 " + f1.get());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    ex.shutdown();      
  }
}

Output

Future f1 Callable lambda is called

ExecutorService shutdown

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

ScheduledExecutorService interface in Java

ScheduledExecutorService extends ExecutorService and provides methods that can schedule commands to run after a given delay, or to execute periodically.

It has methods that execute a Runnable or Callable task after a specified delay.

  • schedule(Callable<V> callable, long delay, TimeUnit unit) - Creates and executes a ScheduledFuture that becomes enabled after the given delay.
  • schedule(Runnable command, long delay, TimeUnit unit) - Creates and executes a one-shot action that becomes enabled after the given delay.

In addition, the interface defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.

  • scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) - Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.
  • scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) - Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

ScheduledThreadPoolExecutor Java Example code

In this ScheduledExecutorService Java example callable task is submitted using schedule method which will be executed after a delay of 2 Sec.

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class STEDemo {
  public static void main(String[] args) {
    ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
    // Callable implemented as lambda
    Callable<String> c = ()->{
      System.out.println("Time of execution- " + new Date());
      return "Callable lambda is called";
    };
    System.out.println("Time before execution- " + new Date());
    // scheduling tasks with callable as param
    // it will execute after a delay of 2 Secs
    ScheduledFuture<String> sf = scheduledExecutor.schedule(c, 2, TimeUnit.SECONDS); 
    try {
      System.out.println("Value- " + sf.get());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
      scheduledExecutor.shutdown();
  }
}

Output

Time before execution- Wed Nov 21 11:37:15 IST 2018
Time of execution- Wed Nov 21 11:37:17 IST 2018
Value- Callable lambda is called

That's all for this topic Executor and ExecutorService in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Callable And Future in Java Concurrency
  2. ArrayBlockingQueue in Java Concurrency
  3. CopyOnWriteArrayList in Java
  4. CyclicBarrier in Java Concurrency
  5. Java Concurrency Interview Questions

You may also like-

  1. How to iterate a Hash map of arraylists of String in Java?
  2. How to sort HashSet in Java
  3. Difference Between Comparable and Comparator in Java
  4. Difference Between Checked & Unchecked Exception in Java
  5. static reference to the non-static method or field error
  6. Race condition in Java multi-threading
  7. interface default methods in Java 8
  8. ThreadLocal class in Java

Monday, June 29, 2020

Display Time in 24 Hours Format in Java

In this article we’ll see a Java program to display time in 24 hour format. The pattern specified in SimpleDateFormat or DateFormatter class (Java 8 onward) for time determines whether time is shown in 12 hour format or 24 hour format. For 24 hour format you will have to use HH for hour not hh.

Time in 24 hour format using DateFormatter

LocalTime time = LocalTime.now();
// Pattern for 24 hrs
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("Time (24 Hour format) - " + time.format(pattern));

Output

Time (24 Hour format) – 16:43:45

Time in 24 hour format using SimpleDateFormat

Date date = new Date();
// Pattern for 24 Hrs.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Time (24 Hour format) - " + sdf.format(date));

Output

Time (24 Hour format) – 16:45:30

That's all for this topic Display Time in 24 Hours Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Format Time in AM-PM Format - Java Program
  2. Create Date Object in Java With Date and Time Values
  3. Java Program to Get Current Date and Time
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. Difference Between Two Dates in Java

You may also like-

  1. Ternary Search Program in Java
  2. Count Total Number of Times Each Character Appears in a String - Java Program
  3. How to Convert a File to Byte Array
  4. Setting And Getting Thread Name And Thread ID - Java Program
  5. Java Lambda Expression as Method Parameter
  6. Interface Default Methods in Java
  7. Service in Angular With Examples
  8. Insert\Update using NamedParameterJDBCTemplate in Spring framework

Wednesday, June 24, 2020

Java Program to Get Current Date and Time

This article shows how to get current date and time in Java. In the new data and time API from Java 8 onward there are following classes that can be used for displaying either current date, current time or both.

  • java.time.LocalDate- To get current date.
  • java.time.LocalTime- To get current time.
  • java.time.LocalDateTime- To get both current date and time.
  • java.time.ZonedDateTime– To get both current date and time with time-zone information.

Other options, mostly applicable, if you are still not using Java 8 version or above are as follows.

  • By using java.util.Date class
  • By using java.util.Calendar class

1. Current date using LocalDate in Java

Using now() method of the LocalDate you can obtain the current date from the system clock in the default time-zone. For formatting the date in required format you can use DateTimeFormatter class also added in Java 8.

LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(currentDate.format(formatter)); //2020-06-22

2. Current time using LocalTime in Java

Using now() method of the LocalTime class you can obtain the current time from the system clock in the default time-zone.

LocalTime currentTime = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
System.out.println(currentTime.format(formatter)); //09:54:09

3. Current date and time using LocalDateTime in Java

Using now() method of LocalDateTime class you can get the current date-time from the system clock in the default time-zone.

LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(currentDateTime.format(formatter)); //2020-06-22T09:58:46

4. Current date and time with zone information

By using ZonedDateTime you can get zone offset and time-zone information too.

ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss z VV");
System.out.println(currentDateTime.format(formatter)); //2020-06-21T21:32:22 GMT-07:00 America/Los_Angeles

5. Getting Date and Time using java.util.Date

When a new Date object is created it is initialized to represent the time at which it was allocated.

Date date = new Date();
System.out.println("Date- " + date); // Date- Mon Jun 22 10:06:12 IST 2020

For formatting date you can use SimpleDateFormat class.

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("Date- " + sdf.format(date)); // 2020-06-22 10:07:38

6. Getting Date and Time using java.util.Calendar

In Calendar class there is a getInstance() method that gives the current date and time.

Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("Date- " + sdf.format(calendar.getTime())); // 2020-06-22 10:10:34

That's all for this topic Java Program to Get Current Date and Time. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Create Date Object in Java With Date and Time Values
  2. How to Convert String to Date in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. How to Compile Java Program at Runtime
  5. Converting double to int in Java

You may also like-

  1. Converting String to Enum Type in Java
  2. Invoking Getters And Setters Using Reflection - Java Program
  3. Connection Pooling Using C3P0 in Java
  4. final Vs finally Vs finalize in Java
  5. Map Operation in Java Stream API
  6. Spring MVC Redirect Example
  7. Spring Boot StandAlone (Console Based) Application Example
  8. Angular ngFor Directive With Examples