List of usage examples for java.lang Class getClassLoader
@CallerSensitive
@ForceInline
public ClassLoader getClassLoader()
From source file:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java
private void assertLoadSucceeds(ClassLoaderUtils clu, String bundledClassName, Class<?> expectedClass) throws ClassNotFoundException { BundledName className = new BundledName(bundledClassName); Class<?> cls = clu.loadClass(bundledClassName); assertEquals(cls.getName(), className.name); if (expectedClass != null) { assertEquals(cls, expectedClass); }/*from w w w .j a v a2 s . co m*/ ClassLoader cl = cls.getClassLoader(); BundledName resource = className.toResource(); String bundledResource = resource.toString(); URL resourceUrl = cl.getResource(resource.name); assertEquals(clu.getResource(bundledResource), resourceUrl); assertEquals(clu.getResources(bundledResource), ImmutableList.of(resourceUrl), "Loading with " + clu); BundledName rootResource = new BundledName(resource.bundle, resource.version, "/" + resource.name); String rootBundledResource = rootResource.toString(); assertEquals(clu.getResource(rootBundledResource), resourceUrl); assertEquals(clu.getResources(rootBundledResource), ImmutableList.of(resourceUrl)); }
From source file:org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper.java
private List<ControllerServiceAPI> mapControllerServiceApis(final ControllerServiceNode service) { final Class<?> serviceClass = service.getControllerServiceImplementation().getClass(); final Set<Class<?>> serviceApiClasses = new HashSet<>(); // get all of it's interfaces to determine the controller service api's it implements final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(serviceClass); for (final Class<?> i : interfaces) { // add all controller services that's not ControllerService itself if (ControllerService.class.isAssignableFrom(i) && !ControllerService.class.equals(i)) { serviceApiClasses.add(i);/*ww w.ja va2 s . c o m*/ } } final List<ControllerServiceAPI> serviceApis = new ArrayList<>(); for (final Class<?> serviceApiClass : serviceApiClasses) { final BundleCoordinate bundleCoordinate = extensionManager.getBundle(serviceApiClass.getClassLoader()) .getBundleDetails().getCoordinate(); final ControllerServiceAPI serviceApi = new ControllerServiceAPI(); serviceApi.setType(serviceApiClass.getName()); serviceApi.setBundle(mapBundle(bundleCoordinate)); serviceApis.add(serviceApi); } return serviceApis; }
From source file:org.apache.sling.validation.impl.ValidationServiceImpl.java
private void validatePropertyValue(String property, ValueMap valueMap, Resource resource, String relativePath, ResourceProperty resourceProperty, CompositeValidationResult result) { Object fieldValues = valueMap.get(property); if (fieldValues == null) { if (resourceProperty.isRequired()) { result.addFailure(relativePath, null, I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, property); }// w w w . j av a 2s.c o m return; } List<ParameterizedValidator> validators = resourceProperty.getValidators(); if (resourceProperty.isMultiple()) { if (!fieldValues.getClass().isArray()) { result.addFailure(relativePath + property, null, I18N_KEY_EXPECTED_MULTIVALUE_PROPERTY); return; } } for (ParameterizedValidator validator : validators) { // convert the type always to an array Class<?> type = validator.getType(); if (!type.isArray()) { try { // https://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getName%28%29 has some hints on class names type = Class.forName("[L" + type.getName() + ";", false, type.getClassLoader()); } catch (ClassNotFoundException e) { throw new SlingValidationException("Could not generate array class for type " + type, e); } } // it is already validated here that the property exists in the value map Object[] typedValue = (Object[]) valueMap.get(property, type); // see https://issues.apache.org/jira/browse/SLING-4178 for why the second check is necessary if (typedValue == null || (typedValue.length > 0 && typedValue[0] == null)) { // here the missing required property case was already treated in validateValueMap result.addFailure(relativePath + property, validator.getSeverity(), I18N_KEY_WRONG_PROPERTY_TYPE, validator.getType()); return; } // see https://issues.apache.org/jira/browse/SLING-662 for a description on how multivalue properties are treated with ValueMap if (validator.getType().isArray()) { // ValueMap already returns an array in both cases (property is single value or multivalue) validateValue(result, typedValue, property, relativePath, valueMap, resource, validator); } else { // call validate for each entry in the array (supports both singlevalue and multivalue) @Nonnull Object[] array = (Object[]) typedValue; if (array.length == 1) { validateValue(result, array[0], property, relativePath, valueMap, resource, validator); } else { int n = 0; for (Object item : array) { validateValue(result, item, property + "[" + n++ + "]", relativePath, valueMap, resource, validator); } } } } }
From source file:com.liferay.maven.plugins.ServiceBuilderMojo.java
protected void initPortalClassLoader() throws Exception { super.initPortalClassLoader(); Class<?> clazz = getClass(); URLClassLoader urlClassLoader = (URLClassLoader) clazz.getClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true);/*from ww w .j av a 2s . c om*/ File file = new File(implResourcesDir); URI uri = file.toURI(); method.invoke(urlClassLoader, uri.toURL()); }
From source file:com.autobizlogic.abl.util.BeanUtil.java
private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass, boolean onlyProtectedAndHigher) { Field[] allFields = cls.getDeclaredFields(); for (Field field : allFields) { if (!field.getName().equals(fieldName)) continue; int modifiers = field.getModifiers(); if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers)) continue; if (argClass != null) { Class<?> genericType = getGenericType(field.getType()); if (!genericType.isAssignableFrom(argClass)) { String extraInfo = ""; // If the two classes have the same name, it's probably a classloader problem, // so we generate more informative output to help debug if (field.getType().getName().equals(argClass.getName())) { extraInfo = ". It looks like the two classes have the same name, so this is " + "probably a classloader issue. The bean field's class comes from " + field.getType().getClassLoader() + ", the other class comes from " + argClass.getClassLoader(); }/* w w w .j a v a2 s . c o m*/ throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName() + " is of the wrong type (" + field.getType().getName() + ") for the given argument, " + "which is of type " + argClass.getName() + extraInfo); } } return field; } return null; }
From source file:me.piebridge.android.preference.PreferenceFragment.java
@Override public void onStart() { super.onStart(); // FIXME: mPreferenceManager.setOnPreferenceTreeClickListener(this); try {/*from w ww. java 2s . c o m*/ Class<?> clazz = Class.forName("android.preference.PreferenceManager$OnPreferenceTreeClickListener"); Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("onPreferenceTreeClick")) { return onPreferenceTreeClick((PreferenceScreen) args[0], (Preference) args[1]); } return null; } }); callVoidMethod(mPreferenceManager, "setOnPreferenceTreeClickListener", new Class[] { clazz }, new Object[] { proxy }); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:hudson.security.SecurityRealm.java
/** * Returns true if this {@link SecurityRealm} allows online sign-up. * This creates a hyperlink that redirects users to {@code CONTEXT_ROOT/signUp}, * which will be served by the {@code signup.jelly} view of this class. * * <p>// ww w .java 2 s . c om * If the implementation needs to redirect the user to a different URL * for signing up, use the following jelly script as {@code signup.jelly} * * <pre>{@code <xmp> * <st:redirect url="http://www.sun.com/" xmlns:st="jelly:stapler"/> * </xmp>}</pre> */ public boolean allowsSignup() { Class clz = getClass(); return clz.getClassLoader().getResource(clz.getName().replace('.', '/') + "/signup.jelly") != null; }
From source file:org.apache.apex.malhar.lib.function.FunctionOperator.java
private byte[] functionClassData(Function f) { Class<? extends Function> classT = f.getClass(); byte[] classBytes = null; byte[] classNameBytes = null; String className = classT.getName(); try {//from w w w .ja v a2 s . c o m classNameBytes = className.replace('.', '/').getBytes(); classBytes = IOUtils.toByteArray( classT.getClassLoader().getResourceAsStream(className.replace('.', '/') + ".class")); int cursor = 0; for (int j = 0; j < classBytes.length; j++) { if (classBytes[j] != classNameBytes[cursor]) { cursor = 0; } else { cursor++; } if (cursor == classNameBytes.length) { for (int p = 0; p < classNameBytes.length; p++) { if (classBytes[j - p] == '$') { classBytes[j - p] = '_'; } } cursor = 0; } } ClassReader cr = new ClassReader(new ByteArrayInputStream(classBytes)); ClassWriter cw = new ClassWriter(0); AnnonymousClassModifier annonymousClassModifier = new AnnonymousClassModifier(Opcodes.ASM4, cw); cr.accept(annonymousClassModifier, 0); classBytes = cw.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } int dataLength = classNameBytes.length + 4 + 4; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(dataLength); DataOutputStream output = new DataOutputStream(byteArrayOutputStream); try { output.writeInt(classNameBytes.length); output.write(className.replace('$', '_').getBytes()); output.writeInt(classBytes.length); output.write(classBytes); } catch (IOException e) { throw new RuntimeException(e); } finally { try { output.flush(); output.close(); } catch (IOException e) { throw new RuntimeException(e); } } return byteArrayOutputStream.toByteArray(); }
From source file:com.github.hrpc.rpc.ProtobufRpcEngine.java
@Override public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy(ConnectionId connId, Option conf, SocketFactory factory) throws IOException { Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class; return new ProtocolProxy<ProtocolMetaInfoPB>(protocol, (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(protocol, connId, conf, factory))); }
From source file:org.apache.hadoop.hbase.ipc.bak.SchedulableWritableRpcEngine.java
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. */ @Override/*from ww w .j a v a 2 s. c o m*/ public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, Configuration conf, int rpcTimeout) throws IOException { if (this.client == null) { throw new IOException("Client must be initialized by calling setConf(Configuration)"); } T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker( client, protocol, addr, userProvider.getCurrent(), conf, HBaseRPC.getRpcTimeout(rpcTimeout))); /* * TODO: checking protocol version only needs to be done once when we setup a new * HBaseClient.Connection. Doing it every time we retrieve a proxy instance is resulting * in unnecessary RPC traffic. */ long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion != clientVersion) { throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion); } return proxy; }