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.ibm.team.build.internal.hjplugin.RTCScm.java

private void sendJarsToSlave(FilePath workspacePath)
        throws MalformedURLException, IOException, InterruptedException {
    VirtualChannel channel = workspacePath.getChannel();
    if (channel instanceof Channel) {
        // try to find our jars
        List<URL> ourJars = new ArrayList<URL>(2);
        Class<?> originalClass = RTCScm.class;
        URLClassLoader originalClassLoader = (URLClassLoader) originalClass.getClassLoader();
        URL[] originalURLs = originalClassLoader.getURLs();
        for (URL url : originalURLs) {
            String file = url.getFile();
            if (file.contains("com.ibm.team.build.hjplugin-rtc") && file.endsWith(".jar")) { //$NON-NLS-1$ //$NON-NLS-2$
                LOGGER.finer("Found our jar for prefetch " + url.getFile()); //$NON-NLS-1$
                ourJars.add(url);/*www  .  j a v  a 2  s  .c  o  m*/
            }
        }
        LOGGER.finer("Found " + ourJars.size() + " jars for remote prefetch"); //$NON-NLS-1$ //$NON-NLS-2$
        URL[] jars = ourJars.toArray(new URL[ourJars.size()]);
        boolean result = ((Channel) channel).preloadJar(originalClassLoader, jars);
        LOGGER.finer("Prefetch result for " + ((Channel) channel).getName() + " is " + result); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:org.eclipse.jubula.tools.internal.serialisation.XStreamXmlSerializer.java

/**
 * {@inheritDoc}/*from w  ww .j  av  a2s. c o  m*/
 *      java.lang.Class)
 */
public Object deserialize(String text, Class clazz) throws SerialisationException {

    Validate.notNull(text);
    Validate.notNull(clazz);
    try {
        ClassLoader streamClassLoader = m_stream.getClassLoader();
        // If this is a CompositeClassLoader, the class loader that
        // has loaded the passed clazz instance, will be added to
        // the CompositeClassLoader. So we ensure that XStream
        // loads the class correctly inside an Eclipse Plugin.
        // If XStream doesn't return the CompositeClassLoader, there
        // is no way to give XStream any class loader support.
        if (streamClassLoader instanceof CompositeClassLoader) {
            synchronized (this) {
                ClassLoader classLoader = clazz.getClassLoader();
                if (!m_addedClassLoaders.contains(classLoader)) {
                    ((CompositeClassLoader) streamClassLoader).add(classLoader);
                    m_addedClassLoaders.add(classLoader);
                }
            }
        }
        // split into Header and Body
        if (text.startsWith("<?")) { //$NON-NLS-1$
            String xmlHeader = text.substring(0, text.indexOf(">") + 1); //$NON-NLS-1$
            String xmlBody = StringUtils.substringAfter(text, ">"); //$NON-NLS-1$
            checkVersion(xmlHeader);
            return m_stream.fromXML(xmlBody);
        }
        return m_stream.fromXML(text);

    } catch (XStreamException e) {
        throw new SerialisationException(e.getMessage(), MessageIDs.E_SERILIZATION_FAILED);
    }
}

From source file:org.eclipse.jubula.tools.serialisation.XStreamXmlSerializer.java

/**
 * {@inheritDoc}/*  w  w  w . j  av  a  2s . com*/
 *      java.lang.Class)
 */
public Object deserialize(String text, Class clazz) throws SerialisationException {

    Validate.notNull(text);
    Validate.notNull(clazz);
    try {
        ClassLoader streamClassLoader = m_stream.getClassLoader();
        // If this is a CompositeClassLoader, the class loader that
        // has loaded the passed clazz instance, will be added to
        // the CompositeClassLoader. So we ensure that XStream
        // loads the class correctly inside an Eclipse Plugin.
        // If XStream doesn't return the CompositeClassLoader, there
        // is no way to give XStream any class loader support.
        if (streamClassLoader instanceof CompositeClassLoader) {
            synchronized (this) {
                ClassLoader classLoader = clazz.getClassLoader();
                if (!m_addedClassLoaders.contains(classLoader)) {
                    ((CompositeClassLoader) streamClassLoader).add(classLoader);
                    m_addedClassLoaders.add(classLoader);
                }
            }
        }
        // split into Header and Body
        if (text.startsWith("<?")) { //$NON-NLS-1$
            String xmlHeader = text.substring(0, text.indexOf(">") + 1); //$NON-NLS-1$
            String xmlBody = StringUtils.substringAfter(text, ">"); //$NON-NLS-1$
            checkVersion(xmlHeader);
            return m_stream.fromXML(xmlBody);
        }
        return m_stream.fromXML(text);

    } catch (BaseException e) {
        throw new SerialisationException(e.getMessage(), MessageIDs.E_SERILIZATION_FAILED);
    }
}

From source file:com.github.hrpc.rpc.ProtobufRpcEngine.java

@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, Option conf,
        SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy) throws IOException {

    final Invoker invoker = new Invoker(protocol, addr, conf, factory, rpcTimeout, connectionRetryPolicy);
    return new ProtocolProxy<T>(protocol,
            (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, invoker));
}

From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java

private <T> T createEntityManagerProxy(Class<T> interfaceClass, Object emProxy) {
    InvocationHandler handler = (proxy, method, args) -> {

        EntityManager em = entityManagerLocal.get() != null ? entityManagerLocal.get()
                : (EntityManager) emProxy;
        switch (method.getName()) {
        case "hashCode":
            return hashCode();
        case "equals":
            return (em == args[0]);
        case "toString":
            return "Camel EntityManager proxy [" + em.toString() + "]";
        }/*from  w ww .ja v a  2s  .  c  o m*/

        if (!em.isJoinedToTransaction()) {
            em.joinTransaction();
        }
        return method.invoke(em, args);
    };
    return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler);
}

From source file:org.apache.oozie.service.ShareLibService.java

/**
 * Find containing jar containing.//  w w w  . ja  v  a  2s .  c o  m
 *
 * @param clazz the clazz
 * @return the string
 */
@VisibleForTesting
protected String findContainingJar(Class clazz) {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                    // URLDecoder is a misnamed class, since it actually
                    // decodes
                    // x-www-form-urlencoded MIME type rather than actual
                    // URL encoding (which the file path has). Therefore it
                    // would
                    // decode +s to ' 's which is incorrect (spaces are
                    // actually
                    // either unencoded or encoded as "%20"). Replace +s
                    // first, so
                    // that they are kept sacred during the decoding
                    // process.
                    toReturn = toReturn.replaceAll("\\+", "%2B");
                    toReturn = URLDecoder.decode(toReturn, "UTF-8");
                    toReturn = toReturn.replaceAll("!.*$", "");
                    return toReturn;
                }
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    return null;
}

From source file:org.apache.hadoop.mapred.JobConf.java

/** 
 * Find a jar that contains a class of the same name, if any.
 * It will return a jar file, even if that is not the first thing
 * on the class path that has a class with the same name.
 * //from w ww . j a  v  a  2s .c o m
 * @param my_class the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

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

public <T> T javascriptProxyForModule(Class<T> baseInterface, Class<?>... otherClasses) {
    Class<?>[] allClasses;//from  www.  j a  va  2s.  co 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 {
            mKirinHelper.jsMethod(method.getName(), (Object[]) args);
            return null;
        }
    };

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

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.NameSupport.java

/**
 * Adds <code>JField</code> with given name and @UiField annotation into "form" <code>JType</code>
 * ./*  ww  w.j  ava  2s .c  o m*/
 */
private void addFormJField(Class<?> componentClass, String name) throws Exception {
    IDevModeBridge bridge = m_context.getState().getDevModeBridge();
    ClassLoader devClassLoader = bridge.getDevClassLoader();
    // prepare "form" JType
    Object formType = bridge.findJType(m_context.getFormType().getFullyQualifiedName());
    // prepare @UiField annotation instance
    Class<?> uiFieldAnnotationClass = devClassLoader.loadClass("com.google.gwt.uibinder.client.UiField");
    java.lang.annotation.Annotation annotation = (java.lang.annotation.Annotation) Proxy.newProxyInstance(
            uiFieldAnnotationClass.getClassLoader(), new Class[] { uiFieldAnnotationClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return Boolean.TRUE;
                }
            });
    // add new JField
    Object newField;
    {
        Constructor<?> fieldConstructor;
        Class<?> fieldClass;
        if (m_context.getState().getVersion().isHigherOrSame(Utils.GWT_2_2)) {
            fieldClass = devClassLoader.loadClass("com.google.gwt.dev.javac.typemodel.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.dev.javac.typemodel.JClassType,java.lang.String,java.util.Map)");
        } else {
            fieldClass = devClassLoader.loadClass("com.google.gwt.core.ext.typeinfo.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.core.ext.typeinfo.JClassType,java.lang.String,java.util.Map)");
        }
        newField = fieldConstructor.newInstance(formType, name,
                ImmutableMap.of(uiFieldAnnotationClass, annotation));
    }
    // set "widget" JType for JField
    Object widgetType = bridge.findJType(ReflectionUtils.getCanonicalName(componentClass));
    ReflectionUtils.invokeMethod(newField, "setType(com.google.gwt.core.ext.typeinfo.JType)", widgetType);
}

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

@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 {

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