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.ambraproject.configuration.ConfigurationStore.java

/**
 * Iterate over all the resources of the given name and add them to our root
 * configuration.//w ww.  java2s.co  m
 * @param root the root configuration to add to
 * @param resource the resource to add
 * @throws ConfigurationException on an error in adding the new config
 */
public static void addResources(CombinedConfiguration root, String resource) throws ConfigurationException {
    Class<?> klass = ConfigurationStore.class;
    if (resource.startsWith("/")) {
        root.addConfiguration(getConfigurationFromUrl(klass.getResource(resource)));
        log.info("Added resource '" + resource + "' to configuration");
    } else {
        try {
            Enumeration<URL> rs = klass.getClassLoader().getResources(resource);
            while (rs.hasMoreElements()) {
                URL resourceUrl = rs.nextElement();
                root.addConfiguration(getConfigurationFromUrl(resourceUrl));
                log.info("Added resource '" + resourceUrl + "' from path '" + resource + "' to configuration");
            }
        } catch (IOException ioe) {
            throw new Error("Unexpected error loading resources", ioe);
        }
    }
}

From source file:com.splicemachine.mrio.api.SpliceTableMapReduceUtil.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.
 *
 * This is shamelessly copied from JobConf
 *
 * @param my_class the class to find.//w w w  .  j av  a  2s. c  o  m
 * @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());
                }
                // 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");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.apache.tajo.yarn.command.LaunchCommand.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.
 *
 * @param clazz the class to find.//from w  w  w. jav a  2s  .c om
 * @return a jar file that contains the class, or null.
 * @throws IOException on any error
 */
private static String findContainingJar(Class<?> clazz) throws IOException {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
        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");
            return toReturn.replaceAll("!.*$", "");
        }
    }

    throw new IOException("Fail to locat a JAR for class: " + clazz.getName());
}

From source file:org.eclipse.wb.tests.designer.TestUtils.java

/**
 * @return the names of methods declared in the given {@link Class}, in same order as in source.
 *///from  ww  w .j a  va 2 s.c o  m
private static List<String> getSourceMethodNames(Class<?> testClass) throws Exception {
    final List<String> sourceMethodNames = Lists.newArrayList();
    String classPath = testClass.getName().replace('.', '/') + ".class";
    InputStream classStream = testClass.getClassLoader().getResourceAsStream(classPath);
    ClassReader classReader = new ClassReader(classStream);
    classReader.accept(new EmptyVisitor() {
        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            sourceMethodNames.add(name);
            return new EmptyVisitor();
        }
    }, 0);
    return sourceMethodNames;
}

From source file:ClassUtils.java

/**
 * Look up the class in the Tread Context ClassLoader and in the "current" ClassLoader.
 * @param className The class name to load
 * @param clazz a class used to get classloader
 * @return the corresponding Class instance
 * @throws ClassNotFoundException if the Class was not found.
 *///w ww. ja  v  a  2 s  .c  o m
public static Class forName(final String className, final Class clazz) throws ClassNotFoundException {
    // Load classes from different classloaders :
    // 1. Thread Context ClassLoader
    // 2. ClassUtils ClassLoader

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Class cls = null;

    try {
        // Try with TCCL
        cls = Class.forName(className, true, tccl);
    } catch (ClassNotFoundException cnfe) {

        // Try now with the classloader used to load ClassUtils
        ClassLoader current = clazz.getClassLoader();
        if (current != null) {
            try {
                cls = Class.forName(className, true, current);
            } catch (ClassNotFoundException cnfe2) {
                // If this is still unknown, throw an Exception
                throw new ClassNotFoundException("Class Not found in current ThreadClassLoader '" + tccl
                        + "' and in '" + current + "' classloaders.", cnfe2);
            }
        } else {
            // rethrow exception
            throw cnfe;
        }
    }

    return cls;
}

From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java

public static void writeBinaryResourceWithContentFromClassPath(final Class<?> clazz,
        final String pathToResource, String targetFileName) throws IOException {
    final InputStream resource = clazz.getClassLoader().getResourceAsStream(pathToResource);
    if (resource == null) {
        throw new RuntimeException("Cannot find resource '" + pathToResource + "'");
    }//ww  w . j  ava2  s .c o m

    if (targetFileName == null) {
        final int pos = pathToResource.lastIndexOf('/');

        if (pos > -1) {
            targetFileName = pathToResource.substring(pos + 1);
        } else {
            targetFileName = pathToResource;
        }
    }

    FileOutputStream to = null;
    try {
        to = new FileOutputStream(new File(targetFileName));
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = resource.read(buffer)) != -1)
            to.write(buffer, 0, bytesRead); // write
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (resource != null)
            try {
                resource.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:com.tesora.dve.common.PEFileUtils.java

/**
 * Save the specified properties back to a file
 * //  w w  w. j a  va 2  s  .c  om
 * @param testClass
 * @param fileName
 * @param props
 * @throws PEException
 */
public static void savePropertiesToClasspath(Class<?> testClass, String fileName, Properties props)
        throws PEException {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(testClass.getClassLoader().getResource(fileName).toURI()));

        // We will encrypt on a cloned copy of the properties so that we can
        // continue using the properties we have
        Properties clonedProps = (Properties) props.clone();

        encrypt(clonedProps);

        clonedProps.store(fos, "This file was last updated by DVE on:");
    } catch (Exception e) {
        throw new PEException("Error saving properties file '" + fileName + "'", e);
    } finally {
        if (fos != null) {
            try {

                fos.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:ipc.RPC.java

private static synchronized RpcEngine getProtocolEngine(Class protocol, Configuration conf) {
    RpcEngine engine = PROTOCOL_ENGINES.get(protocol);
    if (engine == null) {
        Class<?> impl = conf.getClass(ENGINE_PROP + "." + protocol.getName(), WritableRpcEngine.class);
        engine = (RpcEngine) ReflectionUtils.newInstance(impl, conf);
        if (protocol.isInterface())
            PROXY_ENGINES.put(Proxy.getProxyClass(protocol.getClassLoader(), protocol), engine);
        PROTOCOL_ENGINES.put(protocol, engine);
    }//from ww  w .  j  a v  a2 s . c  o m
    return engine;
}

From source file:org.apache.axiom.util.stax.dialect.StAXDialectDetector.java

/**
 * Detect the dialect of a given StAX implementation.
 * //from   ww w  . ja v a 2 s . co  m
 * @param implementationClass
 *            any class that is part of the StAX implementation; typically this should be a
 *            {@link XMLInputFactory}, {@link XMLOutputFactory},
 *            {@link javax.xml.stream.XMLStreamReader} or
 *            {@link javax.xml.stream.XMLStreamWriter} implementation
 * @return the detected dialect
 */
public static StAXDialect getDialect(Class implementationClass) {
    URL rootUrl = getRootUrlForClass(implementationClass);
    if (rootUrl == null) {
        log.warn("Unable to determine location of StAX implementation containing class "
                + implementationClass.getName() + "; using default dialect");
        return UnknownStAXDialect.INSTANCE;
    }
    return getDialect(implementationClass.getClassLoader(), rootUrl);
}

From source file:org.apache.hadoop.hbase.io.crypto.Encryption.java

private static ClassLoader getClassLoaderForClass(Class<?> c) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = c.getClassLoader();
    }//from  w  ww  .j  ava  2  s. com
    if (cl == null) {
        cl = ClassLoader.getSystemClassLoader();
    }
    if (cl == null) {
        throw new RuntimeException("A ClassLoader to load the Cipher could not be determined");
    }
    return cl;
}