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:com.gh.bmd.jrt.android.v4.core.DefaultObjectContextRoutineBuilder.java

@Nonnull
public <TYPE> TYPE buildProxy(@Nonnull final Class<TYPE> itf) {

    if (!itf.isInterface()) {

        throw new IllegalArgumentException(
                "the specified class is not an interface: " + itf.getCanonicalName());
    }/*from  w  ww. j  a va  2 s .  c o  m*/

    final RoutineConfiguration configuration = mConfiguration;

    if (configuration != null) {

        warn(configuration);
    }

    final Object proxy = Proxy.newProxyInstance(itf.getClassLoader(), new Class[] { itf },
            new ProxyInvocationHandler(this, itf));
    return itf.cast(proxy);
}

From source file:com.asakusafw.testdriver.BatchTestDriver.java

/**
 * ?????????//  w  w  w.j av a2 s  . c o  m
 * @param batchDescriptionClass ???
 */
public void runTest(Class<? extends BatchDescription> batchDescriptionClass) {

    try {
        JobflowExecutor executor = new JobflowExecutor(driverContext);

        // ?
        executor.cleanWorkingDirectory();

        // ???Excel???
        storeDatabase();
        setLastModifiedTimestamp(new Timestamp(0L));

        // ???
        BatchDriver batchDriver = BatchDriver.analyze(batchDescriptionClass);
        assertFalse(batchDriver.getDiagnostics().toString(), batchDriver.hasError());

        File compileWorkDir = driverContext.getCompilerWorkingDirectory();
        if (compileWorkDir.exists()) {
            FileUtils.forceDelete(compileWorkDir);
        }

        File compilerOutputDir = new File(compileWorkDir, "output");
        File compilerLocalWorkingDir = new File(compileWorkDir, "build");

        BatchInfo batchInfo = DirectBatchCompiler.compile(batchDescriptionClass, "test.batch",
                Location.fromPath(driverContext.getClusterWorkDir(), '/'), compilerOutputDir,
                compilerLocalWorkingDir,
                Arrays.asList(new File[] { DirectFlowCompiler.toLibraryPath(batchDescriptionClass) }),
                batchDescriptionClass.getClassLoader(), driverContext.getOptions());

        for (JobflowInfo jobflowInfo : batchInfo.getJobflows()) {
            driverContext.prepareCurrentJobflow(jobflowInfo);
            executor.runJobflow(jobflowInfo);
        }

        // ???Excel??DB??
        loadDatabase();
        if (!testUtils.inspect()) {
            Assert.fail(testUtils.getCauseMessage());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        driverContext.cleanUpTemporaryResources();
    }
}

From source file:org.frat.common.converter.DeepConverter.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//  w  w  w  .  j a  v  a  2s . c o m
public Object convert(Object value, Class targetClass, Object context) {
    if (targetClass != null && value != null) {
        Class<? extends Object> sourceClass = value.getClass();
        if (targetClass.equals(sourceClass)) {
            return value;
        }
        // primitive type
        if (sourceClass.isPrimitive() || targetClass.isPrimitive()) {
            return value;
        }
        // collection
        if (Collection.class.isAssignableFrom(sourceClass) && Collection.class.isAssignableFrom(targetClass)) {
            // not supported
            return null;
        } else if (Timestamp.class.isAssignableFrom(sourceClass)
                && targetClass.isAssignableFrom(String.class)) {
            return timeStampFormatter.format((Timestamp) value);
        } else if (Date.class.isAssignableFrom(sourceClass) && targetClass.isAssignableFrom(String.class)) {
            return dateFormatter.format((Date) value);
        } else if (java.util.Date.class.isAssignableFrom(targetClass)
                && sourceClass.isAssignableFrom(String.class)) {
            try {
                return DateUtils.parseDate(value.toString(), new String[] { "yyyy-MM-dd" });
            } catch (ParseException e) {
                return null;
            }
        } else if (targetClass.isAssignableFrom(sourceClass)) {
            return value;
        }
        // complex type
        if (targetClass.getClassLoader() != null && sourceClass.getClassLoader() != null) {
            return ConverterService.convert(value, targetClass, null);
        }

    }
    return null;
}

From source file:com.asakusafw.testdriver.JobFlowTestDriver.java

/**
 * ???????//from www  . j a v  a 2 s . c  om
 * @param jobFlowDescriptionClass ?
 * @throws RuntimeException ?????
 */
public void runTest(Class<? extends FlowDescription> jobFlowDescriptionClass) {

    try {
        JobflowExecutor executor = new JobflowExecutor(driverContext);

        // ?
        executor.cleanWorkingDirectory();

        // ???Excel???
        storeDatabase();
        setLastModifiedTimestamp(new Timestamp(0L));

        // ?
        JobFlowDriver jobFlowDriver = JobFlowDriver.analyze(jobFlowDescriptionClass);
        assertFalse(jobFlowDriver.getDiagnostics().toString(), jobFlowDriver.hasError());
        JobFlowClass jobFlowClass = jobFlowDriver.getJobFlowClass();

        String flowId = jobFlowClass.getConfig().name();
        File compileWorkDir = driverContext.getCompilerWorkingDirectory();
        if (compileWorkDir.exists()) {
            FileUtils.forceDelete(compileWorkDir);
        }

        FlowGraph flowGraph = jobFlowClass.getGraph();
        JobflowInfo jobflowInfo = DirectFlowCompiler.compile(flowGraph, batchId, flowId, "test.jobflow",
                Location.fromPath(driverContext.getClusterWorkDir(), '/'), compileWorkDir,
                Arrays.asList(new File[] { DirectFlowCompiler.toLibraryPath(jobFlowDescriptionClass) }),
                jobFlowDescriptionClass.getClassLoader(), driverContext.getOptions());

        driverContext.prepareCurrentJobflow(jobflowInfo);

        executor.runJobflow(jobflowInfo);

        // ???Excel??DB??
        loadDatabase();
        if (!testUtils.inspect()) {
            Assert.fail(testUtils.getCauseMessage());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        driverContext.cleanUpTemporaryResources();
    }
}

From source file:com.xie.javacase.json.JSONObject.java

private void populateInternalMap(Object bean, boolean includeSuperClass) {
    Class klass = bean.getClass();

    /* If klass.getSuperClass is System class then force includeSuperClass to false. */

    if (klass.getClassLoader() == null) {
        includeSuperClass = false;/*from  w w  w .  ja v a  2 s.  c  o m*/
    }

    Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    key = name.substring(3);
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (key.length() > 0 && Character.isUpperCase(key.charAt(0))
                        && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }

                    Object result = method.invoke(bean, (Object[]) null);
                    if (result == null) {
                        map.put(key, NULL);
                    } else if (result.getClass().isArray()) {
                        map.put(key, new JSONArray(result, includeSuperClass));
                    } else if (result instanceof Collection) { // List or Set
                        map.put(key, new JSONArray((Collection) result, includeSuperClass));
                    } else if (result instanceof Map) {
                        map.put(key, new JSONObject((Map) result, includeSuperClass));
                    } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
                        map.put(key, result);
                    } else {
                        if (result.getClass().getPackage().getName().startsWith("java")
                                || result.getClass().getClassLoader() == null) {
                            map.put(key, result.toString());
                        } else { // User defined Objects
                            map.put(key, new JSONObject(result, includeSuperClass));
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:cn.powerdash.libsystem.common.converter.DeepConverter.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from   w w w. j  a  v a  2s .c  o  m*/
public Object convert(Object value, Class targetClass, Object context) {
    if (targetClass != null && value != null) {
        Class<? extends Object> sourceClass = value.getClass();
        if (targetClass.equals(sourceClass)) {
            return value;
        }
        // primitive type
        if (sourceClass.isPrimitive() || targetClass.isPrimitive()) {
            return value;
        }
        // collection
        if (Collection.class.isAssignableFrom(sourceClass) && Collection.class.isAssignableFrom(targetClass)) {
            // not supported
            return null;
        } else if (Timestamp.class.isAssignableFrom(sourceClass)
                && targetClass.isAssignableFrom(String.class)) {
            return new SimpleDateFormat(TIMESTAMP_FORMAT).format((Timestamp) value);
        } else if (Date.class.isAssignableFrom(sourceClass) && targetClass.isAssignableFrom(String.class)) {
            return new SimpleDateFormat(DATE_FORMAT).format((Date) value);
        } else if (java.util.Date.class.isAssignableFrom(targetClass)
                && sourceClass.isAssignableFrom(String.class)) {
            try {
                return DateUtils.parseDate(value.toString(), new String[] { "yyyy-MM-dd" });
            } catch (ParseException e) {
                return null;
            }
        } else if (targetClass.isAssignableFrom(sourceClass)) {
            return value;
        }
        // complex type
        if (targetClass.getClassLoader() != null && sourceClass.getClassLoader() != null) {
            return ConverterService.convert(value, targetClass, null);
        }

    }
    return null;
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Clear IntrospectionUtils caches of Tomcat and Apache Commons Modeler
 *///from  w  ww.  j a v a2s. c  o m
protected void clearIntrospectionUtilsCache() {
    // Tomcat
    final Class tomcatIntrospectionUtils = findClass("org.apache.tomcat.util.IntrospectionUtils");
    if (tomcatIntrospectionUtils != null) {
        try {
            tomcatIntrospectionUtils.getMethod("clear").invoke(null);
        } catch (Exception ex) {
            if (!mayBeJBoss) // JBoss includes this class, but no cache and no clear() method
                error(ex);
        }
    }

    // Apache Commons Modeler
    final Class modelIntrospectionUtils = findClass("org.apache.commons.modeler.util.IntrospectionUtils");
    if (modelIntrospectionUtils != null
            && !isWebAppClassLoaderOrChild(modelIntrospectionUtils.getClassLoader())) { // Loaded outside web app
        try {
            modelIntrospectionUtils.getMethod("clear").invoke(null);
        } catch (Exception ex) {
            warn("org.apache.commons.modeler.util.IntrospectionUtils needs to be cleared but there was an error, "
                    + "consider upgrading Apache Commons Modeler");
            error(ex);
        }
    }
}

From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java

public <T> T javascriptProxyForResponse(final JSONObject obj, Class<T> baseInterface,
        Class<?>... otherClasses) {
    Class<?>[] allClasses;// w  w  w . ja v a 2 s  .  c o m

    if (otherClasses.length == 0) {
        allClasses = new Class[] { baseInterface };
    } else {
        allClasses = new Class[otherClasses.length + 1];
        allClasses[0] = baseInterface;
        System.arraycopy(otherClasses, 0, allClasses, 1, otherClasses.length);
    }
    InvocationHandler h = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            Class<?> returnType = method.getReturnType();
            if (void.class.equals(returnType) && args.length == 1) {
                String propertyName = findSetter(methodName);
                if (propertyName != null) {
                    handleSetter(obj, propertyName, args[0]);
                }
            }

            String propertyName = findGetter(methodName);
            if (propertyName != null) {
                return handleGetter(obj, returnType, propertyName);
            }

            if ("toString".equals(methodName) && String.class.equals(returnType)) {
                return obj.toString();
            }

            return null;
        }

    };
    Object proxy = Proxy.newProxyInstance(baseInterface.getClassLoader(), allClasses, h);
    return baseInterface.cast(proxy);
}

From source file:com.gs.jrpip.client.FastServletProxyFactory.java

/**
 * Creates a new proxy with the specified URL.  The returned object
 * is a proxy with the interface specified by api.
 * <p/>//from w ww  .  ja  va  2 s.c  om
 * <pre>
 * String url = "http://localhost:7001/objectmanager/JrpipServlet");
 * RemoteObjectManager rom = (RemoteObjectManager) factory.create(RemoteObjectManager.class, url);
 * </pre>
 *
 * @param api           the interface the proxy class needs to implement
 * @param url           the URL where the client object is located.
 * @param timeoutMillis maximum timeoutMillis for remote method call to run, zero for no timeoutMillis
 * @return a proxy to the object with the specified interface.
 */
public <T> T create(Class<T> api, String url, int timeoutMillis, boolean disconnectedMode)
        throws MalformedURLException {
    T result = null;
    if (this.useLocalService) {
        result = JrpipServiceRegistry.getInstance().getLocalService(url, api);
    }
    if (result == null) {
        AuthenticatedUrl authenticatedUrl = new AuthenticatedUrl(url, this.credentials,
                this.authenticationCookies);
        boolean supportsChunking = disconnectedMode || serverSupportsChunking(authenticatedUrl);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("chunking support at {} :{} received client id: {}", url, supportsChunking,
                    getProxyId(authenticatedUrl));
        }
        if (this.useLocalService) {
            result = JrpipServiceRegistry.getInstance().getLocalService(url, api);
        }
        if (result == null) {
            InvocationHandler handler = this.invocationHandlerFunction.getInvocationHandler(authenticatedUrl,
                    api, timeoutMillis);
            result = (T) Proxy.newProxyInstance(api.getClassLoader(), new Class[] { api }, handler);
        }
    }
    return result;
}

From source file:org.apache.juneau.rest.client.RestClient.java

/**
 * Same as {@link #getRemoteableProxy(Class, Object)} but allows you to override the serializer and parser used.
 *
 * @param interfaceClass The interface to create a proxy for.
 * @param restUrl The URL of the REST interface.
 * @param serializer The serializer used to serialize POJOs to the body of the HTTP request.
 * @param parser The parser used to parse POJOs from the body of the HTTP response.
 * @return The new proxy interface./*from  www . j  a  v a 2  s .  co  m*/
 */
@SuppressWarnings({ "unchecked", "hiding" })
public <T> T getRemoteableProxy(final Class<T> interfaceClass, Object restUrl, final Serializer serializer,
        final Parser parser) {

    if (restUrl == null) {
        Remoteable r = ReflectionUtils.getAnnotation(Remoteable.class, interfaceClass);

        String path = r == null ? "" : trimSlashes(r.path());
        if (path.indexOf("://") == -1) {
            if (path.isEmpty())
                path = interfaceClass.getName();
            if (rootUrl == null)
                throw new RemoteableMetadataException(interfaceClass,
                        "Root URI has not been specified.  Cannot construct absolute path to remoteable proxy.");
            path = trimSlashes(rootUrl) + '/' + path;
        }
        restUrl = path;
    }

    final String restUrl2 = restUrl.toString();

    try {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass },
                new InvocationHandler() {

                    final RemoteableMeta rm = new RemoteableMeta(interfaceClass, restUrl2);

                    @Override /* InvocationHandler */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        RemoteableMethodMeta rmm = rm.getMethodMeta(method);

                        if (rmm == null)
                            throw new RuntimeException("Method is not exposed as a remoteable method.");

                        try {
                            String url = rmm.getUrl();
                            String httpMethod = rmm.getHttpMethod();
                            RestCall rc = (httpMethod.equals("POST") ? doPost(url) : doGet(url));
                            rc.serializer(serializer).parser(parser);

                            for (RemoteMethodArg a : rmm.getPathArgs())
                                rc.path(a.name, args[a.index], a.serializer);

                            for (RemoteMethodArg a : rmm.getQueryArgs())
                                rc.query(a.name, args[a.index], a.skipIfNE, a.serializer);

                            for (RemoteMethodArg a : rmm.getFormDataArgs())
                                rc.formData(a.name, args[a.index], a.skipIfNE, a.serializer);

                            for (RemoteMethodArg a : rmm.getHeaderArgs())
                                rc.header(a.name, args[a.index], a.skipIfNE, a.serializer);

                            if (rmm.getBodyArg() != null)
                                rc.input(args[rmm.getBodyArg()]);

                            if (rmm.getRequestBeanArgs().length > 0) {
                                BeanSession bs = getBeanContext().createSession();

                                for (Integer i : rmm.getRequestBeanArgs()) {
                                    BeanMap<?> bm = bs.toBeanMap(args[i]);
                                    for (BeanPropertyValue bpv : bm.getValues(true)) {
                                        BeanPropertyMeta pMeta = bpv.getMeta();
                                        Object val = bpv.getValue();

                                        Path p = pMeta.getAnnotation(Path.class);
                                        if (p != null)
                                            rc.path(getName(p.value(), pMeta), val,
                                                    getPartSerializer(p.serializer()));

                                        Query q1 = pMeta.getAnnotation(Query.class);
                                        if (q1 != null)
                                            rc.query(getName(q1.value(), pMeta), val, false,
                                                    getPartSerializer(q1.serializer()));

                                        QueryIfNE q2 = pMeta.getAnnotation(QueryIfNE.class);
                                        if (q2 != null)
                                            rc.query(getName(q2.value(), pMeta), val, true,
                                                    getPartSerializer(q2.serializer()));

                                        FormData f1 = pMeta.getAnnotation(FormData.class);
                                        if (f1 != null)
                                            rc.formData(getName(f1.value(), pMeta), val, false,
                                                    getPartSerializer(f1.serializer()));

                                        FormDataIfNE f2 = pMeta.getAnnotation(FormDataIfNE.class);
                                        if (f2 != null)
                                            rc.formData(getName(f2.value(), pMeta), val, true,
                                                    getPartSerializer(f2.serializer()));

                                        org.apache.juneau.remoteable.Header h1 = pMeta
                                                .getAnnotation(org.apache.juneau.remoteable.Header.class);
                                        if (h1 != null)
                                            rc.header(getName(h1.value(), pMeta), val, false,
                                                    getPartSerializer(h1.serializer()));

                                        HeaderIfNE h2 = pMeta.getAnnotation(HeaderIfNE.class);
                                        if (h2 != null)
                                            rc.header(getName(h2.value(), pMeta), val, true,
                                                    getPartSerializer(h2.serializer()));
                                    }
                                }
                            }

                            if (rmm.getOtherArgs().length > 0) {
                                Object[] otherArgs = new Object[rmm.getOtherArgs().length];
                                int i = 0;
                                for (Integer otherArg : rmm.getOtherArgs())
                                    otherArgs[i++] = args[otherArg];
                                rc.input(otherArgs);
                            }

                            return rc.getResponse(method.getGenericReturnType());

                        } catch (RestCallException e) {
                            // Try to throw original exception if possible.
                            e.throwServerException(interfaceClass.getClassLoader());
                            throw new RuntimeException(e);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}