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.PropertiesIT.java

@Test
public void propertyCalledClassCanBeSerialized()
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/properties/propertyCalledClass.json", "com.example");

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.PropertyCalledClass");

    String valuesAsJsonString = "{\"class\":\"a\"}";
    Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType);
    JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject);

    assertThat(valueAsJsonNode.path("class").asText(), is("a"));

}

From source file:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile(
            "/schema/additionalProperties/noAdditionalProperties.json", "com.example");

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

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

}

From source file:io.gravitee.gateway.repository.plugins.RepositoryPluginHandler.java

@Override
public void handle(Plugin plugin) {
    try {/*  ww  w  . j  ava 2  s .  c  om*/
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin,
                this.getClass().getClassLoader());

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

        Assert.isAssignable(Repository.class, repositoryClass);

        Repository repository = createInstance((Class<Repository>) repositoryClass);
        for (Scope scope : repository.scopes()) {
            if (!repositories.containsKey(scope)) {
                String requiredRepositoryType = repositoryTypeByScope.get(scope);

                // Load only repository plugin for a given scope (provided in the configuration)
                if (repository.type().equalsIgnoreCase(requiredRepositoryType)) {
                    LOGGER.info("Repository [{}] loaded by {}", scope, repository.type());

                    // Not yet loaded, let's mount the repository in application context
                    try {
                        ApplicationContext repoApplicationContext = pluginContextFactory
                                .create(new AnnotationBasedPluginContextConfigurer(plugin) {
                                    @Override
                                    public Set<Class<?>> configurations() {
                                        return Collections.singleton(repository.configuration(scope));
                                    }
                                });

                        registerRepositoryDefinitions(repository, repoApplicationContext);
                        repositories.put(scope, repository);
                    } catch (Exception iae) {
                        LOGGER.error("Unexpected error while creating context for repository instance", iae);
                        pluginContextFactory.remove(plugin);
                    }
                } else {
                    LOGGER.debug("Scoped repository [{}] must be loaded by {}. Skipping registration", scope,
                            requiredRepositoryType);
                }
            } else {
                LOGGER.warn("Repository scope {} already loaded by {}", scope, repositories.get(scope));
            }
        }
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while create repository instance", iae);
    }
}

From source file:io.gravitee.management.repository.plugins.RepositoryPluginHandler.java

@Override
public void handle(Plugin plugin) {
    try {/*from   w  w w .ja  va  2s. com*/
        ClassLoader classloader = pluginClassLoaderFactory.getOrCreateClassLoader(plugin,
                this.getClass().getClassLoader());

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

        Assert.isAssignable(Repository.class, repositoryClass);

        Repository repository = createInstance((Class<Repository>) repositoryClass);
        Collection<Scope> scopes = scopeByRepositoryType.getOrDefault(repository.type(),
                Collections.EMPTY_LIST);

        for (Scope scope : scopes) {
            if (!repositories.containsKey(scope)) {
                // Not yet loaded, let's mount the repository in application context
                try {
                    ApplicationContext applicationContext = pluginContextFactory
                            .create(new AnnotationBasedPluginContextConfigurer(plugin) {
                                @Override
                                public Set<Class<?>> configurations() {
                                    return Collections.singleton(repository.configuration(scope));
                                }
                            });

                    registerRepositoryDefinitions(repository, applicationContext);
                    repositories.put(scope, repository);
                } catch (Exception iae) {
                    LOGGER.error("Unexpected error while creating context for repository instance", iae);
                    pluginContextFactory.remove(plugin);
                }

            } else {
                LOGGER.warn("Repository scope {} already loaded by {}", scope, repositories.get(scope));
            }
        }
    } catch (Exception iae) {
        LOGGER.error("Unexpected error while create repository instance", iae);
    }
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

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

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

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

}

From source file:com.soapsnake.thrift.license.rpc.ThriftServiceClientProxyFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    //        zookeeper???,?
    //        if (serverAddress != null){
    //            addressProvider = new FixedAddressProvider(serverAddress);
    //        }//  w  w w  . j  ava 2  s.  com
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    //?thrift serviceclass,,??class
    objectClass = classLoader.loadClass(service + "$Iface");

    //??
    Class<TServiceClientFactory<TServiceClient>> fi = (Class<TServiceClientFactory<TServiceClient>>) classLoader
            .loadClass(service + "$Client$Factory");

    //TServiceClientFactory
    TServiceClientFactory<TServiceClient> clientFactory = fi.newInstance();

    //
    ThriftClientPoolFactory clientPool = new ThriftClientPoolFactory(serverAddress, clientFactory, callback);
    //
    GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
    poolConfig.maxActive = maxActive;
    poolConfig.minIdle = 0;
    poolConfig.minEvictableIdleTimeMillis = idleTime;
    poolConfig.timeBetweenEvictionRunsMillis = idleTime / 2L;
    //:ThriftClientPoolFactory,config
    pool = new GenericObjectPool<>(clientPool, poolConfig);

    proxyClient = Proxy.newProxyInstance(classLoader, new Class[] { objectClass }, (o, method, objects) -> {
        //pool?client
        TServiceClient client = pool.borrowObject();
        try {
            return method.invoke(client, objects);
        } catch (Exception e) {
            throw e;
        } finally {
            pool.returnObject(client);
        }
    });
}

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

@Test
@SuppressWarnings("rawtypes")
public void propertiesAreSerializedInCorrectOrder() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/orderedProperties.json",
            "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.OrderedProperties");
    Object instance = generatedType.newInstance();

    new PropertyDescriptor("type", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("id", generatedType).getWriteMethod().invoke(instance, "2");
    new PropertyDescriptor("name", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("hastickets", generatedType).getWriteMethod().invoke(instance, true);
    new PropertyDescriptor("starttime", generatedType).getWriteMethod().invoke(instance, "4");

    String serialized = mapper.valueToTree(instance).toString();

    assertThat("Properties are not in expected order", serialized.indexOf("type"),
            is(lessThan(serialized.indexOf("id"))));
    assertThat("Properties are not in expected order", serialized.indexOf("id"),
            is(lessThan(serialized.indexOf("name"))));
    assertThat("Properties are not in expected order", serialized.indexOf("name"),
            is(lessThan(serialized.indexOf("hastickets"))));
    assertThat("Properties are not in expected order", serialized.indexOf("hastickets"),
            is(lessThan(serialized.indexOf("starttime"))));

}

From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java

public static List<TouchUIWidgetConfigHolder> getAllTouchUIWidgetAnnotations(ClassPool classPool,
        ClassLoader classLoader, Reflections reflections) throws NotFoundException, ClassNotFoundException {
    List<TouchUIWidgetConfigHolder> widgetConfigurations = new ArrayList<TouchUIWidgetConfigHolder>();

    for (Class<?> c : reflections.getTypesAnnotatedWith(TouchUIWidget.class)) {
        CtClass clazz = classPool.getCtClass(c.getName());
        TouchUIWidget widgetAnnotation = (TouchUIWidget) clazz.getAnnotation(TouchUIWidget.class);
        Class<? extends Annotation> annotationClass = widgetAnnotation.annotationClass();
        Class<? extends TouchUIWidgetMaker> widgetMakerClass = widgetAnnotation.makerClass();
        Class<? extends TouchUIDialogElement> widgetClass = classLoader.loadClass(clazz.getName())
                .asSubclass(TouchUIDialogElement.class);

        widgetConfigurations.add(new TouchUIWidgetConfigHolder(annotationClass, widgetClass, widgetMakerClass,
                widgetAnnotation.resourceType(), widgetAnnotation.ranking()));
    }/*w  ww  . ja  v  a  2 s.  c  o m*/

    return widgetConfigurations;
}

From source file:com.googlecode.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void defaultCustomAnnotatorIsNoop()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "none")); // turn off core annotations

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotations().length, is(0));
    assertThat(getter.getAnnotations().length, is(0));
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

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

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

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

}