Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

In this page you can find the example usage for java.lang Class getClassLoader.

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

private ContributionDef createContributionToMasterObjectProvider() {

    return new AbstractContributionDef() {
        @Override//  www  .  j a va2s .co m
        public String getServiceId() {
            return "MasterObjectProvider";
        }

        @Override
        public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
                OrderedConfiguration configuration) {
            final OperationTracker tracker = resources.getTracker();

            final ApplicationContext context = resources.getService(SERVICE_ID, ApplicationContext.class);

            //region CUSTOMIZATION
            final ObjectProvider springBeanProvider = new ObjectProvider() {
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {

                    try {
                        T bean = context.getBean(objectType);
                        if (!objectType.isInterface()) {
                            return bean;
                        }
                        // We proxify here because Tapestry calls toString method on proxy, which realizes the underlying service, with scope issues
                        return (T) Proxy.newProxyInstance(objectType.getClassLoader(),
                                new Class<?>[] { objectType }, new AbstractInvocationHandler() {
                                    @Override
                                    protected Object handleInvocation(Object proxy, Method method,
                                            Object[] args) throws Throwable {
                                        String methodName = method.getName();
                                        if (methodName.equals("equals")) {
                                            // Only consider equal when proxies are identical.
                                            return (proxy == args[0]);
                                        }
                                        if (methodName.equals("hashCode")) {
                                            // Use hashCode of proxy.
                                            return System.identityHashCode(proxy);
                                        }
                                        if (methodName.equals("toString")) {
                                            return "Current Spring " + objectType.getSimpleName();
                                        }
                                        try {
                                            return method.invoke(bean, args);
                                        } catch (InvocationTargetException e) {
                                            throw e.getCause();
                                        }
                                    }
                                });

                    } catch (NoUniqueBeanDefinitionException e) {
                        String message = String.format(
                                "Spring context contains %d beans assignable to type %s.",
                                e.getNumberOfBeansFound(), PlasticUtils.toTypeName(objectType));

                        throw new IllegalArgumentException(message, e);
                    } catch (NoSuchBeanDefinitionException e) {
                        return null;
                    }
                }
            };
            //endregion

            final ObjectProvider springBeanProviderInvoker = new ObjectProvider() {
                @Override
                public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
                        final ObjectLocator locator) {
                    return tracker.invoke("Resolving dependency by searching Spring ApplicationContext",
                            () -> springBeanProvider.provide(objectType, annotationProvider, locator));
                }
            };

            ObjectProvider outerCheck = new ObjectProvider() {
                @Override
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {
                    // I think the following line is the only reason we put the
                    // SpringBeanProvider here,
                    // rather than in SpringModule.

                    if (!applicationContextCreated.get())
                        return null;

                    return springBeanProviderInvoker.provide(objectType, annotationProvider, locator);
                }
            };

            configuration.add("SpringBean", outerCheck, "after:AnnotationBasedContributions",
                    "after:ServiceOverride");
        }
    };
}

From source file:com.sap.prd.mobile.ios.mios.XCodeVerificationCheckMojo.java

private Exception performCheck(ClassRealm verificationCheckRealm, final Check checkDesc)
        throws MojoExecutionException {

    getLog().info(String.format("Performing verification check '%s'.", checkDesc.getClazz()));

    if (getLog().isDebugEnabled()) {

        final Charset defaultCharset = Charset.defaultCharset();
        final ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
        final PrintStream ps;
        try {// ww w  .  ja va2  s. c o  m
            ps = new PrintStream(byteOs, true, defaultCharset.name());
        } catch (UnsupportedEncodingException ex) {
            throw new MojoExecutionException(
                    String.format("Charset '%s' cannot be found.", defaultCharset.name()));
        }

        try {
            verificationCheckRealm.display(ps);
            ps.close();
            getLog().debug(String.format("Using classloader for loading verification check '%s':%s%s",
                    checkDesc.getClazz(), System.getProperty("line.separator"),
                    new String(byteOs.toByteArray(), defaultCharset)));
        } finally {
            IOUtils.closeQuietly(ps);
        }
    }

    try {
        final Class<?> verificationCheckClass = Class.forName(checkDesc.getClazz(), true,
                verificationCheckRealm);

        getLog().debug(String.format("Verification check class %s has been loaded by %s.",
                verificationCheckClass.getName(), verificationCheckClass.getClassLoader()));
        getLog().debug(String.format("Verification check super class %s has been loaded by %s.",
                verificationCheckClass.getSuperclass().getName(),
                verificationCheckClass.getSuperclass().getClassLoader()));
        getLog().debug(String.format("%s class used by this class (%s) has been loaded by %s.",
                VerificationCheck.class.getName(), this.getClass().getName(),
                VerificationCheck.class.getClassLoader()));

        for (final String configuration : getConfigurations()) {
            for (final String sdk : getSDKs()) {
                getLog().info(
                        String.format("Executing verification check: '%s' for configuration '%s' and sdk '%s'.",
                                verificationCheckClass.getName(), configuration, sdk));
                final VerificationCheck verificationCheck = (VerificationCheck) verificationCheckClass
                        .newInstance();
                verificationCheck
                        .setXcodeContext(getXCodeContext(SourceCodeLocation.WORKING_COPY, configuration, sdk));
                verificationCheck.setMavenProject(project);
                verificationCheck.setEffectiveBuildSettings(new EffectiveBuildSettings());
                try {
                    verificationCheck.check();
                } catch (VerificationException ex) {
                    return ex;
                } catch (RuntimeException ex) {
                    return ex;
                }
            }
        }
        return null;
    } catch (ClassNotFoundException ex) {
        throw new MojoExecutionException("Could not load verification check '" + checkDesc.getClazz()
                + "'. May be your classpath has not been properly extended. "
                + "Provide the GAV of the project containing the check as attributes as part of the check defintion in the check configuration file.",
                ex);
    } catch (NoClassDefFoundError err) {
        getLog().error(String.format(
                "Could not load verification check '%s'. "
                        + "May be your classpath has not been properly extended. "
                        + "Additional dependencies need to be declard inside the check definition file: %s",
                checkDesc.getClazz(), err.getMessage()), err);
        throw err;
    } catch (InstantiationException ex) {
        throw new MojoExecutionException(String.format("Could not instanciate verification check '%s': %s",
                checkDesc.getClazz(), ex.getMessage()), ex);
    } catch (IllegalAccessException ex) {
        throw new MojoExecutionException(String.format("Could not access verification check '%s': %s",
                checkDesc.getClazz(), ex.getMessage()), ex);
    }

}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

@SuppressWarnings("unchecked")
private <T> T makeInterface(final Object obj, final Class<T> clazz) {
    if (null == clazz || !clazz.isInterface())
        throw new IllegalArgumentException("interface Class expected");

    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
            (proxy, m, args) -> invokeImpl(obj, m.getName(), args));
}

From source file:com.dilmus.dilshad.scabi.core.async.DComputeNoBlock.java

public Future<HttpResponse> executeClass(Class<? extends DComputeUnit> cls)
        throws ClientProtocolException, IOException {
    HttpPost postRequest = new HttpPost("/Compute/Execute/Class");

    Class<? extends DComputeUnit> p = cls;

    String className = p.getName();
    log.debug("executeClass() className  : {}", className);
    String classAsPath = className.replace('.', '/') + ".class";
    log.debug("executeClass() classAsPath  : {}", classAsPath);

    InputStream in = p.getClassLoader().getResourceAsStream(classAsPath);
    byte b[] = DMUtil.toBytesFromInStreamForJavaFiles(in);
    in.close();/*  w  w  w . j  a v a  2 s .c  om*/
    //log.debug("executeClass() b[] as string : {}", b.toString());
    String hexStr = DMUtil.toHexString(b);
    //log.debug("executeClass() Hex string is : {}", hexStr);

    DMJson djson1 = new DMJson("TotalComputeUnit", "" + m_TU);
    DMJson djson2 = djson1.add("SplitComputeUnit", "" + m_SU);
    DMJson djson3 = djson2.add("JsonInput", "" + m_jsonStrInput);
    DMJson djson4 = djson3.add("ClassName", className);
    DMJson djson5 = djson4.add("ClassBytes", hexStr);

    log.debug("executeClass() m_jarFilePathList.size() : {}", m_jarFilePathList.size());
    if (m_jarFilePathList.size() > 0) {
        djson5 = addJars(djson5);
        m_jarFilePathList.clear();
    }

    log.debug("executeClass() m_isComputeUnitJarsSet : {}", m_isComputeUnitJarsSet);
    if (m_isComputeUnitJarsSet) {
        djson5 = addComputeUnitJars(djson5);
        m_isComputeUnitJarsSet = false;
        m_dcl = null;
    }

    //StringEntity params = new StringEntity(djson5.toString());
    //postRequest.addHeader("content-type", "application/json");
    //postRequest.setEntity(params);

    postRequest.addHeader("Content-Encoding", "gzip");
    postRequest.addHeader("Accept-Encoding", "gzip");

    //=====================================================================
    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    try (GZIPOutputStream gzipstream = new GZIPOutputStream(bytestream)) {
        gzipstream.write(djson5.toString().getBytes("UTF-8"));
    }
    byte[] gzipBytes = bytestream.toByteArray();
    bytestream.close();
    ByteArrayEntity byteEntity = new ByteArrayEntity(gzipBytes);
    postRequest.setEntity(byteEntity);
    //======================================================================

    log.debug("executeClass() executing request to " + m_target + "/Compute/Execute/Class");
    incCountRequests();
    Future<HttpResponse> futureHttpResponse = m_httpClient.execute(m_target, postRequest, null);
    return futureHttpResponse;

}

From source file:org.apache.nifi.controller.AbstractComponentNode.java

private ValidationResult validateControllerServiceApi(final PropertyDescriptor descriptor,
        final ControllerServiceNode controllerServiceNode) {
    final Class<? extends ControllerService> controllerServiceApiClass = descriptor
            .getControllerServiceDefinition();
    final ClassLoader controllerServiceApiClassLoader = controllerServiceApiClass.getClassLoader();
    final ExtensionManager extensionManager = serviceProvider.getExtensionManager();

    final String serviceId = controllerServiceNode.getIdentifier();
    final String propertyName = descriptor.getDisplayName();

    final Bundle controllerServiceApiBundle = extensionManager.getBundle(controllerServiceApiClassLoader);
    if (controllerServiceApiBundle == null) {
        return createInvalidResult(serviceId, propertyName,
                "Unable to find bundle for ControllerService API class "
                        + controllerServiceApiClass.getCanonicalName());
    }// w w w  .  ja v a 2 s .co m
    final BundleCoordinate controllerServiceApiCoordinate = controllerServiceApiBundle.getBundleDetails()
            .getCoordinate();

    final Bundle controllerServiceBundle = extensionManager
            .getBundle(controllerServiceNode.getBundleCoordinate());
    if (controllerServiceBundle == null) {
        return createInvalidResult(serviceId, propertyName,
                "Unable to find bundle for coordinate " + controllerServiceNode.getBundleCoordinate());
    }
    final BundleCoordinate controllerServiceCoordinate = controllerServiceBundle.getBundleDetails()
            .getCoordinate();

    final boolean matchesApi = matchesApi(extensionManager, controllerServiceBundle,
            controllerServiceApiCoordinate);

    if (!matchesApi) {
        final String controllerServiceType = controllerServiceNode.getComponentType();
        final String controllerServiceApiType = controllerServiceApiClass.getSimpleName();

        final String explanation = new StringBuilder().append(controllerServiceType).append(" - ")
                .append(controllerServiceCoordinate.getVersion()).append(" from ")
                .append(controllerServiceCoordinate.getGroup()).append(" - ")
                .append(controllerServiceCoordinate.getId()).append(" is not compatible with ")
                .append(controllerServiceApiType).append(" - ")
                .append(controllerServiceApiCoordinate.getVersion()).append(" from ")
                .append(controllerServiceApiCoordinate.getGroup()).append(" - ")
                .append(controllerServiceApiCoordinate.getId()).toString();

        return createInvalidResult(serviceId, propertyName, explanation);
    }

    return null;
}

From source file:no.sesat.search.datamodel.DataModelFactoryImpl.java

@SuppressWarnings("unchecked")
public DataModel instantiate() {

    try {/*from  w  w w  . j  a  v  a2  s .co  m*/
        final Class<DataModel> cls = DataModel.class;

        final PropertyDescriptor[] propDescriptors = Introspector.getBeanInfo(DataModel.class)
                .getPropertyDescriptors();
        final Property[] properties = new Property[propDescriptors.length];
        for (int i = 0; i < properties.length; ++i) {
            properties[i] = new Property(propDescriptors[i].getName(),
                    propDescriptors[i] instanceof MappedPropertyDescriptor
                            ? new MapDataObjectSupport(Collections.EMPTY_MAP)
                            : null);
        }

        final InvocationHandler handler = new BeanDataModelInvocationHandler(
                new BeanDataModelInvocationHandler.PropertyInitialisor(DataModel.class, properties));

        return (DataModel) ConcurrentProxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, handler);

    } catch (IntrospectionException ie) {
        throw new IllegalStateException("Need to introspect DataModel properties before instantiation");
    }
}

From source file:com.dilmus.dilshad.scabi.core.async.DComputeNoBlock.java

public Future<HttpResponse> executeObject(DComputeUnit obj) throws ClientProtocolException, IOException {
    HttpPost postRequest = new HttpPost("/Compute/Execute/ClassFromObject");

    Class<? extends DComputeUnit> p = obj.getClass();
    String className = p.getName();
    log.debug("executeObject() className  : {}", className);
    String classAsPath = className.replace('.', '/') + ".class";
    log.debug("executeObject() classAsPath  : {}", classAsPath);

    InputStream in = p.getClassLoader().getResourceAsStream(classAsPath);
    byte b[] = DMUtil.toBytesFromInStreamForJavaFiles(in);
    in.close();// ww w. j  av  a2s . c o m
    //log.debug("executeObject() b[] as string : {}", b.toString());
    String hexStr = DMUtil.toHexString(b);
    //log.debug("executeObject() Hex string is : {}", hexStr);

    DMJson djson1 = new DMJson("TotalComputeUnit", "" + m_TU);
    DMJson djson2 = djson1.add("SplitComputeUnit", "" + m_SU);
    DMJson djson3 = djson2.add("JsonInput", "" + m_jsonStrInput);
    DMJson djson4 = djson3.add("ClassName", className);
    DMJson djson5 = djson4.add("ClassBytes", hexStr);

    log.debug("executeObject() m_jarFilePathList.size() : {}", m_jarFilePathList.size());
    if (m_jarFilePathList.size() > 0) {
        djson5 = addJars(djson5);
        m_jarFilePathList.clear();
    }

    log.debug("executeObject() m_isComputeUnitJarsSet : {}", m_isComputeUnitJarsSet);
    if (m_isComputeUnitJarsSet) {
        djson5 = addComputeUnitJars(djson5);
        m_isComputeUnitJarsSet = false;
        m_dcl = null;
    }

    //works StringEntity params = new StringEntity(djson5.toString());
    //works postRequest.addHeader("content-type", "application/json");
    //works postRequest.setEntity(params);

    postRequest.addHeader("Content-Encoding", "gzip");
    postRequest.addHeader("Accept-Encoding", "gzip");

    //=====================================================================
    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    try (GZIPOutputStream gzipstream = new GZIPOutputStream(bytestream)) {
        gzipstream.write(djson5.toString().getBytes("UTF-8"));
    }
    byte[] gzipBytes = bytestream.toByteArray();
    bytestream.close();
    ByteArrayEntity byteEntity = new ByteArrayEntity(gzipBytes);
    postRequest.setEntity(byteEntity);
    //======================================================================

    log.debug("executeObject() executing request to " + m_target + "/Compute/Execute/ClassFromObject");
    incCountRequests();
    Future<HttpResponse> futureHttpResponse = m_httpClient.execute(m_target, postRequest, null);
    return futureHttpResponse;

}

From source file:org.apache.hadoop.ipc.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. 
 * @param <T>*//*from ww w  . j a va  2  s  . c  o m*/
@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout,
        RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth) throws IOException {

    if (connectionRetryPolicy != null) {
        throw new UnsupportedOperationException(
                "Not supported: connectionRetryPolicy=" + connectionRetryPolicy);
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout, fallbackToSimpleAuth));
    return new ProtocolProxy<T>(protocol, proxy, true);
}

From source file:com.homesnap.engine.controller.Controller.java

/**
 * Initializes the state names with their class types in order to prevent from a wrong assigment when the {@link #set(StateName, StateValue)} method is called.
 *//*from  w  w w .  ja v a 2s  .co  m*/
private void initStateTypes(Class<?> clazz) {
    // Check if the controller class is known
    stateTypes = classTypes.get(clazz);
    if (stateTypes == null) {
        Class<?> superClass = clazz.getSuperclass();
        while (!Controller.class.equals(superClass)) {
            initStateTypes(superClass);
            break;
        }
        // Search the ".states" resource which defines the state types of the controller
        String pkgName = clazz.getPackage().getName().replace('.', '/');
        URL url = clazz.getClassLoader().getResource(pkgName + "/" + clazz.getSimpleName() + ".states");
        if (url == null) {
            throw new RuntimeException("Unable to find states definition file for " + clazz.getName());
        }
        // Load the definition file
        StatesReader reader = new StatesReader();
        try {
            reader.load(url.openStream());
        } catch (IOException e) {
            throw new RuntimeException("Unable to load states definition file for " + getClass().getName(), e);
        }
        stateTypes = (StateSection) reader.getControllerSection();
        classTypes.put(clazz, stateTypes);
    }
}