Monday, April 29, 2024

Checkbox in Angular Form Example

In this post we’ll see how to use check boxes in Angular form. We’ll see examples of adding check boxes to both template-driven and reactive form in Angular.

Checkbox in Reactive form Angular example

In this Angular Reactive form example we’ll have a form with two input fields for name and date (with a date picker for picking date) and a group of check boxes to select favorite exercises.

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 in Node.js. 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!

>>>Return to Node.js Tutorial Page


Related Topics

  1. Introduction to Node.js
  2. Creating HTTP server in Node.js
  3. Node.js REPL
  4. NodeJS NPM Package Manager
  5. Node.js Event Driven Architecture

You may also like-

  1. Reading a File in Node.js
  2. Node.js path.basename() Method With Examples
  3. JavaScript Rest Parameter
  4. How to Use ngFor and ngIf in Same Element in Angular
  5. React create-react-app Project Structure
  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

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

Friday, April 19, 2024

Radio Button in Angular Form Example

In this post we’ll see how to use radio buttons in Angular form. We’ll see examples of adding radio button to both template-driven and reactive form in Angular.


Radio button in template driven form example

In this Angular template driven form example we’ll have a form with two input fields for name and email, a date picker for picking date and a group of radio buttons to select membership type.

Thursday, April 18, 2024

Functional Interfaces in Java

A functional interface in Java is an interface with only one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method). An example of functional interface with in Java would be Runnable interface which has only one method run().


Java functional interface example

interface IMyInterface {
  int getValue();
}

In interface IMyInterface there is only single abstract method getValue() (note that in an interface methods are implicitly abstract).

Wednesday, April 17, 2024

FormBuilder in Angular Example

In this tutorial we’ll see how to use FormBuilder in Angular to create a form. FormBuilder is a helper class that reduces the boilerplate code while building a form. It shortens the code to create instances of a FormControl, FormGroup, or FormArray.

Steps needed to use FormBuilder

  1. Import the FormBuilder class.
    import { FormBuilder } from '@angular/forms';
    
  2. Inject the FormBuilder service.
    constructor(private fb: FormBuilder) { }
    
  3. Generate the form contents. The FormBuilder has three factory methods: control(), group(), and array() used to generate instances of FormControl, FormGroup, and FormArray in your component classes.

Tuesday, April 16, 2024

Java Object Cloning - clone() Method

In this post we'll see what is Object cloning in java and what is shallow copy and deep copy in reference to Java object cloning.

In Java if you assign an object variable to another variable the reference is copied which means both variable will share the same reference. In this case any change in one object variable will be reflected in another.

For example, if there is a class Test and you create an object of that class and then assign that reference to another object variable.

Test obj1 = new Test();
Test obj2 = obj1;

Here both obj1 and obj2 will have the same reference.


Java Object cloning

What is the option then if you want to quickly create an object using the existing object in such a way that you get a new instance (reference is not shared) with the same content for the fields in the new object as in existing object.

That’s when you can use clone() method which creates an exact copy of the existing object. Then you can modify the cloned object without those modifications reflecting in original object (Well we’ll go into shallow copy and deep copy a little later).

clone() method in Java

clone() method is defined as protected in the Java Object class which you must override as public in any derived classes that you want to clone.

Signature of clone method in Object class

protected native Object clone() throws CloneNotSupportedException;

Process of object cloning in Java

There are two required steps if you want to clone any object.

  1. You need to call clone() method of the Object class or provide your own implementation by overriding the clone() method in your class.
  2. Your class, whose object you want to clone, must implement Cloneable interface which is part of java.lang package. Not implementing Cloneable interface will result in CloneNotSupportedException exception being thrown when clone method is called.

Here note that Cloneable interface is a marker interface and defines no members of its own.

Object cloning in Java example

When cloning an object in Java you need to call clone() method of the Object class. You can do it from a method or you can override clone() method of the Object class and then call the clone() method of the super class (Object class).

Scenario 1- Calling clone() method from a method

Here we have a class Test which implements Cloneable interface and it has a method cloneIt() which calls the clone() method of the Object class.

Class Test

public class Test implements Cloneable{
  int a;
  float f;
 
 Test cloneIt(){
  Test test = null;
  try {
   // Calling clone() method of Object class
   test = (Test)super.clone();
  } catch (CloneNotSupportedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return test;
  
 }
}

CloningDemo class

public class CloningDemo {

 public static void main(String[] args) {
  Test t1 = new Test();
  t1.a = 10;
  t1.f = 13.4F;
  // Calling method to clone
  Test t2 = t1.cloneIt();
  System.out.println("t1.a " + t1.a + " t1.f " + t1.f);
  
  System.out.println("t2.a " + t2.a + " t2.f " + t2.f);

  if(t1 != t2){
   System.out.println("Different instances");
  }else{
   System.out.println("Same instances");
  }
 }
}

Output

t1.a 10 t1.f 13.4
t2.a 10 t2.f 13.4
Different instances

Here you can see that Test class object t1 is cloned and a new instance t2 is created. In the code, reference equality is checked and you can see that the reference is not shared and both are indeed different instances. New instance t2 has the same values in the properties.

Points to note

Some of the points to note from this code–

  1. Class whose object has to be cloned should implement Cloneable interface, otherwise java.lang.CloneNotSupportedException exception will be thrown.
  2. clone() method is a protected method in Object class, since all the classes inherit from Object class so you can call the protected method of the super class.
  3. While cloning bitwise copy of the object is created.

Scenario 2 – Overriding clone method

Another way to provide object cloning functionality is to override the clone() method in the class, in that case it has to be a public method in order to be accessible.

If we change the classes used in the above example to have overridden clone method and calling that clone method then the structure will be as follows–

Test class

public class Test implements Cloneable{
 int a;
 float f;
 // Override clone method
 public Object clone(){
  Object obj = null;
  try {
   // Calling clone() method of Object class
   obj = super.clone();
   } catch(CloneNotSupportedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return obj;
 }
}

CloningDemo class

public class CloningDemo {

 public static void main(String[] args) {
  Test t1 = new Test();
  t1.a = 10;
  t1.f = 13.4F;
  // Call clone method
  Test t2 = (Test)t1.clone();
  System.out.println("t1.a " + t1.a + " t1.f " + t1.f);
  
  System.out.println("t2.a " + t2.a + " t2.f " + t2.f);
  
  if(t1 != t2){
   System.out.println("Different instances");
  }else{
   System.out.println("Same instances");
  }
 }
}

Output

t1.a 10 t1.f 13.4
t2.a 10 t2.f 13.4
Different instances

Advantages of object cloning

If you have an object, creation of which using the usual way is costly; as example if you have to call DB in order to get data to create and initialize your object. In that scenario rather than hitting DB every time to create your object you can cache it, clone it when object is needed and update it in DB only when needed.

Actually there is a design pattern called prototype design pattern which suggests the same approach.

Shallow copy - Java object cloning

In the above examples only primitive types are used so there is no problem, if you change any primitive value that won’t reflect in other object.

What if there is another object reference in your class? As already mentioned when you clone an object all the values for the fields are copied to the cloned object. Since Java is pass by value, if the field value is a reference to an object (a memory address) it copies that reference to the field of the cloned object. In that case referenced field is shared between both objects and any change made to the referenced field will be reflected in the other object too.

This process of cloning when the field values are copied to the new object is known as shallow copy. Shallow copies are simple to implement and typically cheap, as they can be usually implemented by simply copying the bits exactly.

Deep Copy - Java object cloning

If you don’t want references of object being copied during the cloning process then option is deep copy. When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.

Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

That's all for this topic Java Object Cloning - clone() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Serialization and Deserialization in Java
  2. SerialVersionUID And Versioning in Java Serialization
  3. Java Nested Class And Inner Class
  4. Marker interface in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. instanceof Operator in Java With Examples
  2. BigDecimal in Java With Examples
  3. Java split() Method - Splitting a String
  4. final Vs finally Vs finalize in Java
  5. Parallel Stream in Java Stream API
  6. @FunctionalInterface Annotation in Java
  7. Deadlock in Java Multi-Threading
  8. Java Program to Find The Longest Palindrome in a Given String

Monday, April 15, 2024

Read File Asynchronously Java Program

In this post we’ll see how to read 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.

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 can 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 reading a file.

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

Reading file asynchronously using AsynchronousFileChannel class

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

  1. read() method that returns a Future.
  2. read() method where you can pass CompletionHandler instance as an argument.

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

Reading file asynchronously in Java

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

abstract Future<Integer> read(ByteBuffer dst, long position)- This method reads sequence of bytes from the opened channel into the buffer passed as argument. Reading starts at the passed 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.Future;

public class AsyncFileRead {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // buffer into which data is read
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)){
      Future<Integer> result = asyncChannel.read(buffer, 0);
      while(!result.isDone()) {
        System.out.println("Waiting for read... ");
        // You can do other processing
      }
      /* File data ready */
      //limit is set to the current position 
      //and position is set to zero
      buffer.flip();
      String data = new String(buffer.array()).trim();
      System.out.println(data);
      buffer.clear();            
    } catch (IOException e) {
      System.out.println("Error while reading file- " + e.getMessage());
      e.printStackTrace();
    }        
  }
}

2. In this Java program for reading file asynchronously we’ll use the read() 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.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.channels.CompletionHandler;

public class AsyncFileRead {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // buffer into which data is read
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)){
      asyncChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        // callback methods
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
          System.out.println("Number of bytes read- " + result);
          attachment.flip();
          String data = new String(attachment.array()).trim();
          System.out.println("..." + data.length());
          System.out.println(data);
          attachment.clear();
        }

        @Override
        public void failed(Throwable ex, ByteBuffer attachment) {
          System.out.println("Read operation failed- " + ex.getMessage());                
        }            
      });
      System.out.println("Asynchronous operation in progress.. Once over callback method will be called.");
    } catch (IOException e) {
      System.out.println("Error while reading file- " + e.getMessage());
      e.printStackTrace();
    }        
  }
}

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


Related Topics

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Reading All Files in a Folder - Java Program
  3. How to Read Properties File in Java
  4. How to Read File From The Last Line in Java
  5. How to Create PDF From XML Using Apache FOP

You may also like-

  1. Write to a File in Java
  2. Setting And Getting Thread Name And Thread ID - Java Program
  3. How to Untar a File - Java Program
  4. Converting Numbers to Words - Java Program
  5. Nested Class And Inner Class in Java
  6. Generic Class, Interface And Generic Method in Java
  7. Angular Two-Way Data Binding With Examples
  8. Magic Methods in Python With Examples

Friday, April 12, 2024

Creating Tar File And GZipping Multiple Files in Java

If you want to GZIP multiple files that can’t be done directly as you can only compress a single file using GZIP. In order to GZIP multiple files you will have to archive multiple files into a tar and then compress it to create a .tar.gz compressed file. In this post we'll see how to create a tar file in Java and gzip multiple files.

Refer How to Untar a File in Java to see how to untar a file.

Using Apache Commons Compress

Here I am posting a Java program to create a tar file using Apache Commons Compress library. You can download it from here– https://commons.apache.org/proper/commons-compress/download_compress.cgi

Make sure to add commons-compress-xxx.jar in your application’s class path. I have used commons-compress-1.13 version.

Steps to create tar files

Steps for creating tar files in Java are as follows-

  1. Create a FileOutputStream to the output file (.tar.gz) file.
  2. Create a GZIPOutputStream which will wrap the FileOutputStream object.
  3. Create a TarArchiveOutputStream which will wrap the GZIPOutputStream object.
  4. Then you need to read all the files in a folder.
  5. If it is a directory then just add it to the TarArchiveEntry.
  6. If it is a file then add it to the TarArchiveEntry and also write the content of the file to the TarArchiveOutputStream.

Folder Structure used

Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories. Your Java code should walk through the whole folder structure and create a tar file with all the entries for the directories and files and then compress it.

Test
  abc.txt
  Test1
     test.txt
     test1.txt
  Test2
     xyz.txt

Creating tar file in Java example

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

public class TarGZIPDemo {
 public static void main(String[] args) {
  String SOURCE_FOLDER = "/home/netjs/Documents/netjs/Test";
  TarGZIPDemo tGzipDemo = new TarGZIPDemo();
  tGzipDemo.createTarFile(SOURCE_FOLDER);

 }
  private void createTarFile(String sourceDir){
    TarArchiveOutputStream tarOs = null;
    try {
      File source = new File(sourceDir);
      // Using input name to create output name
      FileOutputStream fos = new FileOutputStream(source.getAbsolutePath().concat(".tar.gz"));
      GZIPOutputStream gos = new GZIPOutputStream(new BufferedOutputStream(fos));
      tarOs = new TarArchiveOutputStream(gos);
      addFilesToTarGZ(sourceDir, "", tarOs);    
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      try {
        tarOs.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
 
 public void addFilesToTarGZ(String filePath, String parent, TarArchiveOutputStream tarArchive) throws IOException {
  File file = new File(filePath);
  // Create entry name relative to parent file path 
  String entryName = parent + file.getName();
  // add tar ArchiveEntry
  tarArchive.putArchiveEntry(new TarArchiveEntry(file, entryName));
  if(file.isFile()){
   FileInputStream fis = new FileInputStream(file);
   BufferedInputStream bis = new BufferedInputStream(fis);
   // Write file content to archive
   IOUtils.copy(bis, tarArchive);
   tarArchive.closeArchiveEntry();
   bis.close();
  }else if(file.isDirectory()){
   // no need to copy any content since it is
   // a directory, just close the outputstream
   tarArchive.closeArchiveEntry();
   // for files in the directories
   for(File f : file.listFiles()){        
    // recursively call the method for all the subdirectories
    addFilesToTarGZ(f.getAbsolutePath(), entryName+File.separator, tarArchive);
   }
  }          
 }
}

On opening the created .tar.gz compressed file using archive manager.

creating .tar.gz file in Java

That's all for this topic Creating Tar File And GZipping Multiple Files 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. Zipping Files And Folders in Java
  2. Unzip File in Java
  3. Compress And Decompress File Using GZIP Format in Java
  4. Java Program to Convert a File to Byte Array
  5. Reading Delimited File in Java Using Scanner

You may also like-

  1. How to Create Deadlock in Java
  2. Convert int to String in Java
  3. Read or List All Files in a Folder in Java
  4. How to Compile Java Program at Runtime
  5. How HashMap Works Internally in Java
  6. Serialization Proxy Pattern in Java
  7. Bounded Type Parameter in Java Generics
  8. Polymorphism in Java

Thursday, April 11, 2024

Creating HTTP server in Node.js

The post Introduction to Node.js gives you an idea about Node.js and the features of Node.js. Building on top of that in this post we'll see how to create a HTTP web server using NodeJS. That also gives you an idea about using JavaScript at server side with NodeJS.

Creating a HTTP Server using NodeJS

We'll start by creating a web server written with Node.js which returns plain text 'Hello World From NodeJS' to the user.

Steps for creating a web server in NodeJS are as given below.

  1. First things you need to do is to load the built-in http module. This module provides functionality for creating an HTTP server.
    const http = require('http');
    
  2. Create server using http.createServer() method.

    http.createServer() method takes requestListener function as an argument and returns a new instance of http.Server.

    This function is meant to handle an incoming HTTP request and return an HTTP response. The requestListener function takes two arguments, a request object and a response object.

    The request object has the data of the HTTP request sent by the user. The response object is used to set the response sent back from the server.

    const requestListener = function (req, res){
    	..
    	..
    }
    

    Pass this requestListener function to the http.createServer() method

    const server = http.createServer(requestListener); 
    
  3. Once the server is created you want it to listen for the connections that is done using server.listen() method. server.listen() method takes three arguments-
    • Port number- Port the created server is bound to as an endpoint.
    • Host name- IP address of the system where server is running.
    • Callback function- A callback function which is executed when the server starts listening at the given port.

nodeserver.js

Create a file nodeserver.js and write the code as given below to create a web server using NodeJS.

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}/`);
});

You can also write the requestListener function as an arrow function that makes the code more compact.

const http = require('http');

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

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

Points to note here-

  1. Port number used is 3000.
  2. Host name is 'localhost' which refers to the local system and used in place of the internal IP address 127.0.0.1. Which means to send a request to the server you’ll have to use the URL- http://localhost:3000/
  3. In the requestListener function response is created. First thing is the HTTP status code of the response which is set as “200” which means “OK”.
  4. Response header is set using res.setHeader() method. In the example it sets content type of the response as plain text.
  5. Response is written using res.write() method which can write chunks of data as response stream.
  6. end() method signals that no more data will be written to the Writable.

You can run the server by executing the JavaScript file.

node nodeserver.js

Server running at http://localhost:3000/

After that you can access http://localhost:3000/ using a browser which will establish a communication with the server. By going to the Chrom Dev tools and then Network tab you can also check the request and response.

HTTP server in Node.js

Response as HTML from NodeJS web server

In the above example content type of the response returned by the server is plain text but NodeJS web server can return content of different formats like HTML, JSON, XML, CSV also.

For that you need to set the 'Content-Type' with the corresponding format in the response header and send the content in the same format.

The following example shows how to return HTML from the server.

const http = require('http');

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

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.write('<html><head><title>My HTML</title></head><body><h2>Hello World from nodeJS</h2></body></html>');
    res.end();
});

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

As you can see now the 'Content-Type' is 'text/html' and the content that is sent back is HTML. If you re-execute the file again after stopping the server (you can use ctrl-c to stop the server) and access the URL- http://localhost:3000/ now the response you see in the browser is of type HTML.

Response as JSON from NodeJS web server

The following example shows how to return JSON from the server.

const http = require('http');

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

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.write(JSON.stringify({msg: "hello world from NodeJS" }));
    res.end();
});

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

As you can see now the 'Content-Type' is ' application/json' and the content that is sent back is in JSON format. If you re-execute the file again after stopping the server (you can use ctrl-c to stop the server) and access the URL- http://localhost:3000/ now the response you see in the browser is of type JSON.

Serving HTML file from webserver using Node.js

Mypage.html

HTML file that the web server will return.

<!DOCTYPE HTML>
<html>
    <head>
        <title>My HTML</title>
    </head>
    <body>
        <h2>Hello World from nodeJS</h2>
        <p>The content is read from a HTML file.</p>
    </body>
</html>

To work with the file system on your computer you need to import Node.js file system module which is called fs.

Also import path module which provides utilities for working with file and directory paths.

In the fs module there is a readFile method method which takes the file path as one argument and a callback function as another argument. The callback function takes two arguments, first as error (if there is some error while reading the file) and second as content of the file (if file is successfully read).

nodeserver.js

const http = require('http');
const path = require('path');
const fs = require('fs');

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

const server = http.createServer((req, res) => {
    const filePath = path.join(__dirname, 'mypage.html');
    console.log(filePath);
    fs.readFile(filePath, (err, data) => {
        if(err){
            res.setHeader('Content-Type', 'text/plain');
            res.statusCode = 404;
            return res.end("Error while reading file");
        }
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.write(data);
        return res.end();
    })
});

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

Points to note here-

  1. Path to the file is constructed using path.join() method which joins all the arguments to the path.join() together and returns the resulting path.
  2. First argument to path.join() is __dirname which is a variable given by Node.js itself storing the directory name of the current module.
  3. In the fs.readFile() callback check has been made to see if there is an error in that case response status is set as '404' which indicates that the server cannot find the requested resource.
  4. If there is no error content of the file is send as response.

That's all for this topic Creating HTTP server in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Node.js Tutorial Page


Related Topics

  1. How to Install Node.js and NPM in Windows
  2. How to Setup a Node.js Project
  3. NodeJS NPM Package Manager
  4. NodeJS Event Loop
  5. Node.js path.basename() Method With Examples

You may also like-

  1. JavaScript Arrow Function With Examples
  2. Angular First App - Hello world Example
  3. JSX in React
  4. React HelloWorld App - First React App
  5. Creating a Thread in Java
  6. Java Concurrency Interview Questions And Answers
  7. Linked List Implementation Java Program
  8. Spring MVC Form Example With Bean Validation