Example usage for java.lang ClassLoader ClassLoader

List of usage examples for java.lang ClassLoader ClassLoader

Introduction

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

Prototype

protected ClassLoader() 

Source Link

Document

Creates a new class loader using the ClassLoader returned by the method #getSystemClassLoader() getSystemClassLoader() as the parent class loader.

Usage

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * The java class/4 creates, compiles and loads a new Java class from a source text
 * @param clSource: is a string representing the text source of the new Java class
 * @param clName: full class name/*from w w w  .  ja v a  2s  .c om*/
 * @param clPathes: is a (possibly empty) Prolog list of class paths that may be required for a successful dynamic compilation of this class
 * @param id: reference to an instance of the meta-class java.lang.Class rep- resenting the newly-created class
 * @return boolean: true if created false otherwise
 * @throws JavaException
 */
public boolean new_class_4(PTerm clSource, PTerm clName, PTerm clPathes, PTerm id) throws JavaException {
    Struct classSource = (Struct) clSource.getTerm();
    Struct className = (Struct) clName.getTerm();
    Struct classPathes = (Struct) clPathes.getTerm();
    id = id.getTerm();
    try {
        String fullClassName = alice.util.Tools.removeApices(className.toString());

        String fullClassPath = fullClassName.replace('.', '/');
        Iterator<? extends PTerm> it = classPathes.listIterator();
        String cp = "";
        while (it.hasNext()) {
            if (cp.length() > 0) {
                cp += ";";
            }
            cp += alice.util.Tools.removeApices(it.next().toString());
        }
        if (cp.length() > 0) {
            cp = " -classpath " + cp;
        }

        String text = alice.util.Tools.removeApices(classSource.toString());
        try {
            FileWriter file = new FileWriter(fullClassPath + ".java");
            file.write(text);
            file.close();
        } catch (IOException ex) {
            getEngine().logger.warn("Compilation of java sources failed");
            getEngine().logger.warn("(creation of " + fullClassPath + ".java fail failed)");
            throw new JavaException(ex);
        }
        String cmd = "javac " + cp + ' ' + fullClassPath + ".java";

        try {
            Process jc = Runtime.getRuntime().exec(cmd);
            int res = jc.waitFor();
            if (res != 0) {
                getEngine().logger.warn("Compilation of java sources failed");
                getEngine().logger.warn("(java compiler (javac) has stopped with errors)");
                throw new IOException("Compilation of java sources failed");
            }
        } catch (IOException ex) {
            getEngine().logger.warn("Compilation of java sources failed");
            getEngine().logger.warn("(java compiler (javac) invocation failed)");
            throw new JavaException(ex);
        }
        try {
            Class<?> the_class;

            /**
             * @author Alessio Mercurio
             * 
             * On Dalvik VM we can only use the DexClassLoader.
             */

            the_class = System.getProperty("java.vm.name").equals("Dalvik")
                    ? Class.forName(fullClassName, true, dynamicLoader)
                    : Class.forName(fullClassName, true, new ClassLoader());

            if (bindDynamicObject(id, the_class))
                return true;
            else
                throw new JavaException(new Exception());
        } catch (ClassNotFoundException ex) {
            getEngine().logger.warn("Compilation of java sources failed");
            getEngine().logger.warn("(Java Class compiled, but not created: " + fullClassName + " )");
            throw new JavaException(ex);
        }
    } catch (Exception ex) {
        throw new JavaException(ex);
    }
}

From source file:org.jahia.data.templates.JahiaTemplatesPackage.java

/**
 * Returns a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and
 * at the end the list of class loaders of modules this module depends on.
 *
 * @return a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and
 *         at the end the list of class loaders of modules this module depends on
 *///  w  w w .  j  a v a2s  .com
public ClassLoader getChainedClassLoader() {

    if (chainedClassLoader != null) {
        return chainedClassLoader;
    }

    final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
    classLoaders.add(Jahia.class.getClassLoader());
    final ClassLoader classLoader = getClassLoader();
    if (classLoader != null) {
        classLoaders.add(classLoader);
    }
    for (JahiaTemplatesPackage dependentPack : getDependencies()) {
        if (dependentPack != null && dependentPack.getClassLoader() != null) {
            classLoaders.add(dependentPack.getClassLoader());
        }
    }

    chainedClassLoader = new ClassLoader() {

        @Override
        public URL getResource(String name) {
            URL url = null;
            for (ClassLoader loader : classLoaders) {
                url = loader.getResource(name);
                if (url != null)
                    return url;
            }
            return url;
        }

        @Override
        public Enumeration<URL> getResources(String name) throws IOException {

            final List<Enumeration<URL>> urlsEnums = new ArrayList<Enumeration<URL>>();
            for (ClassLoader loader : classLoaders) {
                Enumeration<URL> urls = loader.getResources(name);
                if (urls != null && urls.hasMoreElements()) {
                    // we only add enumerations that have elements, make things simpler
                    urlsEnums.add(urls);
                }
            }

            if (urlsEnums.size() == 0) {
                return java.util.Collections.emptyEnumeration();
            }

            return new Enumeration<URL>() {

                int i = 0;
                Enumeration<URL> currentEnum = urlsEnums.get(i);

                @Override
                public boolean hasMoreElements() {
                    if (currentEnum.hasMoreElements()) {
                        return true;
                    }
                    int j = i;
                    do {
                        j++;
                    } while (j < (urlsEnums.size() - 1) && !urlsEnums.get(j).hasMoreElements());
                    if (j <= (urlsEnums.size() - 1)) {
                        return urlsEnums.get(j).hasMoreElements();
                    } else {
                        return false;
                    }
                }

                @Override
                public URL nextElement() {
                    if (currentEnum.hasMoreElements()) {
                        return currentEnum.nextElement();
                    }
                    do {
                        i++;
                        currentEnum = urlsEnums.get(i);
                    } while (!currentEnum.hasMoreElements() && i < (urlsEnums.size() - 1));
                    if (currentEnum.hasMoreElements()) {
                        return currentEnum.nextElement();
                    } else {
                        throw new NoSuchElementException();
                    }
                }
            };
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            for (ClassLoader classLoader : classLoaders) {
                try {
                    Class<?> clazz = classLoader.loadClass(name);
                    if (resolve) {
                        resolveClass(clazz);
                    }
                    return clazz;
                } catch (ClassNotFoundException e) {
                    // keep moving through the classloaders
                }
            }
            throw new ClassNotFoundException(name);
        }
    };

    return chainedClassLoader;
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_RegistrationTCCL1() {
    final Set<String> filterTCCL = Collections.synchronizedSet(new HashSet<String>());
    final Set<String> servletTCCL = Collections.synchronizedSet(new HashSet<String>());
    Filter tcclFilter = new Filter() {

        @Override/*from w  w  w  .  j  a  va  2  s .c  om*/
        public void init(FilterConfig filterConfig) throws ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }
    };
    HttpServlet tcclServlet = new HttpServlet() {

        @Override
        public void destroy() {
            super.destroy();
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            response.getWriter().print(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

    };

    ClassLoader originalTCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader dummy = new ClassLoader() {
    };
    Thread.currentThread().setContextClassLoader(dummy);
    String expected = dummy.getClass().getName();
    String actual = null;
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/tccl", tcclFilter, null, null);
        extendedHttpService.registerServlet("/tccl", tcclServlet, null, null);
        actual = requestAdvisor.request("tccl");
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalTCCL);
        try {
            extendedHttpService.unregister("/tccl");
            extendedHttpService.unregisterFilter(tcclFilter);
        } catch (IllegalArgumentException e) {
            // ignore
        }
    }
    assertEquals(expected, actual);
    assertEquals("Wrong filterTCCL size: " + filterTCCL, 1, filterTCCL.size());
    assertTrue("Wrong filterTCCL: " + filterTCCL, filterTCCL.contains(expected));
    assertEquals("Wrong httpTCCL size: " + servletTCCL, 1, servletTCCL.size());
    assertTrue("Wrong servletTCCL: " + servletTCCL, servletTCCL.contains(expected));

}