List of usage examples for java.lang ClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:com.googlecode.psiprobe.tools.logging.tomcatSlf4jLogback.TomcatSlf4jLogbackFactoryAccessor.java
/** * Attempts to initialize a TomcatSlf4jLogback logger factory via the given class loader. * // www . ja v a 2 s .c o m * @param cl the ClassLoader to use when fetching the factory */ public TomcatSlf4jLogbackFactoryAccessor(ClassLoader cl) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // Get the singleton SLF4J binding, which may or may not be Logback, depending on the binding. Class clazz = cl.loadClass("org.apache.juli.logging.org.slf4j.impl.StaticLoggerBinder"); Method m1 = MethodUtils.getAccessibleMethod(clazz, "getSingleton", new Class[] {}); Object singleton = m1.invoke(null, null); Method m = MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory", new Class[] {}); Object loggerFactory = m.invoke(singleton, null); // Check if the binding is indeed Logback Class loggerFactoryClass = cl.loadClass("org.apache.juli.logging.ch.qos.logback.classic.LoggerContext"); if (!loggerFactoryClass.isInstance(loggerFactory)) { throw new RuntimeException("The singleton SLF4J binding was not Logback"); } setTarget(loggerFactory); }
From source file:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java
@Test public void additionalPropertiesOfStringTypeOnly() throws SecurityException, NoSuchMethodException, ClassNotFoundException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/additionalProperties/additionalPropertiesString.json", "com.example"); 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("setAdditionalProperties", String.class, String.class); }
From source file:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java
public void additionalPropertiesOfObjectTypeCreatesNewClassForPropertyValues() throws SecurityException, NoSuchMethodException, ClassNotFoundException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/additionalProperties/additionalPropertiesObject.json", "com.example"); 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("setAdditionalProperties", String.class, propertyValueType); }
From source file:org.apache.juneau.rest.client.RestCallException.java
/** * Tries to reconstruct and re-throw the server-side exception. * <p>/* ww w . j av a 2 s . co m*/ * The exception is based on the following HTTP response headers: * <ul> * <li><code>Exception-Name:</code> - The full class name of the exception. * <li><code>Exception-Message:</code> - The message returned by {@link Throwable#getMessage()}. * <li><code>Exception-Trace:</code> - The stack trace of the exception returned by {@link Throwable#printStackTrace()}. * </ul> * <p> * Does nothing if the server-side exception could not be reconstructed. * <p> * Currently only supports <code>Throwables</code> with either a public no-arg constructor * or a public constructor that takes in a simple string message. * * @param cl The classloader to use to resolve the throwable class name. * @throws Throwable If the throwable could be reconstructed. */ protected void throwServerException(ClassLoader cl) throws Throwable { if (serverExceptionName != null) { Throwable t = null; try { Class<?> exceptionClass = cl.loadClass(serverExceptionName); Constructor<?> c = ClassUtils.findPublicConstructor(exceptionClass, String.class); if (c != null) t = (Throwable) c.newInstance(serverExceptionMessage); if (t == null) { c = ClassUtils.findPublicConstructor(exceptionClass); if (c != null) t = (Throwable) c.newInstance(); } } catch (Exception e2) { /* Ignore */ } if (t != null) throw t; } }
From source file:com.bfd.harpc.config.spring.ClientBean.java
/** * ?//from w w w. j a v a 2 s .c o m * <p> * * @return {@link Object} */ @SuppressWarnings("unchecked") public Object createProxy() throws Exception { check();// ? CuratorFramework zkClient = null; IRegistry registry = null; ServerNode clientNode = new ServerNode(NetUtils.getLocalHost(), 0); if (getAddress() != null) { registry = new DefaultRegistry(getAddress()); } else { // ?zkClient if (applicationContext != null) { Map<String, RegistryConfig> regMap = applicationContext.getBeansOfType(RegistryConfig.class); if (regMap != null && regMap.size() > 0) { for (RegistryConfig config : regMap.values()) { if (config != null) { try { zkClient = config.obtainZkClient(); registry = new ZkClientRegistry(getService(), zkClient, clientNode); } catch (Exception e) { throw new RpcException("Registry error!", e); } break; } } /* ? for (String key : regMap.keySet()) { if (regMap.get(key) != null) { try { zkClient = regMap.get(key).obtainZkClient(); registry = new ZkClientRegistry(getService(), zkClient, clientNode); } catch (Exception e) { throw new RpcException("Registry error!", e); } break; } } */ } } } if (registry == null) { throw new RpcException("The param addess and registry config cannot all no exist!"); } registry.register(genConfigJson()); // RpcMonitor rpcMonitor = null; if (isMonitor()) { rpcMonitor = new RpcMonitor(getInterval(), zkClient, getService(), true); } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Iface? Class<?> objectClass = classLoader.loadClass(getIface()); GenericKeyedObjectPool<ServerNode, TServiceClient> pool = bulidClientPool(classLoader, objectClass); HeartBeatManager heartBeatManager = new HeartBeatManager(registry.findAllService(), getHeartbeat(), getHeartbeatTimeout(), getHeartbeatTimes(), getHeartbeatInterval(), pool); heartBeatManager.startHeatbeatTimer(); DynamicHostSet hostSet = registry.findAllService(); LoadBalancer<ServerNode> loadBalancer = LoadBalancerFactory.createLoadBalancer(hostSet, getLoadbalance(), heartBeatManager); // ShutdownHook addShutdownHook(registry, rpcMonitor, heartBeatManager); Invoker invoker = new DefaultInvoker(clientNode, pool, loadBalancer, getRetry(), rpcMonitor, hostSet); DynamicClientHandler dynamicClientHandler = new DynamicClientHandler(invoker); return dynamicClientHandler.bind(classLoader, objectClass); }
From source file:org.jsonschema2pojo.integration.PropertiesIT.java
@Test public void propertyNamesThatAreJavaKeywordsCanBeSerialized() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { ClassLoader resultsClassLoader = schemaRule .generateAndCompile("/schema/properties/propertiesThatAreJavaKeywords.json", "com.example"); Class<?> generatedType = resultsClassLoader.loadClass("com.example.PropertiesThatAreJavaKeywords"); String valuesAsJsonString = "{\"public\":\"a\",\"void\":\"b\",\"enum\":\"c\",\"abstract\":\"d\"}"; Object valuesAsObject = mapper.readValue(valuesAsJsonString, generatedType); JsonNode valueAsJsonNode = mapper.valueToTree(valuesAsObject); assertThat(valueAsJsonNode.path("public").asText(), is("a")); assertThat(valueAsJsonNode.path("void").asText(), is("b")); assertThat(valueAsJsonNode.path("enum").asText(), is("c")); assertThat(valueAsJsonNode.path("abstract").asText(), is("d")); }
From source file:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java
@Test @SuppressWarnings("unchecked") public void jacksonCanDeserializeOurAdditionalProperties() throws ClassNotFoundException, IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/additionalProperties/defaultAdditionalProperties.json", "com.example"); 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:com.googlecode.jsonschema2pojo.integration.AdditionalPropertiesIT.java
@Test public void jacksonCanSerializeOurAdditionalProperties() throws ClassNotFoundException, IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException { ClassLoader resultsClassLoader = generateAndCompile( "/schema/additionalProperties/defaultAdditionalProperties.json", "com.example"); Class<?> classWithAdditionalProperties = resultsClassLoader .loadClass("com.example.DefaultAdditionalProperties"); Object deserialized = classWithAdditionalProperties.newInstance(); Method setter = classWithAdditionalProperties.getMethod("setAdditionalProperties", String.class, Object.class); setter.invoke(deserialized, "a", "1"); setter.invoke(deserialized, "b", "2"); String jsonString = mapper.writeValueAsString(deserialized); JsonNode jsonNode = mapper.readTree(jsonString); assertThat(jsonNode.path("a").asText(), is("1")); assertThat(jsonNode.path("b").asInt(), is(2)); }
From source file:com.googlecode.jsonschema2pojo.integration.config.CustomAnnotatorIT.java
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
From source file:org.jsonschema2pojo.integration.PropertiesIT.java
@Test public void propertyNamesAreLowerCamelCase() throws Exception { ClassLoader resultsClassLoader = schemaRule .generateAndCompile("/schema/properties/propertiesAreUpperCamelCase.json", "com.example"); Class<?> generatedType = resultsClassLoader.loadClass("com.example.UpperCase"); Object instance = generatedType.newInstance(); new PropertyDescriptor("property1", generatedType).getWriteMethod().invoke(instance, "1"); new PropertyDescriptor("propertyTwo", generatedType).getWriteMethod().invoke(instance, 2); new PropertyDescriptor("propertyThreeWithSpace", generatedType).getWriteMethod().invoke(instance, "3"); new PropertyDescriptor("propertyFour", generatedType).getWriteMethod().invoke(instance, "4"); JsonNode jsonified = mapper.valueToTree(instance); assertNotNull(generatedType.getDeclaredField("property1")); assertNotNull(generatedType.getDeclaredField("propertyTwo")); assertNotNull(generatedType.getDeclaredField("propertyThreeWithSpace")); assertNotNull(generatedType.getDeclaredField("propertyFour")); assertThat(jsonified.has("Property1"), is(true)); assertThat(jsonified.has("PropertyTwo"), is(true)); assertThat(jsonified.has(" PropertyThreeWithSpace"), is(true)); assertThat(jsonified.has("propertyFour"), is(true)); }