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:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

/**
 * Add new elements to the classpath./*from  w  ww .  j  a v  a2s . c  o m*/
 *
 * @param newPaths
 *          Array of classpath elements
 */
public static ClassLoader addToClassPath(ClassLoader cloader, String[] newPaths) throws Exception {
    URLClassLoader loader = (URLClassLoader) cloader;
    List<URL> curPath = Arrays.asList(loader.getURLs());
    ArrayList<URL> newPath = new ArrayList<URL>(curPath.size());

    // get a list with the current classpath components
    for (URL onePath : curPath) {
        newPath.add(onePath);
    }
    curPath = newPath;

    for (String onestr : newPaths) {
        URL oneurl = urlFromPathString(onestr);
        if (oneurl != null && !curPath.contains(oneurl)) {
            curPath.add(oneurl);
        }
    }

    return new URLClassLoader(curPath.toArray(new URL[0]), loader);
}

From source file:io.hops.hopsworks.common.util.Settings.java

private void addPathToConfig(Configuration conf, File path) {
    // chain-in a new classloader
    URL fileUrl = null;/*  ww  w  .  ja v  a2 s  .c  o m*/
    try {
        fileUrl = path.toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException("Erroneous config file path", e);
    }
    URL[] urls = { fileUrl };
    ClassLoader cl = new URLClassLoader(urls, conf.getClassLoader());
    conf.setClassLoader(cl);
}

From source file:org.infoglue.deliver.invokers.ComponentBasedHTMLPageInvoker.java

/**
 * This method renders the base component and all it's children.
 *//*from  w  w  w . ja v a2s  . c  om*/

private String preProcessComponent(InfoGlueComponent component, TemplateController templateController,
        Integer repositoryId, Integer siteNodeId, Integer languageId, Integer contentId,
        Integer metainfoContentId, List sortedPageComponents) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("\n\n**** Pre processing component ****");
        logger.debug("id: " + component.getId());
        logger.debug("contentId: " + component.getContentId());
        logger.debug("name: " + component.getName());
        logger.debug("slotName: " + component.getSlotName());
    }

    StringBuilder decoratedComponent = new StringBuilder();

    templateController.setComponentLogic(new ComponentLogic(templateController, component));
    templateController.getDeliveryContext().getUsageListeners()
            .add(templateController.getComponentLogic().getComponentDeliveryContext());

    try {
        String componentString = getComponentPreProcessingTemplateString(templateController,
                component.getContentId(), component);
        if (logger.isDebugEnabled())
            logger.debug("componentString:" + componentString);

        String componentModelClassName = getComponentModelClassName(templateController,
                component.getContentId(), component);
        if (logger.isDebugEnabled())
            logger.debug("componentModelClassName:" + componentModelClassName);

        if (componentModelClassName != null && !componentModelClassName.equals("")) {
            templateController.getDeliveryContext().getUsageListeners()
                    .add(templateController.getComponentLogic().getComponentDeliveryContext());
            try {
                Timer t = new Timer();
                DigitalAssetVO asset = templateController.getAsset(component.getContentId(), "jar");

                String path = templateController.getAssetFilePathForAssetWithId(asset.getId());
                if (logger.isDebugEnabled())
                    logger.debug("path: " + path);
                if (path != null && !path.equals("")) {
                    try {
                        File jarFile = new File(path);
                        if (logger.isDebugEnabled())
                            logger.debug("jarFile:" + jarFile.exists());
                        URL url = jarFile.toURL();
                        URLClassLoader child = new URLClassLoader(new URL[] { url },
                                this.getClass().getClassLoader());

                        Class c = child.loadClass(componentModelClassName);
                        boolean isOk = ComponentModel.class.isAssignableFrom(c);
                        if (logger.isDebugEnabled())
                            logger.debug("isOk:" + isOk + " for " + componentModelClassName);
                        if (isOk) {
                            if (logger.isDebugEnabled())
                                logger.debug("Calling prepare on '" + componentModelClassName + "'");
                            ComponentModel componentModel = (ComponentModel) c.newInstance();
                            componentModel.prepare(componentString, templateController, component.getModel());
                        }
                    } catch (Exception e) {
                        logger.error(
                                "Failed loading custom class from asset JAR. Trying normal class loader. Error:"
                                        + e.getMessage());
                        ComponentModel componentModel = (ComponentModel) Thread.currentThread()
                                .getContextClassLoader().loadClass(componentModelClassName).newInstance();
                        componentModel.prepare(componentString, templateController, component.getModel());
                    }
                } else {
                    ComponentModel componentModel = (ComponentModel) Thread.currentThread()
                            .getContextClassLoader().loadClass(componentModelClassName).newInstance();
                    componentModel.prepare(componentString, templateController, component.getModel());
                }
                if (logger.isDebugEnabled())
                    t.printElapsedTime("Invoking custome class took");
            } catch (Exception e) {
                logger.error("The component '" + component.getName() + "' stated that class: "
                        + componentModelClassName
                        + " should be used as model. An exception was thrown when it was invoked: "
                        + e.getMessage(), e);
            }
            templateController.getDeliveryContext().getUsageListeners()
                    .remove(templateController.getComponentLogic().getComponentDeliveryContext());
        }

        if (componentString != null && !componentString.equals("")) {
            templateController.getDeliveryContext().getUsageListeners()
                    .add(templateController.getComponentLogic().getComponentDeliveryContext());

            Map context = getDefaultContext();
            context.put("templateLogic", templateController);
            context.put("model", component.getModel());
            StringWriter cacheString = new StringWriter();
            PrintWriter cachedStream = new PrintWriter(cacheString);
            //Timer t = new Timer();
            new VelocityTemplateProcessor().renderTemplate(context, cachedStream, componentString, false,
                    component, " - PreTemplate");
            //t.printElapsedTime("Rendering of " + component.getName() + " took ");
            componentString = cacheString.toString();

            if (logger.isDebugEnabled())
                logger.debug("componentString:" + componentString);

            templateController.getDeliveryContext().getUsageListeners()
                    .remove(templateController.getComponentLogic().getComponentDeliveryContext());
        }

        String templateComponentString = getComponentString(templateController, component.getContentId(),
                component);
        if (logger.isDebugEnabled())
            logger.debug("templateComponentString:" + templateComponentString);

        int offset = 0;
        int slotStartIndex = templateComponentString.indexOf("<ig:slot", offset);
        int slotStopIndex = 0;

        while (slotStartIndex > -1) {
            slotStopIndex = templateComponentString.indexOf("</ig:slot>", slotStartIndex);

            String slot = templateComponentString.substring(slotStartIndex, slotStopIndex + 10);
            String id = slot.substring(slot.indexOf("id") + 4, slot.indexOf("\"", slot.indexOf("id") + 4));

            boolean inherit = true;
            int inheritIndex = slot.indexOf("inherit");
            if (inheritIndex > -1) {
                String inheritString = slot.substring(inheritIndex + 9, slot.indexOf("\"", inheritIndex + 9));
                inherit = Boolean.parseBoolean(inheritString);
            }

            List subComponents = getInheritedComponents(templateController.getDatabase(), templateController,
                    component, templateController.getSiteNodeId(), id, inherit);
            Iterator subComponentsIterator = subComponents.iterator();
            while (subComponentsIterator.hasNext()) {
                InfoGlueComponent subComponent = (InfoGlueComponent) subComponentsIterator.next();
                if (subComponent.getIsInherited()) {
                    String subComponentString = preProcessComponent(subComponent, templateController,
                            repositoryId, siteNodeId, languageId, contentId, metainfoContentId,
                            sortedPageComponents);
                }
            }

            offset = slotStopIndex;
            slotStartIndex = templateComponentString.indexOf("<ig:slot", offset);
        }
    } catch (Exception e) {
        logger.warn(
                "An component with either an empty template or with no template in the sitelanguages was found:"
                        + e.getMessage(),
                e);
    }

    templateController.getDeliveryContext().getUsageListeners()
            .remove(templateController.getComponentLogic().getComponentDeliveryContext());

    if (logger.isDebugEnabled())
        logger.debug("decoratedComponent:" + decoratedComponent.toString());

    return decoratedComponent.toString();
}

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

/**
 * @param classPath a not null String list of files where resource will be look up.
 * @param resource  a not null ressource to find in the class path.
 * @return the resource from the given classpath or null if not found
 * @see ClassLoader#getResource(String)/*from   ww w  . ja  v a 2 s  . c  om*/
 * @since 2.6
 */
private URL getResource(final List<String> classPath, final String resource) {
    List<URL> urls = new ArrayList<URL>(classPath.size());
    for (String filename : classPath) {
        try {
            urls.add(new File(filename).toURL());
        } catch (MalformedURLException e) {
            getLog().error("MalformedURLException: " + e.getMessage());
        }
    }

    ClassLoader javadocClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null);

    return javadocClassLoader.getResource(resource);
}

From source file:org.kchine.r.server.DirectJNI.java

static private void scanMapping() {
    if (!_initHasBeenCalled) {
        _initHasBeenCalled = true;/*ww w .java  2s  . c o  m*/

        if (DirectJNI.class.getClassLoader().getResource("maps/rjbmaps.xml") != null) {
            System.out.println("<1> " + DirectJNI.class.getClassLoader().getResource("maps/rjbmaps.xml"));
            try {
                init(DirectJNI.class.getClassLoader());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;

        } else if (System.getProperty("java.rmi.server.codebase") != null) {
            ClassLoader codebaseClassLoader = new URLClassLoader(
                    PoolUtils.getURLS(System.getProperty("java.rmi.server.codebase")),
                    DirectJNI.class.getClassLoader());
            if (codebaseClassLoader.getResource("maps/rjbmaps.xml") != null) {
                System.out.println("<2> " + codebaseClassLoader.getResource("maps/rjbmaps.xml"));
                try {
                    init(codebaseClassLoader);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        } else {
            System.out.println("!! No mapping found");
        }
    }
}

From source file:org.kchine.r.server.DirectJNI.java

public static void generateMaps(URL jarUrl, boolean rawClasses) {

    try {// w  w w .j  a  v  a 2  s  .  c  o m

        _mappingClassLoader = new URLClassLoader(new URL[] { jarUrl }, DirectJNI.class.getClassLoader());
        Vector<String> list = new Vector<String>();
        JarURLConnection jarConnection = (JarURLConnection) jarUrl.openConnection();
        JarFile jarfile = jarConnection.getJarFile();
        Enumeration<JarEntry> enu = jarfile.entries();
        while (enu.hasMoreElements()) {
            String entry = enu.nextElement().toString();
            if (entry.endsWith(".class"))
                list.add(entry.replace('/', '.').substring(0, entry.length() - ".class".length()));
        }

        log.info(list);

        for (int i = 0; i < list.size(); ++i) {
            String className = list.elementAt(i);
            if (className.startsWith("org.kchine.r.packages.")
                    && !className.startsWith("org.kchine.r.packages.rservices")) {
                Class<?> c_ = _mappingClassLoader.loadClass(className);

                if (c_.getSuperclass() != null && c_.getSuperclass().equals(RObject.class)
                        && !Modifier.isAbstract(c_.getModifiers())) {

                    if (c_.equals(RLogical.class) || c_.equals(RInteger.class) || c_.equals(RNumeric.class)
                            || c_.equals(RComplex.class) || c_.equals(RChar.class) || c_.equals(RMatrix.class)
                            || c_.equals(RArray.class) || c_.equals(RList.class) || c_.equals(RDataFrame.class)
                            || c_.equals(RFactor.class) || c_.equals(REnvironment.class)
                            || c_.equals(RVector.class) || c_.equals(RUnknown.class)) {
                    } else {
                        String rclass = DirectJNI.getRClassForBean(jarfile, className);
                        _s4BeansHash.put(className, c_);
                        _s4BeansMapping.put(rclass, className);
                        _s4BeansMappingRevert.put(className, rclass);
                    }

                } else if ((rawClasses && c_.getSuperclass() != null && c_.getSuperclass().equals(Object.class))
                        || (!rawClasses && RPackage.class.isAssignableFrom(c_) && (c_.isInterface()))) {

                    String shortClassName = className.substring(className.lastIndexOf('.') + 1);
                    _packageNames.add(shortClassName);

                    Vector<Class<?>> v = _rPackageInterfacesHash.get(className);
                    if (v == null) {
                        v = new Vector<Class<?>>();
                        _rPackageInterfacesHash.put(className, v);
                    }
                    v.add(c_);

                } else {
                    String nameWithoutPackage = className.substring(className.lastIndexOf('.') + 1);
                    if (nameWithoutPackage.indexOf("Factory") != -1
                            && c_.getMethod("setData", new Class[] { RObject.class }) != null) {
                        // if
                        // (DirectJNI._factoriesMapping.get(nameWithoutPackage
                        // )
                        // != null) throw new Exception("Factories Names
                        // Conflict : two " + nameWithoutPackage);
                        _factoriesMapping.put(nameWithoutPackage, className);
                        if (Modifier.isAbstract(c_.getModifiers()))
                            _abstractFactories.add(className);
                    }
                }
            }
        }

        // log.info("s4Beans:" +s4Beans);
        log.info("rPackageInterfaces:" + _packageNames);
        log.info("s4Beans MAP :" + _s4BeansMapping);
        log.info("s4Beans Revert MAP :" + _s4BeansMappingRevert);
        log.info("factories :" + _factoriesMapping);
        log.info("r package interface hash :" + _rPackageInterfacesHash);

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

}