Friday, March 20, 2015

How to call JBPM6's RESTFul API with athentication details

In JBPM 6 the inbuilt RESTFul API is a great feature which makes our lives easier.
In order to use these APIs, you have to provide authentication details with the request in request header.
First join the username and the password with a colon and encode it using Base64 encoder. Then append the word "Basic " (note the space) and put as "Autorization" header.
Ex:-
  "Basic " + Base64Encode(<username> + ":" + <password>)

See below working complete code written in java to get the task list of krisv.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class JBPMRest {
  public static void getTaskSummaryList() throws Exception {
    String status = "Reserved";
    String actor = "krisv";

    String addr = "http://localhost:8080/jbpm-console/rest/task/query?status=" + status + "&potentialOwner=" + actor;
    try {
      HttpClient client = HttpClientBuilder.create().build();
      HttpGet get = new HttpGet(addr);

      String authData = "krisv" + ":" + "krisv";
      String encoded = new sun.misc.BASE64Encoder().encode(authData.getBytes());
      get.setHeader("Authorization", "Basic " + encoded);
      get.setHeader("Content-Type", "application/json");
      get.setHeader("ACCEPT", "application/xml");

      HttpResponse cgResponse = client.execute(get);
      String content = EntityUtils.toString(cgResponse.getEntity());
      System.out.println(content);
    } catch (Exception e) {
      throw new Exception("Error consuming service.", e);
    }
  }
}

Thursday, March 19, 2015

How to pass parameters to a Quartz job

In your Job class(implementation of org.quartz.Job interface) you don't have a way to set external parameters. What you can do is putting parameters in to the SchedulerContext when scheduling the job and get them back in the execute() method of the job.
See below example.

This is your main class where you set the scheduler.
import java.util.Date;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class TestQuartz {

  public static void main(String[] args) throws Exception {
    JobBuilder jobBuilder = JobBuilder.newJob(MyJob.class);
    JobDetail job = jobBuilder.withIdentity("myJob", "group1").build();
    Date sheduleTime = new Date(new Date().getTime() + 5000);
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    //Below line sets a variable named myContextVar in SchedulerContext.
    //Not only strings, you can set any type of object here.
    scheduler.getContext().put("myContextVar", "Hello, this text is from context.");
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }
}

Now in your Job class you can get that variable from the SchedulerContext as below.
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;

public class MyJob implements Job {

  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    try {
      SchedulerContext schedulerContext = arg0.getScheduler().getContext();
      //Below line gets the value from context.
      //Just get it and cast it in to correct type
      String objectFromContext = (String) schedulerContext.get("myContextVar");
      System.out.println(objectFromContext);
    } catch (SchedulerException e1) {
      e1.printStackTrace();
    }
  }
}

Tuesday, March 17, 2015

Creating a web service client using apache Cxf

In this tutorial you will see how to create a web service client(synchronous) using apache Cxf.
First download the apache cxf  binary distribution from cxf download page.
http://cxf.apache.org/download.html
Extract the downloaded archieve and it will create a folder named like apache-cxf-x.x.x.

Now create a new Java project. I name it as CXFClient.
In this tutorial I am going to write a client to consume cdyne.com's Weather service.
This is the WSDL for that service.
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

Now you can create the stub for the above web service as below.
Open command window and point to apache-cxf-x.x.x\bin.
Below command will generate the stub for the above web service in to a folder named mystub inside bin folder.

wsdl2java -ant -client -p com.example.stub -d mystub http://wsf.cdyne.com/Weather.asmx?WSDL

You will see the stub is generated inside the apache-cxf-x.x.x\bin\mystub folder. Open the stub folder and copy the content in to the src(java source) folder of your project.
Now I am going to create my client class to consume the web service. Create a new java class in com.example.client package and name it as WeatherClient.

If you are using eclipse, your project structure will look like this now.


























This is my client class to invoke the weather service. Run this class and you will see the the data is retrieved through the web service.
package com.example.client;

import java.util.List;
import com.example.stub.ArrayOfWeatherDescription;
import com.example.stub.Weather;
import com.example.stub.WeatherDescription;
import com.example.stub.WeatherSoap;

public class WeatherClient {
  public static void main(String[] args) {
    try {
      Weather weatherService = new Weather();
      WeatherSoap weatherSoap = weatherService.getWeatherSoap();
      ArrayOfWeatherDescription forecastReturn = weatherSoap.getWeatherInformation();
      List forecasts = forecastReturn.getWeatherDescription();
      for (WeatherDescription forecast : forecasts) {
        short weatherID = forecast.getWeatherID();
        String description = forecast.getDescription();
        System.out.println("weatherID : " + weatherID);
        System.out.println("description : " + description);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Spring HelloWorld Example

Create new Maven project. These are my configurations.
groupId : com.example
artifactId : SpringHello
packaging : war

Edit the pom.xml file and add Spring dependencies.This is my pom.xml file.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>prageeth.example</groupId>
<artifactId>SpringHello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<springRealeaseVersion>4.1.3.RELEASE</springRealeaseVersion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
</dependencies>
</project>

Create a new Java class "SayHello" in com.example package. This is my SayHello class. This is the class which I am going to convert a Spring bean.

package com.example;

public class SayHello {
  public String getHelloMessage(String username) {
    return "Hello " + username;
  }
}

Now I want to make this class a Spring bean. To do that I need to have a beans xml file.
Create a new folder in src/main/webapp folder and name it as WEB-INF. Create new xml file in this newly created WEB-INF folder. I name the file as context.xml.
You can use any name for it. This is your beans xml file in which you are going to define your Spring beans.
I define my com.example.SayHello as a Spring bean in this file. This is my context.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
    
<bean id="helloBean" class="com.example.SayHello"/>
</beans>

Now what you need to do is tell Spring what your beans xml file is. You can do it in web.xml file. This is my web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.example.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>
</web-app>

That is all. Now my bean is configured and I can use it in my application. For an example assume that I want to invoke a method of helloBean in a servlet.
I can do it like this.

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    SayHello helloBean =(SayHello)ContextLoader.getCurrentWebApplicationContext().getBean("helloBean");
    String message = helloBean.getHelloMessage("John");
    System.out.println(message);
}

Note 1:-
If your Spring application is not a web application, you cannot the configure contextConfigLocation and ContextLoaderListener in a web xml.
In this case you can directly load the context xml by code as below.
First create the context xml file in the src folder. Then load the file and invoke the method like this.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
    SayHello helloBean = (SayHello) context.getBean("helloBean");
    String message = helloBean.getHelloMessage("John");
    System.out.println(message);
}

Note 2:-
You have to design your project to prevent loading the context xml file multiple times. You can easily do this by implementing the singleton design patten.

Monday, March 2, 2015

SOAP web service using Spring and Axis2 - Simple Example

Create new Maven project in eclipse. These are my project settings.
groupId : com.example
artifactId : SpringService
packaging : war

Add axis2m, axis2 and Spring dependencies in to the pom.xml. This is my pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>SpringService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
<dependency>
<groupId>org.axis2m</groupId>
<artifactId>axis2m-spring</artifactId>
<version>1.0M2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-adb</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>

Now I create a new java class. This is the class where I am going to write my service methods. I add getHello() method as below.

public class HelloService {
  public String getMessage(String username) {
    return "Hello " + username + "! from spring web service.";
  }
}

Now I have to register this class as a Spring bean. So we need to create a beans xml file.
Create new xml file in src/main/webapp/WEB-INF folder. I name it as context.xml. This is the content of my context.xml file.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    
<bean id="myService" class="org.axis2m.spring.beans.ServiceBean">
<property name="serviceName" value="TestService" />
<property name="serviceBean" ref="myServiceClass" />
<property name="targetNameSpace" value="com.hello"/>
</bean>

<bean id="myServiceClass" class="services.HelloService" />
</beans>

The line <bean id="myServiceClass" class="com.beans.HelloWorld" /> registers this class as a SpringBean named as 'myServiceClass'.
The block <bean id="testService".... exposes above bean as a web service via axis.

Finally I add the context xml file and axis servlet in to the web xml. This is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>AxisServlet</servlet-name>
    <servlet-class>org.axis2m.spring.servlet.SpringAxis2Servlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
</web-app>


Now run the project in tomcat server. After the application is deployed open the web browser and point to below wsdl location.(My tomcat runs on port 8080)
http://localhost:8080/SpringService/services/TestService?wsdl

Wow! The wsdl for my web service is opened. It means my web service has been successfully published.
Look at the wsdl path again. It can be described as below.


















I use SOAP-UI to test the service. These are my request and the response received.























Note:
All the public methods written in HelloService class are exposed as web services. If you want any public method in this class not to be exposed as a service you just can mention it in context.xml file as below. For an example if you have a public method myHiddenMethod() in HelloService class, you can avoid it being exposed via web service like this.

<bean id="myService" class="org.axis2m.spring.beans.ServiceBean">
    <property name="serviceName" value="TestService" />
    <property name="serviceBean" ref="myServiceClass" />
    <property name="targetNameSpace" value="com.hello"/>
    <property name="excludeOperationsNames" value="myHiddenMethod"/>
</bean>

Tuesday, February 17, 2015

Creating a custom JSF composite component - Simple Example

In a previous tutorial I showed you how to create a JSF UI component by Extending javax.faces.component.UIComponentBase class. That is not the only way that you can create cutom components in JSF. You can also create your own UI components by combining existing JSF components. This kind of components are called composite components.
This example will show you how to create a composite component by combining h:outputLabel and h:inputText components. Below are the steps taht you need to follow.

1. In WebContent/resources folder create a new folder. This is the folder in which you are going to create your composite component. I name this folder as "custom".
2. Create a new xhtml page in this folder. The code of our composite component will be written in this file. I name this file as labelledInputText.xhtml. Note that then "labelledInputText" will become the name of my composite component.
3. This is the content of my labelledInputText.xhtml file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:composite="http://java.sun.com/jsf/composite">
<head>
</head>
<body>
  <composite:interface>
    <composite:attribute name="label"/>
    <composite:attribute name="value"/>
  </composite:interface>
  <composite:implementation>
    <h:outputLabel value="#{cc.attrs.label}" /> : 
    <h:inputText value="#{cc.attrs.value}" />
  </composite:implementation>
</body>
</html>

4. The most imporant parts of above code can be explained as below.
xmlns:composite="http://java.sun.com/jsf/composite" - This tag library should be imported at the to of the page.
<composite:interface> - Within these tags the attributes of the composite component are defined.
<composite:attribute> - You can define attributes of the composite component by using this tag.
<composite:implementation> - Within these tags you and add any number of JSF components. You sould design your final composite component between these tags. This is what you see after the final page is rendered.
#{cc.attr....} - You can access the attributes defined in <composite:interface> section like this.
5. Well, now we have created out composite component. We may use it in out xhtml pages as below.

<cust:labelledInputText label="Name" value="#{myBean.message}"/>

See my sample xhtml page(index.xhtml) below where I use this component.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags"
xmlns:cust="http://java.sun.com/jsf/composite/custom">
<h:head>
</h:head>
<body>
  <h:form>
    <cust:labelledInputText label="Name" value="#{myBean.message}"/> 
    <a4j:commandButton value="Ok" action="#{myBean.print()}"/>
  </h:form>
</body>
</html>

Did you note the namespace declaration xmlns:cust="http://java.sun.com/jsf/composite/ custom" at the top of the page. This is needed to use your component in page. The last part(/custom) is the name of the folder you created inside the resources folder(parent fodler of the labelledInputText.xhtml file).

Below is the sample managed bean I use to test this page.

import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private String message;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public void print() {
    System.out.println(message);
  }
}

Now run the application and point to the index.xhtml page. Wow! you will see a textbox rendered together with a label on page. Now enter a value in to the text box and press the button. See the console. The value you entered will be printed on it.
Congratulations! It means you have successfully created your first JSF composite component.

Creating a java based custom component in JSF 2.2 - Simple example

In JSF 2.2 it is very easy to create java based custom components. In this tutorial I will show you how to do that.
The component which I am going to create can format the date you enter in to a given pattern.
After creating the component I hope to use it in my xhtml page as below.

<tl:date date="#{myBean.date}" pattern="yyyy-MM-dd">

This component has two attributes. The attribute "date" accepts java.util.Date type value. What my component does is it formats the date using the given pattern(the value entered in to the "pattern" attribute) and displays it on the page.
First I create a java class by extending javax.faces.component.UIComponentBase class. My java class represents the custom date component that I am going to create. This is the code of the class.

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@FacesComponent(createTag=true, tagName="date", namespace="http://tech-lead.blogspot.com/tags")
public class Date extends UIComponentBase {

  @Override
  public String getFamily() {
    return "custom.component";
  }

  @Override
  public void encodeBegin(FacesContext context) throws IOException {
    java.util.Date date = (java.util.Date) getAttributes().get("date");
    if(date == null) return;
    
    String pattern = (String) getAttributes().get("pattern");
    ResponseWriter writer = context.getResponseWriter();
    
    if(pattern == null || pattern.isEmpty()) {
      writer.write(date.toString());
    } else {
      DateFormat dateFormat = new SimpleDateFormat(pattern);
      writer.write(dateFormat.format(date));
    }
  }
}

Most important points are described below.
@FacesComponent - This annotation is mandatory. This is needed to identify this class as a JSF component.
createTag - Without setting this as 'true' you can't use this component as a tag in xhtml page
tagName - This is the tag name of this component.(The name you use in xhtml page to refer to this component)
namespace - This is the namespace URI you used to import the tag lib which contains this component.
getFamily() - A family name for your components. You can return an arbitrary string here. Returning null may throws runtime exceptions in some JSF implementations.

That is all. The component is created. Now lets use it in our xhtml page.

This is my index.xhtml page.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags">

<h:head>
</h:head>
<body>
The date is <tl:date date="#{test.date}" pattern="yyyy-MM-dd" />.
</body>
</html>

This is my managed bean, MyBean.java
import java.util.Date;
import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private Date date = new Date();

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }
}

Start the application and point to index.jsf page. You will see the formatted date displayed on page.

Monday, February 16, 2015

How to pass javascript parameters to JSF managed bean using RichFaces <a4j:param> component

In your JSF project if you are using RichFaces it is easy to send javascript values from your xhtml page to your managed bean using a4j:param component.
See below example.

My xhtml page is as below.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
  <script>
    var jsMessage = 'Hello from javascript!';

    function calculate() {
      return 100 + 50;
    }
  </script>
</h:head>
<body>
  <h:form>
    <a4j:commandButton action="#{test.doIt}" value="Do It">
      <a4j:param value="jsMessage" noEscape="true"
             assignTo="#{test.message}" />
      <a4j:param value="calculate()" noEscape="true"
             assignTo="#{test.valueFromFunction}" />
    </a4j:commandButton>
  </h:form>
</body>
</html>

This is my managed bean.
import javax.faces.bean.ManagedBean;

@ManagedBean(name="test")
public class Test {
  private String message;
  private Double valueFromFunction;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public Double getValueFromFunction() {
    return valueFromFunction;
  }

  public void setValueFromFunction(Double valueFromFunction) {
    this.valueFromFunction = valueFromFunction;
  }

  public void doIt() {
    System.out.println("Message : " + message);
    System.out.println("Value From Function : " + valueFromFunction);
  }
}

How to use ExecutorService to create and maintain a thread pool in java

The ExecutorService interface and its implementations which are found in java.util.concurrent package are very useful when you need to maintain a thread pool in your application.

What is a thread pool and why it is used? 
Well, first of all think that a thread pool as a collection of threads. Assume that you have a runnable class and assume that you need 'n' number of threads of this class run in parallel. If one thread finished its task and exit you may need to start another thread to make sure that 'n' number of threads are running in parallel.
The ExecutorService can do this and more other stuff for you.
You can add any number of threads in to the ExecutorService. You can tell the ExecutorService how many threads that you want to run in parallel. The ExecutorService is responsible of keeping the given number of threads running in parallel. If one thread went down by finishing its task, the ExecutorService starts another thread to guarantee that given number of threads are running in parallel. ExecutorService does this until all the threads in its pool are executed or until we signal it to stop.
Below example will show you how to create a thread pool using ExecutorService.

As I mentioned earlier you need to have a runnable class which acts as a thread. My runnable class is as below.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyThread implements Runnable {
  @Override
  public void run() {
    System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted.......");
    }
  }
}

This is my code which creates and executes the thread pool.

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

public class PoolTest {
  public static void main(String[] args) throws InterruptedException {
    int poolSize = 5;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < 20; i++) {
      MyThread thread = new MyThread();
      threadPool.execute(thread);
    }
    System.out.println("All threads are added to the pool....");
    threadPool.shutdown();
    System.out.println("All Executed....");
  }
}

Run and inspect the output of the above method and you will see that five threads have been executed at the same time.
I'll explain the above code line by line.
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
This line creates the thread pool. The integer value passed to this method is the number of threads run in parallel.

threadPool.execute(thread);
The execute() method is used to add threads in to the thread pool. As soon as the execute() method is called first time, the ExecutorService starts execution of threads.

threadPool.shutdown();
After adding all the elements in to the thread pool, we calls this method to tell the ExecutorService, that we are not goint to add more threads in to the pool and it may gracefully shuts down after all the threads provided are executed. It should be noted that, this line does not shuts the thread pool down immediately. Instead it permits the thread pool to shuts down after it completely executed all the threads provided. Another thing to keep in mind is that you can't add more threads in to this thread pool after the shutdown() method is called. It will throw a runtime exception.

If you want to tell the ExecutorService to abort all the tasks and shuts down immediately, you can call threadPool.shutdownNow().

If you inspect the output of the above code carefully, you will see that the line "All Executed...." has been printed before the execution of all threads are finished. What is the reason for that. Yes, as you have already understood the thread pool does its job in background and the main thread which contains the line System.out.println("All Executed...."); gets executed in parallel.

What we can do if we need to print this line after all the threads were executed?
The easiest way is to call awaitTermination() after the shutdown() method. This method blocks the main thread until all tasks have completed execution after a shutdown request(or the given timeout occurs, or the current thread is interrupted, whichever happens first).
After adding the awaitTermination() method, the last lines of the above code will be as below.

System.out.println("All threads are added to the pool....");
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("All Executed....");

Now run the code and you will see that the line "All Executed...." is printed after all the threads are executed.

The other way is to use the ExecutorService.isTerminated() together with Thread.sleep() to check and wait until ExecutorService has been shut down. For an example you can replace the line threadPool.awaitTermination(1, TimeUnit.MINUTES); with below lines.

while (!threadPool.isTerminated()) {
  try {
Thread.sleep(500);
  } catch (InterruptedException e) {
e.printStackTrace();
  }
}

Working with multiple threads is some what tricky and you should act carefully. This tutorial demonstrated the basic usage of ExecutorService to handle thread pools. I think that would help you to design your next multi threaded program in more efficient way.