Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

In this page you can find the example usage for java.lang ClassLoader loadClass.

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:io.github.arven.flare.boot.TomcatContainer.java

private static void addCallersAsEjbModule(final ClassLoader loader, final AppModule app,
        final String... additionalCallers) {
    final Set<String> callers = new HashSet<String>(NewLoaderLogic.callers(Filters
            .classes(TomcatContainer.class.getName(), "org.apache.openejb.maven.plugins.TomEEEmbeddedMojo")));
    if (additionalCallers != null && additionalCallers.length > 0) {
        callers.addAll(asList(additionalCallers));
    }/*from www. ja v a  2  s .c o m*/
    if (callers.isEmpty()) {
        return;
    }
    final EjbJar ejbJar = new EjbJar();
    final OpenejbJar openejbJar = new OpenejbJar();

    for (final String caller : callers) {
        try {
            if (!AnnotationDeployer.isInstantiable(loader.loadClass(caller))) {
                continue;
            }
        } catch (final ClassNotFoundException e) {
            continue;
        }

        final String name = caller.replace("$", "_");
        final ManagedBean bean = ejbJar
                .addEnterpriseBean(new ManagedBean(caller.replace("$", "_"), caller, true));
        bean.localBean();
        bean.setTransactionType(TransactionType.BEAN);
        final EjbDeployment ejbDeployment = openejbJar.addEjbDeployment(bean);
        ejbDeployment.setDeploymentId(name);
    }
    final EjbModule ejbModule = new EjbModule(ejbJar, openejbJar);
    ejbModule.setBeans(new Beans());
    app.getEjbModules().add(ejbModule);
}

From source file:ch.entwine.weblounge.common.impl.content.page.PageTemplateImpl.java

/**
 * Initializes this page template from an XML node that was generated using
 * {@link #toXml()}.//from www.  j  av  a2s  .c  om
 * 
 * @param node
 *          the page template node
 * @param xpath
 *          the xpath processor
 * @throws IllegalStateException
 *           if the page template cannot be parsed
 * @see #fromXml(Node)
 * @see #toXml()
 */
public static PageTemplate fromXml(Node node, XPath xpath) throws IllegalStateException {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // Identifier
    String id = XPathHelper.valueOf(node, "@id", xpath);
    if (id == null)
        throw new IllegalStateException("Missing id in page template definition");

    // Class
    String className = XPathHelper.valueOf(node, "class", xpath);

    // Renderer url
    URL rendererUrl = null;
    String rendererUrlNode = XPathHelper.valueOf(node, "ns:renderer", xpath);
    if (rendererUrlNode == null)
        throw new IllegalStateException("Missing renderer in page template definition");
    try {
        rendererUrl = new URL(rendererUrlNode);
    } catch (MalformedURLException e) {
        throw new IllegalStateException(
                "Malformed renderer url in page template definition: " + rendererUrlNode);
    }

    // Create the page template
    PageTemplate template = null;
    if (className != null) {
        Class<? extends PageTemplate> c = null;
        try {
            c = (Class<? extends PageTemplate>) classLoader.loadClass(className);
            template = c.newInstance();
            template.setIdentifier(id);
            template.setRenderer(rendererUrl);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(
                    "Implementation " + className + " for page template '" + id + "' not found", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(
                    "Error instantiating impelementation " + className + " for page template '" + id + "'", e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for page template '" + id + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for page template '" + id + "'", t);
        }
    } else {
        template = new PageTemplateImpl(id, rendererUrl);
    }

    // Composeable
    template.setComposeable(ConfigurationUtils.isTrue(XPathHelper.valueOf(node, "@composeable", xpath)));

    // Default
    template.setDefault(ConfigurationUtils.isTrue(XPathHelper.valueOf(node, "@default", xpath)));

    // Stage
    String stage = XPathHelper.valueOf(node, "ns:stage", xpath);
    if (stage != null)
        template.setStage(stage);

    // Layout
    String layout = XPathHelper.valueOf(node, "ns:layout", xpath);
    if (layout != null)
        template.setDefaultLayout(layout);

    // client revalidation time
    String recheck = XPathHelper.valueOf(node, "ns:recheck", xpath);
    if (recheck != null) {
        try {
            template.setClientRevalidationTime(ConfigurationUtils.parseDuration(recheck));
        } catch (NumberFormatException e) {
            throw new IllegalStateException(
                    "The page template revalidation time is malformed: '" + recheck + "'");
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "The page template revalidation time is malformed: '" + recheck + "'");
        }
    }

    // cache expiration time
    String valid = XPathHelper.valueOf(node, "ns:valid", xpath);
    if (valid != null) {
        try {
            template.setCacheExpirationTime(ConfigurationUtils.parseDuration(valid));
        } catch (NumberFormatException e) {
            throw new IllegalStateException("The page template valid time is malformed: '" + valid + "'", e);
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException("The page template valid time is malformed: '" + valid + "'", e);
        }
    }

    // name
    String name = XPathHelper.valueOf(node, "m:name", xpath);
    template.setName(name);

    // scripts
    NodeList scripts = XPathHelper.selectList(node, "ns:includes/ns:script", xpath);
    for (int i = 0; i < scripts.getLength(); i++) {
        template.addHTMLHeader(ScriptImpl.fromXml(scripts.item(i)));
    }

    // links
    NodeList links = XPathHelper.selectList(node, "ns:includes/ns:link", xpath);
    for (int i = 0; i < links.getLength(); i++) {
        template.addHTMLHeader(LinkImpl.fromXml(links.item(i)));
    }

    return template;
}

From source file:com.quinsoft.zeidon.standardoe.TaskImpl.java

@SuppressWarnings("unchecked")
@Override//w  w w  .j  a  va2s.  c  o m
public synchronized ScalaHelper getScalaHelper() {
    if (scalaHelper == null) {
        String className = "com.quinsoft.zeidon.scala.ScalaHelperImpl";
        ClassLoader classLoader = getObjectEngine().getClassLoader(className);
        Class<ScalaHelper> operationsClass;
        try {
            operationsClass = (Class<ScalaHelper>) classLoader.loadClass(className);
            scalaHelper = operationsClass.newInstance();
            scalaHelper.setClassLoader(classLoader);
        } catch (ClassNotFoundException e) {
            throw new ZeidonException("Couldn't load %s.  Do you have zeidon-scala in your classpath?",
                    className);
        } catch (Exception e) {
            throw ZeidonException.wrapException(e);
        }
    }

    return scalaHelper;
}

From source file:com.greenpepper.runner.ant.AntTaskRunner.java

private Object createRunner(ClassLoader classLoader, CommandLineRunnerMirror.CommandLineLogger logger,
        CommandLineRunnerMirror.CommandLineMonitor monitor) {
    try {/*from   ww w.  jav a  2s  . c om*/
        Class<?> runnerClass = classLoader.loadClass("com.greenpepper.runner.ant.CommandLineRunnerMirrorImpl");

        if (runnerClass.getClassLoader() != classLoader) {
            throw new BuildException("Overdelegating loader", getLocation());
        }

        Constructor runnerCtr = runnerClass.getConstructor(Object.class, Object.class);

        return runnerCtr.newInstance(logger, monitor);
    } catch (Exception ex) {
        throw new BuildException(ex, getLocation());
    }
}

From source file:com.quinsoft.zeidon.objectdefinition.ViewAttribute.java

private DerivedOper loadDerivedOperation(Task view) {
    DerivedOper derivedOperation = null;

    try {/*from www  . ja  v a2 s .  c o  m*/
        ObjectEngine oe = view.getObjectEngine();
        ClassLoader classLoader = oe.getClassLoader(derivedOperationClassName);
        Class<? extends Object> operationsClass;
        operationsClass = classLoader.loadClass(derivedOperationClassName);

        Constructor<? extends Object> constructor;
        try {
            // First try getting a constructor that uses a view.  Most derived operations are defined
            // in the Object code so it must be created with a view.
            constructor = operationsClass.getConstructor(CONSTRUCTOR_ARG_TYPES1);
        } catch (NoSuchMethodException e) {
            // We couldn't find a constructor that takes a view, so try to find one that
            // takes a TaskQualification.  A derived attribute could be defined in a global
            // operations class, which uses a TaskQual for the constructor.
            try {
                constructor = operationsClass.getConstructor(CONSTRUCTOR_ARG_TYPES2);
            } catch (NoSuchMethodException e2) {
                // One more time: try with no arguments.
                constructor = operationsClass.getConstructor();
            }
        }

        // First try to find a method with the exact name of derivedOperationName.  This is the
        // old-style method as generated by VML.
        Method method;
        try {
            method = operationsClass.getMethod(derivedOperationName, ARGUMENT_TYPES1);
            derivedOperation = new DerivedOper(constructor, method);
        } catch (NoSuchMethodException e) {
            // Try with the JOE-specific parameter list.
            method = operationsClass.getMethod(derivedOperationName, ARGUMENT_TYPES2);

            // If we get here then it worked!
            derivedOperation = new NewDerivedOper(constructor, method);
        }

        return derivedOperation;
    } catch (Exception e) {
        throw ZeidonException.prependMessage(e, "Error loading Derived operation '%s.%s' for %s",
                derivedOperationClassName, derivedOperationName, toString());
    }
}

From source file:org.bytesoft.bytetcc.supports.spring.CompensableContextPostProcessor.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    String targetBeanId = null;//from www.j ava  2  s .  co  m
    List<BeanDefinition> beanDefList = new ArrayList<BeanDefinition>();
    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        Class<?> beanClass = null;
        try {
            beanClass = cl.loadClass(beanClassName);
        } catch (Exception ex) {
            logger.debug("Cannot load class {}, beanId= {}!", beanClassName, beanName, ex);
            continue;
        }

        if (CompensableContextAware.class.isAssignableFrom(beanClass)) {
            beanDefList.add(beanDef);
        }

        if (CompensableContext.class.isAssignableFrom(beanClass)) {
            if (targetBeanId == null) {
                targetBeanId = beanName;
            } else {
                throw new FatalBeanException("Duplicated compensable-context defined.");
            }
        }

    }

    for (int i = 0; targetBeanId != null && i < beanDefList.size(); i++) {
        BeanDefinition beanDef = beanDefList.get(i);
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        RuntimeBeanReference beanRef = new RuntimeBeanReference(targetBeanId);
        mpv.addPropertyValue(CompensableContextAware.COMPENSABLE_CONTEXT_FIELD_NAME, beanRef);
    }

}

From source file:ws.argo.Responder.Responder.java

private ArrayList<ProbeHandlerPluginIntf> loadHandlerPlugins(ArrayList<AppHandlerConfig> configs)
        throws IOException, ClassNotFoundException {

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    ArrayList<ProbeHandlerPluginIntf> handlers = new ArrayList<ProbeHandlerPluginIntf>();

    for (AppHandlerConfig appConfig : configs) {

        Class<?> handlerClass = cl.loadClass(appConfig.classname);
        ProbeHandlerPluginIntf handler;//www.j  av a 2  s.co m

        try {
            handler = (ProbeHandlerPluginIntf) handlerClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            LOGGER.warning(
                    "Could not create an instance of the configured handler class - " + appConfig.classname);
            LOGGER.warning("Using default handler");
            LOGGER.fine("The issue was:");
            LOGGER.fine(e.getMessage());
            handler = new ConfigFileProbeHandlerPluginImpl();
        }

        handler.setPropertiesFilename(appConfig.configFilename);

        handlers.add(handler);
    }

    return handlers;

}

From source file:com.mulesoft.jockey.maven.GenerateMojo.java

protected void populateScripts(File distDir) throws MojoFailureException, MojoExecutionException {
    File binDir = new File(distDir, "/bin");
    binDir.mkdir();// w w w .j a va  2 s . com

    File scriptsDirFile = new File(project.getBasedir(), scriptsSourceDirectory);

    if (!scriptsDirFile.exists()) {
        throw new MojoFailureException("Could not find scripts directory " + scriptsSourceDirectory);
    }

    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader cl = getCompileClassLoader();
        Thread.currentThread().setContextClassLoader(cl);

        copyGroovyScripts(scriptsDirFile.listFiles(), binDir);

        // There has to be a better way to do this, but I am clearly not thinking of it right now
        Class crCls = cl.loadClass(CommandRunner.class.getName());
        Class absCmdCls = cl.loadClass(AbstractCommand.class.getName());
        Class commandWrapperCls = cl.loadClass(GroovyCommandWrapper.class.getName());
        Class generateCmdsCls = cl.loadClass(GenerateCommands.class.getName());

        Object runner = crCls.newInstance();
        Object wrapper = commandWrapperCls.getConstructor(Class.class).newInstance(generateCmdsCls);
        crCls.getMethod("addCommand", absCmdCls).invoke(runner, wrapper);
        crCls.getMethod("run", String[].class).invoke(runner,
                new Object[] { new String[] { "generate-commands", "-p", binDir.getAbsolutePath() } });

        POSIX posix = POSIXFactory.getPOSIX(getHandler(), true);

        for (File file : binDir.listFiles()) {
            posix.chmod(file.getAbsolutePath(), EXECUTABLE_MODE);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Could not copy script files to distribution.", e);
    } catch (Exception e) {
        throw new MojoExecutionException("Could not generate scripts", e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldCL);
    }
}

From source file:com.amalto.core.jobox.JobContainer.java

/**
 * <p>//from  w w w .j av  a2s .c om
 * Loads the job main class using a specific class loader (isolated from caller class loader).
 * </p>
 * <p>
 * Please note that this method also changes {@link Thread#getContextClassLoader()} <b>during</b> load, if
 * caller's class loader isn't already the job class loader (as returned by {@link #getJobClassLoader(JobInfo)}).
 * </p>
 * <p>
 * Once this method is completed {@link Thread#getContextClassLoader()} is equals to the caller's class loader.
 * </p>
 *
 * @param jobInfo A {@link JobInfo} instance.
 * @return The entry point class for job execution.
 */
public Class getJobClass(JobInfo jobInfo) {
    ClassLoader previousCallLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader jobClassLoader = getJobClassLoader(jobInfo);

    try {
        if (previousCallLoader != jobClassLoader) { // TMDM-1733: Change context class loader during job class load.
            Thread.currentThread().setContextClassLoader(jobClassLoader);
        }
        return jobClassLoader.loadClass(jobInfo.getMainClass());
    } catch (ClassNotFoundException e) {
        LOGGER.error("Could not find class '" + jobInfo.getMainClass() + "'", e);
        return null;
    } finally {
        if (previousCallLoader != jobClassLoader) {
            Thread.currentThread().setContextClassLoader(previousCallLoader);
        }
    }
}

From source file:com.legstar.protobuf.cobol.ProtoCobol.java

/**
 * From Google's org.waveprotocol.pst.PstFileDescriptor.
 * /*from w  ww.  jav a  2s. co m*/
 * @param baseDir the base directory where compiled java binaries are
 *            located
 * @param path the path to the java binary file relative to the base
 *            directory
 * @return the java class loaded
 * @throws ProtoCobolException if class cannot be loaded
 */
protected Class<?> loadClass(File baseDir, String path) throws ProtoCobolException {
    try {
        ClassLoader classLoader = new URLClassLoader(new URL[] { baseDir.toURI().toURL() });
        return classLoader.loadClass(getBinaryName(path));
    } catch (Exception e) {
        throw new ProtoCobolException(e);
    }
}