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.stratuscom.harvester.deployer.StarterServiceDeployer.java

private boolean hasServiceStarterConstructor(ClassLoader cl, String className) throws ClassNotFoundException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl);
    try {//  w  w w  .j a va  2  s  .c  om
        Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass });
        return true;
    } catch (NoSuchMethodException nsme) {
        return false;
    }
}

From source file:dpfmanager.shell.modules.report.core.ReportGenerator.java

/**
 * Read filefrom resources string./*w  w  w  .  j a  va2  s.  c o m*/
 *
 * @param pathStr the path str
 * @return the string
 */
public String readFilefromResources(String pathStr) {
    String text = "";
    Path path = Paths.get(pathStr);
    try {
        if (Files.exists(path)) {
            // Look in current dir
            BufferedReader br = new BufferedReader(new FileReader(pathStr));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            text = sb.toString();
            br.close();
        } else {
            // Look in JAR
            Class cls = ReportGenerator.class;
            ClassLoader cLoader = cls.getClassLoader();
            InputStream in = cLoader.getResourceAsStream(pathStr);
            if (in != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder out = new StringBuilder();
                String newLine = System.getProperty("line.separator");
                String line;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                    out.append(newLine);
                }
                text = out.toString();
            }
        }
    } catch (FileNotFoundException e) {
        context.send(BasicConfig.MODULE_MESSAGE,
                new LogMessage(getClass(), Level.ERROR, "Template for html not found in dir."));
    } catch (IOException e) {
        context.send(BasicConfig.MODULE_MESSAGE,
                new LogMessage(getClass(), Level.ERROR, "Error reading " + pathStr));
    }

    return text;
}

From source file:ResourceBundleSupport.java

/**
 * Returns the classloader, which was responsible for loading the given
 * class.//from   w  w  w.  ja  v a2 s. com
 *
 * @param c the classloader, either an application class loader or the
 *          boot loader.
 * @return the classloader, never null.
 * @throws SecurityException if the SecurityManager does not allow to grab
 *                           the context classloader.
 */
public static ClassLoader getClassLoader(final Class c) {
    final String localClassLoaderSource;
    synchronized (ObjectUtilities.class) {
        if (classLoader != null) {
            return classLoader;
        }
        localClassLoaderSource = classLoaderSource;
    }

    if ("ThreadContext".equals(localClassLoaderSource)) {
        final ClassLoader threadLoader = Thread.currentThread().getContextClassLoader();
        if (threadLoader != null) {
            return threadLoader;
        }
    }

    // Context classloader - do not cache ..
    final ClassLoader applicationCL = c.getClassLoader();
    if (applicationCL == null) {
        return ClassLoader.getSystemClassLoader();
    } else {
        return applicationCL;
    }
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private void callMain(ClassLoader cl, String className, String[] args) throws ClassNotFoundException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    try {//  w ww.  ja  v a 2 s .c  o  m
        Method main = clazz.getMethod(Strings.MAIN, new Class[] { String[].class });
        main.invoke(null, new Object[] { args });
    } catch (NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }

}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private Object instantiateService(ClassLoader cl, String className, String[] parms)
        throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl);
    Constructor[] constructors = clazz.getDeclaredConstructors();
    System.out.println("Class is " + clazz);
    for (int i = 0; i < constructors.length; i++) {
        Constructor constructor = constructors[i];
        System.out.println("Found constructor " + constructor + " on " + className);
    }/*  w  w w .ja  v a 2s.c om*/
    Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass });
    constructor.setAccessible(true);
    return constructor.newInstance(parms, null);
}

From source file:dpfmanager.conformancechecker.tiff.reporting.HtmlReport.java

/**
 * Read filefrom resources string./*from w w w . j av  a 2s .c o m*/
 *
 * @param pathStr the path str
 * @return the string
 */
public String readFilefromResources(String pathStr) {
    String text = "";
    Path path = Paths.get(pathStr);
    try {
        if (Files.exists(path)) {
            // Look in current dir
            BufferedReader br = new BufferedReader(new FileReader(pathStr));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            text = sb.toString();
            br.close();
        } else {
            // Look in JAR
            Class cls = ReportGenerator.class;
            ClassLoader cLoader = cls.getClassLoader();
            InputStream in = cLoader.getResourceAsStream(pathStr);
            if (in != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder out = new StringBuilder();
                String newLine = System.getProperty("line.separator");
                String line;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                    out.append(newLine);
                }
                text = out.toString();
            }
        }
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    }

    return text;
}

From source file:org.apache.hadoop.hbase.ipc.bak.MonitoredRpcEngine.java

/**
 * Construct a client-side proxy object that implements the named protocol, talking to a server at
 * the named address.//from   w  w  w . j a  v a  2s . co  m
 */
@Override
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;
}

From source file:org.eclipse.wb.internal.core.model.creation.ThisCreationSupport.java

/**
 * @return <code>true</code> if we need to use {@link Enhancer} for this component, and
 *         <code>false</code> if this component can be created more lightly, without CGLib.
 *//*ww w.ja v  a 2 s.c o m*/
private boolean needEnhancer() {
    ComponentDescription description = m_javaInfo.getDescription();
    if (description.hasTrueParameter("binaryExecutionFlow.no")) {
        return false;
    }
    Class<?> componentClass = description.getComponentClass();
    boolean isSystemClass = componentClass.getClassLoader() == null;
    return !isSystemClass && !Enhancer.isEnhanced(componentClass);
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * A convenience method for returning the configpath for a test.
 * pConfigDirectory is the top level name to be used for the configpath.
 * Returns a file in the baseConfigDirectory (or baseConfigDirectory +
 * "data") subdirectory of the the passed in class's location.<P>
 * <p/>/*from   w ww  . ja  v a2s  . co m*/
 * The directory location is calculated as (in psuedo-code):
 * <code>
 * (classRelativeTo's package location) + "/" + (pConfigDirectory or "data") + "/config"
 * </code>
 *
 * @param classRelativeTo
 *         the class whose package the config/data
 *         (or baseConfigDirectory/data) should be relative in.
 * @param baseConfigDirectory
 *         the base configuration directory If null,
 *         uses "config".
 * @param createDirectory
 *         whether to create the config/data subdirectory if
 *         it does not exist.
 *
 * @return The calculated configuration path.
 */
public static File getConfigPath(Class classRelativeTo, String baseConfigDirectory, boolean createDirectory) {
    Map<String, File> baseConfigToFile = configPath.get(classRelativeTo);
    if (baseConfigToFile == null) {
        baseConfigToFile = new ConcurrentHashMap<String, File>();
        configPath.put(classRelativeTo, baseConfigToFile);
    }

    File fileFound = baseConfigToFile.get(baseConfigDirectory);

    if (!baseConfigToFile.containsKey(baseConfigDirectory)) {
        String configdirname = "config";
        String packageName = StringUtils.replaceChars(classRelativeTo.getPackage().getName(), '.', '/');
        if (baseConfigDirectory != null) {
            configdirname = baseConfigDirectory;
        }

        String configFolder = packageName + "/data/" + configdirname;
        URL dataURL = classRelativeTo.getClassLoader().getResource(configFolder);

        // Mkdir
        if (dataURL == null) {
            URL root = classRelativeTo.getClassLoader().getResource(packageName);

            File f = null;
            if (root != null) {
                f = new File(root.getFile());
            }
            File f2 = new File(f, "/data/" + configdirname);
            if (createDirectory) {
                f2.mkdirs();
            }
            dataURL = NucleusUtils.class.getClassLoader().getResource(configFolder);
            if (dataURL == null) {
                System.err.println("Warning: Could not find resource \"" + configFolder + "\" in CLASSPATH");
            }
        }
        if (dataURL != null) {// check if this URL is contained within a jar file
            // if so, extract to a temp dir, otherwise just return
            // the directory
            fileFound = extractJarDataURL(dataURL);
            baseConfigToFile.put(baseConfigDirectory, fileFound);
        }
    }
    if (fileFound != null) {
        System.setProperty("atg.configpath", fileFound.getAbsolutePath());
    }
    return fileFound;
}

From source file:com.smartsheet.api.internal.SmartsheetImpl.java

/**
 * Compose a User-Agent string that represents this version of the SDK (along with platform info)
 *
 * @return a User-Agent string//from   w  w  w . j a  va  2s .c  o m
 */
private String generateUserAgent(String userAgent) {
    String title = null;
    String thisVersion = null;

    if (userAgent == null) {
        StackTraceElement[] callers = Thread.currentThread().getStackTrace();
        String module = null;
        String callerClass = null;
        int stackIdx;
        for (stackIdx = callers.length - 1; stackIdx >= 0; stackIdx--) {
            callerClass = callers[stackIdx].getClassName();
            try {
                Class<?> clazz = Class.forName(callerClass);
                ClassLoader classLoader = clazz.getClassLoader();
                // skip JRE classes
                if (classLoader == null) {
                    continue;
                }
                String classFilePath = callerClass.replace(".", "/") + ".class";
                URL classUrl = classLoader.getResource(classFilePath);
                if (classUrl != null) {
                    String classUrlPath = classUrl.getPath();
                    int jarSeparator = classUrlPath.indexOf('!');
                    if (jarSeparator > 0) {
                        module = classUrlPath.substring(0, jarSeparator);
                        // extract the last path element (the jar name only)
                        module = module.substring(module.lastIndexOf('/') + 1);
                        break;
                    }
                }
            } catch (Exception ex) {
            }
        }
        userAgent = module + "!" + callerClass;
    }
    try {
        final Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("sdk.properties"));
        thisVersion = properties.getProperty("sdk.version");
        title = properties.getProperty("sdk.name");
    } catch (IOException e) {
    }
    return title + "/" + thisVersion + "/" + userAgent + "/" + System.getProperty("os.name") + " "
            + System.getProperty("java.vm.name") + " " + System.getProperty("java.vendor") + " "
            + System.getProperty("java.version");
}