Monday, 4 August 2014

startAsync (ServletRequest servletRequest, ServletResponse servletResponse)

public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException
Puts this request into asynchronous mode, and The ServletRequest and ServletResponse arguments must be the same instances, or instances of ServletRequestWrapper and ServletResponseWrapper that wrap them, that were passed to the service method of the Servlet or the doFilter method of the Filter, respectively. Response will be delayed until you call 'complete()' method of AsyncContext.

For an example follow the below link




Prevoius                                                 Next                                                 Home

startAsync() : Puts this request into asynchronous mode

public AsyncContext startAsync() throws IllegalStateException
Puts this request into asynchronous mode, and initializes its AsyncContext with the original ServletRequest and ServletResponse objects. Response will be delayed until you call 'complete()' method of AsyncContext.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.AsyncContext;

@WebServlet(urlPatterns = {"/ProcessRequest"}, asyncSupported=true)
public class ProcessRequest extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
        final AsyncContext acontext = req.startAsync();
            
        String threadName = Thread.currentThread().getName();
        long startTime = System.currentTimeMillis();
        System.out.println("Thread " + threadName + " started at " + startTime);

        acontext.start(new Runnable() {
            public void run() {
                String time = req.getParameter("time");
                int wait = Integer.parseInt(time);
                    
                try{
                    Thread.sleep(wait);
                }
                catch(InterruptedException e){
                        
                }
                HttpServletResponse response = (HttpServletResponse)acontext.getResponse();
                try(PrintWriter out = response.getWriter()) {
                    out.println("I am done");
                }
                catch(Exception e){
                        
                }
                acontext.complete();
            }
        });
            
        long endTime = System.currentTimeMillis();
        System.out.println("Thread " + threadName + " finished at " + endTime);
        System.out.println("Total time taken is " +(endTime-startTime) + " Milli Seconds");
       
    }
}

Run the above servlet like below.

As you see the console logs, you can observe the below information messages immediately.

Info: Thread http-listener-1(5) started at 1405140693455
Info: Thread http-listener-1(5) finished at 1405140693456
Info: Total time taken is 1 Milli Seconds

After 10 seconds you can see the response in your browser.







 
Prevoius                                                 Next                                                 Home

Asynchronous Processing

Before discussing about Asynchronous processing, lets observe the below Servlet Application.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/ProcessRequest"})
public class ProcessRequest extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
        try(PrintWriter out = res.getWriter()){
            String time = req.getParameter("time");
            int wait = Integer.parseInt(time);
            
            String threadName = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            out.println("Thread " + threadName + " started at " + startTime);
            
            Thread.sleep(wait);
            
            long endTime = System.currentTimeMillis();
            out.println("Thread " + threadName + " finished at " + endTime);
            out.println("Total time taken is " +(endTime-startTime) + " Milli Seconds");
        }
        catch(InterruptedException e){
            
        }
    }
}

Output

Run the above servlet like below.

time is passed as query string. Servlet simply reads the time parameter in query string and waits for that much time, and sends the response to the client.
In the above servlet are we really doing anything with request and response objects ?

No, But the thread associated with this request can't do anything until the sleep finishes. These kind of long running tasks leads to thread starvation. Since our servlet thread is blocked until all the processing is done, if server gets a lot of requests to process, it will hit the maximum servlet thread limit and further requests will get Connection Refused errors.

As an Application developer, you must ensure that no threads associated with a request are sitting idle, so the container can use them to process new requests. Asynchronous processing provides a facility to assign these blocking operations to a new thread and retuning the thread associated with the request immediately to the container.

If a servlet or a filter reaches a potentially blocking operation when processing a request, it can assign the operation to an asynchronous execution context and return the thread associated with the request immediately to the container without generating a response. The blocking operation completes in the asynchronous execution context in a different thread, which can generate a response or dispatch the request to another servlet.

Example
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.AsyncContext;

@WebServlet(urlPatterns = {"/ProcessRequest"}, asyncSupported=true)
public class ProcessRequest extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
            final AsyncContext acontext = req.startAsync();
            
            String threadName = Thread.currentThread().getName();
            long startTime = System.currentTimeMillis();
            System.out.println("Thread " + threadName + " started at " + startTime);

            acontext.start(new Runnable() {

                public void run() {
                    String time = req.getParameter("time");
                    int wait = Integer.parseInt(time);
                    
                    try{
                        Thread.sleep(wait);
                    }
                    catch(InterruptedException e){
                        
                    }
                    HttpServletResponse response = (HttpServletResponse)acontext.getResponse();
                    try(PrintWriter out = response.getWriter()) {
                        out.println("I am done");
                    }
                    catch(Exception e){
                        
                    }
                    acontext.complete();
                }
            });
            
            long endTime = System.currentTimeMillis();
            System.out.println("Thread " + threadName + " finished at " + endTime);
            System.out.println("Total time taken is " +(endTime-startTime) + " Milli Seconds");
       
    }
}

Run the above servlet like below.

As you see the console logs, you can observe the below information messages immediately.

Info: Thread http-listener-1(5) started at 1405140693455
Info: Thread http-listener-1(5) finished at 1405140693456
Info: Total time taken is 1 Milli Seconds

After 10 seconds you can see the response in your browser.


WebServlet(urlPatterns = {"/ProcessRequest"}, asyncSupported=true)
public class ProcessRequest extends HttpServlet {…}
To enable asynchronous processing on a servlet, set the parameter asyncSupported to true on the @WebServlet annotation as follows:

final AsyncContext acontext = req.startAsync();
above statement is used to get Asynchronous context. The javax.servlet.AsyncContext class provides the functionality that you need to perform asynchronous processing inside service methods. This call puts the request into asynchronous mode and ensures that the response is not committed after exiting the service method.

acontext.start(new Runnable(){..});
The container provides a different thread in which the blocking operation can be processed.

Servlet API provides below methods to support Asynchronous processing.
      AsyncContext getAsyncContext()
      boolean isAsyncStarted()
      boolean isAsyncSupported()
      AsyncContext startAsync()
      AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)





Prevoius                                                 Next                                                 Home

getCookies() : get the Cookies

A Cookie is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity.

The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that are present in the request.

Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/GetCookies">
            <input type="submit">
        </form>
    </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>GetCookies</servlet-name>
        <servlet-class>GetCookies</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GetCookies</servlet-name>
        <url-pattern>/GetCookies</url-pattern>
    </servlet-mapping>
</web-app>


GetCookies.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class GetCookies extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        try(PrintWriter out = res.getWriter()){
           String header = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> <br />";                     
            String footer = "</h1> </body>" +
                    "</html>";
        
           Cookie[] cookies = req.getCookies();
            
           out.println(header);
           for(Cookie c : cookies){
               out.println(c.getName() + " " + c.getValue());
           }
           out.println(footer);
        }
    }
}

Sample Output





Prevoius                                                 Next                                                 Home

getPathTranslated()

public String getPathTranslated()
Returns any extra path information after the servlet name but before the query string, and translates it to a real path. If the URL does not have any extra path information, this method returns null.


Prevoius                                                 Next                                                 Home

Saturday, 2 August 2014

java logging package

      Java Logging
      Simple Logger Example
      Handler
      Logging Levels
      Filters
      Logger Hierarchy
            How Filters work with Log Hierarchy
            Log Levels Vs Log Hierarchy
      Formatters
            Using Custom Formatters
      Log Records
      Configuring logging

configuring logging

It is possible to configure logging API, using configuration file. By default, logging API uses the configuration file at 'jre8\lib\logging.properties.

You can specify custom configuration file at the time of running the program.
java -Djava.util.logging.config.file=myfile ProgName

If no configuration file specified at the time of running, then default configuration file will be taken.

Below are the list properties that you can set for logging

1. handlers : handlers will be installed during VM startup. You can add multiple handlers by specifying comma separated list.
   Ex: handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler

2. .level : Specifies the default logging level.
     Ex: .level= INFO

3. Handler Specific Properties
a. Console Handler Specific
java.util.logging.ConsoleHandler.level specifies the default level for the Handler.
Ex : java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.filter specifies the name of a Filter class to use
Ex: java.util.logging.ConsoleHandler.filter = Custom_Filter
java.util.logging.ConsoleHandler.formatter specifies the name of a Formatter class to use.
Ex: java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.encoding the name of the character set encoding to use.
Ex: java.util.logging.ConsoleHandler.encoding = 'UTF-8'

b. FileHandler Specific
java.util.logging.FileHandler.level specifies the default level for the Handler
java.util.logging.FileHandler.filter specifies the name of a Filter class to use
java.util.logging.FileHandler.formatter specifies the name of a Formatter class to use
java.util.logging.FileHandler.encoding the name of the character set encoding to use
java.util.logging.FileHandler.limit specifies an approximate maximum amount to write (in bytes) to any one file. If limit is set to zero, then there is no limit on the size.
Ex: java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count specifies the number of log files to use in the log file rotation.
java.util.logging.FileHandler.pattern specifies a pattern for generating the output file name.
Ex: java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.append specifies whether the FileHandler should append onto any existing files. You can set value to true/false, based on the value it perform operation.

c. Memory Handler Specific
java.util.logging.MemoryHandler.level specifies the level for the Handler.
java.util.logging.MemoryHandler.filter specifies the name of a Filter class to use.
java.util.logging.MemoryHandler.size defines the buffer size.
java.util.logging.MemoryHandler.push defines the push Level. By default push level set to SEVERE.
Ex: java.util.logging.MemoryHandler.push = SEVERE
java.util.logging.MemoryHandler.target specifies the name of the target Handler class.

d. SocketHandler Specific
java.util.logging.SocketHandler.level specifies the default level for the Handler.
java.util.logging.SocketHandler.filter specifies the name of a Filter class to use.
java.util.logging.SocketHandler.formatter specifies the name of a Formatter class to use.
java.util.logging.SocketHandler.encoding the name of the character set encoding to use.
java.util.logging.SocketHandler.host specifies the target host name to connect to.
java.util.logging.SocketHandler.port specifies the target TCP port to use.
Ex: java.util.logging.SocketHandler.port = 23456

e. StreamHandler specific
java.util.logging.StreamHandler.level specifies the default level for the Handler.
java.util.logging.StreamHandler.filter specifies the name of a Filter class to use.
java.util.logging.StreamHandler.formatter specifies the name of a Formatter class to use.
java.util.logging.StreamHandler.encoding the name of the character set encoding to use.

Application with default configuration
import java.io.IOException;
import java.util.logging.*;

public class ConfigEx {
    static final Logger myLogger = Logger.getLogger("configEx");
    
    public static void main(String args[]) throws IOException{
        FileHandler handle1 = null;
        
        try{
            handle1 =  new FileHandler("log.out");
            myLogger.addHandler(handle1);
            
            myLogger.log(Level.FINE, "FINE Message");
            myLogger.log(Level.FINER, "FINER Message");
            myLogger.log(Level.FINEST, "FINEST Message");
            myLogger.log(Level.INFO, "INFO Message");
            myLogger.log(Level.WARNING, "WARNING Message");
            myLogger.log(Level.SEVERE, "SEVERE Message");
        }
        finally{
            if(handle1 != null)
                handle1.close();
        }
    }
}

Run the Application, then you can see the below messages in console.

Jul 29, 2014 2:22:53 PM ConfigEx main
INFO: INFO Message
Jul 29, 2014 2:22:53 PM ConfigEx main
WARNING: WARNING Message
Jul 29, 2014 2:22:53 PM ConfigEx main
SEVERE: SEVERE Message

'log.out' contains information like below.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2014-07-29T14:24:10</date>
  <millis>1406624050661</millis>
  <sequence>0</sequence>
  <logger>configEx</logger>
  <level>INFO</level>
  <class>ConfigEx</class>
  <method>main</method>
  <thread>1</thread>
  <message>INFO Message</message>
</record>
<record>
  <date>2014-07-29T14:24:10</date>
  <millis>1406624050701</millis>
  <sequence>1</sequence>
  <logger>configEx</logger>
  <level>WARNING</level>
  <class>ConfigEx</class>
  <method>main</method>
  <thread>1</thread>
  <message>WARNING Message</message>
</record>
<record>
  <date>2014-07-29T14:24:10</date>
  <millis>1406624050702</millis>
  <sequence>2</sequence>
  <logger>configEx</logger>
  <level>SEVERE</level>
  <class>ConfigEx</class>
  <method>main</method>
  <thread>1</thread>
  <message>SEVERE Message</message>
</record>
</log>

Application with custom configuration

custom_config.properties file contains below configurations
# Default Level
.level= WARNING

# Adding Handlers
handlers= java.util.logging.ConsoleHandler

# Adding File Handler specific configurations
java.util.logging.FileHandler.limit = 10000
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

Run the same Application like below.
java -Djava.util.logging.config.file=custom_config.properties ConfigEx

Below messages come in console.
Jul 29, 2014 2:28:15 PM ConfigEx main
WARNING: WARNING Message
Jul 29, 2014 2:28:15 PM ConfigEx main
SEVERE: SEVERE Message

log.out contains information like below.
Jul 29, 2014 2:28:15 PM ConfigEx main
WARNING: WARNING Message
Jul 29, 2014 2:28:15 PM ConfigEx main
SEVERE: SEVERE Message







Prevoius                                                 Next                                                 Home