Example usage for java.lang ClassLoader getSystemClassLoader

List of usage examples for java.lang ClassLoader getSystemClassLoader

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemClassLoader.

Prototype

@CallerSensitive
public static ClassLoader getSystemClassLoader() 

Source Link

Document

Returns the system class loader.

Usage

From source file:org.obm.sync.login.LDAPLoginIntegrationTest.java

private void loadLdifBootstrap(String file) throws Exception {
    Entry entry;//from  w  w w . ja  v a2  s .co  m
    LDIFReader reader = new LDIFReader(new LDIFImportConfig(
            new AutoCloseInputStream(ClassLoader.getSystemClassLoader().getResourceAsStream(file))));

    while ((entry = reader.readEntry()) != null) {
        addEntry(entry);
    }
}

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

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

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

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

From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java

public OperatorDiscoverer() {
    classLoader = ClassLoader.getSystemClassLoader();
}

From source file:org.apache.spark.tez.utils.HadoopUtils.java

/**
 * //from  www. j av a 2s. c o m
 */
private static void provisionAndLocalizeScalaLib(FileSystem fs, String appName,
        Map<String, LocalResource> localResources) {
    URL url = ClassLoader.getSystemClassLoader().getResource("scala/Function.class");
    String path = url.getFile();
    path = path.substring(0, path.indexOf("!"));

    try {
        File scalaLibLocation = new File(new URL(path).toURI());
        Path provisionedPath = HadoopUtils.provisionResourceToFs(scalaLibLocation, fs, appName);
        LocalResource localResource = HadoopUtils.createLocalResource(fs, provisionedPath);
        localResources.put(provisionedPath.getName(), localResource);
    } catch (Exception e) {
        throw new RuntimeException("Failed to provision Scala Library", e);
    }
}

From source file:oz.hadoop.yarn.api.core.ApplicationMasterLauncherImpl.java

/**
 * Will package this application JAR in {@link LocalResource}s.
 * TODO make it more general to allow other resources
 *///from ww  w.j a v  a 2 s . c  om
private Map<String, LocalResource> createLocalResources() {
    Map<String, LocalResource> localResources = new LinkedHashMap<String, LocalResource>();
    logger.info(
            "Setting up application classpath by Creating LocalResources and generating JARs if need to. Enable DEBUG for more info.");
    try {
        FileSystem fs = FileSystem.get(this.yarnConfig);

        URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
        for (URL url : cp) {
            File f = new File(url.getFile());
            if (f.isDirectory()) {
                String jarFileName = YayaUtils.generateJarFileName(this.applicationName);
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating JAR: " + jarFileName);
                }
                File jarFile = JarUtils.toJar(f, jarFileName);
                this.addToLocalResources(fs, jarFile.getAbsolutePath(), jarFile.getName(),
                        this.applicationId.getId(), localResources);
                try {
                    new File(jarFile.getAbsolutePath()).delete(); // will delete the generated JAR file
                } catch (Exception e) {
                    logger.warn("Failed to delete generated JAR file: " + jarFile.getAbsolutePath(), e);
                }
            } else {
                if (!this.excluded(f.getName())) {
                    this.addToLocalResources(fs, f.getAbsolutePath(), f.getName(), this.applicationId.getId(),
                            localResources);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Classpath resource " + f.getName()
                                + " is excluded from classpath propagation. You may use"
                                + "classpath.filters file to manage which JARs to exclude from classpath propagation.");
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return localResources;
}

From source file:odin.gateway.ReportAllocation.java

private static void printClassPath() {
    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader) cl).getURLs();

    for (URL url : urls) {
        System.out.println(url.getFile());
    }//from  www . ja  va2  s  .  c o  m
}

From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java

public OperatorDiscoverer(String[] jars) {
    URL[] urls = new URL[jars.length];
    for (int i = 0; i < jars.length; i++) {
        pathsToScan.add(jars[i]);//ww w  . j  ava2  s.c  o  m
        try {
            urls[i] = new URL("file://" + jars[i]);
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        }
    }
    classLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
}

From source file:org.tolven.plugin.repository.ConfigPluginsWrapper.java

/**
 * Unmarshall a Plugins from an InputStream
 * @param xsdStream//  w w w  .j ava  2s.  c  o  m
 * @return
 */
public Plugins loadPlugins(InputStream xsdStream) {
    try {
        JAXBContext jc = JAXBContext.newInstance(RepositoryMetadata.PLUGINS_PACKAGE,
                ClassLoader.getSystemClassLoader());
        Unmarshaller u = jc.createUnmarshaller();
        setPlugins((Plugins) u.unmarshal(xsdStream));
        validate();
        ee = new ExpressionEvaluator();
        Map<String, String> globalPropertyMap = new HashMap<String, String>();
        for (PluginPropertyDetail globalProperty : getPlugins().getProperty()) {
            globalPropertyMap.put(globalProperty.getName(), globalProperty.getValue());
        }
        ee.addVariable("globalProperty", globalPropertyMap);
        for (PluginDetail plugin : getPlugins().getPlugin()) {
            Map<String, String> pMap = new HashMap<String, String>();
            for (PluginPropertyDetail pluginProperty : plugin.getProperty()) {
                updatePropertyMap(pMap, pluginProperty);
            }
            pluginPropertyMap.put(plugin.getId(), pMap);
        }
        return getPlugins();
    } catch (JAXBException ex) {
        throw new RuntimeException("Could not load plugins inputstream", ex);
    }
}

From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java

/**
 * /*from  w  w w .  ja  v  a2  s  . c om*/
 * @param moduleFile
 * @throws IOException
 */
private static void addFile(File moduleFile) throws IOException {
    URL moduleURL = moduleFile.toURI().toURL();
    final Class[] parameters = new Class[] { URL.class };

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { moduleURL });
    } catch (Throwable t) {
        LOGGER.error("Error, could not add URL to system classloader", t);
        throw new IOException("Error, could not add URL to system classloader");
    }
}

From source file:org.apache.openejb.resource.AutoConnectionTracker.java

private Object newProxy(final Object handle, final InvocationHandler invocationHandler) {
    ClassLoader loader = handle.getClass().getClassLoader();
    if (loader == null) {
        loader = ClassLoader.getSystemClassLoader();
    }// www . j  a  v  a  2  s.co  m
    if (!Proxy.isProxyClass(handle.getClass())) {
        final Object proxy = LocalBeanProxyFactory.Unsafe.allocateInstance(getProxy(handle.getClass(), loader));
        DynamicSubclass.setHandler(proxy, invocationHandler);
        return proxy;
    }

    return Proxy.newProxyInstance(loader, getAPi(handle.getClass()), invocationHandler);
}