com.web.server.EARDeployer.java Source code

Java tutorial

Introduction

Here is the source code for com.web.server.EARDeployer.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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.rmi.Remote;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.FileUtil;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.cache.LRUFilesCache;
import org.apache.commons.vfs2.cache.SoftRefFilesCache;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
import org.apache.commons.vfs2.impl.DefaultFileReplicator;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.impl.PrivilegedFileReplicator;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.impl.VFSClassLoader;
import org.apache.commons.vfs2.provider.TemporaryFileStore;
import org.apache.commons.vfs2.provider.jar.JarFileProvider;
import org.apache.log4j.Logger;

import com.web.messaging.MessagingElem;
import com.web.server.util.ClassLoaderUtil;
import com.web.server.util.DirectoryFilterWatcher;
import com.web.services.ExecutorServiceAnnot;
import com.web.services.ExecutorServiceInfo;

public class EARDeployer extends Thread implements Runnable, EARDeployerMBean {
    String scanDirectory;
    String deployDirectory;
    Hashtable executorServiceMap;
    Hashtable urlClassLoaderMap;
    String cacheDir;
    CopyOnWriteArrayList<String> earsDeployed = new CopyOnWriteArrayList();
    Registry registry;

    EARFileListener earFileListener = null;

    Logger log = Logger.getLogger(EARDeployer.class);

    int numberOfEarsDeployed = 0;

    WarDeployer warDeployer;
    ScheduledExecutorService exec;
    EARFileListener task = null;
    Hashtable filesMap = new Hashtable();

    public EARDeployer(Registry registry, String scanDirectory, String deployDirectory,
            Hashtable executorServiceMap, Hashtable urlClassLoaderMap, String cacheDir, WarDeployer warDeployer) {
        this.scanDirectory = scanDirectory.replace("\\", "/");
        this.deployDirectory = deployDirectory.replace("\\", "/");
        this.executorServiceMap = executorServiceMap;
        this.urlClassLoaderMap = urlClassLoaderMap;
        this.cacheDir = cacheDir;
        this.registry = registry;
        this.warDeployer = warDeployer;
    }

    public void run() {
        StandardFileSystemManager fsManager = null;
        fsManager = new StandardFileSystemManager();
        try {
            System.setProperty("java.io.tmpdir", this.cacheDir);
            /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
            //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
            fsManager.setTemporaryFileStore(replicator);*/
            fsManager.init();
        } catch (FileSystemException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }
        // fsManager.addProvider("file", new JarFileProvider());
        File file = new File(scanDirectory);
        File[] files = file.listFiles();
        CopyOnWriteArrayList<String> classList;
        ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
        task = new EARFileListener(executorServiceMap, urlClassLoaderMap, earsDeployed);
        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(".ear")) {
                String filePath = files[i].getAbsolutePath();
                com.web.server.util.FileUtil util = new com.web.server.util.FileUtil();
                FileObject earFile = null;
                try {
                    System.out.println("Before resolve file");
                    System.out.println("jar:file:///" + filePath);
                    earFile = fsManager.resolveFile("jar:file:///" + scanDirectory + "/" + files[i].getName());
                    System.out.println("After resolve file");
                } catch (FileSystemException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    deleteExecutorServicesEar(files[i].getName(), fsManager);
                    deployExecutorServicesEar(files[i].getName(), earFile, fsManager);
                    numberOfEarsDeployed++;
                    log.info("deployed Ear:" + files[i].getName());
                } catch (Exception ex) {
                    // TODO Auto-generated catch block
                    log.info("Could not deploy Ear:" + file.getName(), ex);
                    //e.printStackTrace();
                }
                // logger.info("filePath"+filePath);
                /*filePath = filePath.substring(0, filePath.toLowerCase()
                      .lastIndexOf(".ear"));
                VFSClassLoader customClassLoader = null;
                try {
                   CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
                   System.out.println("EARFILE:/   \n\n\n\n\n\n\n\n\n\n"
                 + earFile);
                   obtainUrls(earFile, earFile, fileObjects, jarClassListMap,
                 fsManager);
                   System.out.println(fileObjects);
                   System.out.println(jarClassListMap);
                   VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
                 fileObjects.toArray(new FileObject[fileObjects
                       .size()]), fsManager, Thread
                       .currentThread().getContextClassLoader());
                   // customClassLoader.loadClass(classList.get(0).toString());
                    
                   Set keys = jarClassListMap.keySet();
                   Iterator key = keys.iterator();
                   for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
                      FileObject jarFileObject = (FileObject) key.next();
                      classList = (CopyOnWriteArrayList<String>) jarClassListMap
                    .get(jarFileObject);
                      for (int classCount = 0; classCount < classList.size(); classCount++) {
                 String classwithpackage = classList.get(classCount)
                       .substring(
                             0,
                             classList.get(classCount).indexOf(
                                   ".class"));
                 classwithpackage = classwithpackage.replace("/",
                       ".");
                 System.out.println("classList:"
                       + classwithpackage.replace("/", "."));
                 try {
                    if (!classwithpackage.contains("$")) {
                       customClassLoader = new VFSClassLoader(
                             jarFileObject, fsManager,
                             customClassLoaderBaseLib);
                       this.urlClassLoaderMap.put(scanDirectory
                             + "/"
                             + files[i].getName()
                             + "/"
                             + jarFileObject.getName()
                                   .getBaseName(),
                             customClassLoader);
                       Class executorServiceClass = customClassLoader
                             .loadClass(classwithpackage);
                       System.out.println(executorServiceClass
                             .newInstance());
                       // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                       // System.out.println();
                       Method[] methods = executorServiceClass
                             .getMethods();
                       for (Method method : methods) {
                          Annotation[] annotations = method
                                .getDeclaredAnnotations();
                          for (Annotation annotation : annotations) {
                             if (annotation instanceof ExecutorServiceAnnot) {
                                ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                                ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                                executorServiceInfo
                                      .setExecutorServicesClass(executorServiceClass);
                                executorServiceInfo
                                      .setMethod(method);
                                executorServiceInfo
                                      .setMethodParams(method
                                            .getParameterTypes());
                                // System.out.println("method="+executorServiceAnnot.servicename());
                                // System.out.println("method info="+executorServiceInfo);
                                // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                                // new Exception();
                                executorServiceMap.put(
                                      executorServiceAnnot
                                            .servicename(),
                                      executorServiceInfo);
                             }
                          }
                       }
                    
                    }
                 } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 } catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 }
                      }
                      jarFileObject.close();
                   }
                   for (FileObject fobject : fileObjects) {
                      fobject.close();
                   }
                } catch (FileSystemException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                }
                try {
                   earFile.close();
                   fsManager.closeFileSystem(earFile.getFileSystem());
                } catch (FileSystemException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                }*/
            }
        }
        //fsManager.close();
        if (exec == null) {
            exec = Executors.newSingleThreadScheduledExecutor();
            exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
        }
    }

    /**
     * This method configures the executor services from the jar file.
     * 
     * @param jarFile
     * @param classList
     * @throws FileSystemException
     */
    public void deployExecutorServicesEar(String earFileName, FileObject earFile,
            StandardFileSystemManager fsManager) throws FileSystemException {
        try {
            System.out.println("EARFILE NAMEs=" + earFileName);
            CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
            CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>();
            ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
            CopyOnWriteArrayList<String> classList;
            obtainUrls(earFile, earFile, fileObjects, jarClassListMap, warObjects, fsManager);
            VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
                    fileObjects.toArray(new FileObject[fileObjects.size()]), fsManager,
                    Thread.currentThread().getContextClassLoader());
            VFSClassLoader customClassLoader = null;
            Set keys = jarClassListMap.keySet();
            Iterator key = keys.iterator();
            FileObject jarFileObject;
            ConcurrentHashMap classLoaderPath = new ConcurrentHashMap();
            filesMap.put(earFileName, classLoaderPath);
            for (FileObject warFileObj : warObjects) {
                if (warFileObj.getName().getBaseName().endsWith(".war")) {
                    //logger.info("filePath"+filePath);
                    String filePath = scanDirectory + "/" + warFileObj.getName().getBaseName();
                    log.info(filePath);
                    String fileName = warFileObj.getName().getBaseName();
                    WebClassLoader classLoader = new WebClassLoader(new URL[] {});
                    log.info(classLoader);
                    warDeployer.deleteDir(
                            new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))));
                    new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs();
                    log.info(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                    urlClassLoaderMap.put(
                            deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")),
                            classLoader);
                    classLoaderPath.put(warFileObj.getName().getBaseName(),
                            deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                    warDeployer.extractWar(new File(filePath), classLoader);

                    if (exec != null) {
                        exec.shutdown();
                    }
                    new File(scanDirectory + "/" + warFileObj.getName().getBaseName()).delete();
                    exec = Executors.newSingleThreadScheduledExecutor();
                    exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
                }
            }
            for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
                jarFileObject = (FileObject) key.next();
                {
                    classList = (CopyOnWriteArrayList<String>) jarClassListMap.get(jarFileObject);
                    customClassLoader = new VFSClassLoader(jarFileObject, fsManager, customClassLoaderBaseLib);
                    this.urlClassLoaderMap.put(
                            scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName(),
                            customClassLoader);
                    classLoaderPath.put(jarFileObject.getName().getBaseName(),
                            scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName());
                    for (int classCount = 0; classCount < classList.size(); classCount++) {
                        String classwithpackage = classList.get(classCount).substring(0,
                                classList.get(classCount).indexOf(".class"));
                        classwithpackage = classwithpackage.replace("/", ".");
                        // System.out.println("classList:"+classwithpackage.replace("/","."));
                        try {
                            if (!classwithpackage.contains("$")) {

                                /*System.out.println("EARFILE NAME="+fileName);
                                System.out
                                      .println(scanDirectory
                                + "/"
                                + fileName
                                + "/"
                                + jarFileObject.getName()
                                      .getBaseName());
                                    
                                System.out.println(urlClassLoaderMap);*/
                                Class executorServiceClass = customClassLoader.loadClass(classwithpackage);

                                Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations();

                                if (classServicesAnnot != null) {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof RemoteCall) {
                                            RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount];
                                            //registry.unbind(remoteCall.servicename());
                                            System.out.println(remoteCall.servicename().trim());
                                            try {
                                                for (int count = 0; count < 2; count++) {
                                                    RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                            .exportObject(
                                                                    (Remote) executorServiceClass.newInstance(), 0);
                                                    registry.rebind(remoteCall.servicename().trim(), reminterface);
                                                }
                                            } catch (Exception ex) {
                                                ex.printStackTrace();
                                            }
                                        }
                                    }
                                }
                                // System.out.println(executorServiceClass.newInstance());
                                // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                // System.out.println();
                                Method[] methods = executorServiceClass.getDeclaredMethods();
                                for (Method method : methods) {
                                    Annotation[] annotations = method.getDeclaredAnnotations();
                                    for (Annotation annotation : annotations) {
                                        if (annotation instanceof ExecutorServiceAnnot) {
                                            ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                                            ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                                            executorServiceInfo.setExecutorServicesClass(executorServiceClass);
                                            executorServiceInfo.setMethod(method);
                                            executorServiceInfo.setMethodParams(method.getParameterTypes());
                                            //                              System.out.println("serice name="
                                            //                                    + executorServiceAnnot
                                            //                                          .servicename());
                                            //                              System.out.println("method info="
                                            //                                    + executorServiceInfo);
                                            //                              System.out.println(method);
                                            // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                                            // new Exception();
                                            executorServiceMap.put(executorServiceAnnot.servicename(),
                                                    executorServiceInfo);
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                jarFileObject.close();
            }
            for (FileObject fobject : fileObjects) {
                fobject.close();
            }
            System.out.println("Channel unlocked");
            earFile.close();
            fsManager.closeFileSystem(earFile.getFileSystem());
            // ClassLoaderUtil.closeClassLoader(customClassLoader);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method removes the executor services from the executor services
     * map.
     * 
     * @param jarFile
     * @param classList
     * @throws FileSystemException
     */
    public void deleteExecutorServicesEar(String fileName, StandardFileSystemManager fsManager)
            throws FileSystemException {
        try {
            synchronized (urlClassLoaderMap) {
                ConcurrentHashMap map = (ConcurrentHashMap) filesMap.get(fileName);
                if (map != null) {
                    //log.info("ClassLoader Map=\n\n\n\n"+urlClassLoaderMap);
                    Set keysinclassloadermap = map.keySet();
                    System.out.println(keysinclassloadermap.size());
                    Iterator classloaders = keysinclassloadermap.iterator();
                    while (classloaders.hasNext()) {
                        String classloader = (String) classloaders.next();
                        System.out.println("ClassLoader=" + classloader);
                        ClassLoader webClassLoader = (ClassLoader) this.urlClassLoaderMap.get(map.get(classloader));
                        this.urlClassLoaderMap.remove(map.get(classloader));
                        ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                        urlClassLoaderMap.remove(map.get(classloader));
                        try {
                            if (webClassLoader instanceof WebClassLoader)
                                ((WebClassLoader) webClassLoader).close();
                            else if (webClassLoader instanceof VFSClassLoader) {
                                FileObject[] fObj = ((VFSClassLoader) webClassLoader).getFileObjects();
                                for (FileObject obj : fObj) {
                                    obj.close();
                                }
                            }
                        } catch (Throwable e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        /*if (classloader.contains(deployDirectory +"/"+ fileName)) {
                           System.out.println("removing classloader" + deployDirectory
                          + classloader);
                              File warDir=new File(fileName);
                              if(warDir.exists()){                                    
                          warDeployer.deleteDir(warDir);
                              }
                              //System.out.println("Before Remove class loader\n\n\n\n"+this.urlClassLoaderMap);                           
                              //System.out.println("Remove class loader\n\n\n\n"+this.urlClassLoaderMap);
                        }*/
                    }
                    System.gc();
                    classloaders = keysinclassloadermap.iterator();
                    while (classloaders.hasNext()) {
                        String classloader = (String) classloaders.next();
                        if (classloader.endsWith(".war")) {
                            warDeployer.removeServlets((String) map.get(classloader), classloader);
                            File warDir = new File((String) map.get(classloader));
                            if (warDir.exists()) {
                                warDeployer.deleteDir(warDir);
                            }
                        }
                    }
                    log.info(this.urlClassLoaderMap);
                }
                filesMap.remove(fileName);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private class EARFileListener extends com.web.server.util.DirectoryWatcher implements Cloneable {

        Hashtable executorServiceMap, urlClassLoaderMap;
        CopyOnWriteArrayList earsDeployed;

        public EARFileListener(Hashtable executorServiceMap, Hashtable urlClassLoaderMap,
                CopyOnWriteArrayList earsDeployed) {
            super(scanDirectory, "");
            this.executorServiceMap = executorServiceMap;
            this.urlClassLoaderMap = urlClassLoaderMap;
            this.earsDeployed = earsDeployed;
        }

        public EARFileListener clone() throws CloneNotSupportedException {
            return (EARFileListener) super.clone();
        }

        /**
         * This method is the implementation of jar file has been modified in
         * the jar deploy directory
         * 
         * @param arg0
         */
        public void onModify(File file) {
            StandardFileSystemManager fsManager = null;
            try {
                CopyOnWriteArrayList classList = new CopyOnWriteArrayList();
                if (file.getName().endsWith(".ear")) {
                    // getJarContent(baseFile.getName().getURI().replace("file:///",
                    // ""),classList);
                    System.out.println("Modify EarDeployer deployed:" + file.getName());
                    // System.out.println("EarDeployer:"+urlClassLoaderMap);
                    // System.out.println("EarDeployer:"+executorServiceMap);
                    //
                    /*
                     * WarDeployer.createDirectory(deployDirectory); try { new
                     * com.web.server.util.FileUtil().copy(file,new
                     * File(deployDirectory)); } catch (IOException e2) { //
                     * TODO Auto-generated catch block e2.printStackTrace(); }
                     */
                    fsManager = new StandardFileSystemManager();
                    /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
                    //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
                    fsManager.setTemporaryFileStore(replicator);*/
                    fsManager.init();
                    FileObject earFile = fsManager
                            .resolveFile("jar:file:///" + scanDirectory + "/" + file.getName());
                    System.out.println(earFile.getChildren().length);
                    deleteExecutorServicesEar(file.getName(), fsManager);
                    deployExecutorServicesEar(file.getName(), earFile, fsManager);
                    numberOfEarsDeployed++;
                    log.info("deployed Ear:" + file.getName());
                }
            } catch (Exception ex) {
                //log.info("Could not deploy Ear:"+file.getName());
                log.info("Could not deploy Ear:" + file.getName(), ex);
            } finally {
                /*try {
                   if (fsManager != null) {
                      fsManager.close();
                   }
                } catch (Exception ex) {
                    
                }*/
            }
        }

        /**
         * This method is the implementation of jar file has been put in the jar
         * deploy directory
         * 
         * @param arg0
         */
        public void onAdd(File file) {
            StandardFileSystemManager fsManager = null;
            try {
                CopyOnWriteArrayList classList = new CopyOnWriteArrayList();
                if (file.getName().endsWith(".ear")) {
                    // getJarContent(baseFile.getName().getURI().replace("file:///",
                    // ""),classList);
                    System.out.println("Modify EarDeployer deployed:" + file.getName());
                    // System.out.println("EarDeployer:"+urlClassLoaderMap);
                    // System.out.println("EarDeployer:"+executorServiceMap);
                    //
                    /*
                     * WarDeployer.createDirectory(deployDirectory); try { new
                     * com.web.server.util.FileUtil().copy(file,new
                     * File(deployDirectory)); } catch (IOException e2) { //
                     * TODO Auto-generated catch block e2.printStackTrace(); }
                     */
                    fsManager = new StandardFileSystemManager();
                    /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
                    //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
                    fsManager.setTemporaryFileStore(replicator);*/
                    fsManager.init();
                    FileObject earFile = fsManager
                            .resolveFile("jar:file:///" + scanDirectory + "/" + file.getName());
                    System.out.println(earFile.getChildren().length);
                    deleteExecutorServicesEar(file.getName(), fsManager);
                    deployExecutorServicesEar(file.getName(), earFile, fsManager);
                    numberOfEarsDeployed++;
                    log.info("deployed Ear:" + file.getName());
                }
            } catch (Exception ex) {
                log.info("Could not deploy Ear:" + file.getName(), ex);
            } finally {
                /*try {
                   if (fsManager != null) {
                      fsManager.close();
                   }
                } catch (Exception ex) {
                    
                }*/
            }
        }

        /**
         * This method is the implementation of jar file has been deleted in the
         * jar deploy directory
         * 
         * @param arg0
         */
        public void onDelete(File file) {
            StandardFileSystemManager fsManager = null;
            try {
                CopyOnWriteArrayList classList = new CopyOnWriteArrayList();
                if (file.getName().endsWith(".ear")) {
                    System.out.println("Deleted: " + file.getName());
                    fsManager = new StandardFileSystemManager();
                    /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
                    //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
                    fsManager.setTemporaryFileStore(replicator);*/
                    fsManager.init();
                    // FileObject earFile =
                    // fsManager.resolveFile("jar:file:///"+scanDirectory+"/"+file.getName());
                    // fileMonitor.stop();
                    deleteExecutorServicesEar(file.getName(), fsManager);
                    this.earsDeployed.remove(file.getAbsolutePath());
                    numberOfEarsDeployed--;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                /*try {
                   if (fsManager != null) {
                      fsManager.close();
                   }
                } catch (Exception ex) {
                    
                }*/
            }
        }

    }

    public void obtainUrls(FileObject rootEar, FileObject ear, CopyOnWriteArrayList<FileObject> fileObjects,
            ConcurrentHashMap jarclassListMap, CopyOnWriteArrayList<FileObject> warObjects,
            StandardFileSystemManager fsManager) throws IOException {
        FileObject[] childrenJars = ear.getChildren();
        for (int childcount = 0; childcount < childrenJars.length; childcount++) {
            if (childrenJars[childcount].getType() == FileType.FOLDER) {
                obtainUrls(rootEar, childrenJars[childcount], fileObjects, jarclassListMap, warObjects, fsManager);
            }
            // System.out.println(childrenJars[childcount]);
            // System.out.println(childrenJars[childcount].getName().getBaseName());
            // System.out.println(ear.getURL());
            if (childrenJars[childcount].getType() == FileType.FILE
                    && (childrenJars[childcount].getName().getBaseName().endsWith(".jar")
                            || childrenJars[childcount].getName().getBaseName().endsWith(".war"))) {
                // System.out.println(childrenJars[childcount].getURL());
                if (childrenJars[childcount].getName().getBaseName().endsWith(".war")) {
                    File file = new File(scanDirectory + "/" + childrenJars[childcount].getName().getBaseName());
                    if (!file.exists() || (file.exists() && file.lastModified() != childrenJars[childcount]
                            .getContent().getLastModifiedTime())) {
                        InputStream fistr = childrenJars[childcount].getContent().getInputStream();
                        byte[] filyByt = new byte[4096];
                        FileOutputStream warFile = new FileOutputStream(
                                scanDirectory + "/" + childrenJars[childcount].getName().getBaseName());
                        int len = 0;
                        while ((len = fistr.read(filyByt)) != -1) {
                            warFile.write(filyByt, 0, len);
                        }
                        warFile.close();
                        fistr.close();
                        warObjects.add(childrenJars[childcount]);
                    }
                }
                // System.out.println(childrenJars[childcount].getURL().toString()+" "+rootEar.getURL());
                else if (!childrenJars[childcount].getURL().toString().trim()
                        .startsWith(rootEar.getURL().toString() + "lib/")) {
                    CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>();
                    getClassList(childrenJars[childcount], classList, fsManager);
                    jarclassListMap.put(childrenJars[childcount], classList);
                } else {
                    System.out.println("ear libs/" + childrenJars[childcount]);
                    fileObjects.add(childrenJars[childcount]);
                }
            } else {
                childrenJars[childcount].close();
            }
        }
    }

    public static void getClassList(FileObject jarFile, CopyOnWriteArrayList classList,
            StandardFileSystemManager fsManager) throws FileSystemException {
        // System.out.println(jarFile);
        FileObject nestedFS = null;
        FileObject[] children = null;
        if (jarFile.getURL().toString().trim().endsWith(".jar")) {
            nestedFS = fsManager.createFileSystem(jarFile);
            children = nestedFS.resolveFile("/").getChildren();
        } else if (jarFile.getType() == FileType.FOLDER) {
            children = jarFile.getChildren();
        }
        // System.out.println();
        // System.out.println( "Children of " + jarFile.getName().getURI() );
        if (children == null)
            return;
        for (int i = 0; i < children.length; i++) {
            // System.out.println(children[i].+" "+
            // children[i].getName().getBaseName() );
            if (children[i].getType() == FileType.FILE && children[i].getName().getBaseName().endsWith(".class"))
                classList.add(children[i].toString().substring(children[i].toString().lastIndexOf('!') + 2));
            getClassList(children[i], classList, fsManager);
        }
    }

    public static void main(String[] args) {
        // EARDeployer eardeplo=new EARDeployer("D:/test",new HashMap(),new
        // HashMap());
        // eardeplo.start();

    }

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