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:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Loads strategy class and creates instance by calling constructor.
    @param strategyText contains full class name followed by
    parameter list for constructor.  Constructor parameters may be
    int, double, boolean, String.  Constructor parameters are parsed by
    splitting on commas and trimming whitespace.
    <pre>/*w  w w. ja v a2 s  . co  m*/
    mypkg.MyStrategy(12, -345.67, true, false, Alpha Strategy)
    </pre>
**/
protected TradingStrategy loadStrategy(String strategyText)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        ExceptionInInitializerError, InstantiationException, InvocationTargetException {
    Pattern strategyPattern = // matches full.class.Name(args...)
            Pattern.compile("^([A-Za-z](?:[A-Za-z0-9_.]*))\\s*[(](.*)[)]$");
    Matcher matcher = strategyPattern.matcher(strategyText);
    if (!matcher.matches())
        throw new IllegalArgumentException(
                "Bad Strategy: " + strategyText + "\n" + "Expected: full.class.name(-123.45, 67, true, false)");

    final String strategyClassName = matcher.group(1).trim();
    String parameters[] = matcher.group(2).split(",");

    // clean parameters
    for (int i = 0; i < parameters.length; i++)
        parameters[i] = parameters[i].trim();
    if (parameters.length == 1 && parameters[0].length() == 0)
        parameters = new String[] {}; // 0 parameters

    // build classpath
    String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator);
    ArrayList<URL> classPathURLs = new ArrayList<URL>();
    for (int i = 0; i < classPath.length; i++) {
        String path = classPath[i];
        if (".".equals(path))
            path = System.getProperty("user.dir");
        path = path.replace(File.separatorChar, '/');
        if (!path.endsWith("/") && !path.endsWith(".jar"))
            path += "/";
        try {
            classPathURLs.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            // bad directory in class path, skip
        }
    }
    final String strategyPackagePrefix = strategyClassName.substring(0,
            Math.max(0, strategyClassName.lastIndexOf('.') + 1));
    ClassLoader loader = new URLClassLoader(classPathURLs.toArray(new URL[] {}),
            this.getClass().getClassLoader()) {
        /** Don't search parent for classes with strategyPackagePrefix.
            Exception: interface TradingStrategy **/
        protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
            Class<?> loadedClass = findLoadedClass(className);
            if (loadedClass != null)
                return loadedClass;
            if (!className.startsWith(strategyPackagePrefix)
                    || className.equals(TradingStrategy.class.getName())) {
                loadedClass = this.getParent().loadClass(className);
                if (loadedClass != null)
                    return loadedClass;
            }
            loadedClass = findClass(className);
            if (loadedClass != null) {
                if (resolve)
                    resolveClass(loadedClass);
                return loadedClass;
            } else
                throw new ClassNotFoundException(className);
        }
    };
    // load class.  Throws ClassNotFoundException if not found.
    Class<?> strategyClass = loader.loadClass(strategyClassName);

    // Make sure it is a TradingStrategy.
    if (!TradingStrategy.class.isAssignableFrom(strategyClass))
        throw new ClassCastException(strategyClass.getName() + " does not implement TradingStrategy");

    // Find constructor compatible with parameters
    Constructor[] constructors = strategyClass.getConstructors();
    findConstructor: for (Constructor constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length != parameters.length)
            continue;
        Object[] values = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            if (boolean.class.equals(parameterTypes[i])) {
                String parameter = parameters[i].toLowerCase();
                if ("false".equals(parameter))
                    values[i] = Boolean.FALSE;
                else if ("true".equals(parameter))
                    values[i] = Boolean.TRUE;
                else
                    continue findConstructor;
            } else if (int.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Integer(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (double.class.equals(parameterTypes[i])) {
                try {
                    values[i] = new Double(parameters[i]);
                } catch (NumberFormatException e) {
                    continue findConstructor;
                }
            } else if (String.class.equals(parameterTypes[i])) {
                values[i] = parameters[i];
            } else
                continue findConstructor; // unsupported parameter type, skip
        }
        // all values matched types, so create instance
        return (TradingStrategy) constructor.newInstance(values);
    }
    throw new NoSuchMethodException(strategyText);
}

From source file:org.apache.struts2.jasper.JspC.java

/**
 * Initializes the classloader as/if needed for the given
 * compilation context./*from   w w w.  j a va 2  s. c o m*/
 *
 * @param clctxt The compilation context
 * @throws IOException If an error occurs
 */
private void initClassLoader(JspCompilationContext clctxt) throws IOException {

    classPath = getClassPath();

    ClassLoader jspcLoader = getClass().getClassLoader();
    // Turn the classPath into URLs
    ArrayList urls = new ArrayList();
    StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator);
    while (tokenizer.hasMoreTokens()) {
        String path = tokenizer.nextToken();
        try {
            File libFile = new File(path);
            urls.add(libFile.toURL());
        } catch (IOException ioe) {
            // Failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak uot
            throw new RuntimeException(ioe.toString());
        }
    }

    //TODO: add .tld files to the URLCLassLoader

    URL urlsA[] = new URL[urls.size()];
    urls.toArray(urlsA);
    loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());

}

From source file:org.apache.maven.plugin.javadoc.AbstractFixJavadocMojo.java

/**
 * @return the classLoader for the given project using lazy instantiation.
 * @throws MojoExecutionException if any
 *///from  w  w  w. j  a v  a  2 s .  c o m
private ClassLoader getProjectClassLoader() throws MojoExecutionException {
    if (projectClassLoader == null) {
        List<String> classPath;
        try {
            classPath = getCompileClasspathElements(project);
        } catch (DependencyResolutionRequiredException e) {
            throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
        }

        List<URL> urls = new ArrayList<URL>(classPath.size());
        for (String filename : classPath) {
            try {
                urls.add(new File(filename).toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException("MalformedURLException: " + e.getMessage(), e);
            }
        }

        projectClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
    }

    return projectClassLoader;
}

From source file:org.kepler.ddp.director.DDPEngine.java

/** Get a list of jars required for director to start. 
 *  It also set _classLoader value based on the jars.
 *///from  w w  w .jav  a  2 s  .c  om
protected List<URI> _getJarList() throws IllegalActionException {
    final List<URI> jarPaths = new LinkedList<URI>();
    final List<File> jarsWithRelativePaths = new LinkedList<File>();

    for (String additionalJar : _additionalJars) {
        jarsWithRelativePaths.add(new File(additionalJar));
    }

    // get the jars in the director's includeJars parameter
    String includeJarsStr = _director.includeJars.stringValue();
    if (includeJarsStr != null && !includeJarsStr.isEmpty()) {
        for (String jarPath : includeJarsStr.split(",")) {
            File jarFile = new File(jarPath);
            // see if jar is an absolute path
            if (jarFile.isAbsolute()) {
                if (!jarFile.exists() || !jarFile.canRead()) {
                    throw new IllegalActionException(_director,
                            "Jar does not exist or cannot be read: " + jarFile);
                }
                // jars with absolute paths are added directly
                System.out.println("Adding jar: " + jarFile.getAbsolutePath());
                jarPaths.add(jarFile.toURI());
            } else {
                jarsWithRelativePaths.add(jarFile);
            }
        }
    }

    // add the module jars, e.g., actors.jar, ptolemy.jar, etc.
    // also add any jars in includeJars with a relative path - these jars
    // are assumed to be module/lib/jar.
    final ModuleTree moduleTree = ModuleTree.instance();
    for (Module module : moduleTree) {

        final File moduleJar = module.getTargetJar();

        // add the module jar if it exists.
        // some modules, e.g., outreach, do not have jars.
        if (moduleJar.exists()) {
            jarPaths.add(moduleJar.toURI());
        }

        final List<File> moduleJars = module.getJars();
        for (File jar : moduleJars) {
            // include kepler-tasks.jar since we need classes
            // in org.kepler.build to initialize kepler in the
            // stub. see StubUtilities.initializeKepler()
            if (jar.getName().equals("kepler-tasks.jar")) {
                //System.out.println("adding jar " + jar);
                jarPaths.add(jar.toURI());
            } else if (jar.getName().matches("^log4j.*jar$") || //add log4j jar since it is used for display-redirect function in DDP.
                    jar.getName().equals("ant.jar")) {
                jarPaths.add(jar.toURI());
            } else if (!jarsWithRelativePaths.isEmpty()) {
                for (File jarFile : jarsWithRelativePaths) {
                    if (jar.getName().equals(jarFile.getName())) {
                        System.out.println("Adding jar in module " + module.getName() + ": " + jar);
                        jarPaths.add(jar.toURI());
                    }
                }
            }
        }
    }

    // add any jars specified by the actors.
    final List<DDPPatternActor> actors = _container.entityList(DDPPatternActor.class);
    for (DDPPatternActor actor : actors) {
        final String jarsStr = actor.getJars();
        if (!jarsStr.isEmpty()) {
            final String[] jars = jarsStr.split(",");
            for (String jar : jars) {
                final File jarFile = new File(jar);
                if (!jarFile.exists() || !jarFile.canRead()) {
                    throw new IllegalActionException(actor,
                            "Jar does not exist or cannot be read: " + jarFile.getAbsolutePath());
                }
                System.out.println("Adding jar for " + actor.getFullName() + ": " + jarFile.getAbsolutePath());
                jarPaths.add(jarFile.toURI());
            }
        }
    }

    URL[] jarArray;
    try {
        List<URL> jarURLs = new LinkedList<URL>();
        for (URI jarURI : jarPaths) {
            jarURLs.add(jarURI.toURL());
        }

        jarArray = jarURLs.toArray(new URL[jarURLs.size()]);

        if (jarArray != null && jarArray.length > 0) {
            _classLoader = new URLClassLoader(jarArray, Thread.currentThread().getContextClassLoader());
            Thread.currentThread().setContextClassLoader(_classLoader);
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new IllegalActionException(_director, e.getMessage());
    }

    return jarPaths;
}

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private ClassLoader createClassLoader() throws MojoExecutionException {
    URL[] classpath = createClasspath();

    return new URLClassLoader(classpath, ClassLoader.getSystemClassLoader());
}

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

@Override
public void fileCreated(FileChangeEvent arg0) throws Exception {
    try {//w  w  w  .  j a v  a 2  s . c om
        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:org.kchine.r.server.http.frontend.CommandServlet.java

protected void doAny(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = null;/*from   w  w w  . ja  v a2s. c o  m*/
    Object result = null;

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}

From source file:org.apache.jasper.JspC.java

private void initClassLoader(JspCompilationContext clctxt) throws IOException {

    classPath = getClassPath();// w  w w  .j av a 2 s  . co m

    ClassLoader jspcLoader = getClass().getClassLoader();
    if (jspcLoader instanceof AntClassLoader) {
        classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath();
    }

    // Turn the classPath into URLs
    ArrayList urls = new ArrayList();
    StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator);
    while (tokenizer.hasMoreTokens()) {
        String path = tokenizer.nextToken();
        try {
            File libFile = new File(path);
            urls.add(libFile.toURL());
        } catch (IOException ioe) {
            // Failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak uot
            throw new RuntimeException(ioe.toString());
        }
    }

    File webappBase = new File(uriRoot);
    if (webappBase.exists()) {
        File classes = new File(webappBase, "/WEB-INF/classes");
        try {
            if (classes.exists()) {
                classPath = classPath + File.pathSeparator + classes.getCanonicalPath();
                urls.add(classes.getCanonicalFile().toURL());
            }
        } catch (IOException ioe) {
            // failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak out
            throw new RuntimeException(ioe.toString());
        }
        File lib = new File(webappBase, "/WEB-INF/lib");
        if (lib.exists() && lib.isDirectory()) {
            String[] libs = lib.list();
            for (int i = 0; i < libs.length; i++) {
                if (libs[i].length() < 5)
                    continue;
                String ext = libs[i].substring(libs[i].length() - 4);
                if (!".jar".equalsIgnoreCase(ext)) {
                    if (".tld".equalsIgnoreCase(ext)) {
                        log.warn("TLD files should not be placed in " + "/WEB-INF/lib");
                    }
                    continue;
                }
                try {
                    File libFile = new File(lib, libs[i]);
                    classPath = classPath + File.pathSeparator + libFile.getCanonicalPath();
                    urls.add(libFile.getCanonicalFile().toURL());
                } catch (IOException ioe) {
                    // failing a toCanonicalPath on a file that
                    // exists() should be a JVM regression test,
                    // therefore we have permission to freak out
                    throw new RuntimeException(ioe.toString());
                }
            }
        }
    }

    // What is this ??
    urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL());

    URL urlsA[] = new URL[urls.size()];
    urls.toArray(urlsA);
    loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(loader);
}

From source file:org.eclipse.wb.internal.core.parser.AbstractParseFactory.java

/**
 * @return the composite {@link ClassLoader} based on given main {@link ClassLoader} with addition
 *         of {@link BundleClassLoader}'s and {@link IByteCodeProcessor}'s.
 *///w  w w  .j a  va  2  s .co m
protected static CompositeClassLoader createCompositeLoader(ClassLoader mainClassLoader, String toolkitId)
        throws Exception {
    List<IConfigurationElement> toolkitElements = DescriptionHelper.getToolkitElements(toolkitId);
    CompositeClassLoader compositeClassLoader = new CompositeClassLoader();
    // add project class loader
    compositeClassLoader.add(mainClassLoader, null);
    // add processors for "classPath-byteCode-processor"
    if (mainClassLoader instanceof ProjectClassLoader) {
        ProjectClassLoader projectClassLoader = (ProjectClassLoader) mainClassLoader;
        for (IConfigurationElement toolkitElement : toolkitElements) {
            IConfigurationElement[] contributorElements = toolkitElement
                    .getChildren("classPath-byteCode-processor");
            for (IConfigurationElement contributorElement : contributorElements) {
                IByteCodeProcessor processor = (IByteCodeProcessor) contributorElement
                        .createExecutableExtension("processor");
                projectClassLoader.add(processor);
            }
        }
    }
    // add class loaders for "classLoader-library" contributions
    for (IConfigurationElement toolkitElement : toolkitElements) {
        IConfigurationElement[] contributorElements = toolkitElement.getChildren("classLoader-library");
        if (contributorElements.length != 0) {
            URL[] urls = new URL[contributorElements.length];
            for (int i = 0; i < contributorElements.length; i++) {
                IConfigurationElement contributorElement = contributorElements[i];
                Bundle bundle = getExistingBundle(contributorElement);
                // prepare URL for JAR
                String jarPath = contributorElement.getAttribute("jar");
                URL jarEntry = bundle.getEntry(jarPath);
                Assert.isNotNull(jarEntry, "Unable to find %s in %s", jarPath, bundle.getSymbolicName());
                urls[i] = FileLocator.toFileURL(jarEntry);
            }
            // add ClassLoader with all libraries
            compositeClassLoader.add(new URLClassLoader(urls, mainClassLoader), null);
        }
    }
    // return final ClassLoader
    return compositeClassLoader;
}

From source file:azkaban.webapp.AzkabanWebServer.java

private static Map<String, TriggerPlugin> loadTriggerPlugins(Context root, String pluginPath,
        AzkabanWebServer azkabanWebApp) {
    File triggerPluginPath = new File(pluginPath);
    if (!triggerPluginPath.exists()) {
        return new HashMap<String, TriggerPlugin>();
    }/*from   www.  ja  v  a 2 s .c  om*/

    Map<String, TriggerPlugin> installedTriggerPlugins = new HashMap<String, TriggerPlugin>();
    ClassLoader parentLoader = AzkabanWebServer.class.getClassLoader();
    File[] pluginDirs = triggerPluginPath.listFiles();
    ArrayList<String> jarPaths = new ArrayList<String>();
    for (File pluginDir : pluginDirs) {
        if (!pluginDir.exists()) {
            logger.error("Error! Trigger plugin path " + pluginDir.getPath() + " doesn't exist.");
            continue;
        }

        if (!pluginDir.isDirectory()) {
            logger.error("The plugin path " + pluginDir + " is not a directory.");
            continue;
        }

        // Load the conf directory
        File propertiesDir = new File(pluginDir, "conf");
        Props pluginProps = null;
        if (propertiesDir.exists() && propertiesDir.isDirectory()) {
            File propertiesFile = new File(propertiesDir, "plugin.properties");
            File propertiesOverrideFile = new File(propertiesDir, "override.properties");

            if (propertiesFile.exists()) {
                if (propertiesOverrideFile.exists()) {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile);
                } else {
                    pluginProps = PropsUtils.loadProps(null, propertiesFile);
                }
            } else {
                logger.error("Plugin conf file " + propertiesFile + " not found.");
                continue;
            }
        } else {
            logger.error("Plugin conf path " + propertiesDir + " not found.");
            continue;
        }

        String pluginName = pluginProps.getString("trigger.name");
        List<String> extLibClasspath = pluginProps.getStringList("trigger.external.classpaths",
                (List<String>) null);

        String pluginClass = pluginProps.getString("trigger.class");
        if (pluginClass == null) {
            logger.error("Trigger class is not set.");
        } else {
            logger.error("Plugin class " + pluginClass);
        }

        URLClassLoader urlClassLoader = null;
        File libDir = new File(pluginDir, "lib");
        if (libDir.exists() && libDir.isDirectory()) {
            File[] files = libDir.listFiles();

            ArrayList<URL> urls = new ArrayList<URL>();
            for (int i = 0; i < files.length; ++i) {
                try {
                    URL url = files[i].toURI().toURL();
                    urls.add(url);
                } catch (MalformedURLException e) {
                    logger.error(e);
                }
            }
            if (extLibClasspath != null) {
                for (String extLib : extLibClasspath) {
                    try {
                        File file = new File(pluginDir, extLib);
                        URL url = file.toURI().toURL();
                        urls.add(url);
                    } catch (MalformedURLException e) {
                        logger.error(e);
                    }
                }
            }

            urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader);
        } else {
            logger.error("Library path " + propertiesDir + " not found.");
            continue;
        }

        Class<?> triggerClass = null;
        try {
            triggerClass = urlClassLoader.loadClass(pluginClass);
        } catch (ClassNotFoundException e) {
            logger.error("Class " + pluginClass + " not found.");
            continue;
        }

        String source = FileIOUtils.getSourcePathFromClass(triggerClass);
        logger.info("Source jar " + source);
        jarPaths.add("jar:file:" + source);

        Constructor<?> constructor = null;
        try {
            constructor = triggerClass.getConstructor(String.class, Props.class, Context.class,
                    AzkabanWebServer.class);
        } catch (NoSuchMethodException e) {
            logger.error("Constructor not found in " + pluginClass);
            continue;
        }

        Object obj = null;
        try {
            obj = constructor.newInstance(pluginName, pluginProps, root, azkabanWebApp);
        } catch (Exception e) {
            logger.error(e);
        }

        if (!(obj instanceof TriggerPlugin)) {
            logger.error("The object is not an TriggerPlugin");
            continue;
        }

        TriggerPlugin plugin = (TriggerPlugin) obj;
        installedTriggerPlugins.put(pluginName, plugin);
    }

    // Velocity needs the jar resource paths to be set.
    String jarResourcePath = StringUtils.join(jarPaths, ", ");
    logger.info("Setting jar resource path " + jarResourcePath);
    VelocityEngine ve = azkabanWebApp.getVelocityEngine();
    ve.addProperty("jar.resource.loader.path", jarResourcePath);

    return installedTriggerPlugins;
}