Example usage for org.apache.commons.vfs2.impl StandardFileSystemManager resolveFile

List of usage examples for org.apache.commons.vfs2.impl StandardFileSystemManager resolveFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs2.impl StandardFileSystemManager resolveFile.

Prototype

@Override
public FileObject resolveFile(final String uri) throws FileSystemException 

Source Link

Document

Locates a file by URI.

Usage

From source file:com.app.server.SARDeployer.java

public CopyOnWriteArrayList<String> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager) throws IOException {
    outputDir.mkdirs();//from   w w w . jav  a2 s .co m
    URLClassLoader webClassLoader;
    CopyOnWriteArrayList<String> classPath = new CopyOnWriteArrayList<String>();
    final FileObject packFileObject = fileSystemManager
            .resolveFile("jar:" + unpackFileObject.toString() + "!/");
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] libs = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        /*String replaceString="file:///"+outputDir.getAbsolutePath().replace("\\","/");
        replaceString=replaceString.endsWith("/")?replaceString:replaceString+"/";*/
        // System.out.println(replaceString);
        for (FileObject lib : libs) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            classPath.add(lib.getName().getFriendlyURI());
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return classPath;
}

From source file:com.app.server.WarDeployer.java

public Vector<URL> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager, ConcurrentHashMap<String, String> jsps)
        throws IOException {
    outputDir.mkdirs();//from  w  w w.j  ava2  s .  co m
    URLClassLoader webClassLoader;
    Vector<URL> libraries = new Vector<URL>();
    final FileObject packFileObject = fileSystemManager.resolveFile(unpackFileObject.toString());
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] jspFiles = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jsp")
                        || arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        String replaceString = "file:///" + outputDir.getAbsolutePath().replace("\\", "/");
        replaceString = replaceString.endsWith("/") ? replaceString : replaceString + "/";
        // System.out.println(replaceString);
        for (FileObject jsplibs : jspFiles) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            if (jsplibs.getName().getBaseName().endsWith(".jar")) {
                libraries.add(new URL(jsplibs.getName().getFriendlyURI()));
            } else {
                String relJspName = jsplibs.getName().getFriendlyURI().replace(replaceString, "");
                jsps.put(relJspName, relJspName);
            }
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return libraries;
}

From source file:com.app.server.WarDeployer.java

public void extractWar(FileObject fileObject, WebClassLoader customClassLoader,
        StandardFileSystemManager fsManager) {

    int numBytes;
    try {/* w ww  .  ja v  a  2  s.c  o  m*/
        String directoryName = fileObject.getName().getBaseName();
        fileObject = fsManager.resolveFile("jar:" + fileObject.toString() + "!/");
        StringBuffer classPath = new StringBuffer();
        ConcurrentHashMap<String, String> jspMap = new ConcurrentHashMap<String, String>();
        ArrayList<String> libs = new ArrayList<String>();

        // String fileName=file.getName();

        directoryName = directoryName.substring(0, directoryName.indexOf('.'));

        /*try {
           ((VFSClassLoader)customClassLoader.getParent()).
                   
           // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
           customClassLoader.addURL(new URL("file:" + scanDirectory + "/"
          + directoryName + "/WEB-INF/classes/")
          );
           // new WebServer().addURL(new
           // URL("file://"+warDirectoryPath+"/"),customClassLoader);
        } catch (Exception e) {
           log.error("syntax of the URL is incorrect", e);
           //e1.printStackTrace();
        }*/
        Vector<URL> libVec = unpack(fileObject, new File(scanDirectory + "/" + directoryName), fsManager,
                jspMap);
        //FileObject[] libraries=((VFSClassLoader)customClassLoader.getParent()).getFileObjects();
        libVec.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"));
        //URL[] liburl=new URL[libraries.length];
        for (URL lib : libVec) {
            customClassLoader.addURL(lib);
        }
        //WebClassLoader web=new WebClassLoader(libVec.toArray(new URL[libVec.size()]),getClass().getClassLoader());
        System.out.println(jspMap);
        System.out.println(libs);
        /*customClassLoader.addURL(new URL("file:" + scanDirectory + "/"
              + directoryName + "/WEB-INF/classes/")
              );*/
        /*String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
           ze = entries.nextElement();
           // //log.info("Unzipping " + ze.getName());
           String filePath = scanDirectory + "/" + directoryName + "/"
          + ze.getName();
           if (!ze.isDirectory()) {
              fileDirectory = filePath.substring(0,
             filePath.lastIndexOf('/'));
           } else {
              fileDirectory = filePath;
           }
           // //log.info(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")) {
          customClassLoader.addURL(new URL("file:///"
                + scanDirectory + "/" + directoryName + "/"
                + ze.getName()));
          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();
        // log.info(classPath.toString());
        if (jspIterator.hasNext()) {

            /*customClassLoader=new WebClassLoader(new URL[]{new URL("file:" + scanDirectory
                  + "/temp/" + directoryName + "/")},customClassLoader);*/
            customClassLoader.addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"));
            urlClassLoaderMap.put(serverConfig.getDeploydirectory() + "/" + directoryName, customClassLoader);
        } else {
            urlClassLoaderMap.put(serverConfig.getDeploydirectory() + "/" + 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.app.server"+filepackageInternal,classPath.toString());
            synchronized (customClassLoader) {
                String fileNameInWar = filepackageInternalTmp;
                jspFiles.add(fileNameInWar.replace("/", "\\"));
                if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                    customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                            "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                    + fileNameWithoutExtension);
                } else {
                    customClassLoader.addURL("/" + fileNameInWar,
                            "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                    + fileNameWithoutExtension);
                }
            }
        }
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            //Thread.currentThread().setContextClassLoader(customClassLoader);
            JspCompiler jspc = null;
            try {
                jspc = new JspCompiler();
                jspc.setUriroot(scanDirectory + "/" + directoryName);
                jspc.setAddWebXmlMappings(false);
                jspc.setCompile(true);
                //jspc.setClassPath("d:/deploy/StrutsProj/WEB-INF/classes/");
                jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                jspc.setPackage("com.app.server");
                StringBuffer buffer = new StringBuffer();
                for (String jspFile : jspFiles) {
                    buffer.append(",");
                    buffer.append(jspFile);
                }
                String jsp = buffer.toString();
                jsp = jsp.substring(1, jsp.length());
                //log.info(jsp);
                jspc.setJspFiles(jsp);
                //jspc.init();
                jspc.initCL(customClassLoader);
                jspc.execute();
                //jspc.closeClassLoader();
            } catch (Throwable je) {
                log.error("Error in compiling the jsp page", je);
                //je.printStackTrace();
            } finally {
                //jspc.closeClassLoader();
                //Thread.currentThread().setContextClassLoader(oldCL);
            }
            //Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        //System.out.println(customClassLoader.loadClass("org.apache.struts.action.ActionForm"));
        try {
            File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml");
            if (execxml.exists()) {
                new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml,
                        customClassLoader);
            }
        } catch (Exception e) {
            log.error("error in getting executor services ", e);
            // e.printStackTrace();
        }
        try {
            File messagingxml = new File(
                    scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml");
            if (messagingxml.exists()) {
                new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml,
                        customClassLoader, messagingClassMap);
            }
        } catch (Exception e) {
            log.error("Error in getting the messaging classes ", e);
            // 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 {
            //log.info("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) {
            log.error("Error in pasrsing the web.xml", e);
            //e.printStackTrace();
        }
        // ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (Exception ex) {
        log.error("Error in Deploying war " + fileObject.getName().getURI(), ex);
    }
}

From source file:hpmonitoringaudit.sftp.java

public boolean startFTP(String propertiesFilename, String fileToDownload) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {//from  w  ww .j  a  v a2 s.  c o  m

        props.load(new FileInputStream("properties/" + propertiesFilename));
        String serverAddress = props.getProperty("serverAddress").trim();
        String userId = props.getProperty("userId").trim();
        String password = props.getProperty("password").trim();
        String remoteDirectory = props.getProperty("remoteDirectory").trim();
        String localDirectory = props.getProperty("localDirectory").trim();

        //Initializes the file manager
        manager.init();

        //Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        //Create the SFTP URI using the host name, userid, password,  remote path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory
                + fileToDownload;

        // Create local file object
        String filepath = localDirectory + fileToDownload;
        File file = new File(filepath);
        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
        System.out.println("File download successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}

From source file:com.app.server.JarDeployer.java

/**
 * This method implements the jar deployer which configures the executor services. 
 * Frequently monitors the deploy directory and configures the executor services map 
 * once the jar is deployed in deploy directory and reconfigures if the jar is modified and 
 * placed in the deploy directory.//from w  ww. j av  a  2s .c o m
 */
public void run() {

    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    try {
        fsManager.init();
        DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);
    } catch (FileSystemException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    File file = new File(scanDirectory.split(";")[0]);
    File[] files = file.listFiles();
    CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>();
    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(".jar")) {
            String filePath = files[i].getAbsolutePath();
            FileObject jarFile = null;
            try {
                jarFile = fsManager.resolveFile("jar:" + filePath);
            } catch (FileSystemException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            //logger.info("filePath"+filePath);
            filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar"));
            WebClassLoader customClassLoader = null;
            try {
                URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                URL[] urls = loader.getURLs();
                try {
                    customClassLoader = new WebClassLoader(urls);
                    log.info(customClassLoader.geturlS());
                    customClassLoader.addURL(new URL("file:/" + files[i].getAbsolutePath()));
                    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
                    getUsersJars(new File(libDir), jarList);
                    for (String jarFilePath : jarList)
                        customClassLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
                    log.info("deploy=" + customClassLoader.geturlS());
                    this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader);
                    jarsDeployed.add(files[i].getName());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                log.info(urlClassLoaderMap);
                getChildren(jarFile, classList);
            } catch (FileSystemException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            for (int classCount = 0; classCount < classList.size(); classCount++) {
                String classwithpackage = classList.get(classCount).substring(0,
                        classList.get(classCount).indexOf(".class"));
                classwithpackage = classwithpackage.replace("/", ".");
                log.info("classList:" + classwithpackage.replace("/", "."));
                try {
                    if (!classwithpackage.contains("$")) {
                        Class executorServiceClass = customClassLoader.loadClass(classwithpackage);
                        //log.info("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        //log.info();
                        if (!executorServiceClass.isInterface()) {
                            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());
                                        log.info(remoteCall.servicename().trim());
                                        try {
                                            //for(int count=0;count<500;count++){
                                            RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                    .exportObject((Remote) executorServiceClass.newInstance(),
                                                            2004);
                                            registry.rebind(remoteCall.servicename().trim(), reminterface);
                                            //}
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }

                        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());
                                    //log.info("method="+executorServiceAnnot.servicename());
                                    //log.info("method info="+executorServiceInfo);
                                    //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception();
                                    executorServiceMap.put(executorServiceAnnot.servicename(),
                                            executorServiceInfo);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            ClassLoaderUtil.closeClassLoader(customClassLoader);
            try {
                jarFile.close();
            } catch (FileSystemException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            fsManager.closeFileSystem(jarFile.getFileSystem());
        }
    }
    fsManager.close();
    fsManager = new StandardFileSystemManager();
    try {
        DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);
    } catch (FileSystemException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap,
            jarsDeployed);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    jarFileListener.setFm(fm);
    FileObject listendir = null;
    String[] dirsToScan = scanDirectory.split(";");
    try {
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (FileSystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(3000);
    fm.start();
    //fsManager.close();
}

From source file:com.web.server.JarDeployer.java

/**
 * This method implements the jar deployer which configures the executor services. 
 * Frequently monitors the deploy directory and configures the executor services map 
 * once the jar is deployed in deploy directory and reconfigures if the jar is modified and 
 * placed in the deploy directory./*from w w w . j av  a  2 s . c om*/
 */
public void run() {

    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    try {
        fsManager.init();
        DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);
    } catch (FileSystemException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    File file = new File(scanDirectory.split(";")[0]);
    File[] files = file.listFiles();
    CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>();
    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(".jar")) {
            String filePath = files[i].getAbsolutePath();
            FileObject jarFile = null;
            try {
                jarFile = fsManager.resolveFile("jar:" + filePath);
            } catch (FileSystemException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            //logger.info("filePath"+filePath);
            filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar"));
            WebClassLoader customClassLoader = null;
            try {
                URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                URL[] urls = loader.getURLs();
                try {
                    customClassLoader = new WebClassLoader(urls);
                    System.out.println(customClassLoader.geturlS());
                    new WebServer().addURL(new URL("file:/" + files[i].getAbsolutePath()), customClassLoader);
                    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
                    getUsersJars(new File(libDir), jarList);
                    for (String jarFilePath : jarList)
                        new WebServer().addURL(new URL("file:/" + jarFilePath.replace("\\", "/")),
                                customClassLoader);
                    System.out.println("deploy=" + customClassLoader.geturlS());
                    this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader);
                    jarsDeployed.add(files[i].getName());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(urlClassLoaderMap);
                getChildren(jarFile, classList);
            } catch (FileSystemException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            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("$")) {
                        Class executorServiceClass = customClassLoader.loadClass(classwithpackage);
                        //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        //System.out.println();
                        if (!executorServiceClass.isInterface()) {
                            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<500;count++){
                                            RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                    .exportObject((Remote) executorServiceClass.newInstance(),
                                                            2004);
                                            registry.rebind(remoteCall.servicename().trim(), reminterface);
                                            //}
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }

                        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("method="+executorServiceAnnot.servicename());
                                    //System.out.println("method info="+executorServiceInfo);
                                    //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception();
                                    executorServiceMap.put(executorServiceAnnot.servicename(),
                                            executorServiceInfo);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            ClassLoaderUtil.closeClassLoader(customClassLoader);
            try {
                jarFile.close();
            } catch (FileSystemException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            fsManager.closeFileSystem(jarFile.getFileSystem());
        }
    }
    fsManager.close();
    fsManager = new StandardFileSystemManager();
    try {
        DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);
    } catch (FileSystemException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap,
            jarsDeployed);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    jarFileListener.setFm(fm);
    FileObject listendir = null;
    String[] dirsToScan = scanDirectory.split(";");
    try {
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (FileSystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(3000);
    fm.start();
    //fsManager.close();
}

From source file:com.app.server.EJBDeployer.java

public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) {
    try {//from www.jav a  2s.c  o  m
        Vector<EJBContext> ejbContexts = null;
        EJBContext ejbContext;
        log.info(url.toURI());
        ConcurrentHashMap<String, RARArchiveData> rardata = (ConcurrentHashMap<String, RARArchiveData>) mbeanServer
                .getAttribute(rarDeployerName, "RARArchiveDataAllAdapters");
        Collection<RARArchiveData> rarcls = rardata.values();
        Iterator<RARArchiveData> rarcl = rarcls.iterator();
        RARArchiveData rararcdata;

        FileObject filetoScan = manager.resolveFile("jar:" + url.toString() + "!/");
        HashSet<Class<?>>[] classes = new HashSet[] { new HashSet(), new HashSet(), new HashSet() };

        VFSClassLoader jarCL;

        if (cL != null) {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, cL);
        } else {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager,
                    Thread.currentThread().getContextClassLoader());
        }
        Class[] annot = new Class[] { Stateless.class, Stateful.class, MessageDriven.class };
        scanJar(filetoScan, classes, annot, jarCL);
        Set<Class<?>> clsStateless = classes[0];
        Set<Class<?>> clsStateful = classes[1];
        Set<Class<?>> clsMessageDriven = classes[2];
        //System.gc();
        staticObjs = null;
        EJBContainer container = EJBContainer.getInstance(classes);
        container.inject();
        if (clsStateless.size() > 0) {
            staticObjs = new Vector<Object>();
            ejbContexts = new Vector<EJBContext>();
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            for (Class<?> ejbInterface : clsStateless) {
                BeanPool.getInstance().create(ejbInterface);
                obj = BeanPool.getInstance().get(ejbInterface);
                System.out.println(obj);
                ProxyFactory factory = new ProxyFactory();
                proxyobj = factory.createWithBean(obj);
                staticObjs.add(proxyobj);
                Object unicastobj = UnicastRemoteObject.exportObject((Remote) proxyobj, 0);
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + obj);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, (Remote) unicastobj);
                    ejbContext.put(remoteBinding, obj.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsStateful.size() > 0) {
            if (staticObjs == null) {
                staticObjs = new Vector<Object>();
            }
            if (ejbContexts == null) {
                ejbContexts = new Vector<EJBContext>();
            }
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            StatefulBeanObject statefulBeanObject = null;
            for (Class<?> ejbInterface : clsStateful) {
                BeanPool.getInstance().create(ejbInterface);
                obj1 = ejbInterface.newInstance();
                if (statefulBeanObject == null) {
                    statefulBeanObject = new StatefulBeanObject(obj1, url.toString());
                } else {
                    statefulBeanObject.addStatefulSessionBeanObject(obj1);
                }
                //System.out.println(obj1);
                staticObjs.add(statefulBeanObject);
                /*Object unicastobj1 = UnicastRemoteObject.exportObject(
                      (Remote) obj1,
                      0);*/
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + statefulBeanObject);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, statefulBeanObject);
                    ejbContext.put(remoteBinding, statefulBeanObject.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj1);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsMessageDriven.size() > 0) {

            MDBContext mdbContext = null;
            ConcurrentHashMap<String, MDBContext> mdbContexts;
            if (jarMDBMap.get(url.toString()) != null) {
                mdbContexts = jarMDBMap.get(url.toString());
            } else {
                mdbContexts = new ConcurrentHashMap<String, MDBContext>();
            }
            jarMDBMap.put(url.toString(), mdbContexts);
            MDBContext mdbContextOld;
            for (Class<?> mdbBean : clsMessageDriven) {
                String classwithpackage = mdbBean.getName();
                //System.out.println("class package" + classwithpackage);
                classwithpackage = classwithpackage.replace("/", ".");
                //System.out.println("classList:"
                //   + classwithpackage.replace("/", "."));
                final Class mdbBeanCls = mdbBean;
                try {
                    if (!classwithpackage.contains("$")) {
                        // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        // System.out.println();
                        if (!mdbBean.isInterface()) {
                            Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                            if (classServicesAnnot != null) {
                                Adapter adapter = null;
                                ActivationConfigProperty[] activationConfigProp = null;
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof Adapter) {
                                        adapter = (Adapter) classServicesAnnot[annotcount];
                                    } else if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                        MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                        activationConfigProp = messageDrivenAnnot.activationConfig();
                                        mdbContext = new MDBContext();
                                        mdbContext.setMdbName(messageDrivenAnnot.name());
                                    }
                                }
                                if (adapter != null) {
                                    /*if(rarcl.hasNext()){
                                       rararcdata=rardata.get(rarDeployerName);
                                          rararcdata=rarcl.next();
                                          //classLoader = new VFSClassLoader(rararcdata.getVfsClassLoader().getFileObjects(),rararcdata.getFsManager(),classLoader);
                                          FileObject[] fileObjectArray=rararcdata.getVfsClassLoader().getFileObjects();
                                          //urlset.addAll(ClasspathHelper.forClassLoader(rararcdata.getVfsClassLoader()));
                                          for(FileObject fileObject:fileObjectArray){
                                             fileObjects.add(fileObject.getURL());
                                             //urlset.add(fileObject.getURL());
                                             //System.out.println(Vfs.fromURL(fileObject.getURL()).getFiles().iterator().next().getRelativePath());
                                          }
                                          classLoader = new URLClassLoader(fileObjects.toArray(new URL[fileObjects.size()]),Thread.currentThread().getContextClassLoader());
                                    }*/
                                    RARArchiveData rarArchiveData = (RARArchiveData) mbeanServer.invoke(
                                            rarDeployerName, "getRARArchiveData",
                                            new Object[] { adapter.adapterName() },
                                            new String[] { String.class.getName() });
                                    if (rarArchiveData == null)
                                        throw new Exception("RAR Adapter " + adapter.adapterName()
                                                + " Not found in deploy folder");
                                    Class resourceAdapterClass = rarArchiveData.getResourceAdapterClass();
                                    final ResourceAdapter resourceAdapter = (ResourceAdapter) resourceAdapterClass
                                            .newInstance();
                                    Class activationSpecClass = rarArchiveData.getActivationspecclass();
                                    final ActivationSpec activationSpec = (ActivationSpec) activationSpecClass
                                            .newInstance();
                                    Vector<ConfigProperty> configProperties = rarArchiveData.getConfigPropery();
                                    Integer configPropertyInteger;
                                    Long configPropertyLong;
                                    Boolean configPropertyBoolean;
                                    Method method;
                                    if (configProperties != null) {
                                        for (ConfigProperty configProperty : configProperties) {
                                            String property = configProperty.getConfigpropertyname();
                                            property = (property.charAt(0) + "").toUpperCase()
                                                    + property.substring(1);
                                            Class propertytype = Class
                                                    .forName(configProperty.getConfigpropertytype());
                                            try {

                                                method = activationSpecClass.getMethod("set" + property,
                                                        propertytype);
                                                if (propertytype == String.class) {
                                                    method.invoke(activationSpec,
                                                            configProperty.getConfigpropertyvalue());
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } else if (propertytype == Integer.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyInteger = new Integer(
                                                                configProperty.getConfigpropertyvalue());
                                                        try {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger);
                                                        } catch (Exception ex) {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                        }
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Long.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyLong = new Long(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyLong);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Boolean.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyBoolean = new Boolean(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyBoolean);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                }
                                            } catch (Exception ex) {
                                                try {
                                                    if (propertytype == Integer.class) {
                                                        method = activationSpecClass.getMethod("set" + property,
                                                                int.class);
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, int.class);
                                                            configPropertyInteger = new Integer(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);                                       
                                                        }
                                                    } else if (propertytype == Long.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, long.class);
                                                            configPropertyLong = new Long(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyLong.longValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    } else if (propertytype == Boolean.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, boolean.class);
                                                            configPropertyBoolean = new Boolean(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyBoolean.booleanValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    }
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } catch (Exception ex1) {
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                }
                                                //log.error("Could not set Configuration for rar activation spec", ex);
                                            }
                                        }
                                    }
                                    for (ActivationConfigProperty activationConfig : activationConfigProp) {
                                        String property = activationConfig.propertyName();
                                        property = (property.charAt(0) + "").toUpperCase()
                                                + property.substring(1);
                                        try {
                                            method = activationSpecClass.getMethod("set" + property,
                                                    String.class);
                                            method.invoke(activationSpec, activationConfig.propertyValue());
                                        } catch (Exception ex) {
                                            try {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            } catch (Exception ex1) {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        Boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            }
                                        }

                                    }
                                    final Class listenerClass = rarArchiveData.getMessagelistenertype();
                                    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
                                    Thread.currentThread()
                                            .setContextClassLoader(resourceAdapter.getClass().getClassLoader());
                                    resourceAdapter
                                            .start(new com.app.server.connector.impl.BootstrapContextImpl());
                                    MessageEndPointFactoryImpl messageEndPointFactoryImpl = new MessageEndPointFactoryImpl(
                                            listenerClass, mdbBeanCls.newInstance(), jarCL);
                                    resourceAdapter.endpointActivation(messageEndPointFactoryImpl,
                                            activationSpec);
                                    Thread.currentThread().setContextClassLoader(cCL);
                                    if (mdbContext != null) {
                                        mdbContext.setResourceAdapter(resourceAdapter);
                                        mdbContext.setMessageEndPointFactory(messageEndPointFactoryImpl);
                                        mdbContext.setActivationSpec(activationSpec);
                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                    }
                                    /*new Thread(){
                                       public void run(){
                                          try {
                                             resourceAdapter.endpointActivation(new com.app.server.connector.impl.MessageEndPointFactoryImpl(listenerClass, mdbBeanCls.newInstance(),raCl), activationSpec);
                                          } catch (
                                                Exception e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                                          }
                                       }
                                    }.start();*/

                                } else {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("Error : ", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }
        if (staticObjs != null) {
            staticObjsEjbMap.put(url.toString(), staticObjs);
        }
        this.jarsDeployed.add(url.toURI().toString());
        log.info(url.toString() + " Deployed");
    } catch (Exception ex) {
        log.error("Error in deploying the jar file: " + url, ex);
        //ex.printStackTrace();
    } finally {
        /*if(classLoader!=null){
           try {
              classLoader.close();
           } catch (Exception e) {
              log.error("error in closing the classloader", e);
              // TODO Auto-generated catch block
              //e.printStackTrace();
           }
           ClassLoaderUtil.closeClassLoader(classLoader);
        }*/
    }

}

From source file:com.web.server.EARDeployer.java

public void run() {
    StandardFileSystemManager fsManager = null;
    fsManager = new StandardFileSystemManager();
    try {//from www .  ja  v  a2  s  .co  m
        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);
    }
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public void initializeOverlay(RemoteSession session, PluginInfo pluginInfo, String designFolder)
        throws WGAServiceException {

    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    try {/*from w w w  .  j  a  va  2s.  co m*/
        fsManager.init();
        if (!isAdminServiceEnabled()) {
            throw new WGAServiceException("Administrative services are disabled");
        }

        if (!isAdminSession(session)) {
            throw new WGAServiceException("You need an administrative login to access this service.");
        }

        WGAPlugin basePlugin = _core.getPluginSet().getPluginsByInstallationKey()
                .get(pluginInfo.getInstallationKey());
        if (basePlugin == null) {
            throw new WGAServiceException(
                    "No plugin is installed with installation key " + pluginInfo.getInstallationKey());
        }
        WGDatabase pluginDB = _core.getContentdbs().get(basePlugin.buildDatabaseKey());
        if (pluginDB == null) {
            throw new WGAServiceException(
                    "Plugin database not connected for plugin " + basePlugin.getIdentification());
        }

        FileSystemDesignSource fsDesignSource = (FileSystemDesignSource) _core.getDesignManager()
                .getDesignSources().get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM);
        WGADesign overlayDesign = fsDesignSource.getDesign(designFolder);
        if (overlayDesign == null) {
            throw new WGAServiceException("File Directory Design '" + designFolder + "' does not exist");
        }

        String designFolderLocation = fsDesignSource.getDesignLocation(overlayDesign);

        FileObject designFolderObj = fsManager.resolveFile(designFolderLocation);
        if (!designFolderObj.exists() || !designFolderObj.getType().equals(FileType.FOLDER)) {
            throw new WGAServiceException(
                    "Design folder '" + designFolder + "' cannot be found or is no folder");
        }

        // Determine design encoding of folder to import to
        DesignDefinition designDef = null;
        FileObject designDefFile = designFolderObj.resolveFile("design.xml");
        if (designDefFile.exists()) {
            designDef = DesignDefinition.load(designDefFile);
        }

        CSConfig csConfig = null;
        FileObject csConfigFile = designFolderObj.resolveFile("files/system/csconfig.xml");
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }

        String designEncoding = FileSystemDesignManager.determineDesignEncoding(designDef, csConfig);

        // Trigger overlay init/uprade process
        OverlayStatus status = FileSystemDesignProvider.determineOverlayStatus(
                (FileSystemDesignProvider) pluginDB.getDesignProvider(), basePlugin.getPluginID(),
                designFolderObj, designEncoding, _core.getLog(), _core.getDesignFileValidator());
        FileSystemDesignProvider.upgradeOverlay((FileSystemDesignProvider) pluginDB.getDesignProvider(),
                basePlugin.getPluginID(), status, designFolderObj, designEncoding, _core.getLog(),
                _core.getDesignFileValidator());

        // Disconnect consumer apps
        WGADesignManager designManager = _core.getDesignManager();
        for (WGDatabase consumerDb : _core.getContentdbs().values()) {

            WGDesignProvider provider = consumerDb.getDesignProvider();
            if (provider instanceof OverlayDesignProvider) {
                OverlayDesignProvider overlayProvider = (OverlayDesignProvider) provider;
                if (overlayProvider.getOverlay() instanceof FileSystemDesignProvider) {
                    FileSystemDesignProvider fsProvider = (FileSystemDesignProvider) overlayProvider
                            .getOverlay();
                    if (fsProvider.getBaseFolder().equals(designFolderObj)) {
                        _core.removeContentDB(consumerDb.getDbReference());
                    }
                }
            }
        }

        // Run update content dbs to reconnect
        _core.updateContentDBs();

    } catch (Exception e) {
        if (e instanceof WGAServiceException) {
            throw (WGAServiceException) e;
        } else {
            throw new WGAServiceException("Overlay initialisation failed.", e);
        }
    } finally {
        fsManager.close();
    }

}

From source file:com.seer.datacruncher.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l/*from   ww w  . j a v a 2  s.  com*/
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}