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:org.jsonschema2pojo.integration.AdditionalPropertiesIT.java

@Test
public void additionalPropertiesOfBooleanTypeOnly()
        throws SecurityException, NoSuchMethodException, ClassNotFoundException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/additionalPropertiesPrimitiveBoolean.json", "com.example",
            config("usePrimitives", true, "generateBuilders", true));

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesPrimitiveBoolean");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

    assertThat(((ParameterizedType) getter.getGenericReturnType()).getActualTypeArguments()[1],
            is(equalTo((Type) Boolean.class)));

    // setter with these types should exist:
    classWithNoAdditionalProperties.getMethod("setAdditionalProperty", String.class, boolean.class);

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            boolean.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

From source file:com.netflix.nicobar.core.module.ScriptModuleLoaderTest.java

/**
 * Test that the compiler plugin classloader is available through the ScriptModuleLoader.
 * @throws IOException//www .ja va2s . c  o  m
 * @throws ModuleLoadException
 * @throws ClassNotFoundException
 */
@Test
public void testCompilerPluginClassloader() throws ModuleLoadException, IOException, ClassNotFoundException {
    ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder()
            .addPluginSpec(new ScriptCompilerPluginSpec.Builder("mockPlugin")
                    .withPluginClassName(MockScriptCompilerPlugin.class.getName()).build())
            .build();
    ClassLoader classLoader = moduleLoader.getCompilerPluginClassLoader("mockPlugin");
    assertNotNull(classLoader);
    Class<?> pluginClass = classLoader.loadClass(MockScriptCompilerPlugin.class.getName());
    assertNotNull(pluginClass);
}

From source file:com.xpn.xwiki.plugin.ldap.XWikiLDAPConfig.java

/**
 * @param context the XWiki context.//from  ww w  .j  a  v a  2  s  .  com
 * @return the secure provider to use for SSL.
 * @throws XWikiLDAPException error when trying to instantiate secure provider.
 * @since 1.5M1
 */
public Provider getSecureProvider(XWikiContext context) throws XWikiLDAPException {
    Provider provider;

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    String className = getLDAPParam("ldap_ssl.secure_provider", DEFAULT_SECUREPROVIDER, context);

    try {
        provider = (java.security.Provider) cl.loadClass(className).newInstance();
    } catch (Exception e) {
        throw new XWikiLDAPException("Fail to load secure ssl provider.", e);
    }

    return provider;
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void initUtils() throws Exception {
    ClassLoader classLoader = getToolsClassLoader();

    Class<?> clazz = classLoader.loadClass("com.liferay.portal.util.EntityResolver");

    EntityResolver entityResolver = (EntityResolver) clazz.newInstance();

    SAXReaderUtil.setEntityResolver(entityResolver);
}

From source file:io.smartspaces.workbench.project.test.JunitTestClassDetector.java

/**
 * Test the specified class for any test methods.
 *
 * <p>/*from   w  w  w .j  a v  a2 s. c  o  m*/
 * Superclasses are searched.
 *
 * @param packagePrefix
 *          the prefix package path
 * @param classFileName
 *          the classname for the potential test class
 * @param classLoader
 *          the classloader for test classes
 * @param testClasses
 *          the growing list of classes to test
 * @param log
 *          the logger to use
 */
private void testClassForTests(StringBuilder packagePrefix, String classFileName, ClassLoader classLoader,
        List<Class<?>> testClasses, Log log) {
    StringBuilder fullyQualifiedClassName = new StringBuilder(packagePrefix);
    if (fullyQualifiedClassName.length() != 0) {
        fullyQualifiedClassName.append(CLASS_PACKAGE_COMPONENT_SEPARATOR);
    }
    fullyQualifiedClassName.append(classFileName.substring(0, classFileName.indexOf(FILE_EXTENSION_SEPARATOR)));
    try {
        Class<?> potentialTestClass = classLoader.loadClass(fullyQualifiedClassName.toString());

        if (isTestClass(potentialTestClass, log)) {
            testClasses.add(potentialTestClass);
        }
    } catch (Exception e) {
        log.error(String.format("Could not test class %s for test methods", fullyQualifiedClassName));
    }
}

From source file:ch.entwine.weblounge.common.impl.site.ActionSupport.java

/**
 * Initializes this action from an XML node that was generated using
 * {@link #toXml()}./* www  .j av a2s.co m*/
 * 
 * @param config
 *          the action node
 * @param xpath
 *          xpath processor to use
 * @throws IllegalStateException
 *           if the configuration cannot be parsed
 * @see #toXml()
 */
@SuppressWarnings("unchecked")
public static Action fromXml(Node config, XPath xpath) throws IllegalStateException {

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

    // identifier
    String identifier = XPathHelper.valueOf(config, "@id", xpath);
    if (identifier == null)
        throw new IllegalStateException("Unable to create actions without identifier");

    // class
    Action action = null;
    String className = XPathHelper.valueOf(config, "m:class", xpath);
    if (className != null) {
        try {
            Class<? extends Action> c = (Class<? extends Action>) classLoader.loadClass(className);
            action = c.newInstance();
            action.setIdentifier(identifier);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(
                    "Implementation " + className + " for action handler '" + identifier + "' not found", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException("Error instantiating impelementation " + className
                    + " for action handler '" + identifier + "'", e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for action handler '" + identifier + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for action handler '" + identifier + "'",
                    t);
        }
    } else {
        action = new HTMLActionSupport();
        action.setIdentifier(identifier);
    }

    // mountpoint
    String mountpoint = XPathHelper.valueOf(config, "m:mountpoint", xpath);
    if (mountpoint == null)
        throw new IllegalStateException("Action '" + identifier + " has no mountpoint");
    action.setPath(mountpoint);
    // TODO: handle /, /*

    // content url
    String targetUrl = XPathHelper.valueOf(config, "m:page", xpath);
    if (StringUtils.isNotBlank(targetUrl)) {
        if (!(action instanceof HTMLActionSupport))
            throw new IllegalStateException("Target page configuration for '" + action.getIdentifier()
                    + "' requires subclassing HTMLActionSupport");
        ((HTMLActionSupport) action).setPageURI(targetUrl);
    }

    // template
    String targetTemplate = XPathHelper.valueOf(config, "m:template", xpath);
    if (StringUtils.isNotBlank(targetTemplate)) {
        if (!(action instanceof HTMLActionSupport))
            throw new IllegalStateException("Target template configuration for '" + action.getIdentifier()
                    + "' requires subclassing HTMLActionSupport");
        ((HTMLActionSupport) action).setDefaultTemplate(targetTemplate);
    }

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

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

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

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

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

    // options
    Node optionsNode = XPathHelper.select(config, "m:options", xpath);
    OptionsHelper.fromXml(optionsNode, action, xpath);

    return action;
}

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

@SuppressWarnings("unchecked")
private int executeScalaConstraint(View view, ObjectConstraintType type) {
    String className = "com.quinsoft.zeidon.scala.ScalaHelperImpl";
    ObjectEngine oe = view.getObjectEngine();
    ClassLoader classLoader = oe.getClassLoader(className);
    Class<ScalaHelper> operationsClass;
    try {/*from ww  w.j  av  a2s.  c o  m*/
        operationsClass = (Class<ScalaHelper>) classLoader.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new ZeidonException("Couldn't load %s.  Do you have zeidon-scala in your classpath?", className);
    }

    try {
        ScalaHelper instance = operationsClass.newInstance();
        return instance.executeObjectConstraint(view, type, classLoader);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java

/** Create MBean for Object.
 * Attempts to create an MBean for the object by searching the
 * package and class name space.  For example an object of the
 * type <PRE>//  w  w w  .j  a v  a2  s .c  o  m
 *   class com.acme.MyClass extends com.acme.util.BaseClass
 * </PRE>
 * Then this method would look for the following
 * classes:<UL>
 * <LI>com.acme.MyClassMBean
 * <LI>com.acme.jmx.MyClassMBean
 * <LI>com.acme.util.BaseClassMBean
 * <LI>com.acme.util.jmx.BaseClassMBean
 * </UL>
 * @param o The object
 * @return A new instance of an MBean for the object or null.
 */
public static ModelMBean mbeanFor(Object o) {
    try {
        Class oClass = o.getClass();
        ClassLoader loader = oClass.getClassLoader();

        ModelMBean mbean = null;
        boolean jmx = false;
        Class[] interfaces = null;
        int i = 0;

        while (mbean == null && oClass != null) {
            Class focus = interfaces == null ? oClass : interfaces[i];
            String pName = focus.getPackage().getName();
            String cName = focus.getName().substring(pName.length() + 1);
            String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean";

            try {
                Class mClass = loader.loadClass(mName);
                if (log.isTraceEnabled())
                    log.trace("mbeanFor " + o + " mClass=" + mClass);
                mbean = (ModelMBean) mClass.newInstance();
                mbean.setManagedResource(o, "objectReference");
                if (log.isDebugEnabled())
                    log.debug("mbeanFor " + o + " is " + mbean);
                return mbean;
            } catch (ClassNotFoundException e) {
                if (e.toString().endsWith("MBean")) {
                    if (log.isTraceEnabled())
                        log.trace(e.toString());
                } else
                    log.warn(LogSupport.EXCEPTION, e);
            } catch (Error e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            } catch (Exception e) {
                log.warn(LogSupport.EXCEPTION, e);
                mbean = null;
            }

            if (jmx) {
                if (interfaces != null) {
                    i++;
                    if (i >= interfaces.length) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                } else {
                    interfaces = oClass.getInterfaces();
                    i = 0;
                    if (interfaces == null || interfaces.length == 0) {
                        interfaces = null;
                        oClass = oClass.getSuperclass();
                    }
                }
            }
            jmx = !jmx;
        }
    } catch (Exception e) {
        LogSupport.ignore(log, e);
    }
    return null;
}

From source file:net.sf.joost.trax.TransformerFactoryImpl.java

private Class loadClass(String className) throws TransformerConfigurationException {
    try {/*from   w ww. j a  va 2s . c  o  m*/
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null) {
            try {
                return loader.loadClass(className);
            } catch (Exception ex) {
                return Class.forName(className);
            }
        } else {
            return Class.forName(className);
        }
    } catch (Exception e) {
        throw new TransformerConfigurationException("Failed to load " + className, e);
    }
}

From source file:org.bytesoft.bytejta.supports.spring.TransactionBeanFactoryPostProcessor.java

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

    String beanFactoryBeanId = null;
    List<BeanDefinition> beanFactoryAwareBeanIdList = 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 {/*from   w  w  w .j a  v  a 2s  .c  o m*/
            beanClass = cl.loadClass(beanClassName);
        } catch (Exception ex) {
            continue;
        }

        if (TransactionBeanFactoryAware.class.isAssignableFrom(beanClass)) {
            beanFactoryAwareBeanIdList.add(beanDef);
        }

        if (TransactionBeanFactory.class.isAssignableFrom(beanClass)) {
            if (beanFactoryBeanId == null) {
                beanFactoryBeanId = beanName;
            } else {
                throw new FatalBeanException("Duplicated transaction-bean-factory defined.");
            }
        }

    }

    for (int i = 0; beanFactoryBeanId != null && i < beanFactoryAwareBeanIdList.size(); i++) {
        BeanDefinition beanDef = beanFactoryAwareBeanIdList.get(i);
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        RuntimeBeanReference beanRef = new RuntimeBeanReference(beanFactoryBeanId);
        mpv.addPropertyValue(TransactionBeanFactoryAware.BEAN_FACTORY_FIELD_NAME, beanRef);
    }

}