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.

How to use dynamic parameters in strings in java

In programming it is common to keep commonly used strings in a properties file or as constants and use them in multiple places in your code.

For an example below message can be put in a properties file to be used in different places.
message=The user is not authorized for this operation.

Then you can use this in various places.
But what happens if you need to include the "username" of the user in to this message?
For an example if the username is "john", the message should be

"The user john is not authorized for this operation."

If the username is "tom", the message should be

"The user tom is not authorized for this operation."

In this kind of situations you can use a parametrized messages in your property file as below.
message = The user {0} is not authorized for this operation.

In the places where you use this message you can use java.text.MessageFormat class to replace the parameter with the proper value as below.

String message = properties.getProperty("message");
String formattedMessage = MessageFormat.format(message, "john");

This will print
The user john is not authorized for this operation.

Similarly if you want you can have multiple parameters in the string.
String message = "The user {0} is not authorized for {1} operation.";
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);

This will print
The user john is not authorized for billing operation.

Friday, February 13, 2015

How to get/calculate the remaining time for session time out

In Servlet API there is no straight forward method to get the remaining active time of the session. But you can use below two methods provided in HttpSession to calculate this time.

HttpSession.getLastAccessTime() - This method returns the time(in milliseconds) that the client associated with this session sent the last request to the server.
HttpSession.getMaxInactiveInterval() - This is the configured session time out period.

In your servlet you can calculate remaining time as below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
long now = new Date().getTime();
long lastAccessed = session.getLastAccessedTime();
long timeoutPeriod = session.getMaxInactiveInterval();
long remainingTime = ((timeoutPeriod * 1000) - (now - lastAccessed))/1000;
System.out.println("Remaining time is " + remainingTime + " seconds");
}

Note that if you are using JSF, you can get the associated session as below.
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);