com.web.server.WarDeployer.java Source code

Java tutorial

Introduction

Here is the source code for com.web.server.WarDeployer.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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.*;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.apache.jasper.JspC;
import org.apache.log4j.Logger;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.Message.Flag;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.web.messaging.MessagingClassConstruct;
import com.web.messaging.MessagingElem;
import com.web.messaging.Queue;
import com.web.messaging.Topic;
import com.web.server.servlet.ServletMapping;
import com.web.server.servlet.Servlets;
import com.web.server.servlet.WebAppConfig;
import com.web.server.util.ClassLoaderUtil;
import com.web.server.util.FarmWarFileTransfer;
import com.web.services.ExecutorServicesConstruct;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * This class is the implementation of war deployer which deploys the war in exploded form and 
 * configures the executor and its services, messaging.
 * @author arun
 *
 */
public class WarDeployer extends Thread implements Runnable, WarDeployerMBean {
    String scanDirectory;
    Hashtable urlClassLoaderMap;
    Hashtable executorServiceMap;
    Hashtable messagingClassMap;
    Digester serverdigester;
    Digester messagedigester;
    Digester webxmldigester;
    MessagingElem messagingElem;
    static int numberOfWarDeployed = 0;
    private String[] warDeployed;
    private CopyOnWriteArrayList warsDeployed;
    ConcurrentHashMap servletMapping;
    ConcurrentHashMap sessionObjects;
    FarmWarFileTransfer farmWarFileTransfer = null;

    public WarDeployer(String scanDirectory, String farmwarDir, String clusterGroup, Hashtable urlClassLoaderMap,
            Hashtable executorServiceMap, Hashtable messagingClassMap, ConcurrentHashMap servletMapping,
            MessagingElem messagingElem, ConcurrentHashMap sessionObjects) {
        this.scanDirectory = scanDirectory;
        this.urlClassLoaderMap = urlClassLoaderMap;
        this.executorServiceMap = executorServiceMap;
        this.messagingClassMap = messagingClassMap;
        this.servletMapping = servletMapping;
        this.sessionObjects = sessionObjects;
        farmWarFileTransfer = FarmWarFileTransfer.getInstance(scanDirectory + "/", farmwarDir, clusterGroup);
        try {
            farmWarFileTransfer.start();
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        try {
            DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

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

                }
            });
            serverdigester = serverdigesterLoader.newDigester();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

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

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

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

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

                }
            });
            webxmldigester = serverdigesterLoader.newDigester();
        } catch (Exception ex) {
            //ex.printStackTrace();
        }
        synchronized (messagingElem) {
            this.messagingElem = messagingElem;
            ConcurrentHashMap randomQueue = messagingElem.randomQueue;
            Set<String> randomQueueSet = randomQueue.keySet();
            Iterator<String> ite = randomQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) randomQueue.get(ite.next());
                ConcurrentHashMap randomqueuemap = (ConcurrentHashMap) messagingClassMap.get("RandomQueue");
                if (randomqueuemap == null) {
                    randomqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RandomQueue", randomqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) randomqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    randomqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap roundrobinQueue = messagingElem.roundrobinQueue;
            Set<String> roundrobinQueueSet = roundrobinQueue.keySet();
            ite = roundrobinQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) roundrobinQueue.get(ite.next());
                ConcurrentHashMap roundrobinqueuemap = (ConcurrentHashMap) messagingClassMap.get("RoundRobinQueue");
                if (roundrobinqueuemap == null) {
                    roundrobinqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RoundRobinQueue", roundrobinqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) roundrobinqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    roundrobinqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap topicMap = messagingElem.topicMap;
            Set<String> topicSet = topicMap.keySet();
            Iterator<String> iter = topicSet.iterator();
            while (iter.hasNext()) {
                Topic topic = (Topic) topicMap.get(iter.next());
                ConcurrentHashMap topicmap = (ConcurrentHashMap) messagingClassMap.get("Topic");
                if (topicmap == null) {
                    topicmap = new ConcurrentHashMap();
                    messagingClassMap.put("Topic", topicmap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) topicmap.get(topic.getTopicname());
                if (randomqueuelist == null)
                    topicmap.put(topic.getTopicname(), new CopyOnWriteArrayList());
            }
            System.out.println(messagingClassMap);
        }

    }

    Logger logger = Logger.getLogger(WarDeployer.class);

    /**
     * This method is the implementation of the war deployer which frequently scans the deploy
     * directory and if there is a change in war redeploys and configures the map
     */
    public void run() {
        File file;
        ConcurrentHashMap filePrevMap = new ConcurrentHashMap();
        ConcurrentHashMap fileCurrMap = new ConcurrentHashMap();
        ;

        FileInfo filePrevLastModified;
        FileInfo fileCurrLastModified;
        String filePath;
        FileInfo fileinfoTmp;
        URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL[] urls = loader.getURLs();
        warsDeployed = new CopyOnWriteArrayList();
        //System.out.println("URLS="+urls[0]);
        WebClassLoader customClassLoader;
        while (true) {
            file = new File(scanDirectory);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory())
                    continue;
                //Long lastModified=(Long) fileMap.get(files[i].getName());
                if (files[i].getName().endsWith(".war")) {
                    filePath = files[i].getAbsolutePath();
                    //logger.info("filePath"+filePath);
                    filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                    File warDirectory = new File(filePath);
                    fileinfoTmp = new FileInfo();
                    fileinfoTmp.setFile(files[i]);
                    fileinfoTmp.setLastModified(files[i].lastModified());
                    if (!warDirectory.exists() || fileCurrMap.get(files[i].getName()) == null
                            && filePrevMap.get(files[i].getName()) == null) {
                        if (warDirectory.exists()) {
                            deleteDir(warDirectory);
                        }
                        customClassLoader = new WebClassLoader(urls);
                        synchronized (urlClassLoaderMap) {
                            logger.info("WARDIRECTORY=" + warDirectory.getAbsolutePath());
                            urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"),
                                    customClassLoader);
                        }
                        extractWar(files[i], customClassLoader);
                        //System.out.println("War Deployed Successfully in path: "+filePath);
                        AddUrlToClassLoader(warDirectory, customClassLoader);
                        numberOfWarDeployed++;
                        logger.info(files[i] + " Deployed");
                        warsDeployed.add(files[i].getName());
                        filePrevMap.put(files[i].getName(), fileinfoTmp);
                    }
                    fileCurrMap.put(files[i].getName(), fileinfoTmp);
                }
                /*if(lastModified==null||lastModified!=files[i].lastModified()){
                   fileMap.put(files[i].getName(),files[i].lastModified());
                }*/
            }
            Set keyset = fileCurrMap.keySet();
            Iterator ite = keyset.iterator();
            String fileName;
            while (ite.hasNext()) {
                fileName = (String) ite.next();
                //logger.info("fileName"+fileName);
                filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
                fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
                if (filePrevLastModified != null)
                    //logger.info("lastmodified="+filePrevLastModified.getLastModified());
                    //System.out.println("prevmodified"+fileCurrLastModified.getLastModified()+""+filePrevLastModified.getLastModified());
                    if (fileCurrLastModified != null) {
                        //System.out.println("prevmodified"+fileCurrLastModified.getLastModified());
                    }
                if (filePrevLastModified == null
                        || filePrevLastModified.getLastModified() != fileCurrLastModified.getLastModified()) {
                    filePath = fileCurrLastModified.getFile().getAbsolutePath();
                    //logger.info("filePath"+filePath);
                    filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                    File warDirectory = new File(filePath);
                    //logger.info("WARDIRECTORY="+warDirectory.getAbsolutePath());
                    if (warDirectory.exists()) {
                        WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap
                                .get(warDirectory.getAbsolutePath().replace("\\", "/"));
                        synchronized (executorServiceMap) {
                            try {
                                new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap,
                                        new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                                + "executorservices.xml"),
                                        webClassLoader);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            //System.out.println("executorServiceMap"+executorServiceMap);
                        }
                        synchronized (messagingClassMap) {
                            try {
                                new MessagingClassConstruct().removeMessagingClass(messagedigester,
                                        new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                                + "messagingclass.xml"),
                                        messagingClassMap);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            System.out.println("executorServiceMap" + executorServiceMap);
                        }
                        ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                        try {
                            webClassLoader.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        logger.info("ServletMapping" + servletMapping);
                        logger.info("warDirectory=" + warDirectory.getAbsolutePath().replace("\\", "/"));
                        urlClassLoaderMap.remove(warDirectory.getAbsolutePath().replace("\\", "/"));
                        WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                                .remove(warDirectory.getAbsolutePath().replace("\\", "/"));
                        System.gc();
                        deleteDir(warDirectory);
                        warsDeployed.remove(fileName);
                        removeServletFromSessionObject(webAppConfig,
                                warDirectory.getAbsolutePath().replace("\\", "/"));
                        numberOfWarDeployed--;
                    }
                    customClassLoader = new WebClassLoader(urls);
                    logger.info(customClassLoader);
                    urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"), customClassLoader);
                    extractWar(fileCurrLastModified.getFile(), customClassLoader);
                    //System.out.println("War Deployed Successfully in path: "+fileCurrLastModified.getFile().getAbsolutePath());
                    AddUrlToClassLoader(warDirectory, customClassLoader);
                    numberOfWarDeployed++;
                    warsDeployed.add(fileName);
                    logger.info(filePath + ".war Deployed");
                }
            }
            keyset = filePrevMap.keySet();
            ite = keyset.iterator();
            while (ite.hasNext()) {
                fileName = (String) ite.next();
                filePrevLastModified = (FileInfo) filePrevMap.get(fileName);
                fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName);
                if (fileCurrLastModified == null) {
                    filePath = filePrevLastModified.getFile().getAbsolutePath();
                    filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
                    logger.info("filePath" + filePath);
                    File deleteDirectory = new File(filePath);
                    logger.info("Delete Directory" + deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap
                            .get(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    ;
                    synchronized (executorServiceMap) {

                        try {
                            new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap,
                                    new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                            + "executorservices.xml"),
                                    webClassLoader);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //System.out.println("executorServiceMap"+executorServiceMap);
                    }
                    synchronized (messagingClassMap) {
                        try {
                            new MessagingClassConstruct().removeMessagingClass(messagedigester,
                                    new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/"
                                            + "messagingclass.xml"),
                                    messagingClassMap);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //System.out.println("executorServiceMap"+executorServiceMap);
                    }
                    WebAppConfig webAppConfig = (WebAppConfig) servletMapping
                            .remove(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    urlClassLoaderMap.remove(deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    logger.info("ServletMapping" + servletMapping);
                    logger.info("warDirectory=" + deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    try {
                        logger.info(webClassLoader);
                        logger.info("CLASSLOADER IS CLOSED");
                        webClassLoader.close();
                    } catch (Throwable e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.gc();
                    deleteDir(deleteDirectory);
                    numberOfWarDeployed--;
                    warsDeployed.remove(fileName);
                    try {
                        removeServletFromSessionObject(webAppConfig,
                                deleteDirectory.getAbsolutePath().replace("\\", "/"));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    logger.info(filePath + ".war Undeployed");
                }
            }
            filePrevMap.keySet().removeAll(filePrevMap.keySet());
            filePrevMap.putAll(fileCurrMap);
            fileCurrMap.keySet().removeAll(fileCurrMap.keySet());
            //System.out.println("filePrevMap="+filePrevMap);
            //System.out.println("fileCurrMap="+fileCurrMap);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void removeServlets(String warDirectoryPath, String fileName) {
        WebAppConfig webAppConfig = (WebAppConfig) servletMapping.remove(warDirectoryPath);
        warsDeployed.remove(fileName);
        removeServletFromSessionObject(webAppConfig, warDirectoryPath);
        numberOfWarDeployed--;
    }

    public void removeServletFromSessionObject(WebAppConfig webAppConfig, String warDirectory) {
        Enumeration sessionKeys = sessionObjects.keys();
        while (sessionKeys.hasMoreElements()) {
            String sessionKey = (String) sessionKeys.nextElement();
            HttpSessionServer session = (HttpSessionServer) sessionObjects.get(sessionKey);
            ConcurrentHashMap servletMap = webAppConfig.getServlets();
            Enumeration servlets = servletMap.keys();
            while (servlets.hasMoreElements()) {
                String servletname = (String) servlets.nextElement();
                Servlets servletsMapping = (Servlets) servletMap.get(servletname);
                logger.info("SERVLETNAME:" + warDirectory + servletsMapping.getServletName()
                        + session.getAttribute("SERVLETNAME:" + warDirectory + servletsMapping.getServletName()));
                session.removeAttribute("SERVLETNAME:" + warDirectory + servletsMapping.getServletName());
            }
        }
    }

    /**
     * This method adds the url to the classloader.
     * @param warDirectory
     * @param classLoader
     */
    private void AddUrlToClassLoader(File warDirectory, WebClassLoader classLoader) {
        File webInfDirectory = new File(warDirectory.getAbsolutePath() + "/WEB-INF/lib/");
        //logger.info(webInfDirectory.getAbsolutePath());
        if (webInfDirectory.exists()) {
            File[] jarfiles = webInfDirectory.listFiles();
            for (int jarcount = 0; jarcount < jarfiles.length; jarcount++) {
                //logger.info(jarfiles[jarcount]);
                if (jarfiles[jarcount].getName().endsWith(".jar")) {
                    try {
                        //   //System.out.println("Adding absolute path "+jarfiles[jarcount].getAbsolutePath());
                        new WebServer().addURL(new URL("file:" + jarfiles[jarcount].getAbsolutePath()),
                                classLoader);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //To delete a war directory
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

    /**
     * This method deploys the war in exploded form and configures it. 
     * @param file
     * @param customClassLoader
     * @param warDirectoryPath
     */
    public void extractWar(File file, WebClassLoader customClassLoader) {

        StringBuffer classPath = new StringBuffer();
        int numBytes;
        try {
            ConcurrentHashMap jspMap = new ConcurrentHashMap();
            ZipFile zip = new ZipFile(file);
            ZipEntry ze = null;
            //String fileName=file.getName();
            String directoryName = file.getName();
            directoryName = directoryName.substring(0, directoryName.indexOf('.'));
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                //logger.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
                new WebServer().addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"),
                        customClassLoader);
                //new WebServer().addURL(new URL("file://"+warDirectoryPath+"/"),customClassLoader);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String fileDirectory;
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ze = entries.nextElement();
                // //System.out.println("Unzipping " + ze.getName());
                String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName();
                if (!ze.isDirectory()) {
                    fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
                } else {
                    fileDirectory = filePath;
                }
                // //System.out.println(fileDirectory);
                createDirectory(fileDirectory);
                if (!ze.isDirectory()) {
                    FileOutputStream fout = new FileOutputStream(filePath);
                    byte[] inputbyt = new byte[8192];
                    InputStream istream = zip.getInputStream(ze);
                    while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                        fout.write(inputbyt, 0, numBytes);
                    }
                    fout.close();
                    istream.close();
                    if (ze.getName().endsWith(".jsp")) {
                        jspMap.put(ze.getName(), filePath);
                    } else if (ze.getName().endsWith(".jar")) {
                        new WebServer().addURL(
                                new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()),
                                customClassLoader);
                        classPath.append(filePath);
                        classPath.append(";");
                    }
                }
            }
            zip.close();
            Set jsps = jspMap.keySet();
            Iterator jspIterator = jsps.iterator();
            classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes/;");
            ArrayList<String> jspFiles = new ArrayList();
            //System.out.println(classPath.toString());
            if (jspIterator.hasNext())
                new WebServer().addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"),
                        customClassLoader);
            while (jspIterator.hasNext()) {
                String filepackageInternal = (String) jspIterator.next();
                String filepackageInternalTmp = filepackageInternal;
                if (filepackageInternal.lastIndexOf('/') == -1) {
                    filepackageInternal = "";
                } else {
                    filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/'))
                            .replace("/", ".");
                    filepackageInternal = "." + filepackageInternal;
                }
                createDirectory(scanDirectory + "/temp/" + directoryName);
                File jspFile = new File((String) jspMap.get(filepackageInternalTmp));
                String fName = jspFile.getName();
                String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp";
                //String fileCreated=new JspCompiler().compileJsp((String) jspMap.get(filepackageInternalTmp), scanDirectory+"/temp/"+fileName, "com.web.server"+filepackageInternal,classPath.toString());
                synchronized (customClassLoader) {
                    String fileNameInWar = filepackageInternalTmp;
                    jspFiles.add(fileNameInWar.replace("/", "\\"));
                    if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                        customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                                "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                    } else {
                        customClassLoader.addURL("/" + fileNameInWar,
                                "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                    }
                }
            }
            if (jspFiles.size() > 0) {
                ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(customClassLoader);
                try {
                    JspC jspc = new JspC();
                    jspc.setUriroot(scanDirectory + "/" + directoryName + "/");
                    jspc.setAddWebXmlMappings(false);
                    jspc.setCompile(true);
                    jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                    jspc.setPackage("com.web.server");
                    StringBuffer buffer = new StringBuffer();
                    for (String jspFile : jspFiles) {
                        buffer.append(",");
                        buffer.append(jspFile);
                    }
                    String jsp = buffer.toString();
                    jsp = jsp.substring(1, jsp.length());
                    System.out.println(jsp);
                    jspc.setJspFiles(jsp);
                    jspc.execute();
                } catch (Throwable je) {
                    je.printStackTrace();
                } finally {
                    Thread.currentThread().setContextClassLoader(oldCL);
                }
                Thread.currentThread().setContextClassLoader(customClassLoader);
            }
            try {
                new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap,
                        new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"),
                        customClassLoader);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
            try {
                new MessagingClassConstruct().getMessagingClass(messagedigester,
                        new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"),
                        customClassLoader, messagingClassMap);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
            webxmldigester.setNamespaceAware(true);
            webxmldigester.setValidating(true);
            //digester.setRules(null);
            FileInputStream webxml = new FileInputStream(
                    scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml");
            InputSource is = new InputSource(webxml);
            try {
                System.out.println("SCHEMA");
                synchronized (webxmldigester) {
                    //webxmldigester.set("config/web-app_2_4.xsd");
                    WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is);
                    servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig);
                }
                webxml.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //ClassLoaderUtil.closeClassLoader(customClassLoader);

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

        }
    }

    /**
     * This method creates the directory for SAR
     * @param dir
     */
    public static void createDirectory(String dir) {
        String[] dirs = dir.split("/");
        String tmpDirPath = dirs[0];
        for (int i = 1; i < dirs.length; i++) {
            tmpDirPath += "/" + dirs[i];
            File file = new File(tmpDirPath);
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        /*WarDeployer warDeployer=new WarDeployer("D:/WebServer/Deploy",new HashMap(),new HashMap());
            
        warDeployer.start();
        try {
           warDeployer.join();
        } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/
    }

    /**
     * This method returns the number of war deployed 
     */
    @Override
    public int getNumberOfWarDeployed() {
        // TODO Auto-generated method stub
        return numberOfWarDeployed;
    }

    /**
     * This method returns the war file names that is deployed
     */
    @Override
    public String[] getWarNames() {
        // TODO Auto-generated method stub
        warDeployed = (String[]) warsDeployed.toArray(new String[warsDeployed.size()]);
        return warDeployed;
    }

    /**
     * This method redeploys the war file again.
     */
    @Override
    public void setRedeployTarget(String warName) {
        System.out.println("RedeployTarget=" + warName);
        System.out.println(scanDirectory + "/" + warName);
        if (warName != null && !warName.trim().equals("")) {
            File warDirectory = new File(scanDirectory + "/" + warName);
            if (warDirectory.isDirectory() && warDirectory.exists()) {
                deleteDir(warDirectory);
                numberOfWarDeployed--;
            }
        }
    }
}