Search in sources :

Example 31 with URLClassLoader

use of java.net.URLClassLoader in project head by mifos.

the class PluginManager method initializePluginClassLoader.

/**
     * Extend classloader by loading jars from ${MIFOS_CONF}/plugins at runtime
     *
     * @return pluginClassLoader
     */
private ClassLoader initializePluginClassLoader() {
    ConfigurationLocator configurationLocator = new ConfigurationLocator();
    String libDir = configurationLocator.getConfigurationDirectory() + "/plugins";
    File dependencyDirectory = new File(libDir);
    File[] files = dependencyDirectory.listFiles();
    ArrayList<URL> urls = new ArrayList<URL>();
    if (files != null) {
        urls.addAll(getPluginURLs(files));
    }
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
}
Also used : URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) ConfigurationLocator(org.mifos.framework.util.ConfigurationLocator) File(java.io.File) URL(java.net.URL)

Example 32 with URLClassLoader

use of java.net.URLClassLoader in project mvel by mikebrock.

the class CoreConfidenceTests method testNestedEnumFromJar.

public void testNestedEnumFromJar() throws ClassNotFoundException, SecurityException, NoSuchFieldException {
    String expr = "EventRequest.Status.ACTIVE";
    // creating a classloader for the jar
    URL resource = getClass().getResource("/eventing-example.jar");
    assertNotNull(resource);
    URLClassLoader loader = new URLClassLoader(new URL[] { resource }, getClass().getClassLoader());
    // loading the class to prove it works
    Class<?> er = loader.loadClass("org.drools.examples.eventing.EventRequest");
    assertNotNull(er);
    assertEquals("org.drools.examples.eventing.EventRequest", er.getCanonicalName());
    // getting the value of the enum to prove it works:
    Class<?> st = er.getDeclaredClasses()[0];
    assertNotNull(st);
    Field active = st.getField("ACTIVE");
    assertNotNull(active);
    // now, trying with MVEL
    ParserConfiguration pconf = new ParserConfiguration();
    pconf.setClassLoader(loader);
    pconf.addImport(er);
    ParserContext pctx = new ParserContext(pconf);
    pctx.setStrongTyping(true);
    Serializable compiled = MVEL.compileExpression(expr, pctx);
    Object result = MVEL.executeExpression(compiled);
    assertNotNull(result);
}
Also used : Field(java.lang.reflect.Field) Serializable(java.io.Serializable) URLClassLoader(java.net.URLClassLoader) URL(java.net.URL)

Example 33 with URLClassLoader

use of java.net.URLClassLoader in project jsonschema2pojo by joelittlejohn.

the class ProjectClasspath method getClassLoader.

/**
     * Provides a class loader that can be used to load classes from this
     * project classpath.
     * 
     * @param project
     *            the maven project currently being built
     * @param parent
     *            a classloader which should be used as the parent of the newly
     *            created classloader.
     * @param log
     *            object to which details of the found/loaded classpath elements
     *            can be logged.
     * 
     * @return a classloader that can be used to load any class that is
     *         contained in the set of artifacts that this project classpath is
     *         based on.
     * @throws DependencyResolutionRequiredException
     *             if maven encounters a problem resolving project dependencies
     */
public ClassLoader getClassLoader(MavenProject project, final ClassLoader parent, Log log) throws DependencyResolutionRequiredException {
    @SuppressWarnings("unchecked") List<String> classpathElements = project.getCompileClasspathElements();
    final List<URL> classpathUrls = new ArrayList<URL>(classpathElements.size());
    for (String classpathElement : classpathElements) {
        try {
            log.debug("Adding project artifact to classpath: " + classpathElement);
            classpathUrls.add(new File(classpathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            log.debug("Unable to use classpath entry as it could not be understood as a valid URL: " + classpathElement, e);
        }
    }
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parent);
        }
    });
}
Also used : MalformedURLException(java.net.MalformedURLException) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) File(java.io.File) URL(java.net.URL)

Example 34 with URLClassLoader

use of java.net.URLClassLoader in project hudson-2.x by hudson.

the class WebAppMain method contextInitialized.

/**
     * Creates the sole instance of {@link Hudson} and register it to the {@link ServletContext}.
     */
public void contextInitialized(ServletContextEvent event) {
    try {
        final ServletContext context = event.getServletContext();
        // Install the current servlet context, unless its already been set
        final WebAppController controller = WebAppController.get();
        try {
            // Attempt to set the context
            controller.setContext(context);
        } catch (IllegalStateException e) {
        // context already set ignore
        }
        // Setup the default install strategy if not already configured
        try {
            controller.setInstallStrategy(new DefaultInstallStrategy());
        } catch (IllegalStateException e) {
        // strategy already set ignore
        }
        // use the current request to determine the language
        LocaleProvider.setProvider(new LocaleProvider() {

            public Locale get() {
                Locale locale = null;
                StaplerRequest req = Stapler.getCurrentRequest();
                if (req != null)
                    locale = req.getLocale();
                if (locale == null)
                    locale = Locale.getDefault();
                return locale;
            }
        });
        // quick check to see if we (seem to) have enough permissions to run. (see #719)
        JVM jvm;
        try {
            jvm = new JVM();
            new URLClassLoader(new URL[0], getClass().getClassLoader());
        } catch (SecurityException e) {
            controller.install(new InsufficientPermissionDetected(e));
            return;
        }
        try {
            // remove Sun PKCS11 provider if present. See http://wiki.hudson-ci.org/display/HUDSON/Solaris+Issue+6276483
            Security.removeProvider("SunPKCS11-Solaris");
        } catch (SecurityException e) {
        // ignore this error.
        }
        installLogger();
        File dir = getHomeDir(event);
        try {
            dir = dir.getCanonicalFile();
        } catch (IOException e) {
            dir = dir.getAbsoluteFile();
        }
        final File home = dir;
        home.mkdirs();
        LOGGER.info("Home directory: " + home);
        // check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
        if (!home.exists()) {
            controller.install(new NoHomeDir(home));
            return;
        }
        // make sure that we are using XStream in the "enhanced" (JVM-specific) mode
        if (jvm.bestReflectionProvider().getClass() == PureJavaReflectionProvider.class) {
            // nope
            controller.install(new IncompatibleVMDetected());
            return;
        }
        // make sure this is servlet 2.4 container or above
        try {
            ServletResponse.class.getMethod("setCharacterEncoding", String.class);
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleServletVersionDetected(ServletResponse.class));
            return;
        }
        // make sure that we see Ant 1.7
        try {
            FileSet.class.getMethod("getDirectoryScanner");
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleAntVersionDetected(FileSet.class));
            return;
        }
        // make sure AWT is functioning, or else JFreeChart won't even load.
        if (ChartUtil.awtProblemCause != null) {
            controller.install(new AWTProblem(ChartUtil.awtProblemCause));
            return;
        }
        // check that and report an error
        try {
            File f = File.createTempFile("test", "test");
            f.delete();
        } catch (IOException e) {
            controller.install(new NoTempDir(e));
            return;
        }
        // try to correct it
        try {
            TransformerFactory.newInstance();
        // if this works we are all happy
        } catch (TransformerFactoryConfigurationError x) {
            // no it didn't.
            LOGGER.log(Level.WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details", x);
            System.setProperty(TransformerFactory.class.getName(), "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            try {
                TransformerFactory.newInstance();
                LOGGER.info("XSLT is set to the JAXP RI in JRE");
            } catch (TransformerFactoryConfigurationError y) {
                LOGGER.log(Level.SEVERE, "Failed to correct the problem.");
            }
        }
        installExpressionFactory(event);
        controller.install(new HudsonIsLoading());
        new Thread("hudson initialization thread") {

            @Override
            public void run() {
                try {
                    // Creating of the god object performs most of the booting muck
                    Hudson hudson = new Hudson(home, context);
                    // once its done, hook up to stapler and things should be ready to go
                    controller.install(hudson);
                    // trigger the loading of changelogs in the background,
                    // but give the system 10 seconds so that the first page
                    // can be served quickly
                    Trigger.timer.schedule(new SafeTimerTask() {

                        public void doRun() {
                            User.getUnknown().getBuilds();
                        }
                    }, 1000 * 10);
                } catch (Error e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                    throw e;
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                }
            }
        }.start();
    } catch (Error e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    } catch (RuntimeException e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    }
}
Also used : Locale(java.util.Locale) JVM(com.thoughtworks.xstream.core.JVM) IncompatibleAntVersionDetected(hudson.util.IncompatibleAntVersionDetected) StaplerRequest(org.kohsuke.stapler.StaplerRequest) NoHomeDir(hudson.util.NoHomeDir) ServletContext(javax.servlet.ServletContext) HudsonFailedToLoad(hudson.util.HudsonFailedToLoad) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IncompatibleVMDetected(hudson.util.IncompatibleVMDetected) Hudson(hudson.model.Hudson) InsufficientPermissionDetected(hudson.util.InsufficientPermissionDetected) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IOException(java.io.IOException) WebAppController(hudson.stapler.WebAppController) HudsonIsLoading(hudson.util.HudsonIsLoading) NoTempDir(hudson.util.NoTempDir) AWTProblem(hudson.util.AWTProblem) NamingException(javax.naming.NamingException) IOException(java.io.IOException) DefaultInstallStrategy(hudson.stapler.WebAppController.DefaultInstallStrategy) LocaleProvider(org.jvnet.localizer.LocaleProvider) URLClassLoader(java.net.URLClassLoader) IncompatibleServletVersionDetected(hudson.util.IncompatibleServletVersionDetected) File(java.io.File) SafeTimerTask(hudson.triggers.SafeTimerTask)

Example 35 with URLClassLoader

use of java.net.URLClassLoader in project jmxtrans by jmxtrans.

the class MonitorableApp method getCurrentClasspath.

private String getCurrentClasspath() {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    return Joiner.on(":").join(from(asList(urls)).transform(new Function<URL, String>() {

        @Nullable
        @Override
        public String apply(URL input) {
            return input.toString();
        }
    }));
}
Also used : Function(com.google.common.base.Function) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) URL(java.net.URL)

Aggregations

URLClassLoader (java.net.URLClassLoader)1351 URL (java.net.URL)872 File (java.io.File)514 Test (org.junit.Test)317 IOException (java.io.IOException)256 ArrayList (java.util.ArrayList)202 MalformedURLException (java.net.MalformedURLException)186 Method (java.lang.reflect.Method)177 InvocationTargetException (java.lang.reflect.InvocationTargetException)68 JarFile (java.util.jar.JarFile)54 InputStream (java.io.InputStream)50 HashSet (java.util.HashSet)49 HashMap (java.util.HashMap)44 URISyntaxException (java.net.URISyntaxException)41 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)35 Path (java.nio.file.Path)33 QuickTest (com.hazelcast.test.annotation.QuickTest)32 Test (org.junit.jupiter.api.Test)28 URI (java.net.URI)27 List (java.util.List)27