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.gravitee.management.idp.core.plugin.IdentityProviderPluginHandler.java

@Override
public void handle(Plugin plugin) {
    try {//from w ww.j a  va  2  s. c  o m
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin,
                this.getClass().getClassLoader());

        final Class<?> identityProviderClass = classloader.loadClass(plugin.clazz());
        LOGGER.info("Register a new identity provider plugin: {} [{}]", plugin.id(), plugin.clazz());

        Assert.isAssignable(IdentityProvider.class, identityProviderClass);

        IdentityProvider identityIdentityProvider = createInstance(
                (Class<IdentityProvider>) identityProviderClass);
        identityProviderManager.register(new IdentityProviderDefinition(identityIdentityProvider, plugin));
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while create identity provider instance", iae);
    }
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Send a mail message using a JNDI resource.<br>
 * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the
 * MailSessionFactory offered to payloads, making it accessible also to the engine.
 * //from  w ww.j av  a  2 s  .co  m
 * @param to
 * @param subject
 * @param body
 * @param mailSessionJndiAlias
 * @throws MessagingException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias)
        throws MessagingException {
    jqmlogger.debug("sending mail to " + to + " - subject is " + subject);
    ClassLoader extLoader = getExtClassLoader();
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Object mailSession = null;

    try {
        mailSession = InitialContext.doLookup(mailSessionJndiAlias);
    } catch (NamingException e) {
        throw new MessagingException("could not find mail session description", e);
    }

    try {
        Thread.currentThread().setContextClassLoader(extLoader);
        Class transportZ = extLoader.loadClass("javax.mail.Transport");
        Class sessionZ = extLoader.loadClass("javax.mail.Session");
        Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage");
        Class messageZ = extLoader.loadClass("javax.mail.Message");
        Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType");
        Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession);

        mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg,
                recipientTypeZ.getField("TO").get(null), to);
        mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject);
        mimeMessageZ.getMethod("setText", String.class).invoke(msg, body);

        transportZ.getMethod("send", messageZ).invoke(null, msg);
        jqmlogger.trace("Mail was sent");
    } catch (Exception e) {
        throw new MessagingException("an exception occurred during mail sending", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:flashgateway.io.ASObject.java

/**
 * @return this method may return null//from  www . j  av a  2  s  .  c  om
 * 
 * @see #setType(String)
 * @see #getType()
 *  
 */
public Object instantiate() {
    Object ret;
    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass(type);
        ret = clazz.newInstance();
    } catch (Exception e) {
        ret = null;
    }
    return ret;
}

From source file:org.jsonschema2pojo.integration.config.PrefixSuffixIT.java

@Test
public void customClassSuffix() throws ClassNotFoundException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("classNameSuffix", "Dao"));
    resultsClassLoader.loadClass("com.example.PrimitivePropertiesDao");
}

From source file:org.jsonschema2pojo.integration.config.PrefixSuffixIT.java

@Test(expected = ClassNotFoundException.class)
public void NotExitstingClassSufix() throws ClassNotFoundException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("classNameSuffix", "Dao"));
    resultsClassLoader.loadClass("com.example.NotExistingPrimitiveProperties");
}

From source file:org.jsonschema2pojo.integration.JacksonViewIT.java

private Annotation jsonViewTest(String annotationStyle, Class<? extends Annotation> annotationType)
        throws ClassNotFoundException, NoSuchFieldException {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/views/views.json", "com.example",
            config("annotationStyle", annotationStyle));

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.Views");
    Field fieldInView = generatedType.getDeclaredField("inView");
    assertThat(fieldInView.getAnnotation(annotationType), notNullValue());

    Field fieldNotInView = generatedType.getDeclaredField("notInView");
    assertThat(fieldNotInView.getAnnotation(annotationType), nullValue());

    return fieldInView.getAnnotation(annotationType);
}

From source file:com.flipkart.flux.impl.task.LocalJvmTask.java

@Override
public Pair<Object, FluxError> execute(EventData[] events) {
    Object[] parameters = new Object[events.length];
    Class<?>[] parameterTypes = toInvoke.getParameterTypes();
    try {/*from   w  ww .  j  a v a2 s.c  om*/
        /* TODO
        While this works for methods with all unique param types, it
        will fail for methods where we have mutliple params of the same type.
         */
        ClassLoader classLoader = ((TaskExecutableImpl) toInvoke).getDeploymentUnitClassLoader();
        Class objectMapper = classLoader.loadClass("com.fasterxml.jackson.databind.ObjectMapper");
        Object objectMapperInstance = objectMapper.newInstance();

        for (int i = 0; i < parameterTypes.length; i++) {
            for (EventData anEvent : events) {
                if (Class.forName(anEvent.getType(), true, classLoader).equals(parameterTypes[i])) {
                    parameters[i] = objectMapper.getMethod("readValue", String.class, Class.class).invoke(
                            objectMapperInstance, anEvent.getData(),
                            Class.forName(anEvent.getType(), true, classLoader));
                }
            }
            if (parameters[i] == null) {
                logger.warn("Could not find a paramter of type {} in event list {}", parameterTypes[i], events);
                throw new RuntimeException("Could not find a paramter of type " + parameterTypes[i]);
            }
        }

        Method writeValueAsString = objectMapper.getMethod("writeValueAsString", Object.class);

        final Object returnObject = toInvoke.execute(parameters);
        SerializedEvent serializedEvent = null;
        if (returnObject != null) {
            serializedEvent = new SerializedEvent(returnObject.getClass().getCanonicalName(),
                    (String) writeValueAsString.invoke(objectMapperInstance, returnObject));
        }
        return new Pair<>(serializedEvent, null);
    } catch (Exception e) {
        logger.warn("Bad things happened while trying to execute {}", toInvoke, e);
        return new Pair<>(null, new FluxError(FluxError.ErrorType.runtime, e.getMessage(), e));
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test(expected = ClassNotFoundException.class)
public void arrayAtRootProducesNoJavaTypes() throws Exception {

    ClassLoader resultsClassLoader = generateAndCompile("/json/arrayAsRoot.json", "com.example",
            config("sourceType", "json"));

    resultsClassLoader.loadClass("com.example.ArrayAsRoot");

}

From source file:org.jsonschema2pojo.integration.config.PrefixSuffixIT.java

@Test
public void customClassPrefix() throws ClassNotFoundException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("classNamePrefix", "Abstract"));
    resultsClassLoader.loadClass("com.example.AbstractPrimitiveProperties");
}

From source file:org.jsonschema2pojo.integration.config.PrefixSuffixIT.java

@Test(expected = ClassNotFoundException.class)
public void NotExitstingClassPrefix() throws ClassNotFoundException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("classNamePrefix", "Abstract"));
    resultsClassLoader.loadClass("com.example.NotExistingPrimitiveProperties");
}