Example usage for java.lang Class getProtectionDomain

List of usage examples for java.lang Class getProtectionDomain

Introduction

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

Prototype

public java.security.ProtectionDomain getProtectionDomain() 

Source Link

Document

Returns the ProtectionDomain of this class.

Usage

From source file:jenkins.model.RunIdMigrator.java

private static String getUnmigrationCommandLine(File jenkinsHome) {
    StringBuilder cp = new StringBuilder();
    for (Class<?> c : new Class<?>[] { RunIdMigrator.class,
            /* TODO how to calculate transitive dependencies automatically? */Charsets.class,
            WriterOutputStream.class, BuildException.class, FastDateFormat.class }) {
        URL location = c.getProtectionDomain().getCodeSource().getLocation();
        String locationS = location.toString();
        if (location.getProtocol().equals("file")) {
            try {
                locationS = new File(location.toURI()).getAbsolutePath();
            } catch (URISyntaxException x) {
                // never mind
            }//  w  ww .  jav  a  2s.  c  o m
        }
        if (cp.length() > 0) {
            cp.append(File.pathSeparator);
        }
        cp.append(locationS);
    }
    return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome);
}

From source file:azkaban.jobtype.HadoopSparkJob.java

private static String getSourcePathFromClass(final Class<?> containedClass) {
    File file = new File(containedClass.getProtectionDomain().getCodeSource().getLocation().getPath());

    if (!file.isDirectory() && file.getName().endsWith(".class")) {
        final String name = containedClass.getName();
        final StringTokenizer tokenizer = new StringTokenizer(name, ".");
        while (tokenizer.hasMoreTokens()) {
            tokenizer.nextElement();//from   www .j  a  va2  s  .com
            file = file.getParentFile();
        }

        return file.getPath();
    } else {
        return containedClass.getProtectionDomain().getCodeSource().getLocation().getPath();
    }
}

From source file:com.seleniumtests.core.SeleniumTestsContextManager.java

/**
 * Build the root path of STF /*  w ww. j a  va 2  s .c  om*/
 * method for guessing it is different if we are inside a jar (built mode) or in development
 * @param clazz
 * @param path
 * @return
 */
public static void getPathFromClass(Class<?> clazz, StringBuilder path) {

    try {
        String url = URLDecoder.decode(clazz.getProtectionDomain().getCodeSource().getLocation().getFile(),
                "UTF-8");
        if (url.endsWith(".jar")) {
            path.append((new File(url).getParentFile().getAbsoluteFile().toString() + "/")
                    .replace(File.separator, "/"));
            deployedMode = true;
        } else {
            path.append((new File(url).getParentFile().getParentFile().getAbsoluteFile().toString() + "/")
                    .replace(File.separator, "/"));
            deployedMode = false;
        }
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
    }
}

From source file:com.datatorrent.stram.StramClient.java

public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
        try {//  w ww.j a  v  a 2 s.com
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
            jarClasses.add(clazz);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Failed to load class " + className, e);
        }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
        // process class and super classes (super does not require deploy annotation)
        for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
            //LOG.debug("checking " + c);
            jarClasses.add(c);
            jarClasses.addAll(Arrays.asList(c.getInterfaces()));
        }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
        LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
        if (jarClass.getProtectionDomain().getCodeSource() == null) {
            // system class
            continue;
        }
        String sourceLocation = jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
        String jar = sourceToJar.get(sourceLocation);
        if (jar == null) {
            // don't create jar file from folders multiple times
            jar = JarFinder.getJar(jarClass);
            sourceToJar.put(sourceLocation, jar);
            LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
        }
        if (jar == null) {
            throw new AssertionError("Cannot resolve jar file for " + jarClass);
        }
        localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
        String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
        localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * /* w  ww. ja v a  2 s  . co  m*/
 * @param clazz
 *          the Class
 * @param results,
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class<?> clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n.." + parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n...." + urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null)
        results.append("\n++++CodeSource: " + clazzCS);
    else
        results.append("\n++++Null CodeSource");
    results.append("\nImplemented Interfaces:");
    Class<?>[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        results.append("\n++" + ifaces[i]);
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: " + loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null)
            results.append("\n++++CodeSource: " + cs);
        else
            results.append("\n++++Null CodeSource");
    }
}

From source file:Main.java

public Main() {
    Class cls = this.getClass();
    ProtectionDomain pDomain = cls.getProtectionDomain();
    CodeSource cSource = pDomain.getCodeSource();
    URL loc = cSource.getLocation();

}

From source file:Main.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * //from  w ww.j a  va  2s . c  om
 * @param clazz
 *          the Class
 * @param results -
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the clazz
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n");
    results.append(clazz.getName());
    results.append("(");
    results.append(Integer.toHexString(clazz.hashCode()));
    results.append(").ClassLoader=");
    results.append(cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n..");
        results.append(parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n....");
            results.append(urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) {
        results.append("\n++++CodeSource: ");
        results.append(clazzCS);
    } else
        results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        Class iface = ifaces[i];
        results.append("\n++");
        results.append(iface);
        results.append("(");
        results.append(Integer.toHexString(iface.hashCode()));
        results.append(")");
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: ");
        results.append(loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            results.append("\n++++CodeSource: ");
            results.append(cs);
        } else
            results.append("\n++++Null CodeSource");
    }
}

From source file:com.uber.hoodie.cli.commands.UtilsCommand.java

@CliCommand(value = "utils loadClass", help = "Load a class")
public String loadClass(@CliOption(key = { "class" }, help = "Check mode") final String clazz)
        throws Exception {
    Class klass = Class.forName(clazz);
    return klass.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
}

From source file:ClassVersionInfo.java

public ClassVersionInfo(String name, ClassLoader loader) throws ClassNotFoundException {
    this.name = name;
    Class c = loader.loadClass(name);
    CodeSource cs = c.getProtectionDomain().getCodeSource();
    if (cs != null)
        location = cs.getLocation();/*from  w  w  w . ja  va 2  s  .  c om*/
    if (c.isInterface() == false) {
        ObjectStreamClass osc = ObjectStreamClass.lookup(c);
        if (osc != null) {
            serialVersion = osc.getSerialVersionUID();
            try {
                c.getDeclaredField("serialVersionUID");
                hasExplicitSerialVersionUID = true;
            } catch (NoSuchFieldException e) {
                hasExplicitSerialVersionUID = false;
            }
        }
    }
}

From source file:com.blackducksoftware.tools.commonframework.core.util.CodeSourceLocationCheck.java

public void findCodeSourceLocation(Class<Base64> codeSourceClass) {
    log.info("CODESOURCE LOCATION: " + codeSourceClass.getProtectionDomain().getCodeSource().getLocation());
}