Example usage for java.util.concurrent CopyOnWriteArrayList toArray

List of usage examples for java.util.concurrent CopyOnWriteArrayList toArray

Introduction

In this page you can find the example usage for java.util.concurrent CopyOnWriteArrayList toArray.

Prototype

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

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

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

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

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

                            Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations();

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

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

/**
 * This method deploys the war in exploded form and configures it.
 * //from  w w  w  .  j a va  2  s . c o  m
 * @param file
 * @param customClassLoader
 * @param warDirectoryPath
 */
public void extractWar(File file, ClassLoader classLoader) {

    StringBuffer classPath = new StringBuffer();
    int numBytes;
    WebClassLoader customClassLoader = null;
    CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>();
    try {
        ConcurrentHashMap jspMap = new ConcurrentHashMap();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        // String fileName=file.getName();
        String directoryName = file.getName();
        directoryName = directoryName.substring(0, directoryName.indexOf('.'));
        try {
            /*ClassLoader classLoader = Thread.currentThread()
                  .getContextClassLoader();*/
            // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
            jarUrls.add(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();
        }
        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")) {
                    jarUrls.add(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;");
        jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;"));
        ArrayList<String> jspFiles = new ArrayList();
        // log.info(classPath.toString());
        if (jspIterator.hasNext()) {
            jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"));
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
            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);
                    }
                }
            }
        } else {
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
        }
        String filePath = file.getAbsolutePath();
        // log.info("filePath"+filePath);
        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
        urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader);
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            //Thread.currentThread().setContextClassLoader(customClassLoader);
            String classPathBefore = "";
            try {
                JspCompiler jspc = new JspCompiler();
                jspc.setUriroot(scanDirectory + "/" + directoryName);
                jspc.setAddWebXmlMappings(false);
                jspc.setListErrors(false);
                jspc.setCompile(true);
                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);
                classPathBefore = System.getProperty("java.class.path");
                System.setProperty("java.class.path",
                        System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\"));
                //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\"));
                jspc.setJspFiles(jsp);
                jspc.initCL(customClassLoader);
                jspc.execute();
                //jspc.closeClassLoader();
                //jspc.closeClassLoader();
            } catch (Throwable je) {
                log.error("Error in compiling the jsp page", je);
                //je.printStackTrace();
            } finally {
                System.setProperty("java.class.path", classPathBefore);
                //Thread.currentThread().setContextClassLoader(oldCL);
            }
            //Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        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();
        }
        //customClassLoader.close();
        // ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (Exception ex) {
        log.error("Error in Deploying war " + file.getAbsolutePath(), ex);
    }
}