Sunday, July 15, 2012

Embedding Jetty Tutorial

Jetty :

Jetty is an open source servlet container, which means it serves Java-based web content such as servlets and JSPs. Jetty is written in Java and its API is available as a set of JARs. Developers can instantiate a Jetty container as an object, instantly adding network and web connectivity to a stand-alone Java app.

Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO. Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server. 

To embed a Jetty server, the following steps are typical:
  1. Create the server
  2. Add/Configure Connectors
  3. Add/Configure Handlers
  4. Add/Configure Servlets/Webapps to Handlers
  5. Start the server
  6. Wait (join the server to prevent main exiting)

Creating a Server 

public class SimpleServer {
    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        server.start();
        server.join();
    }
}
 
This runs an HTTP server on port 8080.  It is not a very useful server as it has no handlers and 
thus returns a 404 error for every request. 
 

Writing Handlers

To produce a response to a request, Jetty requires a Handler to be set on the server. 

public class SimpleHandler extends AbstractHandler {
    public void handle(String target,Request baseRequest,HttpServletRequest
          request, HttpServletResponse response)  
          throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>Hello World</h1>");
    }
}
 
The parameters passed to the handle method are:
  • target–the target of the request, which is either a URI or a name from a named dispatcher.
  • baseRequest–the Jetty mutable request object, which is always unwrapped.
  • request–the immutable request object, which might have been wrapped.
  • response–the response, which might have been wrapped. 

how a Jetty server can use this handler: 

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    server.setHandler(new HelloHandler());
    server.start();
    server.join();
}

Some of the handlers available in Jetty in the org.eclipse.jetty.server.handler package.  

Configuring Connectors

To configure the HTTP connectors that the server uses, you can set one or more connectors on the server. You can configure each connector with details such as interface, port, buffer sizes, timeouts, thread pool etc.

How to set and configure multiples connectors :

public class MultipleConnectors {
    public static void main(String[] args) throws Exception {
  
        Server server = new Server();
 
        SelectChannelConnector connector0 = new SelectChannelConnector();
        connector0.setPort(8080);
        connector0.setMaxIdleTime(30000);
        connector0.setRequestHeaderSize(8192);
 
        SelectChannelConnector connector1 = new SelectChannelConnector();
        connector1.setHost("127.0.0.1");
        connector1.setPort(8888);
        connector1.setThreadPool(new QueuedThreadPool(20));
        connector1.setName("Thread Name");
 
        SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
        String jetty_home = 
          System.getProperty("jetty.home","../jetty-distribution/target/distribution");
        System.setProperty("jetty.home",jetty_home);
        ssl_connector.setPort(8443);
        SslContextFactory cf = ssl_connector.getSslContextFactory();
        cf.setKeyStore(jetty_home + "/etc/keystore");
        cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
        cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
 
        server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector });
        server.setHandler(new HelloHandler());
 
        server.start();
        server.join();
    }
}

Setting a Web Application Context 

A Web Applications context is a variation of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:  

public class SimpleWebApp {
    public static void main(String[] args) throws Exception {
        String jetty_home = System.getProperty("jetty.home","..");
 
        Server server = new Server(8080);
 
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setWar(jetty_home+"/webapps/test.war");
        server.setHandler(webapp);
 
        //If you have not assembled your application into a WAR file,  
        /*  
        WebAppContext context = new WebAppContext();
        context.setDescriptor(webapp+"/WEB-INF/web.xml");
        context.setResourceBase("../test-jetty-webapp/src/main/webapp");
        context.setContextPath("/");
        context.setParentLoaderPriority(true);
 
        server.setHandler(context);*/
 
        //How to set ThreadPool
        QueueThreadPool pool = new QueueThreadPool();
        pool.setMaxthreads(20);
        pool.setMinthreads(5);
        server.setThread(pool);
 
        server.start();
        server.join();
    }
}
 
Important URL:
Download jetty link

 References :
 

 Tutorial :

 Very soooon... 

 


Friday, July 6, 2012

How to find default thread pool size programmatically

To find out jetty thread pool size programmatically :

ThreadPool tp = (ThreadPool) server.getThreadPool();
if(tp instanceof QueuedThreadPool) {
QueuedThreadPool qtp = (QueuedThreadPool) tp;
int minThreads = qtp.getMinThreads();
int maxThreads = qtp.getMaxThreads();
LOG.info("minThreads : " + minThreads + "\t maxThreads :" + maxThreads)
}

Tuesday, June 19, 2012

How to get RAM size using java?

package com.demo.memoryheap;

import java.lang.management.ManagementFactory;

/**
 * @author abdul
 *
 */
public class FreeMemoryUsingMxBean {

    /**
     * @param args
     */
    public static void main(String[] args) {
        com.sun.management.OperatingSystemMXBean mxbean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
       
        System.out.println("Total Memory in MB: " + mxbean.getTotalPhysicalMemorySize()/(1024*1024));
       
        System.out.println("Free Memory in MB: " + mxbean.getFreePhysicalMemorySize()/(1024*1024));
    }
}

Note : If you get access restriction error while working on Eclipse , check this :
Access Restriction issue

Access restriction on class due to restriction on required library rt.jar for OperatingSystemMXBean ?

Its work for me :
  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me

Wednesday, June 13, 2012

How to convert InputStream to String in Java?

/**
 *
 */
package convert.stream.to.string;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author abdul
 *
 */
public class StreamToString {

    /**
     * @param args
     */
    public static void main(String[] args) {
        StreamToString streamToString = new StreamToString();
     
        //intilize an InputStream
        InputStream is = new ByteArrayInputStream("file content:\nData1\nData2".getBytes());
     
        /*
         * Call the method to convert the stream to string
         */
        System.out.println(streamToString.convertStreamToString(is));
    }

    private String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}



Output:
file content:
Data1
Data2



How to find exact version of Red Hat Linux


[root@localhost ]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.2 (Tikanga)


For others:

Slackware: /etc/slackware-version
Mandrake: /etc/mandrake-release
Red Hat: /etc/redhat-release
Fedora: /etc/fedora-release

Tuesday, June 12, 2012

How to configure session timeout for putty

Click on the upper left hand corner of your putty screen, then click on 'Change Settings', then 'Connection'. I have my 'keepalive' set to 300.
Now It will time out after 5 minutes.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...