Example usage for java.net URLClassLoader close

List of usage examples for java.net URLClassLoader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this URLClassLoader, so that it can no longer be used to load new classes or resources that are defined by this loader.

Usage

From source file:net.sf.jabref.gui.openoffice.OOBibBase.java

private XDesktop simpleBootstrap(String pathToExecutable) throws Exception {

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    if (loader instanceof URLClassLoader) {
        URLClassLoader cl = (URLClassLoader) loader;
        Class<URLClassLoader> sysclass = URLClassLoader.class;
        try {/*from  ww w.j  ava 2 s. c o  m*/
            Method method = sysclass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(cl, new File(pathToExecutable).toURI().toURL());
        } catch (SecurityException | NoSuchMethodException | MalformedURLException t) {
            LOGGER.error("Error, could not add URL to system classloader", t);
            cl.close();
            throw new IOException("Error, could not add URL to system classloader", t);
        }
    } else {
        LOGGER.error("Error occured, URLClassLoader expected but " + loader.getClass()
                + " received. Could not continue.");
    }

    //Get the office component context:
    XComponentContext xContext = Bootstrap.bootstrap();
    //Get the office service manager:
    XMultiComponentFactory xServiceManager = xContext.getServiceManager();
    //Create the desktop, which is the root frame of the
    //hierarchy of frames that contain viewable components:
    Object desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
    XDesktop xD = UnoRuntime.queryInterface(XDesktop.class, desktop);

    UnoRuntime.queryInterface(XComponentLoader.class, desktop);

    return xD;

}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Runs tests in testLocation on the source code given in the parameter.
 *
 * @param submissionBinariesLocation/*from ww w  .  ja  va2s.  c o m*/
 *            The path to the compiled binaries of the submission.
 *
 * @return the {@link TestOutput} containing the test results.
 *
 * @throws ClassNotFoundException
 *             Throws if the loaded Classes are not found
 * @throws IOException
 *             Throws if the sourceCodeLocation is malformed or the
 *             {@link URLClassLoader} can't be closed.
 */
@Override
public TestOutput testSubmission(Path submissionBinariesLocation) throws ClassNotFoundException, IOException {

    // if there are no tests create and empty TestOutput with didTest false
    if ((testLocation == null) || testLocation.toString().isEmpty()) {
        return new TestOutput(null, false);
    } else {

        List<Result> results = new LinkedList<>();

        // create the classloader
        URL submissionURL = submissionBinariesLocation.toUri().toURL();
        URL testsURL = testLocation.toUri().toURL();

        // URLClassLoader loader =
        // new URLClassLoader(new URL[] { submissionURL, testsURL });

        URLClassLoader loader = new URLClassLoader(new URL[] { testsURL, submissionURL });

        // iterate submission source code files and load the .class files.
        /*
         * We need to iterate all files in a directory and thus are using
         * the apache commons io utility FileUtils.listFiles. This needs a)
         * the directory, and b) a file filter for which we also use the
         * one supplied by apache commons io.
         */

        Path submissionBin = submissionBinariesLocation.toAbsolutePath();
        List<Path> exploreDirectory = exploreDirectory(submissionBin, ExplorationType.CLASSFILES);
        for (Path path : exploreDirectory) {

            String quallifiedName = getQuallifiedName(submissionBin, path);
            loader.loadClass(quallifiedName);
        }

        // iterate tests, load them and run them
        Path testLoc = testLocation.toAbsolutePath();
        List<Path> exploreDirectory2 = exploreDirectory(testLoc, ExplorationType.SOURCEFILES);
        for (Path path : exploreDirectory2) {

            String unitTestName = getQuallifiedNameFromSource(path);
            try {
                Class<?> testerClass = loader.loadClass(unitTestName);
                Result runClasses = JUnitCore.runClasses(testerClass);
                results.add(runClasses);
            } catch (Throwable e) {
                LOGGER.severe("can't load class: " + unitTestName);
                LOGGER.severe(e.getMessage());
            }
        }

        loader.close();
        // creates new TestOutput from results and returns it
        return new TestOutput(results, true);
    }
}

From source file:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java

@SuppressWarnings({ "unchecked" })
String invokeEvaluateFunctionFromJar(String expression, String[] fieldNames, Object[] values) {
    LOGGER.debug("Evaluating expression from jar");
    String output = null;/*from  w  w  w.j  a v a2  s.  c  om*/
    Object[] returnObj;
    expression = ValidateExpressionToolButton.getExpressionText(expression);
    URLClassLoader child = null;
    try {
        returnObj = ValidateExpressionToolButton.getBuildPathForMethodInvocation();
        List<URL> urlList = (List<URL>) returnObj[0];
        String userFunctionsPropertyFileName = (String) returnObj[2];
        child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]));
        Thread.currentThread().setContextClassLoader(child);
        Class<?> class1 = Class.forName(
                ValidateExpressionToolButton.HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child);
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getParameterTypes().length == 4
                    && StringUtils.equals(method.getName(), EVALUATE_METHOD_OF_EXPRESSION_JAR)) {
                method.getDeclaringClass().getClassLoader();
                output = String.valueOf(
                        method.invoke(null, expression, userFunctionsPropertyFileName, fieldNames, values));
                break;
            }
        }
    } catch (JavaModelException | MalformedURLException | ClassNotFoundException | IllegalAccessException
            | IllegalArgumentException exception) {
        evaluateDialog.showError(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION);
        LOGGER.error(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION, exception);
    } catch (InvocationTargetException | RuntimeException exception) {
        if (exception.getCause().getCause() != null) {
            if (StringUtils.equals(exception.getCause().getCause().getClass().getSimpleName(),
                    TARGET_ERROR_EXCEPTION_CLASS)) {
                evaluateDialog.showError(getTargetException(exception.getCause().getCause().toString()));
            } else
                evaluateDialog.showError(exception.getCause().getCause().getMessage());
        } else
            evaluateDialog.showError(exception.getCause().getMessage());
        LOGGER.debug("Invalid Expression....", exception);
    } finally {
        if (child != null) {
            try {
                child.close();
            } catch (IOException ioException) {
                LOGGER.error("Error occurred while closing classloader", ioException);
            }
        }
    }
    return output;
}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java

/**
 * Run the matrix model./*ww  w.  j a  va  2 s .co  m*/
 *
 * @return the double
 */
public Double runMatrixModel() {

    // Create a results holder.
    Double results = Double.NaN;

    // Attempt to run the model.
    try {

        // Setup a temporary class loader.
        URL[] urls = new URL[] { new File(Util.TEMP_DIR).toURI().toURL() };
        URLClassLoader classLoader = new URLClassLoader(urls, null, null);

        // Attempt to load the compiled file.
        @SuppressWarnings("rawtypes")
        Constructor constructor = classLoader
                .loadClass(MatrixModel.PACKAGE_NAME + "." + MatrixModel.CONCRETE_CLASS_NAME)
                .getDeclaredConstructor(double.class);
        constructor.setAccessible(true);
        Object object = constructor.newInstance(this.stepSize);

        // Call "matrixFormulation.step(steps)".
        Method method = object.getClass().getSuperclass().getMethod("step", int.class);
        method.invoke(object, this.stepCount);

        // Call matrixFormulation.calculateFitnessValue();
        method = object.getClass().getSuperclass().getMethod("calculateFitnessValue");
        results = (Double) method.invoke(object);

        // Clear the given class loader, which should not be
        // a child of another class loader.
        object = null;
        method = null;
        classLoader.close();
        ResourceBundle.clearCache(classLoader);
        classLoader = null;
        Introspector.flushCaches();
        System.runFinalization();
        System.gc();

        // Catch exceptions.
    } catch (Exception e) {

        // Return the default result.
        results = Double.NaN;

    }

    // Return the results.
    return results;

}

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

@Override
public void fileChanged(FileChangeEvent arg0) throws Exception {
    try {/*  www.j a v  a  2s.  co  m*/
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            fileDeleted(arg0);
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (cls.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : cls) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), mdbContexts);
                MDBContext mdbContextOld;
                for (Class<?> mdbBean : clsMessageDriven) {
                    String classwithpackage = mdbBean.getName();
                    System.out.println("class package" + classwithpackage);
                    classwithpackage = classwithpackage.replace("/", ".");
                    System.out.println("classList:" + classwithpackage.replace("/", "."));
                    try {
                        if (!classwithpackage.contains("$")) {
                            //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            //System.out.println();
                            if (!mdbBean.isInterface()) {
                                Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                if (classServicesAnnot != null) {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
            System.out.println(baseFile.getName().getURI() + " Deployed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void fileCreated(FileChangeEvent arg0) throws Exception {
    try {/*  w w  w  .  ja v  a  2 s. co  m*/
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            System.out.println(baseFile.getName().getURI());
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (clsStateless.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : clsStateless) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), mdbContexts);
                MDBContext mdbContextOld;
                for (Class<?> mdbBean : clsMessageDriven) {
                    String classwithpackage = mdbBean.getName();
                    System.out.println("class package" + classwithpackage);
                    classwithpackage = classwithpackage.replace("/", ".");
                    System.out.println("classList:" + classwithpackage.replace("/", "."));
                    try {
                        if (!classwithpackage.contains("$")) {
                            //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            //System.out.println();
                            if (!mdbBean.isInterface()) {
                                Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                if (classServicesAnnot != null) {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
        }
        System.out.println(baseFile.getName().getURI() + " Deployed");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;/*from www.j  a  v a  2  s.c  om*/
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                mdbContexts);
                        MDBContext mdbContextOld;
                        for (Class<?> mdbBean : clsMessageDriven) {
                            String classwithpackage = mdbBean.getName();
                            System.out.println("class package" + classwithpackage);
                            classwithpackage = classwithpackage.replace("/", ".");
                            System.out.println("classList:" + classwithpackage.replace("/", "."));
                            try {
                                if (!classwithpackage.contains("$")) {
                                    //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                    //System.out.println();
                                    if (!mdbBean.isInterface()) {
                                        Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                        if (classServicesAnnot != null) {
                                            for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                                if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                                    MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                                    ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                            .activationConfig();
                                                    mdbContext = new MDBContext();
                                                    mdbContext.setMdbName(messageDrivenAnnot.name());
                                                    for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                        if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATIONTYPE)) {
                                                            mdbContext.setDestinationType(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATION)) {
                                                            mdbContext.setDestination(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                            mdbContext.setAcknowledgeMode(
                                                                    activationConfigProperty.propertyValue());
                                                        }
                                                    }
                                                    if (mdbContext.getDestinationType()
                                                            .equals(Queue.class.getName())) {
                                                        mdbContextOld = null;
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld != null
                                                                    && mdbContext.getDestination().equals(
                                                                            mdbContextOld.getDestination())) {
                                                                throw new Exception(
                                                                        "Only one MDB can listen to destination:"
                                                                                + mdbContextOld
                                                                                        .getDestination());
                                                            }
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Queue queue = (Queue) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(queue);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Queue=" + queue);
                                                    } else if (mdbContext.getDestinationType()
                                                            .equals(Topic.class.getName())) {
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld.getConsumer() != null)
                                                                mdbContextOld.getConsumer()
                                                                        .setMessageListener(null);
                                                            if (mdbContextOld.getSession() != null)
                                                                mdbContextOld.getSession().close();
                                                            if (mdbContextOld.getConnection() != null)
                                                                mdbContextOld.getConnection().close();
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Topic topic = (Topic) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(topic);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Topic=" + topic);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java

/**
 * Attempts to load and register functions from remote function registry.
 * First checks if there is no missing jars.
 * If yes, enters synchronized block to prevent other loading the same jars.
 * Again re-checks if there are no missing jars in case someone has already loaded them (double-check lock).
 * If there are still missing jars, first copies jars to local udf area and prepares {@link JarScan} for each jar.
 * Jar registration timestamp represented in milliseconds is used as suffix.
 * Then registers all jars at the same time. Returns true when finished.
 * In case if any errors during jars coping or registration, logs errors and proceeds.
 *
 * If no missing jars are found, checks current local registry version.
 * Returns false if versions match, true otherwise.
 *
 * @param version local function registry version
 * @return true if new jars were registered or local function registry version is different, false otherwise
 */// w  w w.j av  a2s. c  o m
public boolean loadRemoteFunctions(long version) {
    List<String> missingJars = getMissingJars(remoteFunctionRegistry, localFunctionRegistry);
    if (!missingJars.isEmpty()) {
        synchronized (this) {
            missingJars = getMissingJars(remoteFunctionRegistry, localFunctionRegistry);
            List<JarScan> jars = Lists.newArrayList();
            for (String jarName : missingJars) {
                Path binary = null;
                Path source = null;
                URLClassLoader classLoader = null;
                try {
                    binary = copyJarToLocal(jarName, remoteFunctionRegistry);
                    source = copyJarToLocal(JarUtil.getSourceName(jarName), remoteFunctionRegistry);
                    URL[] urls = { binary.toUri().toURL(), source.toUri().toURL() };
                    classLoader = new URLClassLoader(urls);
                    ScanResult scanResult = scan(classLoader, binary, urls);
                    localFunctionRegistry.validate(jarName, scanResult);
                    jars.add(new JarScan(jarName, scanResult, classLoader));
                } catch (Exception e) {
                    deleteQuietlyLocalJar(binary);
                    deleteQuietlyLocalJar(source);
                    if (classLoader != null) {
                        try {
                            classLoader.close();
                        } catch (Exception ex) {
                            logger.warn("Problem during closing class loader for {}", jarName, e);
                        }
                    }
                    logger.error("Problem during remote functions load from {}", jarName, e);
                }
            }
            if (!jars.isEmpty()) {
                localFunctionRegistry.register(jars);
                return true;
            }
        }
    }
    return version != localFunctionRegistry.getVersion();
}

From source file:org.deventropy.shared.utils.ClassUtilTest.java

@Test
public void testCallerClassloader() throws Exception {

    // Write the source file - see
    // http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class
    final File sourceFolder = workingFolder.newFolder();
    // Prepare source somehow.
    final String source = "package test; public class Test { }";
    // Save source in .java file.
    final File sourceFile = new File(sourceFolder, "test/Test.java");
    sourceFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(sourceFile, source, "UTF-8");

    // Compile the file
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
    compiler.getTask(null, fileManager, null, null, null, compilationUnit).call();

    // Create the class loader
    final URLClassLoader urlcl = new URLClassLoader(new URL[] { sourceFolder.toURI().toURL() });
    final Class<?> loadedClass = urlcl.loadClass("test.Test");

    final ContextClNullingObject testObj = new ContextClNullingObject(loadedClass.newInstance());
    final Thread worker = new Thread(testObj);
    worker.start();//from w  ww  .ja  v a2  s .c o  m
    worker.join();

    assertEquals(urlcl, testObj.getReturnedCl());

    urlcl.close();
}

From source file:org.dkpro.tc.core.util.SaveModelUtils.java

public static List<ExternalResourceDescription> loadExternalResourceDescriptionOfFeatures(File tcModelLocation,
        UimaContext aContext) throws Exception {
    List<ExternalResourceDescription> erd = new ArrayList<>();

    File classFile = new File(tcModelLocation + "/" + Constants.MODEL_FEATURE_CLASS_FOLDER);
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { classFile.toURI().toURL() });

    File file = new File(tcModelLocation, MODEL_FEATURE_EXTRACTOR_CONFIGURATION);
    for (String l : FileUtils.readLines(file)) {
        String[] split = l.split("\t");
        String name = split[0];//from  w w w .j a  va2s .  c  o m
        Object[] parameters = getParameters(split);

        Class<? extends Resource> feClass = urlClassLoader.loadClass(name).asSubclass(Resource.class);

        List<Object> idRemovedParameters = filterId(parameters);
        String id = getId(parameters);

        idRemovedParameters = addModelPathAsPrefixIfParameterIsExistingFile(idRemovedParameters,
                tcModelLocation.getAbsolutePath());

        TcFeature feature = TcFeatureFactory.create(id, feClass, idRemovedParameters.toArray());
        ExternalResourceDescription exRes = feature.getActualValue();

        // Skip feature extractors that are not dependent on meta collectors
        if (!MetaDependent.class.isAssignableFrom(feClass)) {
            erd.add(exRes);
            continue;
        }

        Map<String, String> overrides = loadOverrides(tcModelLocation, META_COLLECTOR_OVERRIDE);
        configureOverrides(tcModelLocation, exRes, overrides);
        overrides = loadOverrides(tcModelLocation, META_EXTRACTOR_OVERRIDE);
        configureOverrides(tcModelLocation, exRes, overrides);

        erd.add(exRes);
    }

    urlClassLoader.close();

    return erd;
}