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:com.dotosoft.dot4command.config.xml.XmlConfigParser.java

public XmlConfigParser(String ruleSet, ClassLoader loader) {
    if (ruleSet == null) {
        throw new IllegalArgumentException(
                "ConfigParser can't be " + "instantiated with a null ruleSet class name");
    }//from   w w  w.  ja  va2 s .c om
    if (loader == null) {
        throw new IllegalArgumentException(
                "ConfigParser can't be " + "instantiated with a null class loader reference");
    }

    try {
        Class<?> clazz = loader.loadClass(ruleSet);
        setRuleSet((RuleSet) clazz.newInstance());
    } catch (Exception e) {
        throw new RuntimeException(
                "Exception initializing RuleSet '" + ruleSet + "' instance: " + e.getMessage());
    }
}

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

@Test
public void jacksonCanSerializeOurAdditionalPropertiesWithoutIncludeAccessors()
        throws ClassNotFoundException, IOException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/defaultAdditionalProperties.json", "com.example",
            config("includeAccessors", false));

    Class<?> classWithAdditionalProperties = resultsClassLoader
            .loadClass("com.example.DefaultAdditionalProperties");
    String jsonWithAdditionalProperties = "{\"a\":1, \"b\":2};";
    Object instanceWithAdditionalProperties = mapper.readValue(jsonWithAdditionalProperties,
            classWithAdditionalProperties);

    JsonNode jsonNode = mapper.readTree(mapper.writeValueAsString(instanceWithAdditionalProperties));

    assertThat(jsonNode.path("a").asText(), is("1"));
    assertThat(jsonNode.path("b").asInt(), is(2));
}

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

@Test
public void withAdditionalPropertyStoresValue() throws Exception {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/additionalPropertiesString.json", "com.example",
            config("generateBuilders", true));

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesString");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            String.class);

    Object value = "value";
    Object instance = classWithNoAdditionalProperties.newInstance();
    Object result = builderMethod.invoke(instance, "prop", value);
    Object stored = ((Map<?, ?>) getter.invoke(instance)).get("prop");

    assertThat("the builder returned the instance", result, sameInstance(instance));
    assertThat("the getter returned the value", stored, sameInstance(value));

}

From source file:org.mule.modules.zuora.ZuoraModule.java

private Class<?> getClassForType(String type) throws ClassNotFoundException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    Class<?> cls = cl.loadClass("com.zuora.api.object." + type);
    return cls;//from   w w  w.j a v a  2  s .c om
}

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

@Test
@SuppressWarnings("unchecked")
public void jacksonCanDeserializeOurAdditionalPropertiesWithoutIncludeAccessors()
        throws ClassNotFoundException, IOException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/defaultAdditionalProperties.json", "com.example",
            config("includeAccessors", false));

    Class<?> classWithAdditionalProperties = resultsClassLoader
            .loadClass("com.example.DefaultAdditionalProperties");

    Object deserialized = mapper.readValue("{\"a\":\"1\", \"b\":2}", classWithAdditionalProperties);

    Method getter = classWithAdditionalProperties.getMethod("getAdditionalProperties");

    assertThat(getter.invoke(deserialized), is(notNullValue()));
    assertThat(((Map<String, Object>) getter.invoke(deserialized)).containsKey("a"), is(true));
    assertThat((String) ((Map<String, Object>) getter.invoke(deserialized)).get("a"), is("1"));
    assertThat(((Map<String, Object>) getter.invoke(deserialized)).containsKey("b"), is(true));
    assertThat((Integer) ((Map<String, Object>) getter.invoke(deserialized)).get("b"), is(2));

}

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

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

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

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

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

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

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

}

From source file:com.jeeframework.util.resource.ResolverUtil.java

/**
 * Add the class designated by the fully qualified class name provided to the set of
 * resolved classes if and only if it is approved by the Test supplied.
 *
 * @param test the test used to determine if the class matches
 * @param fqn the fully qualified name of a class
 *//* ww  w .  ja  va 2s  .  co m*/
protected void addIfMatching(Test test, String fqn) {
    try {
        String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
        ClassLoader loader = getClassLoader();
        if (log.isDebugEnabled()) {
            log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
        }

        Class type = loader.loadClass(externalName);
        if (test.matches(type)) {
            matches.add((Class<T>) type);
        }
    } catch (Throwable t) {
        log.warn("Could not examine class '" + fqn + "' due to a " + t.getClass().getName() + " with message: "
                + t.getMessage());
    }
}

From source file:com.moss.nomad.core.runner.Runner.java

public void run(String migrationPathName, MigrationHistory history, byte[] env) throws Exception {

    MigrationPath path = findPath(migrationPathName);
    if (path == null) {
        throw new RuntimeException("Cannot find a migration path by the name of '" + migrationPathName + "'");
    }/*from  w  w w. j av  a 2 s.  c om*/

    Set<MigrationDef> executed = new HashSet<MigrationDef>();
    for (Migration migration : history.migrations()) {
        executed.add(migration.def());
    }

    /*
     * NOTE: How we determine what migrations to perform could be a lot more
     * sophisticated. We aren't checking the history to make sure that
     * migrations are only executed in sequence. This is how schematrax
     * works, but we might want to improve on it.
     */

    List<MigrationPackage> unexecuted = new ArrayList<MigrationPackage>();
    for (MigrationPackage pkg : path.packages()) {

        if (!executed.contains(pkg.def())) {
            unexecuted.add(pkg);
        }
    }

    if (unexecuted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No migrations remain to be executed, doing nothing.");
        }
        return;
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (MigrationPackage pkg : unexecuted) {

        if (pkg.resources() == null) {
            throw new RuntimeException(
                    "Cannot perform migration, migration resource not available in migration jar: "
                            + pkg.def());
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing migration: " + pkg.def());
        }

        Migration migration = new Migration(new Instant(), pkg.def());
        MigrationResources res = pkg.resources();

        List<URL> urls = new ArrayList<URL>();
        for (String req : res.classpath()) {

            String[] pathSegments = req.split("\\/");

            File copyTarget = workDir;
            for (String s : pathSegments) {
                copyTarget = new File(copyTarget, s);
            }

            if (!copyTarget.getParentFile().exists() && !copyTarget.getParentFile().mkdirs()) {
                throw new RuntimeException("Cannot create directory: " + copyTarget.getParentFile());
            }

            if (!copyTarget.exists()) {

                if (log.isDebugEnabled()) {
                    log.debug("Copying classpath resource " + req + " -> " + copyTarget);
                }

                JarEntry entry = packageJar.getJarEntry(req);

                if (entry == null) {
                    throw new RuntimeException("Expected package jar entry not found: " + req);
                }

                InputStream in = packageJar.getInputStream(entry);
                OutputStream out = new FileOutputStream(copyTarget);
                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                    out.write(buffer, 0, numRead);
                }
                in.close();
                out.close();
            }

            urls.add(copyTarget.toURL());
        }

        ClassLoader cl;
        {
            URL[] cp = urls.toArray(new URL[0]);
            cl = new URLClassLoader(cp, null);
        }

        Class clazz = cl.loadClass("com.moss.nomad.api.v1.ClassLoaderBridge");

        Method method = clazz.getMethod("execute", String.class, byte[].class);

        ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
        try {
            firePreMigration(migration);

            /*
             * NOTE, the reason we're setting the context class loader here
             * is for java 5 compatibility. JAXBContext seems to load its
             * classes from the current thread context class loader. In
             * java 5 this causes problems, in java 6 it doesn't because
             * the JAXB stuff is in the boot classpath. Ah well.
             */

            Thread.currentThread().setContextClassLoader(cl);

            String stacktrace = (String) method.invoke(null, res.className(), env);

            Thread.currentThread().setContextClassLoader(currentCl);

            if (stacktrace != null) {
                throw new MigrationFailureException(stacktrace);
            }

            firePostMigration(migration);
        } catch (Exception ex) {
            Thread.currentThread().setContextClassLoader(currentCl);

            log.error("Failed to complete migration for migration-def " + pkg.def(), ex);
            fireMigrationFailure(migration, ex);
            throw ex;
        }
    }
}

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

@Test(expected = UnrecognizedPropertyException.class)
public void additionalPropertiesAreNotDeserializableWhenDisabledGlobally()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IOException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/defaultAdditionalProperties.json", "com.example",
            config("includeAdditionalProperties", false));

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.DefaultAdditionalProperties");

    mapper.readValue("{\"a\":\"1\", \"b\":2}", classWithNoAdditionalProperties);

}

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

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

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

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesObject");
    Class<?> propertyValueType = resultsClassLoader.loadClass("com.example.AdditionalPropertiesObjectProperty");

    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

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

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

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            propertyValueType);//w w w.  j  av  a  2  s  . c o  m
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}