com.web.server.WebServer.java Source code

Java tutorial

Introduction

Here is the source code for com.web.server.WebServer.java

Source

package com.web.server;

/*Copyright 2013 - 2015, Arun_Soundararajan (arun_srajan_2007@yahoo.com).and/or its affiliates.
    
All files in this repository or distribution are licensed under the
Apache License, Version 2.0 (the "License");
you may not use any files in this repository or distribution except
in compliance with the License.
    
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.naming.Context;
import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.nio.DefaultHttpServerIODispatch;
import org.apache.http.impl.nio.DefaultNHttpServerConnection;
import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
import org.apache.http.impl.nio.SSLNHttpServerConnectionFactory;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpConnectionFactory;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BasicAsyncRequestConsumer;
import org.apache.http.nio.protocol.BasicAsyncResponseProducer;
import org.apache.http.nio.protocol.HttpAsyncExchange;
import org.apache.http.nio.protocol.HttpAsyncRequestConsumer;
import org.apache.http.nio.protocol.HttpAsyncRequestHandler;
import org.apache.http.nio.protocol.HttpAsyncService;
import org.apache.http.nio.protocol.UriHttpAsyncRequestHandlerMapper;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.jasper.runtime.HttpJspBase;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.web.messaging.MessagingElem;
import com.web.messaging.MessagingServer;
import com.web.messaging.RandomQueueMessagePicker;
import com.web.messaging.RoundRobinQueueMessagePicker;
import com.web.messaging.TopicMessagePicker;
import com.web.server.servlet.FilterMapping;
import com.web.server.servlet.Request;
import com.web.server.servlet.Response;
import com.web.server.servlet.ServletMapping;
import com.web.server.servlet.Servlets;
import com.web.server.servlet.WebAppConfig;
import com.web.server.servlet.WebFilterChain;
import com.web.server.servlet.WebInstanceManager;
import com.web.server.servlet.WebServletConfig;
import com.web.server.util.ClassLoaderUtil;
import com.web.server.util.FarmWarDirWatcher;
import com.web.services.ATAConfig;
import com.web.services.ATAServer;
import com.web.services.ATAConfigClient;
import com.web.services.ExecutorServiceThread;
import org.apache.http.Header;
import org.hornetq.jms.server.embedded.EmbeddedJMS;

/**
 * This class is the implementation of the WebServer which implements the HTTP protocol
 * 
 * @author arun
 *
 */
public class WebServer extends Thread implements Runnable {
    static Hashtable cache = new Hashtable();
    Hashtable urlClassLoaderMap;
    ConcurrentHashMap servletMapping;
    Logger logger = Logger.getLogger(WebServer.class);
    Socket socket;
    int requestPort;
    String deployDirectory;
    int shutdownPort;
    Digester serverdigester;
    static ConcurrentHashMap sessionObjects = new ConcurrentHashMap();
    static Object shutDownObject = new Object();

    public WebServer() {
        this.socket = null;
        this.requestPort = 0;
        this.deployDirectory = null;
        this.shutdownPort = 0;
        serverdigester = null;

    }

    public WebServer(Socket sock, int requestPort, String deployDirectory, int shutdownPort,
            Digester serverdigester, Hashtable urlClassLoaderMap, ConcurrentHashMap servletMapping) {
        this.socket = sock;
        this.requestPort = requestPort;
        this.deployDirectory = deployDirectory;
        this.shutdownPort = shutdownPort;
        this.serverdigester = serverdigester;
        this.urlClassLoaderMap = urlClassLoaderMap;
    }

    /**
     * This methos is the implementation of the HTPP request and sends the response.
     */
    public void run() {
        byte[] response;
        byte[] content;
        byte[] uploadData = null;
        HttpHeaderClient httpHeaderClient = null;
        InputStream istream = null;
        OutputStream ostream = null;
        HttpHeaderServer serverParam = new HttpHeaderServer();
        StringBuffer buffer = new StringBuffer();
        String value;
        char c;
        String endvalue = "\r\n\r\n";
        String urlFormEncoded;
        int responseCode;
        try {
            ////System.out.println("value=");
            istream = socket.getInputStream();
            BufferedInputStream bistr = new BufferedInputStream(istream);
            //socket.setReceiveBufferSize(10000);
            //System.out.println("value1=");
            int availbleStream;
            int totalBytRead = 0;
            int ch;
            ByteArrayOutputStream bytout = new ByteArrayOutputStream();
            ByteArrayOutputStream contentout = new ByteArrayOutputStream();
            //System.out.println(istream.available());
            int bytesRead;
            int endbytIndex = 0;
            int contentbytIndex = 0;
            boolean httpHeaderEndFound = false;
            byte[] byt;
            while ((ch = bistr.read()) != -1) {
                bytout.write(ch);
                if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                    endbytIndex++;
                    if (endbytIndex == endvalue.length()) {
                        byt = bytout.toByteArray();
                        value = new String(ObtainBytes(byt, 0, byt.length - 4));
                        //System.out.println(value);
                        httpHeaderClient = parseHttpHeaders(value);
                        httpHeaderEndFound = true;
                        bytout.close();
                        endbytIndex = 0;
                        if (httpHeaderClient.getContentLength() == null)
                            break;
                    }
                } else {
                    endbytIndex = 0;
                }
                if (httpHeaderClient != null && httpHeaderEndFound) {
                    contentout.write(ch);
                    contentbytIndex++;
                    if (httpHeaderClient.getContentLength() != null
                            && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                        break;
                    }
                }
                totalBytRead++;
            }
            /*while(totalBytRead==0){
               while((ch = bistr.read())!=-1){
                  System.out.println((char)ch);
                  ////System.out.println("availableStream="+availbleStream);
                  bytarrayOutput.write(ch);
                  totalBytRead++;
               }
            }*/
            if (totalBytRead == 0) {
                System.out.println("Since byte is 0 sock and istream os closed");
                //istream.close();
                socket.close();
                return;
            }
            //istream.read(bt,0,9999999);
            System.out.println("bytes read");
            byte[] contentByte = contentout.toByteArray();
            contentout.close();
            //System.out.println("String="+new String(bt));
            /*int index=containbytes(bt,endvalue.getBytes());
            if(index==-1)index=totalBytRead;
            value=new String(ObtainBytes(bt,0,index));*/
            System.out.println("value2=");

            ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
            HttpSessionServer session = null;
            if (httpCookies != null) {
                Iterator<String> cookieNames = httpCookies.keySet().iterator();
                for (; cookieNames.hasNext();) {
                    String cookieName = cookieNames.next();
                    //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                    if (cookieName.equals("SERVERSESSIONID")) {
                        session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                        httpHeaderClient.setSession(session);
                        //break;
                    }
                }
            }
            //System.out.println("Session="+session);
            if (session == null) {
                HttpCookie cookie = new HttpCookie();
                cookie.setKey("SERVERSESSIONID");
                cookie.setValue(UUID.randomUUID().toString());
                httpCookies.put("SERVERSESSIONID", cookie);
                session = new HttpSessionServer();
                sessionObjects.put(cookie.getValue(), session);
                httpHeaderClient.setSession(session);
            }
            if (httpHeaderClient.getContentType() != null
                    && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
                ////System.out.println(new String(uploadData));
                ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
                httpHeaderClient.setParameters(paramMap);
                ////logger.info(uploadData);
            } else if (httpHeaderClient.getContentType() != null
                    && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
                urlFormEncoded = new String(contentByte);
                ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
                httpHeaderClient.setParameters(paramMap);
            }
            ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
            ////System.out.println("value3=");

            ////logger.info(new String(bt));
            serverParam.setContentType("text/html");
            URLDecoder decoder = new URLDecoder();
            System.out.println("content Length= " + socket);
            responseCode = 200;
            File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
            FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
            if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
                System.out.println("In cache");
                content = (byte[]) fileContent.getContent();
            } else {
                content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                        httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
                System.out.println("content Length2= " + content);
                if (content == null) {
                    //System.out.println("In caching content");
                    content = obtainContent(
                            deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                    if (content != null) {
                        fileContent = new FileContent();
                        fileContent.setContent(content);
                        fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                        fileContent.setLastModified(file.lastModified());
                        cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                    }
                }
                ////System.out.println("value4=");

            }

            if (content == null) {
                responseCode = 404;
                content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                        + " Not Found</H1><body></html>").getBytes();
            }
            ////System.out.println("content Length3= ");
            serverParam.setContentLength("" + (content.length + 4));
            if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
                serverParam.setContentType("image/png");
            }
            ////System.out.println("value5=");

            ////System.out.println("content Length4= ");
            response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
            ////System.out.println("value6=");
            ostream = socket.getOutputStream();
            //logger.info("Response="+new String(response));
            //System.out.println("value6=");
            //logger.info("Response="+new String(response));
            ////System.out.println("content "+"Response="+new String(response));
            ostream.write(response);
            ostream.flush();
            ostream.close();
            socket.close();
        } catch (IOException e) {
            Socket socket;
            e.printStackTrace();

            //logger.error(e);
            try {
                socket = new Socket("localhost", shutdownPort);
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
                outputStream.close();
            } catch (Exception ex) {

                ex.printStackTrace();
            }
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * This method copies the content from start to end
     * @param content
     * @param start
     * @param end
     * @return byte[]
     * @throws Exception
     */
    private static byte[] ObtainBytes(byte[] content, int start, int end) throws Exception {
        if (start >= end) {
            throw new Exception("Start byte should be lesser than end byte");
        }
        byte[] resultBt = new byte[end - start];
        for (int count = start; count < end; count++) {
            resultBt[count - start] = content[count];
        }
        return resultBt;
    }

    private int containbytes(byte[] byt1, byte[] byt2) {
        int count = 0;
        boolean isEqual = true;
        for (count = 0; count < byt1.length; count++) {
            isEqual = true;
            for (int secondbytcount = 0; secondbytcount < byt2.length; secondbytcount++) {
                if (byt1[count + secondbytcount] != byt2[secondbytcount]) {
                    isEqual = false;
                    break;
                }
            }
            if (isEqual) {
                return count;
            }
        }
        return -1;
    }

    /**
     * This is the start of the all the services in web server
     * @param args
     * @throws IOException 
     * @throws SAXException 
     */
    public static void main(String[] args) throws IOException, SAXException {

        Hashtable urlClassLoaderMap = new Hashtable();
        Hashtable executorServicesMap = new Hashtable();
        Hashtable ataMap = new Hashtable<String, ATAConfig>();
        Hashtable messagingClassMap = new Hashtable();
        ConcurrentHashMap servletMapping = new ConcurrentHashMap();
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        Digester serverdigester = serverdigesterLoader.newDigester();
        final ServerConfig serverconfig = (ServerConfig) serverdigester
                .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
        DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml")));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
        Digester messagingdigester = messagingdigesterLoader.newDigester();
        MessagingElem messagingconfig = (MessagingElem) messagingdigester
                .parse(new InputSource(new FileInputStream("./config/messaging.xml")));
        //System.out.println(messagingconfig);
        ////System.out.println(serverconfig.getDeploydirectory());
        PropertyConfigurator.configure("log4j.properties");
        /*MemcachedClient cache=new MemcachedClient(
            new InetSocketAddress("localhost", 1000));*/

        // Store a value (async) for one hour
        //c.set("someKey", 36, new String("arun"));
        // Retrieve a value.        
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool();

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = null;
        try {
            name = new ObjectName("com.web.server:type=WarDeployer");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        WarDeployer warDeployer = new WarDeployer(serverconfig.getDeploydirectory(), serverconfig.getFarmWarDir(),
                serverconfig.getClustergroup(), urlClassLoaderMap, executorServicesMap, messagingClassMap,
                servletMapping, messagingconfig, sessionObjects);
        warDeployer.setPriority(MIN_PRIORITY);
        try {
            mbs.registerMBean(warDeployer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //warDeployer.start();
        executor.execute(warDeployer);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getPort())));

        serverSocketChannel.configureBlocking(false);

        final byte[] shutdownBt = new byte[50];
        WebServerRequestProcessor webserverRequestProcessor = new WebServer().new WebServerRequestProcessor(
                servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
                Integer.parseInt(serverconfig.getShutdownport()), 1);
        webserverRequestProcessor.setPriority(MIN_PRIORITY);
        try {
            name = new ObjectName("com.web.server:type=WebServerRequestProcessor");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(webserverRequestProcessor, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //webserverRequestProcessor.start();
        executor.execute(webserverRequestProcessor);

        for (int i = 0; i < 10; i++) {
            WebServerRequestProcessor webserverRequestProcessor1 = new WebServer().new WebServerRequestProcessor(
                    servletMapping, urlClassLoaderMap, serverSocketChannel, serverconfig.getDeploydirectory(),
                    Integer.parseInt(serverconfig.getShutdownport()), 2);
            webserverRequestProcessor1.setPriority(MIN_PRIORITY);
            try {
                name = new ObjectName("com.web.server:type=WebServerRequestProcessor" + (i + 1));
            } catch (MalformedObjectNameException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                mbs.registerMBean(webserverRequestProcessor1, name);
            } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            executor.execute(webserverRequestProcessor1);
        }

        ServerSocketChannel serverSocketChannelServices = ServerSocketChannel.open();

        serverSocketChannelServices
                .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverconfig.getServicesport())));

        serverSocketChannelServices.configureBlocking(false);

        ExecutorServiceThread executorService = new ExecutorServiceThread(serverSocketChannelServices,
                executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap, urlClassLoaderMap,
                serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
                serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

        try {
            name = new ObjectName("com.web.services:type=ExecutorServiceThread");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(executorService, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //executorService.start();
        executor.execute(executorService);

        for (int i = 0; i < 10; i++) {
            ExecutorServiceThread executorService1 = new ExecutorServiceThread(serverSocketChannelServices,
                    executorServicesMap, Integer.parseInt(serverconfig.getShutdownport()), ataMap,
                    urlClassLoaderMap, serverconfig.getDeploydirectory(), serverconfig.getServicesdirectory(),
                    serverconfig.getEarservicesdirectory(), serverconfig.getNodesport());

            try {
                name = new ObjectName("com.web.services:type=ExecutorServiceThread" + (i + 1));
            } catch (MalformedObjectNameException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                mbs.registerMBean(executorService1, name);
            } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            executor.execute(executorService1);
        }

        WebServerHttpsRequestProcessor webserverHttpsRequestProcessor = new WebServer().new WebServerHttpsRequestProcessor(
                servletMapping, urlClassLoaderMap, Integer.parseInt(serverconfig.getHttpsport()),
                serverconfig.getDeploydirectory(), Integer.parseInt(serverconfig.getShutdownport()),
                serverconfig.getHttpscertificatepath(), serverconfig.getHttpscertificatepasscode(), 1);
        try {
            name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(webserverHttpsRequestProcessor, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY);
        //webserverRequestProcessor.start();
        executor.execute(webserverHttpsRequestProcessor);

        /* for(int i=0;i<2;i++){
            webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1);
              
          try {
        name = new ObjectName("com.web.server:type=WebServerHttpsRequestProcessor"+(i+1));
          } catch (MalformedObjectNameException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
          } 
              
          try {
        mbs.registerMBean(webserverHttpsRequestProcessor, name);
          } catch (InstanceAlreadyExistsException | MBeanRegistrationException
           | NotCompliantMBeanException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
          }
              
          executor.execute(webserverHttpsRequestProcessor);
        }*/

        /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap);
            
        try {
           name = new ObjectName("com.web.services:type=ATAServer");
        } catch (MalformedObjectNameException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } 
            
        try {
           mbs.registerMBean(ataServer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException
        | NotCompliantMBeanException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }
            
            
        ataServer.start();*/

        /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap);
            
        try {
           name = new ObjectName("com.web.services:type=ATAConfigClient");
        } catch (MalformedObjectNameException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } 
            
        try {
           mbs.registerMBean(ataClient, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException
        | NotCompliantMBeanException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }
        ataClient.start();*/

        MessagingServer messageServer = new MessagingServer(serverconfig.getMessageport(), messagingClassMap);

        try {
            name = new ObjectName("com.web.messaging:type=MessagingServer");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(messageServer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //messageServer.start();
        executor.execute(messageServer);

        RandomQueueMessagePicker randomqueuemessagepicker = new RandomQueueMessagePicker(messagingClassMap);

        try {
            name = new ObjectName("com.web.messaging:type=RandomQueueMessagePicker");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(randomqueuemessagepicker, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //randomqueuemessagepicker.start();
        executor.execute(randomqueuemessagepicker);

        RoundRobinQueueMessagePicker roundrobinqueuemessagepicker = new RoundRobinQueueMessagePicker(
                messagingClassMap);

        try {
            name = new ObjectName("com.web.messaging:type=RoundRobinQueueMessagePicker");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(roundrobinqueuemessagepicker, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //roundrobinqueuemessagepicker.start();
        executor.execute(roundrobinqueuemessagepicker);

        TopicMessagePicker topicpicker = new TopicMessagePicker(messagingClassMap);

        try {
            name = new ObjectName("com.web.messaging:type=TopicMessagePicker");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(topicpicker, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //topicpicker.start();
        executor.execute(topicpicker);

        try {
            name = new ObjectName("com.web.server:type=SARDeployer");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        SARDeployer sarDeployer = SARDeployer.newInstance(serverconfig.getDeploydirectory());
        try {
            mbs.registerMBean(sarDeployer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        executor.execute(sarDeployer);
        /*try {
           mbs.invoke(name, "startDeployer", null, null);
        } catch (InstanceNotFoundException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } catch (ReflectionException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } catch (MBeanException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }
        */
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
        System.setProperty(Context.PROVIDER_URL, "rmi://localhost:" + serverconfig.getServicesregistryport());
        ;
        Registry registry = LocateRegistry.createRegistry(Integer.parseInt(serverconfig.getServicesregistryport()));

        /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap);
        try {
           name = new ObjectName("com.web.server:type=JarDeployer");
        } catch (MalformedObjectNameException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        } 
            
        try {
           mbs.registerMBean(jarDeployer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException
        | NotCompliantMBeanException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
        }
            
        //jarDeployer.start();
        executor.execute(jarDeployer);*/

        EARDeployer earDeployer = new EARDeployer(registry, serverconfig.getEarservicesdirectory(),
                serverconfig.getDeploydirectory(), executorServicesMap, urlClassLoaderMap,
                serverconfig.getCachedir(), warDeployer);
        try {
            name = new ObjectName("com.web.server:type=EARDeployer");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(earDeployer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //earDeployer.start();
        executor.execute(earDeployer);

        JVMConsole jvmConsole = new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort()));

        try {
            name = new ObjectName("com.web.server:type=JVMConsole");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(jvmConsole, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        executor.execute(jvmConsole);

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        XMLDeploymentScanner xmlDeploymentScanner = new XMLDeploymentScanner(serverconfig.getDeploydirectory(),
                serverconfig.getServiceslibdirectory());
        exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS);

        EmbeddedJMS embeddedJMS = null;
        try {
            embeddedJMS = new EmbeddedJMS();
            embeddedJMS.start();
        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        EJBDeployer ejbDeployer = new EJBDeployer(serverconfig.getServicesdirectory(), registry,
                Integer.parseInt(serverconfig.getServicesregistryport()), embeddedJMS);
        try {
            name = new ObjectName("com.web.server:type=EJBDeployer");
        } catch (MalformedObjectNameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            mbs.registerMBean(ejbDeployer, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //jarDeployer.start();
        executor.execute(ejbDeployer);

        new Thread() {
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport()));
                    while (true) {
                        Socket sock = serverSocket.accept();
                        InputStream istream = sock.getInputStream();
                        istream.read(shutdownBt);
                        String shutdownStr = new String(shutdownBt);
                        String[] shutdownToken = shutdownStr.split("\r\n\r\n");
                        //System.out.println(shutdownStr);
                        if (shutdownToken[0].startsWith("shutdown WebServer")) {
                            synchronized (shutDownObject) {
                                shutDownObject.notifyAll();
                            }
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                System.out.println("IN shutdown Hook");
                synchronized (shutDownObject) {
                    shutDownObject.notifyAll();
                }
            }
        }));
        try {
            synchronized (shutDownObject) {
                shutDownObject.wait();
            }
            executor.shutdownNow();
            serverSocketChannel.close();
            serverSocketChannelServices.close();
            embeddedJMS.stop();

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("IN shutdown Hook1");
        /*try{
           Thread.sleep(10000);
        }
        catch(Exception ex){
               
        }*/

        //webserverRequestProcessor.stop();
        //webserverRequestProcessor1.stop();

        /*warDeployer.stop();
        executorService.stop();
        //ataServer.stop();
        //ataClient.stop();
        messageServer.stop();
        randomqueuemessagepicker.stop();
        roundrobinqueuemessagepicker.stop();
        topicpicker.stop();*/
        /*try {
           mbs.invoke(new ObjectName("com.web.server:type=SARDeployer"), "destroyDeployer", null, null);
        } catch (InstanceNotFoundException | MalformedObjectNameException
        | ReflectionException | MBeanException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/
        //earDeployer.stop();
        System.exit(0);
    }

    /**
     * This method parses the encoded url 
     * @param urlEncoded
     * @return
     */
    public static ConcurrentHashMap parseUrlEncoded(String urlEncoded) {
        ConcurrentHashMap ParamValue = new ConcurrentHashMap();
        URLDecoder urlDecoder = new URLDecoder();
        StringTokenizer paramGroup = new StringTokenizer(urlDecoder.decode(urlEncoded), "&");

        while (paramGroup.hasMoreTokens()) {

            StringTokenizer token = new StringTokenizer(paramGroup.nextToken(), "=");
            String key = "";
            String value = "";
            if (token.hasMoreTokens())
                key = token.nextToken();
            if (token.hasMoreTokens())
                value = token.nextToken();
            ParamValue.put(key, value);

        }
        return ParamValue;
    }

    /**
     * This method obtains the content executor which executes the executor services
     * @param deployDirectory
     * @param resource
     * @param httpHeaderClient
     * @param serverdigester
     * @return byte[]
     */
    public byte[] ObtainContentExecutor(String deployDirectory, String resource, HttpHeaderClient httpHeaderClient,
            Digester serverdigester, Hashtable urlClassLoaderMap, ConcurrentHashMap servletMapping,
            com.web.server.HttpSessionServer session) {
        //System.out.println("In content Executor");
        String[] resourcepath = resource.split("/");
        //System.out.println("createDigester1");
        Method method = null;
        //System.out.println("createDigester2");
        ////System.out.println();
        com.web.server.Executors serverconfig;
        if (resourcepath.length > 1) {
            ////System.out.println(resource);

            try {
                ClassLoader oldCL = null;
                String urlresource = ObtainUrlFromResource(resourcepath);
                try {
                    //System.out.println(servletMapping);
                    //System.out.println(deployDirectory+"/"+resourcepath[1]);
                    HttpSessionServer httpSession;
                    logger.info(deployDirectory + "/" + resourcepath[1] + " "
                            + servletMapping.get(deployDirectory + "/" + resourcepath[1]));
                    if (servletMapping.get(deployDirectory + "/" + resourcepath[1]) != null) {
                        WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                                .get(deployDirectory + "/" + resourcepath[1]);
                        webAppConfig = webAppConfig.clone();
                        webAppConfig.setWebApplicationAbsolutePath(deployDirectory + "/" + resourcepath[1]);
                        WebClassLoader customClassLoader = null;
                        Class customClass = null;
                        customClassLoader = (WebClassLoader) urlClassLoaderMap
                                .get(deployDirectory + "/" + resourcepath[1]);
                        oldCL = Thread.currentThread().getContextClassLoader();
                        Thread.currentThread().setContextClassLoader(customClassLoader);
                        ConcurrentHashMap servletMappingsURL = webAppConfig.getServletMappingURL();
                        Enumeration urlPattern = servletMappingsURL.keys();
                        while (urlPattern.hasMoreElements()) {
                            String pattern = (String) urlPattern.nextElement();
                            Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));
                            Matcher m = r.matcher(urlresource);
                            if (m.find()) {
                                urlresource = pattern;
                                break;
                            }
                        }
                        LinkedHashMap<String, Vector<FilterMapping>> filterMappings = webAppConfig
                                .getFilterMappingURL();
                        Set<String> filterMappingKeys = filterMappings.keySet();
                        Iterator<String> filterMappingRoller = filterMappingKeys.iterator();
                        Vector<FilterMapping> filterMapping = null;
                        while (filterMappingRoller.hasNext()) {
                            String pattern = (String) filterMappingRoller.next();
                            Pattern r = Pattern.compile(pattern.replace("*", "(.*)"));
                            Matcher m = r.matcher(urlresource);
                            if (m.find()) {
                                filterMapping = filterMappings.get(pattern);
                                break;
                            }
                        }
                        if (servletMappingsURL.get(urlresource) != null) {
                            ServletMapping servletMappings = (ServletMapping) servletMappingsURL.get(urlresource);
                            ConcurrentHashMap servlets = webAppConfig.getServlets();
                            Servlets servlet = (Servlets) servlets.get(servletMappings.getServletName());

                            HttpServlet httpServlet = null;
                            System.out.println("Session " + session);
                            if (session.getAttribute("SERVLETNAME:" + deployDirectory + "/" + resourcepath[1]
                                    + servletMappings.getServletName()) != null) {
                                httpServlet = (HttpServlet) session.getAttribute("SERVLETNAME:" + deployDirectory
                                        + "/" + resourcepath[1] + servletMappings.getServletName());
                                httpServlet.init();
                            } else {
                                Class servletClass = customClassLoader.loadClass(servlet.getServletClass());
                                httpServlet = (HttpServlet) servletClass.newInstance();
                                httpServlet.init(new WebServletConfig(servlet.getServletName().trim(), webAppConfig,
                                        customClassLoader));
                                httpServlet.init();
                                session.setAttribute("SERVLETNAME:" + deployDirectory + "/" + resourcepath[1]
                                        + servletMappings.getServletName(), httpServlet);
                                //ClassLoaderUtil.closeClassLoader(customClassLoader);
                            }
                            if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("GET")
                                    || httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("POST")) {
                                Response response = new Response(httpHeaderClient);
                                StringBuffer servletPath = new StringBuffer();
                                if (resourcepath.length > 1) {
                                    int pathcount = 0;
                                    for (String servPath : resourcepath) {
                                        if (pathcount > 1) {
                                            servletPath.append("/");
                                            servletPath.append(servPath);
                                        }
                                        pathcount++;
                                    }
                                }
                                String servletpath = servletPath.toString();
                                if (servletpath.length() == 0)
                                    servletpath = "/";
                                Request request = new Request(httpHeaderClient, session, servletpath,
                                        customClassLoader);
                                if (filterMapping != null) {
                                    WebFilterChain webFilterChain = new WebFilterChain(httpServlet, webAppConfig,
                                            filterMapping, customClassLoader);
                                    webFilterChain.doFilter(request, response);
                                } else {
                                    httpServlet.service(request, response);
                                }

                                //System.out.println("RESPONSE="+new String(response.getResponse()));
                                //httpServlet.destroy();
                                response.flushBuffer();
                                return response.getResponse();
                            }

                            //httpServlet.destroy();
                        } else {
                            if (customClassLoader != null) {
                                Map map = customClassLoader.classMap;
                                if (map.get(urlresource) != null) {
                                    Class jspBaseCls = customClassLoader.loadClass((String) map.get(urlresource));
                                    HttpJspBase jspBase = (HttpJspBase) jspBaseCls.newInstance();
                                    WebServletConfig servletConfig = new WebServletConfig();
                                    servletConfig.getServletContext().setAttribute(
                                            "org.apache.tomcat.InstanceManager",
                                            new WebInstanceManager(urlresource));
                                    //servletConfig.getServletContext().setAttribute(org.apache.tomcat.InstanceManager, arg1);
                                    jspBase.init(servletConfig);
                                    jspBase._jspInit();
                                    Response response = new Response(httpHeaderClient);
                                    StringBuffer servletPath = new StringBuffer();
                                    if (resourcepath.length > 1) {
                                        int pathcount = 0;
                                        for (String servPath : resourcepath) {
                                            if (pathcount > 1) {
                                                servletPath.append("/");
                                                servletPath.append(servPath);
                                            }
                                            pathcount++;
                                        }
                                    }
                                    String servletpath = servletPath.toString();
                                    if (servletpath.length() == 0)
                                        servletpath = "/";
                                    jspBase._jspService(
                                            new Request(httpHeaderClient, session, servletpath, customClassLoader),
                                            response);
                                    jspBase.destroy();
                                    response.flushBuffer();
                                    return response.getResponse();
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();

                } finally {
                    if (oldCL != null) {
                        Thread.currentThread().setContextClassLoader(oldCL);
                    }
                }
                File file = new File(deployDirectory + "/" + resourcepath[1] + "/WEB-INF/executor-config.xml");
                if (!file.exists()) {
                    return null;
                }
                WebClassLoader customClassLoader = (WebClassLoader) urlClassLoaderMap
                        .get(deployDirectory + "/" + resourcepath[1]);
                Class customClass = null;
                if ((file.isFile() && file.exists())) {
                    synchronized (serverdigester) {
                        serverconfig = (com.web.server.Executors) serverdigester.parse(file);
                    }
                    ConcurrentHashMap urlMap = serverconfig.getExecutorMap();
                    //System.out.println("ObtainUrlFromResource1");

                    //logger.info("urlresource"+urlresource);
                    Executor executor = (Executor) urlMap.get(urlresource);

                    //System.out.println("ObtainUrlFromResource2"+executor);
                    //System.out.println("custom class Loader1"+urlClassLoaderMap);
                    //System.out.println("custom class Loader2"+customClassLoader);                     //System.out.println("CUSTOM CLASS lOADER path"+deployDirectory+"/"+resourcepath[1]);
                    ////System.out.println("custom class loader" +customClassLoader);                
                    if (executor != null && customClassLoader != null) {
                        customClass = customClassLoader.loadClass(executor.getExecutorclass());
                        ExecutorInterface executorInstance = (ExecutorInterface) customClass.newInstance();
                        Object buffer = null;
                        if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("GET")) {
                            buffer = executorInstance.doGet(httpHeaderClient);
                        } else if (httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("POST")) {
                            buffer = executorInstance.doPost(httpHeaderClient);
                        }
                        if (executor.getResponseResource() != null) {
                            httpHeaderClient.setExecutorBuffer(buffer);
                            //System.out.println("Method:"+httpHeaderClient.getHttpMethod());
                            String resourceClass = (String) customClassLoader.getClassMap()
                                    .get(executor.getResponseResource().trim());
                            customClass = customClassLoader.loadClass(resourceClass);
                            HttpJspBase jspBase = (HttpJspBase) customClass.newInstance();
                            WebServletConfig servletConfig = new WebServletConfig();
                            servletConfig.getServletContext().setAttribute("org.apache.tomcat.InstanceManager",
                                    new WebInstanceManager(urlresource));
                            //servletConfig.getServletContext().setAttribute(org.apache.tomcat.InstanceManager, arg1);
                            jspBase.init(servletConfig);
                            jspBase._jspInit();
                            Response response = new Response(httpHeaderClient);
                            jspBase._jspService(new Request(httpHeaderClient, session, null, customClassLoader),
                                    response);
                            jspBase.destroy();
                            response.flushBuffer();
                            return response.getResponse();
                        }
                        return buffer.toString().getBytes();
                    }
                } else if (customClassLoader != null) {
                    //System.out.println("url resource"+urlresource);
                    String resourceClass = (String) customClassLoader.getClassMap().get(urlresource);
                    //System.out.println(resourceClass);
                    //System.out.println(customClassLoader.getClassMap());
                    if (resourceClass == null)
                        return null;
                    customClass = customClassLoader.loadClass(resourceClass);
                    ExecutorInterface executorInstance = (ExecutorInterface) customClass.newInstance();
                    Object buffer = executorInstance.doGet(httpHeaderClient);
                    return buffer.toString().getBytes();
                }
                ////System.out.println("executor resource 1");
                //Object buffer = method.invoke(customClass.newInstance(), new Object[]{httpHeaderClient});

                // //logger.info(buffer.toString());

            } catch (IOException | SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } /*catch (InvocationTargetException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              } catch (NoSuchMethodException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              } */catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * This method obtains the url from the resource
     * @param resource
     * @return
     */
    private String ObtainUrlFromResource(String[] resource) {
        if (resource != null && resource.length > 2) {
            StringBuffer resourcepath = new StringBuffer();
            for (int resourcepathcount = 2; resourcepathcount < resource.length; resourcepathcount++) {
                resourcepath.append("/");
                resourcepath.append(resource[resourcepathcount]);
            }
            return resourcepath.toString();
        }
        return "";
    }

    /**
     * This method parses the http headers from the Http content
     * @param httpheader
     * @return
     */
    public HttpHeaderClient parseHttpHeaders(String httpheader) {
        char c = (char) 13;
        String[] header = httpheader.split("" + c);
        HttpHeaderClient httpClient = new HttpHeaderClient();
        String httpHeader = header[0];
        String[] httpHeaderArray = httpHeader.split(" ");
        httpClient.setHttpMethod(httpHeaderArray[0]);
        ConcurrentHashMap urlParams = new ConcurrentHashMap();
        httpClient.setResourceToObtain(ObtainUrlAndParams(httpHeaderArray[1], urlParams));
        httpClient.setParameters(urlParams);
        httpClient.setHttpVersion(httpHeaderArray[2]);
        String tmpHeader;
        String[] headerParam;
        String boundary;
        String boundaryValue;
        for (int i = 1; i < header.length; i++) {
            tmpHeader = header[i];
            //logger.info(tmpHeader);
            headerParam = splitHeaderParams(tmpHeader);
            if (headerParam[0].equals(HttpHeaderParamNames.HOST)) {
                httpClient.setHost(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT)) {
                httpClient.setAcceptResource(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT_ENCODING)) {
                httpClient.setAcceptEncoding(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT_LANGUAGE)) {
                httpClient.setAcceptLanguage(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.CONNECTION)) {
                httpClient.setConnection(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.USERAGENT)) {
                httpClient.setUserAgent(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.CONTENTLENGTH)) {
                httpClient.setContentLength(headerParam[1]);
            } else if (headerParam[0].equals(HttpHeaderParamNames.COOKIE)) {
                String[] cookies = headerParam[1].split(";");
                String[] cookieKeyValue;
                HttpCookie httpCookie;
                for (String cookie : cookies) {
                    cookieKeyValue = cookie.split("=");
                    httpCookie = new HttpCookie();
                    httpCookie.setKey(cookieKeyValue[0].trim());
                    httpCookie.setValue(cookieKeyValue[1].trim());
                    httpClient.addCookie(httpCookie);
                }
            } else if (headerParam[0].equals(HttpHeaderParamNames.CONTENTTYPE)) {
                String[] headerParamValue = headerParam[1].split(";");
                httpClient.setContentType(headerParamValue[0].trim());
                if (headerParamValue != null && headerParamValue.length > 1) {
                    if (httpClient.getContentType().equalsIgnoreCase(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
                        if (headerParamValue[1].contains(HttpHeaderParamNames.BOUNDARY)) {
                            int equalToIndexInBoundary = headerParamValue[1].indexOf('=');
                            boundary = headerParamValue[1].substring(0, equalToIndexInBoundary).trim();
                            boundaryValue = headerParamValue[1].substring(equalToIndexInBoundary + 1).trim();
                            httpClient.setBoundary(boundaryValue);
                        }
                    }

                }
            }
        }

        return httpClient;
    }

    /**
     * This method obtains the url parameters
     * @param url
     * @param params
     * @return string
     */
    public String ObtainUrlAndParams(String url, ConcurrentHashMap params) {

        URLDecoder decoder = new URLDecoder();
        url = decoder.decode(url);
        if (url.indexOf("?") > -1) {
            String paramaters = url.substring(url.indexOf("?") + 1);
            StringTokenizer paramGroup = new StringTokenizer(paramaters, "&");

            while (paramGroup.hasMoreTokens()) {

                StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "=");
                String param = null;
                if (value.hasMoreTokens()) {
                    param = value.nextToken();
                }
                String paramValue = null;
                if (value.hasMoreTokens()) {
                    paramValue = value.nextToken();
                }
                if (param != null && paramValue != null) {
                    if (params.get(param) != null) {
                        if (params.get(param) instanceof String[]) {
                            String[] parameters = (String[]) params.get(param);
                            String[] paramValues = new String[parameters.length + 1];
                            for (int paramcount = 0; paramcount < parameters.length; paramcount++) {
                                paramValues[paramcount] = parameters[paramcount];
                            }
                            paramValues[parameters.length] = paramValue;
                            params.put(param, paramValues);
                        } else if (params.get(param) instanceof String) {
                            String[] paramValues = new String[2];
                            paramValues[0] = (String) params.get(param);
                            paramValues[1] = paramValue;
                            params.put(param, paramValues);
                        }
                    } else {
                        params.put(param, paramValue);
                    }
                }
            }
        }
        if (url.indexOf("?") != -1) {
            return url.substring(0, url.indexOf("?"));
        }
        return url;
    }

    /**
     * This method splits the header params
     * @param headerParams
     * @return param
     */
    public String[] splitHeaderParams(String headerParams) {
        int indexToSplit = headerParams.indexOf(":");
        String[] param = new String[2];
        param[0] = headerParams.substring(0, indexToSplit).trim();
        param[1] = headerParams.substring(indexToSplit + 1).trim();
        return param;
    }

    /**
     * This method forms the http response
     * @param responseCode
     * @param httpHeader
     * @param content
     * @return
     */
    private byte[] formHttpResponseHeader(int responseCode, HttpHeaderServer httpHeader, byte[] content,
            ConcurrentHashMap<String, HttpCookie> httpCookies) {
        StringBuffer buffer = new StringBuffer();
        String colon = ": ";
        String crlf = "\r\n";
        if (responseCode == 200) {
            buffer.append("HTTP/1.1 200 OK");
            buffer.append(crlf);
            buffer.append(HttpHeaderServerParamNames.DATE);
            buffer.append(colon);
            buffer.append(httpHeader.getDate());
            buffer.append(crlf);
            buffer.append(HttpHeaderServerParamNames.SERVER);
            buffer.append(colon);
            buffer.append(httpHeader.getServer());
            buffer.append(crlf);
            buffer.append(HttpHeaderServerParamNames.CONTENT_TYPE);
            buffer.append(colon);
            buffer.append(httpHeader.getContentType());
            buffer.append(crlf);
            buffer.append(HttpHeaderServerParamNames.CONTENT_LENGTH);
            buffer.append(colon);
            buffer.append(httpHeader.getContentLength());
            buffer.append(crlf);
            buffer.append(HttpHeaderServerParamNames.LAST_MODIFIED);
            buffer.append(colon);
            buffer.append(httpHeader.getLastModified());
            if (httpCookies != null) {
                Iterator<String> cookieNames = httpCookies.keySet().iterator();
                HttpCookie httpCookie;
                for (; cookieNames.hasNext();) {
                    String cookieName = cookieNames.next();
                    httpCookie = (HttpCookie) httpCookies.get(cookieName);
                    buffer.append(crlf);
                    buffer.append(HttpHeaderServerParamNames.SETCOOKIE);
                    buffer.append(colon);
                    buffer.append(httpCookie.getKey());
                    buffer.append("=");
                    buffer.append(httpCookie.getValue());
                    if (httpCookie.getExpires() != null) {
                        buffer.append("; ");
                        buffer.append(HttpHeaderServerParamNames.SETCOOKIEEXPIRES);
                        buffer.append("=");
                        buffer.append(httpCookie.getExpires());
                    }
                }
            }
        } else if (responseCode == 404) {
            buffer.append("HTTP/1.1 404 Not Found");
        }
        buffer.append(crlf);
        buffer.append(crlf);
        byte[] byt1 = buffer.toString().getBytes();
        byte[] byt2 = new byte[byt1.length + content.length + crlf.length() * 2];
        /////System.out.println("Header="+new String(byt1));
        for (int count = 0; count < byt1.length; count++) {
            byt2[count] = byt1[count];
        }
        for (int count = 0; count < content.length; count++) {
            byt2[count + byt1.length] = content[count];
        }
        for (int count = 0; count < crlf.length() * 2; count++) {
            byt2[count + byt1.length + content.length] = (byte) crlf.charAt(count % 2);
        }
        ////System.out.println("Header with content="+new String(byt2));
        /*try {
           buffer.append(new String(content, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/
        return byt2;
    }

    /**
     * This methods obtains the stream bytes from the file
     * @param filepath
     * @return
     */
    private byte[] obtainContent(String filepath) {
        byte[] filebt = null;
        try {
            File file = new File(filepath);
            if (file.isFile() && file.exists()) {
                FileInputStream stream = new FileInputStream(filepath);
                filebt = new byte[(int) file.length()];
                stream.read(filebt, 0, (int) file.length());
                stream.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            filebt = null;
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            filebt = null;
            e.printStackTrace();
        } catch (Exception ex) {
            filebt = null;
            ex.printStackTrace();
        }
        return filebt;

    }

    public void addURL(URL url, WebClassLoader customClassLoader) throws IOException {
        try {
            customClassLoader.addURL(url);
        } catch (Throwable t) {
            t.printStackTrace();
        } //end try catch
    }//end method

    public interface WebServerRequestProcessorMBean {
        public int getNumberOfRequests();
    }

    public interface WebServerHttpsRequestProcessorMBean {
        public int getNumberOfRequests();
    }

    class WebServerHttpsRequestProcessor extends Thread implements Runnable, WebServerHttpsRequestProcessorMBean {
        String deployDirectory;
        int shutdownPort;
        Hashtable urlClassLoaderMap;
        int numberOfRequests = 0;
        int instanceNumber;
        ConcurrentHashMap cache = new ConcurrentHashMap();
        int requestPort;
        ConcurrentHashMap sessionObjects = new ConcurrentHashMap();
        ConcurrentHashMap servletMapping;
        String certstore;
        String passcode;

        public WebServerHttpsRequestProcessor() {

        }

        public WebServerHttpsRequestProcessor(ConcurrentHashMap servletMapping, Hashtable urlClassLoaderMap,
                int requestPort, String deployDirectory, int shutdownPort, String certstore, String passcode,
                int instanceNumber) {
            this.requestPort = requestPort;
            this.deployDirectory = deployDirectory;
            this.shutdownPort = shutdownPort;
            this.urlClassLoaderMap = urlClassLoaderMap;
            this.servletMapping = servletMapping;
            this.instanceNumber = instanceNumber;
            this.certstore = certstore;
            this.passcode = passcode;
        }
        /*public void run(){
        SSLServerSocket sslServerSocket = null;
           SSLSocket  sock;
           try {
        System.out.println(certstore);
        System.out.println(passcode);
        System.setProperty("javax.net.ssl.keyStore", certstore);
        System.setProperty("javax.net.ssl.keyStorePassword", passcode);
        ServerSocketFactory factory =
              (ServerSocketFactory) SSLServerSocketFactory.getDefault();
           System.out.println("factory created");
               
           sslServerSocket = (SSLServerSocket) factory.createServerSocket();
           sslServerSocket.bind(new InetSocketAddress("0.0.0.0", requestPort), 10000);
           String[] suites = sslServerSocket.getSupportedCipherSuites();
            for (int i = 0; i < suites.length; i++) {
              System.out.println(suites[i]);
            }
            sslServerSocket.setEnabledCipherSuites(suites);
            String[] protocols = sslServerSocket.getSupportedProtocols();
            for (int i = 0; i < protocols.length; i++) {
              System.out.println(protocols[i]);
            }
           } catch (Exception  e) {
        // TODO Auto-generated catch block
        System.out.println("Exception in ssl server socket="+e.getMessage());
           }
           Digester serverdigester = null;
           try {
        serverdigester = DigesterLoader.createDigester(new InputSource(new FileInputStream("./config/executorconfig-rules.xml")));
           } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
           }
           java.util.concurrent.ExecutorService executor = new java.util.concurrent.ScheduledThreadPoolExecutor(250);
           while(true){
            
        try{
               
            
               
           sock=(SSLSocket) sslServerSocket.accept();
           sock.startHandshake();
           System.out.println("A new Socket="+sock);
           //System.out.println("A new Socket1="+sock);
           WebServer webserver=new WebServer(sock,this.requestPort,this.deployDirectory,this.shutdownPort,serverdigester,urlClassLoaderMap);
           //System.out.println("starting web request");
           executor.execute(webserver);
           //webserver.start();
           //System.out.println("starting web request1");
           numberOfRequests++;
        }
        catch(Exception ex){
           System.out.println("Exception in socket="+ex.getMessage());
           //break;
        }
           }
        }*/

        public void run() {

            // Create HTTP protocol processing chain
            HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                    .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
                    .build();
            // Create request handler registry
            UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
            // Register the default handler for all URIs

            DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

                protected void loadRules() {
                    // TODO Auto-generated method stub
                    try {
                        loadXMLRules(new InputSource(new FileInputStream("./config/executorconfig-rules.xml")));
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            Digester serverdigester = serverdigesterLoader.newDigester();
            reqistry.register("*",
                    new HttpFileHandler(new File(this.deployDirectory), serverdigester, urlClassLoaderMap));
            // Create server-side HTTP protocol handler
            HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) {

                @Override
                public void connected(final NHttpServerConnection conn) {
                    //   System.out.println(conn + ": connection open");
                    super.connected(conn);
                }

                @Override
                public void closed(final NHttpServerConnection conn) {
                    //  System.out.println(conn + ": connection closed");
                    super.closed(conn);
                }

            };
            try {
                // Create HTTP connection factory
                NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
                // Initialize SSL context
                KeyStore keystore = KeyStore.getInstance("jks");
                keystore.load(new FileInputStream(certstore), passcode.toCharArray());
                KeyManagerFactory kmfactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmfactory.init(keystore, passcode.toCharArray());
                KeyManager[] keymanagers = kmfactory.getKeyManagers();
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(keymanagers, null, null);
                connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
                // Create server-side I/O event dispatch
                IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
                // Set I/O reactor defaults
                IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(300).setSoTimeout(3000)
                        .setConnectTimeout(3000).setTcpNoDelay(true).setInterestOpQueued(true).build();
                // Create server-side I/O reactor
                ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config);

                // Listen of the given port
                ioReactor.listen(new InetSocketAddress("0.0.0.0", requestPort));
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                ex.printStackTrace();
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //System.out.println("Shutdown");
        }

        class HttpFileHandler implements HttpAsyncRequestHandler<HttpRequest> {

            private final File docRoot;
            private final Digester serverDigester;
            Hashtable urlClassLoaderMap;

            public HttpFileHandler(final File docRoot, final Digester serverDigester, Hashtable urlClassLoaderMap) {
                super();
                this.docRoot = docRoot;
                this.serverDigester = serverDigester;
                this.urlClassLoaderMap = urlClassLoaderMap;
            }

            public HttpAsyncRequestConsumer<HttpRequest> processRequest(final HttpRequest request,
                    final HttpContext context) {
                // Buffer request content in memory for simplicity
                return new BasicAsyncRequestConsumer();
            }

            public void handle(final HttpRequest request, final HttpAsyncExchange httpexchange,
                    final HttpContext context) throws HttpException, IOException {
                HttpResponse response = httpexchange.getResponse();
                handleInternal(request, response, context);
                httpexchange.submitResponse(new BasicAsyncResponseProducer(response));
            }

            private void handleInternal(final HttpRequest request, final HttpResponse response,
                    final HttpContext context) throws HttpException, IOException {

                HttpCoreContext coreContext = HttpCoreContext.adapt(context);

                String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
                if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                    throw new MethodNotSupportedException(method + " method not supported");
                }

                String target = request.getRequestLine().getUri();
                // System.out.println("REQUESTED URi:"+request.getRequestLine().getUri());
                String resourceToObtain = URLDecoder.decode(target, "UTF-8");
                HttpHeaderClient httpHeaderClient = new HttpHeaderClient();
                httpHeaderClient.setHttpMethod(method);

                String urlToFetch = null;
                if (resourceToObtain.indexOf('?') != -1) {
                    urlToFetch = resourceToObtain.substring(0, resourceToObtain.indexOf('?'));
                    String param = resourceToObtain.substring(resourceToObtain.indexOf('?') + 1,
                            resourceToObtain.length());
                    httpHeaderClient.setParameters(parseUrlEncoded(param));
                } else {
                    urlToFetch = resourceToObtain;
                    httpHeaderClient.setParameters(new ConcurrentHashMap());
                }
                Header[] header = request.getHeaders(HttpHeaderParamNames.COOKIE);
                // System.out.println(header);
                if (header != null && header.length >= 1) {
                    //System.out.println(header[0].getValue());
                    String[] cookies = header[0].getValue().split(";");
                    String[] cookieKeyValue;
                    HttpCookie httpCookie;
                    for (String cookie : cookies) {
                        cookieKeyValue = cookie.split("=");
                        httpCookie = new HttpCookie();
                        httpCookie.setKey(cookieKeyValue[0].trim());
                        httpCookie.setValue(cookieKeyValue[1].trim());
                        // System.out.println(cookieKeyValue[0].trim());
                        //System.out.println(cookieKeyValue[1].trim());
                        httpHeaderClient.addCookie(httpCookie);
                    }
                }
                ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
                HttpSessionServer session = null;
                if (httpCookies != null) {
                    Iterator<String> cookieNames = httpCookies.keySet().iterator();
                    for (; cookieNames.hasNext();) {
                        String cookieName = cookieNames.next();
                        //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                        if (cookieName.equals("SERVERSESSIONID")) {
                            session = (HttpSessionServer) sessionObjects
                                    .get(httpCookies.get(cookieName).getValue());
                            httpHeaderClient.setSession(session);
                            //break;
                        }
                    }
                }
                //System.out.println("Session="+session);
                if (session == null) {
                    HttpCookie cookie = new HttpCookie();
                    cookie.setKey("SERVERSESSIONID");
                    cookie.setValue(UUID.randomUUID().toString());
                    httpCookies.put("SERVERSESSIONID", cookie);
                    session = new HttpSessionServer();
                    sessionObjects.put(cookie.getValue(), session);
                    httpHeaderClient.setSession(session);
                }

                //System.out.println(urlToFetch);
                //System.out.println(deployDirectory);
                //System.out.println(serverDigester);
                //System.out.println(urlClassLoaderMap);
                numberOfRequests++;
                byte[] content = ObtainContentExecutor(deployDirectory, urlToFetch, httpHeaderClient,
                        serverDigester, urlClassLoaderMap, servletMapping, session);
                if (content == null) {
                    final File file = new File(this.docRoot, resourceToObtain);
                    if (!file.exists()) {

                        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                        NStringEntity entity = new NStringEntity(
                                "<html><body><h1>File" + file.getPath() + " not found</h1></body></html>",
                                ContentType.create("text/html", "UTF-8"));
                        response.setEntity(entity);
                        // System.out.println("File " + file.getPath() + " not found");

                    } else if (!file.canRead() || file.isDirectory()) {

                        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
                        NStringEntity entity = new NStringEntity("<html><body><h1>Access denied</h1></body></html>",
                                ContentType.create("text/html", "UTF-8"));
                        response.setEntity(entity);
                        // System.out.println("Cannot read file " + file.getPath());

                    } else {
                        NHttpConnection conn = coreContext.getConnection(NHttpConnection.class);
                        response.setStatusCode(HttpStatus.SC_OK);
                        NFileEntity body = new NFileEntity(file, ContentType.create("text/html"));
                        response.setEntity(body);
                        //System.out.println(conn + ": serving file " + file.getPath());
                    }
                } else {
                    NByteArrayEntity byteArrayEntity = new NByteArrayEntity(content);
                    response.setEntity(byteArrayEntity);
                    httpCookies = httpHeaderClient.getCookies();
                    System.out.println(httpCookies);
                    if (httpCookies != null) {
                        Iterator<String> cookieNames = httpCookies.keySet().iterator();
                        HttpCookie httpCookie;
                        StringBuffer buffer = new StringBuffer();
                        for (; cookieNames.hasNext();) {
                            String cookieName = cookieNames.next();
                            httpCookie = (HttpCookie) httpCookies.get(cookieName);
                            buffer.append(httpCookie.getKey());
                            buffer.append("=");
                            buffer.append(httpCookie.getValue());
                            //System.out.println(httpCookie.getKey());
                            //System.out.println(httpCookie.getValue());
                            if (httpCookie.getExpires() != null) {
                                buffer.append("; ");
                                buffer.append(HttpHeaderServerParamNames.SETCOOKIEEXPIRES);
                                buffer.append("=");
                                buffer.append(httpCookie.getExpires());
                            }
                            //System.out.println(HttpHeaderServerParamNames.SETCOOKIE+""+buffer.toString());
                            response.addHeader(HttpHeaderServerParamNames.SETCOOKIE, buffer.toString());
                            buffer.delete(0, buffer.length());
                        }
                    }

                }
                header = response.getAllHeaders();
                for (Header hdr : header) {
                    System.out.println("NAMe: " + hdr.getName() + " value: " + hdr.getValue());
                }
            }

        }

        @Override
        public int getNumberOfRequests() {
            // TODO Auto-generated method stub
            return numberOfRequests;
        }
    }

    /**
     * This class processes the http request 
     * @author arun
     *
     */
    class WebServerRequestProcessor extends Thread implements Runnable, WebServerRequestProcessorMBean {
        private int requestPort;
        private String deployDirectory;
        private int shutdownPort;
        private Hashtable urlClassLoaderMap;
        private int numberOfRequests = 0;
        private int instanceNumber;
        private ServerSocketChannel serverSocketChannel;

        private ConcurrentHashMap servletMapping;

        public WebServerRequestProcessor() {

        }

        public WebServerRequestProcessor(ConcurrentHashMap servletMapping, Hashtable urlClassLoaderMap,
                ServerSocketChannel serverSocketChannel, String deployDirectory, int shutdownPort,
                int instanceNumber) {
            this.requestPort = requestPort;
            this.deployDirectory = deployDirectory;
            this.shutdownPort = shutdownPort;
            this.urlClassLoaderMap = urlClassLoaderMap;
            this.instanceNumber = instanceNumber;
            this.serverSocketChannel = serverSocketChannel;
            this.servletMapping = servletMapping;
        }

        private String manualIntern(WeakHashMap<String, WeakReference<String>> s_manualCache, final String key,
                final String str) {
            final WeakReference<String> cached = s_manualCache.get(key);
            if (cached != null) {
                final String value = cached.get();
                if (value != null)
                    return value;
            }
            s_manualCache.put(key, new WeakReference<String>(str));
            return str;
        }

        public void run() {
            String CLIENTCHANNELNAME = "clientChannel" + instanceNumber;
            String SERVERCHANNELNAME = "serverChannel" + instanceNumber;
            String channelType = "channelType" + instanceNumber;
            byte[] response;
            byte[] content;
            byte[] uploadData = null;
            HttpHeaderClient httpHeaderClient;
            InputStream istream = null;
            OutputStream ostream = null;
            HttpHeaderServer serverParam = new HttpHeaderServer();
            String value;
            char c;
            String endvalue = "\r\n\r\n";
            String urlFormEncoded;
            int responseCode;
            ConcurrentHashMap clientkey = new ConcurrentHashMap();
            Digester serverdigester = null;
            DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

                protected void loadRules() {
                    // TODO Auto-generated method stub
                    try {
                        loadXMLRules(new InputSource(new FileInputStream("./config/executorconfig-rules.xml")));
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            serverdigester = serverdigesterLoader.newDigester();
            try {

                ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);

                //ByteBuffer writeBuffer = ByteBuffer.allocateDirect(1024*1024);

                Selector selector = Selector.open();

                SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector,
                        SelectionKey.OP_ACCEPT);

                Set<SelectionKey> selectedKeys;
                // logger.info("Instance Number"+instanceNumber);
                Iterator<SelectionKey> iterator = null;
                //socketServerSelectionKey.attach(properties);
                SelectionKey key = null;
                SocketChannel clientChannel = null;
                while (true) {
                    try {

                        if (selector.select() >= 0) {
                            selectedKeys = selector.selectedKeys();
                            iterator = selectedKeys.iterator();
                        }
                        while (iterator != null && iterator.hasNext()) {
                            key = iterator.next();
                            //logger.info("instanceName"+instanceNumber+" ::: "+key);
                            if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                                SocketChannel clientSocketChannel = serverSocketChannel.accept();

                                if (clientSocketChannel != null) {
                                    // set the client connection to be non blocking
                                    clientSocketChannel.configureBlocking(false);
                                    SelectionKey clientKey = clientSocketChannel.register(selector,
                                            SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                    clientKey.interestOps(SelectionKey.OP_READ);
                                }

                            } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                                // data is available for read
                                // buffer for reading
                                //System.out.println("read="+key);;
                                clientChannel = (SocketChannel) key.channel();
                                int bytesRead = 0;
                                ByteArrayOutputStream headerData = new ByteArrayOutputStream();
                                int totalBytRead = 0;
                                if (key.isReadable()) {
                                    // the channel is non blocking so keep it open till the
                                    // count is >=0
                                    //System.out.println(key);
                                    //System.out.println(clientChannel);
                                    /*while (true) {
                                       buffer.clear();
                                        
                                       bytesRead = clientChannel.read(buffer);
                                        
                                         if (bytesRead <= 0) {
                                           break;
                                         }
                                        
                                         buffer.flip();
                                        
                                         headerData.write(buffer.array(),0,bytesRead);
                                         buffer.compact();
                                         totalBytRead += bytesRead;
                                       }*/

                                    /*while (true) {
                                       if(!((bytesRead = clientChannel.read(buffer)) >0)){
                                          break;
                                       }
                                       buffer.flip(); 
                                       headerData.write(buffer.array(),0,bytesRead);
                                       buffer.clear();
                                       //buffer.compact(); 
                                       totalBytRead += bytesRead;
                                       }*/
                                    /*while (clientChannel.read(buffer) >= 0 || buffer.position() > 0) {
                                         buffer.flip();
                                         headerData.write(buffer.array(),0,bytesRead);
                                         //buffer.compact();
                                     }*/
                                    while ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        buffer.flip();
                                        //System.out.println(Charset.defaultCharset().decode(
                                        //      buffer));
                                        for (int bytcount = 0; bytcount < bytesRead; bytcount++) {
                                            headerData.write(buffer.get(bytcount));
                                        }
                                        Thread.sleep(50);
                                        buffer.clear();
                                        totalBytRead += bytesRead;
                                    }
                                    //System.out.println("Total bytes Read"+totalBytRead);
                                    if (totalBytRead == 0)
                                        continue;
                                    //System.out.println("totalBytRead"+totalBytRead);
                                    // System.out.println("ClientChannel="+clientChannel);
                                    byte[] bt = headerData.toByteArray();
                                    // System.out.println(new String(bt));
                                    int index = containbytes(bt, endvalue.getBytes());
                                    // System.out.println("index="+index);
                                    if (index == -1)
                                        index = totalBytRead;
                                    value = new String(ObtainBytes(bt, 0, index));
                                    //System.out.println("value2="+value);
                                    httpHeaderClient = parseHttpHeaders(value);
                                    //System.out.println(httpHeaderClient.getResourceToObtain());
                                    ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient
                                            .getCookies();
                                    HttpSessionServer session = null;
                                    if (httpCookies != null) {
                                        Iterator<String> cookieNames = httpCookies.keySet().iterator();
                                        for (; cookieNames.hasNext();) {
                                            String cookieName = cookieNames.next();
                                            //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                                            if (cookieName.equals("SERVERSESSIONID")) {
                                                session = (HttpSessionServer) sessionObjects
                                                        .get(httpCookies.get(cookieName).getValue());
                                                httpHeaderClient.setSession(session);
                                                //break;
                                            }
                                        }
                                    }
                                    //System.out.println("Session="+session);
                                    if (session == null) {
                                        HttpCookie cookie = new HttpCookie();
                                        cookie.setKey("SERVERSESSIONID");
                                        cookie.setValue(UUID.randomUUID().toString());
                                        httpCookies.put("SERVERSESSIONID", cookie);
                                        session = new HttpSessionServer();
                                        sessionObjects.put(cookie.getValue(), session);
                                        httpHeaderClient.setSession(session);
                                    }
                                    if (httpHeaderClient.getContentType() != null && httpHeaderClient
                                            .getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
                                        uploadData = ObtainBytes(bt, index + endvalue.length(),
                                                index + endvalue.length()
                                                        + Integer.parseInt(httpHeaderClient.getContentLength()));
                                        ////System.out.println(new String(uploadData));
                                        ConcurrentHashMap paramMap = new MultipartFormData()
                                                .parseContent(uploadData, httpHeaderClient);
                                        httpHeaderClient.setParameters(paramMap);
                                        ////logger.info(uploadData);
                                    } else if (httpHeaderClient.getContentType() != null && httpHeaderClient
                                            .getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
                                        urlFormEncoded = new String(
                                                ObtainBytes(bt, index + endvalue.length(), index + endvalue.length()
                                                        + Integer.parseInt(httpHeaderClient.getContentLength())));
                                        ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
                                        httpHeaderClient.setParameters(paramMap);
                                    }
                                    ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
                                    ////System.out.println("value3=");

                                    ////logger.info(new String(bt));
                                    serverParam.setContentType("text/html");
                                    URLDecoder decoder = new URLDecoder();
                                    ////System.out.println("content Length= "+socket);
                                    responseCode = 200;
                                    File file = new File(deployDirectory
                                            + decoder.decode(httpHeaderClient.getResourceToObtain()));
                                    FileContent fileContent = (FileContent) cache
                                            .get(httpHeaderClient.getResourceToObtain());
                                    if (fileContent != null
                                            && file.lastModified() == fileContent.getLastModified()) {
                                        //System.out.println("In cache");
                                        content = (byte[]) fileContent.getContent();
                                    } else {
                                        content = ObtainContentExecutor(deployDirectory,
                                                httpHeaderClient.getResourceToObtain(), httpHeaderClient,
                                                serverdigester, urlClassLoaderMap, servletMapping, session);
                                        ////System.out.println("content Length2= ");
                                        if (content == null) {
                                            //System.out.println("In caching content");
                                            content = obtainContent(deployDirectory
                                                    + decoder.decode(httpHeaderClient.getResourceToObtain()));
                                            if (content != null) {
                                                fileContent = new FileContent();
                                                fileContent.setContent(content);
                                                fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                                                fileContent.setLastModified(file.lastModified());
                                                //cache.put(httpHeaderClient.getResourceToObtain(),fileContent);
                                            }
                                        }
                                        ////System.out.println("value4=");

                                    }

                                    if (content == null) {
                                        responseCode = 404;
                                        content = ("<html><body><H1>The Request resource "
                                                + httpHeaderClient.resourceToObtain
                                                + " Not Found</H1><body></html>").getBytes();
                                    }
                                    ////System.out.println("content Length3= ");
                                    serverParam.setContentLength("" + (content.length + 4));
                                    if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
                                        serverParam.setContentType("image/png");
                                    }
                                    ////System.out.println("value5=");

                                    ////System.out.println("content Length4= ");
                                    response = formHttpResponseHeader(responseCode, serverParam, content,
                                            httpHeaderClient.getCookies());
                                    ////System.out.println("value6=");
                                    //logger.info("Response="+new String(response));

                                    /*if (bytesRead < 0) {
                                       System.out.println("bytesRead as 0");
                                        // the key is automatically invalidated once the
                                        // channel is closed
                                       key.cancel();
                                       clientChannel.close();
                                    }
                                    else{
                                       clientkey.put(key, response);                                 
                                    }
                                    key.interestOps(SelectionKey.OP_WRITE);*/
                                    ByteBuffer source = ByteBuffer.wrap(response);
                                    SelectionKey key2 = clientChannel.register(selector, SelectionKey.OP_WRITE);
                                    key2.attach(source);
                                    key2.interestOps(SelectionKey.OP_WRITE);
                                }

                            } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                                // the channel is non blocking so keep it open till the
                                // count is >=0
                                //System.out.println("write="+key);;
                                /*response=(byte[]) clientkey.get(key);
                                ByteBuffer responseBuffer=ByteBuffer.wrap(response);
                                 while (responseBuffer.hasRemaining()) {
                                    clientChannel.write(responseBuffer);
                                 }
                                 key.cancel();*/
                                ByteBuffer output = (ByteBuffer) key.attachment();
                                if (!output.hasRemaining()) {
                                    output.rewind();
                                }
                                clientChannel.write(output);
                                //key.interestOps(SelectionKey.OP_READ);
                                key.cancel();
                                clientChannel.close();
                                numberOfRequests++;
                            }
                            // once a key is handled, it needs to be removed
                            iterator.remove();

                        }
                    } catch (Exception ex) {
                        key.cancel();
                        //key.interestOps(SelectionKey.OP_READ);
                        clientChannel.close();
                        logger.error("Error in socket channel", ex);
                    }
                }
            } catch (Exception ex) {
                logger.error("Error in socket channel", ex);
            }
        }

        /**
         * This method start the webserver thread for each http 
         * request 
         */
        /*public void run(){
               
           ServerSocket serverSocket = null;
           Socket sock=new Socket();
           try {
        serverSocket=new ServerSocket(this.requestPort);
           } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
           }
           Digester serverdigester = null;
           try {
        serverdigester = DigesterLoader.createDigester(new InputSource(new FileInputStream("./config/executorconfig-rules.xml")));
           } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
           }
           java.util.concurrent.ExecutorService executor = new java.util.concurrent.ScheduledThreadPoolExecutor(1000);
           while(true){
            
        try{
           //System.out.println("A new Socket="+sock);
           sock=serverSocket.accept();
           //System.out.println("A new Socket1="+sock);
           WebServer webserver=new WebServer(sock,this.requestPort,this.deployDirectory,this.shutdownPort,serverdigester,urlClassLoaderMap);
           //System.out.println("starting web request");
           executor.execute(webserver);
           //webserver.start();
           //System.out.println("starting web request1");
           numberOfRequests++;
        }
        catch(Exception ex){
           try {
              socket = new Socket("localhost",shutdownPort);
              OutputStream outputStream=socket.getOutputStream();
              outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
              outputStream.close();
           } catch (IOException e1) {
                  
              e1.printStackTrace();
           }   
        }
           }
        }*/
        /**
         * This method returns the number of http requests.
         */
        @Override
        public int getNumberOfRequests() {
            // TODO Auto-generated method stub
            return numberOfRequests;
        }
    }
}