Example usage for java.net URLClassLoader URLClassLoader

List of usage examples for java.net URLClassLoader URLClassLoader

Introduction

In this page you can find the example usage for java.net URLClassLoader URLClassLoader.

Prototype

URLClassLoader(URL[] urls, AccessControlContext acc) 

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    File f = new File("c:/mysql-connector-java-5.1.18-bin.jar");
    URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURL() }, System.class.getClassLoader());

    Class mySqlDriver = urlCl.loadClass("com.mysql.jdbc.Driver");
    System.out.println(mySqlDriver.newInstance());
    System.out.println("Is this interface? = " + mySqlDriver.isInterface());

    Class interfaces[] = mySqlDriver.getInterfaces();
    int i = 1;//from  ww  w .jav  a 2  s  . c  o m
    for (Class _interface : interfaces) {
        System.out.println("Implemented Interface Name " + (i++) + " = " + _interface.getName());
    }

    Constructor constructors[] = mySqlDriver.getConstructors();
    for (Constructor constructor : constructors) {
        System.out.println("Constructor Name = " + constructor.getName());
        System.out.println("Is Constructor Accessible? = " + constructor.isAccessible());
    }
}

From source file:org.kchine.rpf.MainServer.java

public static void main(String[] args) throws Exception {

    PoolUtils.initLog4J();/*  w  w w. ja va  2 s . c o m*/
    PoolUtils.ensurePublicIPIsUsedForRMI();
    PoolUtils.noGui();

    try {

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new YesSecurityManager());
        }

        boolean isNodeProvided = System.getProperty("node") != null && !System.getProperty("node").equals("");
        if (isNodeProvided) {
            NodeDataDB nodeData = null;
            try {
                rmiRegistry = ServerDefaults.getRmiRegistry();
                nodeData = ((DBLayerInterface) rmiRegistry)
                        .getNodeData("NODE_NAME='" + System.getProperty("node") + "'").elementAt(0);
            } catch (Exception e) {
                log.info("Couldn't retrieve Node Info for node <" + System.getProperty("node") + ">");
                e.printStackTrace();
                return;
            }
            System.setProperty("autoname", "true");
            _servantPoolPrefix = nodeData.getPoolPrefix();

            System.out.println("nodedata:" + nodeData);
        }

        if (System.getProperty("autoname") != null && System.getProperty("autoname").equalsIgnoreCase("true")) {
            log.info("Instantiating " + _mainServantClassName + " with autonaming, prefix "
                    + _servantPoolPrefix);
            servantName = null;
        } else {
            // no autonaming, check the name here
            if (System.getProperty("name") != null && !System.getProperty("name").equals("")) {
                servantName = System.getProperty("name");
            }
            log.info("Instantiating " + _mainServantClassName + " with name " + servantName + " , prefix "
                    + _servantPoolPrefix);
        }

        if (rmiRegistry == null)
            rmiRegistry = ServerDefaults.getRmiRegistry();

        System.out.println("### code base:" + System.getProperty("java.rmi.server.codebase"));

        ClassLoader cl = new URLClassLoader(PoolUtils.getURLS(System.getProperty("java.rmi.server.codebase")),
                MainServer.class.getClassLoader());
        Thread.currentThread().setContextClassLoader(cl);
        System.out.println(Arrays.toString(PoolUtils.getURLS(System.getProperty("java.rmi.server.codebase"))));

        mainServantClass = cl.loadClass(_mainServantClassName);

        boolean isPrivateServant = !isNodeProvided && ((System.getProperty("private") != null
                && System.getProperty("private").equalsIgnoreCase("true")));

        String servantCreationListenerStub = System.getProperty("listener.stub");
        if (servantCreationListenerStub != null && !servantCreationListenerStub.equals("")) {
            servantCreationListener = (ServantCreationListener) PoolUtils
                    .hexToObject(servantCreationListenerStub);
        }

        if (!isPrivateServant) {
            mservant = (ManagedServant) mainServantClass
                    .getConstructor(new Class[] { String.class, String.class, Registry.class })
                    .newInstance(new Object[] { servantName, _servantPoolPrefix, rmiRegistry });

        } else {

            mservant = (ManagedServant) mainServantClass
                    .getConstructor(new Class[] { String.class, String.class, Registry.class })
                    .newInstance(new Object[] { null, "PRIVATE_", rmiRegistry });

        }

        //System.out.println("clone:"+mservant.cloneServer());
        if (servantCreationListener != null) {
            PoolUtils.callBack(servantCreationListener, mservant, null);
        }

        String sname = mservant.getServantName();
        log.info("sname :::" + sname);
        if (rmiRegistry instanceof DBLayerInterface) {
            if (System.getProperty("node") != null && !System.getProperty("node").equalsIgnoreCase("")) {
                ((DBLayerInterface) rmiRegistry).updateServantNodeName(sname, System.getProperty("node"));
            } else {
                Vector<NodeDataDB> nodes = ((DBLayerInterface) rmiRegistry).getNodeData("");
                for (int i = 0; i < nodes.size(); ++i) {
                    String nodeName = nodes.elementAt(i).getNodeName();
                    String nodeIp = nodes.elementAt(i).getHostIp();
                    String nodePrefix = nodes.elementAt(i).getPoolPrefix();
                    if (sname.startsWith(nodePrefix) && nodeIp.equals(PoolUtils.getHostIp())) {
                        ((DBLayerInterface) rmiRegistry).updateServantNodeName(sname, nodeName);
                        break;
                    }
                }
            }

            HashMap<String, Object> attributes = new HashMap<String, Object>();
            Enumeration<Object> sysPropKeys = (Enumeration<Object>) System.getProperties().keys();
            while (sysPropKeys.hasMoreElements()) {
                String key = (String) sysPropKeys.nextElement();
                if (key.startsWith("attr.")) {
                    attributes.put(key, System.getProperty(key));
                }
            }

            ((DBLayerInterface) rmiRegistry).updateServantAttributes(sname, attributes);
        }
        //log.info("*************************$$$$$$$$$$$$");
        log.info("Servant " + sname + " instantiated successfully.");

    } catch (InvocationTargetException ite) {
        if (servantCreationListener != null) {
            PoolUtils.callBack(servantCreationListener, null,
                    new RemoteException("", ite.getTargetException()));
        }
        throw new Exception(PoolUtils.getStackTraceAsString(ite.getTargetException()));

    } catch (Exception e) {

        log.info("----------------------");
        log.info(PoolUtils.getStackTraceAsString(e));
        e.printStackTrace();
        log.error(e);

        if (servantCreationListener != null) {
            PoolUtils.callBack(servantCreationListener, null, new RemoteException("", e));
        }

        System.exit(1);
    }
}

From source file:LauncherBootstrap.java

/**
 * The main method./*  w  ww  .  j  a v a  2  s.  c  o  m*/
 *
 * @param args command line arguments
 */
public static void main(String[] args) {

    try {

        // Try to find the LAUNCHER_JAR_FILE_NAME file in the class
        // loader's and JVM's classpath.
        URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
        if (coreURL == null)
            throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);

        // Coerce the coreURL's directory into a file
        File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile();

        // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same
        // directory as this class
        File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME);
        if (!propsFile.canRead())
            throw new FileNotFoundException(propsFile.getPath());

        // Load the properties in the LAUNCHER_PROPS_FILE_NAME 
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);
        fis.close();

        // Create a class loader that contains the Launcher, Ant, and
        // JAXP classes.
        URL[] antURLs = LauncherBootstrap
                .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME));
        URL[] urls = new URL[1 + antURLs.length];
        urls[0] = coreURL;
        for (int i = 0; i < antURLs.length; i++)
            urls[i + 1] = antURLs[i];
        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
        URLClassLoader loader = null;
        if (parentLoader != null)
            loader = new URLClassLoader(urls, parentLoader);
        else
            loader = new URLClassLoader(urls);

        // Load the LAUNCHER_MAIN_CLASS_NAME class
        launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME);

        // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString()
        // method as we need it for printing the usage statement
        Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString",
                new Class[] { String.class });

        // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
        // If the ant.class.path property is not set correctly in the 
        // LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
        Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class });
        int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue();
        // Always exit cleanly after invoking the start() method
        System.exit(returnValue);

    } catch (Throwable t) {

        t.printStackTrace();
        System.exit(1);

    }

}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("Xfu").longOpt("Xforceupdate").desc("Force the patching process").build());
    options.addOption(Option.builder("Xh").longOpt("Xhelp").desc("Help!").build());
    CommandLineParser parser = new DefaultParser();
    try {//from  www  . ja v a2s . c  o m
        CommandLine commandLine = parser.parse(options, args, true);
        if (commandLine.hasOption("Xhelp")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar bootstrapper.jar", options);
        } else if (commandLine.hasOption("Xforceupdate")) {
            forceUpdate();
        } else {
            //                boolean shouldStart = true;
            //                ServerSocket socket = null;
            //                try {
            //                    socket = new ServerSocket(21354);
            //                } catch (IOException e) {
            //                    shouldStart = false;
            //                } finally {
            //                    if (socket != null) {
            //                        socket.close();
            //                    }
            //                }

            //                if (shouldStart) {
            String[] forward = commandLine.getArgs();
            HeliosData heliosData = loadHelios();
            System.out.println("Running Helios version " + heliosData.buildNumber);

            System.getProperties().put("com.heliosdecompiler.buildNumber",
                    String.valueOf(heliosData.buildNumber));
            System.getProperties().put("com.heliosdecompiler.version", String.valueOf(heliosData.version));
            System.getProperties().put("com.heliosdecompiler.args", args);

            new Thread(new UpdaterTask(heliosData.buildNumber)).start();

            ClassLoader classLoader = new URLClassLoader(new URL[] { IMPL_FILE.toURI().toURL() }, null);
            Class<?> bootloader = Class.forName(heliosData.mainClass, false, classLoader);
            bootloader.getMethod("main", String[].class).invoke(null, new Object[] { forward });
            //                } else {
            //                    String message = Arrays.asList(forward).stream().collect(Collectors.joining(" "));
            //                    Socket clientSocket = new Socket("127.0.0.1", 21354);
            //                    clientSocket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
            //                    clientSocket.getOutputStream().close();
            //                    clientSocket.close();
            //                }
        }
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:org.apache.metron.dataservices.Main.java

public static void main(String[] args) throws Exception {

    Options options = new Options();

    options.addOption("homeDir", true, "Home directory for the service");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    Properties configProps = new Properties();

    String homeDir = cmd.getOptionValue("homeDir");

    if (homeDir.endsWith("/")) {
        homeDir = homeDir.substring(0, homeDir.length() - 1);
    }/*from   w w  w .  j  a  va  2  s. co m*/

    DOMConfigurator.configure(homeDir + "/log4j.xml");

    logger.warn("DataServices Server starting...");

    File configFile = new File(homeDir + "/config.properties");
    FileReader configFileReader = new FileReader(configFile);
    try {
        configProps.load(configFileReader);

        Option[] cmdOptions = cmd.getOptions();
        for (Option opt : cmdOptions) {
            String argName = opt.getOpt();
            String argValue = opt.getValue();

            configProps.put(argName, argValue);
        }

    } finally {
        if (configFileReader != null) {
            configFileReader.close();
        }
    }

    WebAppContext context = new WebAppContext();

    Injector injector = Guice.createInjector(new DefaultServletModule(configProps),
            new AlertsServerModule(configProps),
            new DefaultShiroWebModule(configProps, context.getServletContext()), new AbstractModule() {

                @Override
                protected void configure() {
                    binder().requireExplicitBindings();
                    bind(GuiceFilter.class);
                    bind(GuiceResteasyBootstrapServletContextListener.class);
                    bind(EnvironmentLoaderListener.class);

                }
            });

    injector.getAllBindings();
    injector.createChildInjector().getAllBindings();

    Server server = new Server(port);

    /***************************************************
     *************** enable SSL ************************
     ***************************************************/

    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);
    http_config.setRequestHeaderSize(8192);
    http_config.setResponseHeaderSize(8192);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);
    // httpConfig.addCustomizer(new ForwardedRequestCustomizer())
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    String sslKeystorePath = configProps.getProperty("sslKeystorePath", "/keystore");
    logger.debug("sslKeystorePath: " + sslKeystorePath);
    sslContextFactory.setKeyStorePath(homeDir + sslKeystorePath);

    String sslKeystorePassword = configProps.getProperty("sslKeystorePassword");
    sslContextFactory.setKeyStorePassword(sslKeystorePassword);

    String sslKeyManagerPassword = configProps.getProperty("sslKeyManagerPassword");
    if (sslKeyManagerPassword != null && !sslKeyManagerPassword.isEmpty()) {
        sslContextFactory.setKeyManagerPassword(sslKeyManagerPassword);
    }

    String sslTruststorePath = configProps.getProperty("sslTruststorePath");
    if (sslTruststorePath != null && !sslTruststorePath.isEmpty()) {
        sslContextFactory.setTrustStorePath(homeDir + sslTruststorePath);
    }

    String sslTruststorePassword = configProps.getProperty("sslTruststorePassword");
    if (sslTruststorePassword != null && !sslTruststorePassword.isEmpty()) {
        sslContextFactory.setTrustStorePassword(sslTruststorePassword);
    }

    sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");

    // SSL HTTP Configuration
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
    sslConnector.setPort(8443);
    server.addConnector(sslConnector);

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));

    /** For JSP support.  Used only for testing and debugging for now.  This came come out
     * once the real consumers for this service are in place
     */
    URL indexUri = Main.class.getResource(WEBROOT_INDEX);
    if (indexUri == null) {
        throw new FileNotFoundException("Unable to find resource " + WEBROOT_INDEX);
    }

    // Points to wherever /webroot/ (the resource) is
    URI baseUri = indexUri.toURI();

    // Establish Scratch directory for the servlet context (used by JSP compilation)
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    File scratchDir = new File(tempDir.toString(), "embedded-jetty-jsp");

    if (!scratchDir.exists()) {
        if (!scratchDir.mkdirs()) {
            throw new IOException("Unable to create scratch directory: " + scratchDir);
        }
    }

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    context.setAttribute("javax.servlet.context.tempdir", scratchDir);
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());

    //Ensure the jsp engine is initialized correctly
    JettyJasperInitializer sci = new JettyJasperInitializer();
    ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(context);
    ContainerInitializer initializer = new ContainerInitializer(sci, null);
    List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
    initializers.add(initializer);

    context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
    context.addBean(sciStarter, true);

    // Set Classloader of Context to be sane (needed for JSTL)
    // JSP requires a non-System classloader, this simply wraps the
    // embedded System classloader in a way that makes it suitable
    // for JSP to use
    // new URL( "file:///home/prhodes/.m2/repository/javax/servlet/jsp/javax.servlet.jsp-api/2.3.1/javax.servlet.jsp-api-2.3.1.jar" ) 
    ClassLoader jspClassLoader = new URLClassLoader(new URL[] {},
            Thread.currentThread().getContextClassLoader());
    context.setClassLoader(jspClassLoader);

    // Add JSP Servlet (must be named "jsp")
    ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class);
    holderJsp.setInitOrder(0);
    holderJsp.setInitParameter("logVerbosityLevel", "DEBUG");
    holderJsp.setInitParameter("fork", "false");
    holderJsp.setInitParameter("xpoweredBy", "false");
    holderJsp.setInitParameter("compilerTargetVM", "1.7");
    holderJsp.setInitParameter("compilerSourceVM", "1.7");
    holderJsp.setInitParameter("keepgenerated", "true");
    context.addServlet(holderJsp, "*.jsp");
    //context.addServlet(holderJsp,"*.jspf");
    //context.addServlet(holderJsp,"*.jspx");

    // Add Default Servlet (must be named "default")
    ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
    holderDefault.setInitParameter("resourceBase", baseUri.toASCIIString());
    holderDefault.setInitParameter("dirAllowed", "true");
    context.addServlet(holderDefault, "/");

    /** end "for JSP support */

    context.setResourceBase(baseUri.toASCIIString());

    context.setInitParameter("resteasy.guice.modules",
            "org.apache.metron.dataservices.modules.guice.RestEasyModule");
    context.setInitParameter("resteasy.servlet.mapping.prefix", "/rest");

    context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
    context.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    server.setHandler(context);
    server.start();

    AlertsProcessingServer alertsServer = injector.getInstance(AlertsProcessingServer.class);

    alertsServer.startProcessing();

    server.join();
}

From source file:com.dx.ss.plugins.ptree.utils.ClassloaderUtility.java

public static ClassLoader getCustomClassloader(String classpathEntry) {
    File file = null;/*w ww .  j  a v  a  2 s .  co  m*/
    try {
        if (StringUtils.isNotBlank(classpathEntry)) {
            file = new File(classpathEntry);
            if (file.exists()) {
                ClassLoader parent = Thread.currentThread().getContextClassLoader();
                URLClassLoader ucl = new URLClassLoader(new URL[] { file.toURI().toURL() }, parent);
                return ucl;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.o3project.odenos.core.util.ComponentLoader.java

/**
 * create Class Loader./* w  ww.  j  a va 2  s .  c  o  m*/
 * @param dirname package path name.
 * @return class loader.
 * @throws IOException exception.
 */
public static ClassLoader createClassLoader(final String dirname) throws IOException {
    URL[] url = new URL[1];
    File file;
    if (dirname.endsWith("/")) {
        file = new File(dirname);
    } else {
        file = new File(dirname + "/");
    }
    url[0] = file.toURI().toURL();

    ClassLoader parent = ClassLoader.getSystemClassLoader();
    URLClassLoader loader = new URLClassLoader(url, parent);

    return loader;
}

From source file:cz.lbenda.common.ClassLoaderHelper.java

public static ClassLoader createClassLoader(List<String> libs, boolean useSystemClassPath) {
    List<URL> urls = new ArrayList<>(libs.size());
    libs.forEach(lib -> {//  w w  w  .ja  v  a  2 s.c  o  m
        try {
            urls.add((new File(lib)).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new RuntimeException("The file wasn't readable: " + lib, e);
        }
    });

    URLClassLoader urlCl;
    if (useSystemClassPath) {
        urlCl = new URLClassLoader(urls.toArray(new URL[urls.size()]), System.class.getClassLoader());
    } else {
        urlCl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    }
    return urlCl;
}

From source file:org.onecmdb.core.utils.OneCMDBClassLoader.java

public static Object newInstance(String className, List<String> classpath) {
    List<URL> urls = new ArrayList<URL>();
    if (classpath != null) {
        for (String urlStr : classpath) {
            URL url;//from  ww w  .  j a  v  a 2 s  . co  m
            try {
                url = new URL(urlStr);
                urls.add(url);
            } catch (MalformedURLException e) {
                log.warn("Classpath <" + urlStr + "> not an url! Ignoring...");
            }

        }
    }
    Object instance = null;

    ClassLoader loader = new URLClassLoader((URL[]) urls.toArray(new URL[0]),
            OneCMDBClassLoader.class.getClassLoader());
    try {
        Class clazz = loader.loadClass(className);
        instance = clazz.newInstance();
    } catch (ClassNotFoundException e) {
        log.error("Class <" + className + "> not found!", e);
    } catch (InstantiationException e) {
        log.error("Class <" + className + "> not instanciable!", e);
    } catch (IllegalAccessException e) {
        log.error("Class <" + className + "> not accessiable!", e);
    }

    return (instance);
}

From source file:com.ms.commons.test.classloader.util.AntxconfigUtil.java

@SuppressWarnings("deprecation")
public static void changeClassLoader() throws Exception {
    File tmp = new File(TEMP_DIR);
    URLClassLoader cl = new URLClassLoader(new URL[] { tmp.toURL() },
            Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(cl);
}