Friday, April 26, 2024

Printing Numbers in Sequence Using Threads Java Program

This post shows how you can print numbers in sequence using three threads in Java. If there are three threads thread1, thread2 and thread3 then numbers should be printed alternatively by these threads like this.

thread1 - 1
thread2 - 2
thread3 – 3
thread1 - 4
thread2 - 5
thread3 – 6
...
...
...

Print numbers in sequence using three threads in Java

While printing numbers in sequence using threads trick is to use modulo division to check which thread can print the number and which threads are to be blocked waiting.

Each thread is assigned one of the numbers 0, 1 and 2. Each number is divided by 3 (number of threads), remainder will be any one of these numbers 0, 1 or 2. That is what is checked; if (remainder = number assigned to thread) only then thread can work otherwise it goes into waiting state.

class SharedPrinter{
  int number = 1;
  int numOfThreads;
  int numInSequence;
  SharedPrinter(int numInSequence, int numOfThreads){
    this.numInSequence = numInSequence;
    this.numOfThreads = numOfThreads;
  }
  public void printNum(int result){
    synchronized(this) {
      while (number < numInSequence - 1) {
        while(number % numOfThreads != result){
          try {
            this.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        System.out.println(Thread.currentThread().getName() + " - " + number++);
        this.notifyAll();
      }
    }
  }
}
class SeqRunnable implements Runnable{
  SharedPrinter sp;
  int result;
  static Object sharedObj = new Object();
  SeqRunnable(SharedPrinter sp, int result){
    this.sp = sp;
    this.result = result;
  }
  @Override
  public void run() {
    sp.printNum(result);
  }
}
public class SeqNumber {
  final static int NUMBERS_IN_SEQUENCE = 10;
  final static int NUMBER_OF_THREADS = 3;
  public static void main(String[] args) {
    // Shared object
    SharedPrinter sp = new SharedPrinter(NUMBERS_IN_SEQUENCE, NUMBER_OF_THREADS);
    // Creating 3 threads
    Thread t1 = new Thread(new SeqRunnable(sp, 1), "Thread1");
    Thread t2 = new Thread(new SeqRunnable(sp, 2), "Thread2");
    Thread t3 = new Thread(new SeqRunnable(sp, 0), "Thread3");

    t1.start();
    t2.start();
    t3.start();
  }
}

Output

Thread1 - 1
Thread2 - 2
Thread3 - 3
Thread1 - 4
Thread2 - 5
Thread3 - 6
Thread1 - 7
Thread2 - 8
Thread3 - 9
Thread1 - 10

That's all for this topic Printing Numbers in Sequence Using Threads Java Program. 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 Run Threads in Sequence in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Producer-Consumer Java Program Using ArrayBlockingQueue
  4. How to Create Deadlock in Java
  5. Race condition in Java multi-threading

You may also like-

  1. Converting String to Enum Type in Java
  2. Connection Pooling Using C3P0 in Java
  3. Java Program to Find First Non-Repeated Character in a Given String
  4. How to Convert String to Date in Java
  5. Java Multithreading Interview Questions And Answers
  6. How and Why to Synchronize ArrayList in Java
  7. BigDecimal in Java With Examples
  8. Introduction to Hadoop Framework

Thursday, April 25, 2024

FormGroup in Angular With Examples

Using FormGroup in Angular forms you can group FormControl instances and track the value and validity state of those instances as a group rather than for each individual FormControl instance. In this post we'll see example of using FormGroup with Angular template-driven form as well as with Reactive form.


Wednesday, April 24, 2024

How to Setup a Node.js Project

In this article we'll see how to set up a Node.js project with a package.json file so that you can easily install other dependencies using NPM. This also shows how you'll use NodeJS' module pattern to create projects which is a collection of many files and packages.

Prerequisite to creating a project is that Node.js is installed in your system (which also install NPM) and you have an IDE like Visual Studio Code.

Check this post How to Install Node.js and NPM in Windows to see how to install Node.js

Setting up NodeJS project

To start with, let's create a new directory and you can name it nodeapp or any other meaningful name. If you open this directory in Visual Studio Code as expected you won't have anything with in it!

In order to make it a Node project you'll have to use the command npm init which creates a package.json file by asking you few questions. If you want to bypass these questions and answer "yes" by default for all the questions you can use npm init -y command instead.

Go to the directory you have just created and run the npm init command to initialize your Node project.

nodeapp>npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodeapp)
version: (1.0.0)
description: A node project
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\NETJS\NetJS_2017\NodeJS\nodeapp\package.json:

{
  "name": "nodeapp",
  "version": "1.0.0",
  "description": "A node project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

As you can see for most of the questions asked, I have just pressed enter, only entry is for the "description". You can always go later to the created package.json file and edit it so no worries.

If you go to Visual Studio code now you should see the generated package.json file.

Setting NodeJS project

Since the starting file is named as "index.js" so let's create such a file in our "nodeapp" project.

index.js

console.log("It's a new Node project");

Running this JavaScript file should output the content as expected.

node index.js

It's a new Node project

Now let's change our package.json a little and add a kay-value entry in the "scripts" section.

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },

This instructs Node to use start script as the executor of the command given as value "node index.js". Now you can use npm start command to start your project.

npm start

> nodeapp@1.0.0 start
> node index.js
It's a new Node project

Importing packages in NodeJS

Let's try to import and use modules in our code files. To start with we'll import built-in Node modules for which you don't need any extra installation as these modules are already there in NodeJS.

We'll use fs and path modules to write a file. The 'fs' module is used to handle the file system and the 'path' module is used to handle file paths.

In order to use these modules, you'll need to import them, in NodeJS you can do it as given below.

const fs = require('fs');

const path = require('path');

Using writeFile() method of the fs package we'll write to a file. Here is the description of the writeFile() method.

fs.writeFile( file, data, options, callback )
  • file: Path of the file where it has to be written.
  • data: The data you want to write to the file.
  • options: To specify optional parameters like encoding
  • callback: It is the function that would be called when the method is executed.

index.js

Here is the modified index.js file.

const fs = require('fs');
const path = require('path');
console.log(__dirname);
console.log("It's a new Node project");
const content = "A test file";
fs.writeFile(path.join(__dirname, 'test.txt'), content, (err) => {
    if (err)
      console.log(err);
    else {
      console.log("File written successfully\n");
    }
});

Note that __dirname is a variable that tells you the absolute path of the directory containing the currently executing file. Using path.join() method an absolute path for the file is given.

If you run npm start command now you should see a file "test.txt" created within your root project directory.

Installing third party packages in Node project

In the above example we used built-in modules that don’t need any installation but you will definitely use many other third-party packages that would need installation. For that you will use npm install <package_name> command.

In our project we'll try to install Nodemon package that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

To see Nodemon in use we'll change the index.js to create a HTTP Server using Node.js

index.js

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const requestListener = function(req, res){
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.write('Hello World');
    res.write(' From NodeJS\n');
    res.end();
}
const server = http.createServer(requestListener);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

If you run the npm start command now and go to the URL http://localhost:3000/ once the server is started you should see the response as sent by the server.

If we make a slight change in the code now and change the line from res.write(' From NodeJS\n'); to this res.write(' From NodeJS Project\n');

Above change won't be reflected automatically and you'll have to stop the server and restart it to get this change reflected. That's where Nodemon can help as it automatically restarts the node application when file changes are detected.

npm install options

You can control where and how the specified packages get saved by using some additional flags with npm install

-P, --save-prod: Package will appear in your dependencies. You'll use this option if you want the installed package to be part of production build too. This is the default also

-D, --save-dev: Package will appear in your devDependencies. You'll use this option if you want the installed package to be used during development only.

-O, --save-optional: Package will appear in your optionalDependencies.

--no-save: Prevents saving to dependencies.

It makes sense to install Nodemon as dev dependency so use the following command to install Nodemon.

npm install nodemon --save-dev

Once the installation is done if you go back to your project structure you'll see some new directories and files like package-lock.json and node_modules folder.

package-lock.json- Provides version information for all packages installed into node_modules by the npmclient.
node_modules- Provides npm packages to the entire workspace. That's the directory where packages are installed.

Node project structure

In the package.json file now you'll see a "devDependencies" entry.

"devDependencies": {
    "nodemon": "^3.1.0"
  }

You'll need to make one more change in the start script to start using nodemon rather than node.

"start": "nodemon index.js"

With that if you use npm start command.

npm start

> nodeapp@1.0.0 start
> nodemon index.js

[nodemon] 3.1.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`
Server running at http://localhost:3000/

If you make changes in index.js file you can see that the application starts automatically now.

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server running at http://localhost:3000/

That's all for this topic How to Setup a Node.js Project. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Introduction to Node.js
  2. Creating HTTP server in Node.js
  3. JavaScript Rest Parameter
  4. JavaScript filter Method With Examples

You may also like-

  1. Count Number of Words in a String Java Program
  2. How to Use ngFor and ngIf in Same Element in Angular
  3. Angular @Input and @Output Example
  4. React create-react-app Project Structure
  5. BigDecimal in Java With Examples
  6. Spring Boot Hello World Web Application Example
  7. Java Exception Handling Interview Questions And Answers
  8. Creating PDF in Java Using iText

Tuesday, April 23, 2024

Difference Between StackOverflowError and OutOfMemoryError in Java

Differences between StackOverflowError and OutOfMemoryError in Java is a frequently asked Java interview question. You may also encounter one of these errors in your application. Before going into StackOverflowError Vs OutOfMemoryError let’s get some background about these errors.


StackOverflowError in Java

Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program.

For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table.

Once the method execution is completed corresponding stack frame is popped out of the stack.

JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size. A very common scenario where you may see StackOverflowError is when you have a recursive method with no terminating condition. For example following program that calculates factorial of a number using recursive method call. Since there is no exit condition defined so recursive method call never ends resulting in StackOverflowError.

public class StackOFErrorExp {
  public static void main(String[] args) {
    double factorialResult = factorial(1000);
    System.out.println(factorialResult);
  }
  private static int factorial(int i) {
    /*
     * if (i == 0 || i == 1 ) '
     *  return 1;
     */
    return i * factorial(i - 1);
  }
}

OutOfMemoryError in Java

In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory.

If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

Here is an example of java.lang.OutOfMemoryError where objects are added to an ArrayList in an infinite loop. Since objects stored to the List are not garbage collected so heap memoery will finally run out of memory resulting in OutOfMemoryError.

public class OutofMemoryExp {
  public static void main(String[] args) {
    List list = new ArrayList<>();
    int i = 0;
    // results in indefinite loop
    while(true) {
      i++;
      list.add(i * 1000000);
    }  
  }
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at java.base/java.util.Arrays.copyOf(Arrays.java:3721)
 at java.base/java.util.Arrays.copyOf(Arrays.java:3690)
 at java.base/java.util.ArrayList.grow(ArrayList.java:237)
 at java.base/java.util.ArrayList.grow(ArrayList.java:242)
 at java.base/java.util.ArrayList.add(ArrayList.java:485)
 at java.base/java.util.ArrayList.add(ArrayList.java:498)
 at org.netjs.examples.OutofMemoryExp.main(OutofMemoryExp.java:14)

StackOverflowError Vs OutOfMemoryError in Java

  1. StackOverflowError is thrown when there is no sufficient stack space for storing method data.
    OutOfMemoryError is thrown when no sufficient heap space left for creating new objects or requested array size is more than heap memory.
  2. StackOverflowError happens when you have Recursive methods with out terminating condition.
    OutOfMemoryError happens when new objects can’t be allocated on the heap as existing objects still have references so can’t be garbage collected.
  3. In order to avoid StackOverflowError ensure that methods are finishing their execution and corresponding stack memory is freed.
    In order to avoid OutOfMemoryError ensure that there are no references to objects which you don’t need anymore so that such objects can be garbage collected freeing heap memory in the process.

That's all for this topic Difference Between StackOverflowError and OutOfMemoryError in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between Checked And Unchecked Exceptions in Java
  2. Difference Between throw And throws in Java
  3. final Vs finally Vs finalize in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

You may also like-

  1. Java Exception Handling Interview Questions And Answers
  2. Array in Java With Examples
  3. Varargs (Variable-length Arguments) in Java
  4. Type Erasure in Java Generics
  5. Pre-defined Functional Interfaces in Java
  6. Linear Search (Sequential Search) Java Program
  7. Introduction to Node.js
  8. Bean Scopes in Spring With Examples

Monday, April 22, 2024

What is In-place Algorithm

An in-place algorithm is an algorithm that doesn’t use any auxiliary space to transform the input. Though theoretically that would mean if you have an array of length n then you should use that n space itself to transform the input array but in reality you will definitely use some variables and index for array and that kind of auxiliary space is allowed for an in-place algorithm.

Examples of in-place algorithm are sorting algorithms like Bubble sort, Selection Sort, Insertion Sort which doesn’t require any extra space to perform sorting. That is why space complexity for these algorithms is O(1).

Merge sort, Bucket sort are examples of not in-place or out-of-place sorting algorithms.

In-place algorithm example

Let’s try to understand this auxiliary space requirement of in-place algorithm by taking an algorithm to reverse an array by using separate input and output arrays making it a not in-place algorithm.

import java.util.Arrays;

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    // Using another array
    int[] tempArray = new int[n];
    for (int i = 0; i < n; i++) { 
      tempArray[n - i - 1] = intArray[i]; 
    } 
    System.out.println("Reversed Array- " + Arrays.toString(tempArray));
  }
}

But the algorithm to reverse an array can very well be written to use the same input array to reverse it. There is no need to use a separate array making it an in-place algorithm.

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    for (int i = 0; i < n / 2; i++) {
      int temp = intArray[i];
      intArray[i] = intArray[n - 1 - i];
      intArray[n - 1 - i] = temp;
    }
    System.out.println("Reversed Array- " + Arrays.toString(intArray));
  }
}

That's all for this topic What is In-place Algorithm. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Shell Sort Program in Java
  2. Tree Sort in Java Using Binary Search Tree
  3. Linear Search (Sequential Search) Java Program
  4. Reverse Each Word in a String Java Program
  5. How to Remove Elements From an Array Java Program

You may also like-

  1. Converting String to Enum Type in Java
  2. How to Read File From The Last Line in Java
  3. Java Program to Get Current Date and Time
  4. Running Dos/Windows Commands From Java Program
  5. How to Loop Through a Map in Java
  6. Difference Between Abstract Class And Interface in Java
  7. Angular One-Way Data Binding Using String Interpolation
  8. Changing String Case in Python

Sunday, April 21, 2024

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 the latest 8.x.x version. 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>8.0.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-api</artifactId>
    <version>2.0.13</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.13</version>
</dependency>

Please be aware you will always need kernel, io and layout dependencies while working with iText library. Not having slf4j produces a warning so better have the dependencies available.

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();
  }   
 }
}

Adding table in PDF using iText - Java Program

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

Adding background image to PDF using iText

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

Adding image to PDF using iText - Java Program

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();
    } 
  }
}

Adding List to PDF using iText - Java Program

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

iText: Render PDF 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

Password protected PDF with user permissions using iText - Java Program

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 IText Bouncy Castle Connector is as follows-

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>bouncy-castle-connector</artifactId>
    <version>${itext.version}</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>bouncy-castle-adapter</artifactId>
    <version>${itext.version}</version>
</dependency>
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. Convert double to int in Java

You may also like-

  1. How to Count Lines in a File in Java
  2. Creating Tar File And GZipping Multiple Files in Java
  3. Comparing Enum to String in Java
  4. Remove Duplicate Elements From an Array in Java
  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

Saturday, April 20, 2024

Writing a File Asynchronously Java Program

In this post we’ll see how to write a file asynchronously in Java using java.nio.channels.AsynchronousFileChannel class added in Java 7. Using AsynchronousFileChannel class you can create an asynchronous channel for reading, writing, and manipulating a file.

To see how to read a file asynchronously in Java, refer this post- Read File Asynchronously Java Program

Opening an Asynchronous channel

Whether you are reading or writing a file asynchronously first thing you need to do is to create an asynchronous channel. For that you need to use static open() method of the AsynchronousFileChannel class which opens or creates a file for reading or writing, returning an asynchronous file channel to access the file.

Following code snippet shows how you can create an asynchronous file channel for writing to a file.

Path path = Paths.get("F:\\netjs\\WriteFile.txt");
AsynchronousFileChannel asyncFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)

Writing file asynchronously using AsynchronousFileChannel class

For writing a file asynchronously there are two versions of write() method in the AsynchronousFileChannel class.

  1. write() method that writes the passed buffer to the file and returns a Future representing the result of the write operation.
  2. write() method where you pass CompletionHandler instance as an argument.

We’ll see examples of of both of these ways to write a file asynchronously to have a better idea.

Writing to a file asynchronously in Java

1. In the first Java program we’ll use the write method that returns a Future.

Future<Integer> write(ByteBuffer src, long position)- This method writes a sequence of bytes to this channel from the passed buffer, starting at the given file position.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncFileWrite {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    // Write Data to buffer
    buffer.put("This will be written to a file.".getBytes());
    buffer.flip();
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)){
      // Write to async channel from buffer
      // starting from position 0
      Future<Integer> future =  asyncChannel.write(buffer, 0);
      while(!future.isDone()) {
        System.out.println("Waiting for async write operation... ");
        // You can do other processing
      }            
      buffer.clear();            
      System.out.println("Total bytes written- " + future.get());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

2. In this Java program for writing file asynchronously we’ll use the write() method where CompletionHandler instance is passed as an argument.

CompletionHandler interface defines two callback methods which you need to implement.

  • completed(V result, A attachment)- Invoked when an operation has completed.
  • failed(Throwable exc, A attachment)- Invoked when an operation fails.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.channels.CompletionHandler;

public class AsyncFileWrite {
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("F:\\netjs\\test.txt");
    if(!Files.exists(path)){
      Files.createFile(path);
    }
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    // Write Data to buffer
    buffer.put("This will be written to a file.".getBytes());
    buffer.flip();
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)){
      // Write to channel from buffer, start from position 0
      asyncChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
          System.out.println("Total bytes written- " + result);
        }

        @Override
        public void failed(Throwable ex, ByteBuffer attachment) {
          System.out.println("Write operation failed- " + ex.getMessage());                    
        }
      });            
    }
  }
}

That's all for this topic Writing a File Asynchronously Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Write to a File in Java
  2. How to Append to a File in Java
  3. How to Write Excel File in Java Using Apache POI
  4. Creating Temporary File in Java
  5. Reading File in Java Using BufferedReader

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. Creating PDF in Java Using Apache PDFBox
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. Invoking Getters And Setters Using Reflection in Java
  5. HashMap in Java With Examples
  6. Interface in Java
  7. Passing Arguments to getBean() Method in Spring
  8. YARN in Hadoop