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:org.neo4j.test.TargetDirectory.java

private static File locateTarget(Class<?> owningTest) {
    try {/*from   w  ww .ja va 2s .  c o m*/
        File codeSource = new File(owningTest.getProtectionDomain().getCodeSource().getLocation().toURI());
        if (codeSource.isDirectory()) {
            // code loaded from a directory
            return codeSource.getParentFile();
        }
    } catch (URISyntaxException e) {
        // ignored
    }
    return new File("target");
}

From source file:org.nuclos.server.report.ejb3.ReportFacadeBean.java

public static String getClassPathFor(Class<?>... classes) {
    StringBuilder sb = new StringBuilder();
    for (Class<?> clazz : classes) {
        if (sb.length() > 0) {
            sb.append(File.pathSeparator);
        }//w w w  . j a va  2 s .c o m
        try {
            ProtectionDomain protectionDomain = clazz.getProtectionDomain();
            CodeSource codeSource = protectionDomain.getCodeSource();
            URL location = codeSource.getLocation();
            String path = location.getFile();
            path = URLDecoder.decode(path, "UTF-8");
            sb.append(path);
        } catch (Exception e) {
            throw new NuclosFatalException("Cannot configure JasperReports classpath ", e);
        }
    }
    return sb.toString();
}

From source file:org.openadaptor.util.ClasspathUtils.java

/**
 * Utility to find where a class was originally loaded from.
 * This may be handy to debug issues where it seems an incorrect
 * class is being loaded (e.g. where the same class may exist in 
 * multiple jars)./*from  ww w .  jav  a2 s.co  m*/
 * It returns null if the class was loaded from JRE (I think!)
 * @param cls The class to lookup
 * @return URL where class was loaded from, or null if JRE
 * @since 3.4.5
 */
public static URL getClassOrigin(Class cls) {
    URL result = null;
    ProtectionDomain domain = cls.getProtectionDomain();
    if (cls != null) {
        CodeSource source = domain.getCodeSource();
        if (source != null) {
            result = source.getLocation();
        }
    }
    return result;
}

From source file:org.opencms.setup.CmsUpdateBean.java

/**
 * Preloads classes from the same jar file as a given class.<p>
 * /*ww w. ja  v  a2 s  .com*/
 * @param cls the class for which the classes from the same jar file should be loaded 
 */
public void preload(Class<?> cls) {

    try {
        File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile());
        java.util.jar.JarFile jarfile = new JarFile(jar);
        try {
            Enumeration<JarEntry> entries = jarfile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                if (name.endsWith(".class")) {
                    String className = name.replaceFirst("\\.class$", "");
                    className = className.replace('/', '.');
                    try {
                        Class.forName(className);
                    } catch (VirtualMachineError e) {
                        throw e;
                    } catch (Throwable e) {
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                }
            }
        } finally {
            jarfile.close();
        }
    } catch (VirtualMachineError e) {
        throw e;
    } catch (Throwable e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
}

From source file:org.openmrs.module.ModuleClassLoader.java

/**
 * Get the base class url of the given <code>cls</code>. Used for checking against system class
 * loads vs classloader loads/*  ww  w.j  a  v a2 s  . c o  m*/
 *
 * @param cls Class name
 * @return URL to the class
 */
private static URL getClassBaseUrl(final Class<?> cls) {
    ProtectionDomain pd = cls.getProtectionDomain();

    if (pd != null) {
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            return cs.getLocation();
        }

    }

    return null;
}

From source file:org.openspaces.test.client.executor.ExecutorUtils.java

/**
 * This is a very cool method which returns jar or directory from where the supplied class has
 * loaded./*from  w w  w  .j av  a2s.  co  m*/
 *
 * @param claz the class to get location.
 * @return jar/path location of supplied class.
 */
@SuppressWarnings("rawtypes")
public static String getClassLocation(Class claz) {
    return claz.getProtectionDomain().getCodeSource().getLocation().toString().substring(5);
}

From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java

/**
 * get a jar file from a sample class/*  www.  j  a va 2  s. c  o  m*/
 * @param sampleClass
 * @return the jar file
 */
public static File jarFile(Class sampleClass) {
    try {
        CodeSource codeSource = sampleClass.getProtectionDomain().getCodeSource();
        if (codeSource != null && codeSource.getLocation() != null) {
            String fileName = URLDecoder.decode(codeSource.getLocation().getFile(), "UTF-8");
            return new File(fileName);
        }
        String resourcePath = sampleClass.getName();
        resourcePath = resourcePath.replace('.', '/') + ".class";
        URL url = computeUrl(resourcePath, true);
        String urlPath = url.toString();

        if (urlPath.startsWith("jar:")) {
            urlPath = urlPath.substring(4);
        }
        if (urlPath.startsWith("file:")) {
            urlPath = urlPath.substring(5);
        }
        urlPath = prefixOrSuffix(urlPath, "!", true);

        urlPath = URLDecoder.decode(urlPath, "UTF-8");

        File file = new File(urlPath);
        if (urlPath.endsWith(".jar") && file.exists() && file.isFile()) {
            return file;
        }
    } catch (Exception e) {
        LOG.warn("Cant find jar for class: " + sampleClass + ", " + e.getMessage(), e);
    }
    return null;
}

From source file:org.owasp.dependencycheck.utils.FileUtils.java

/**
 * Retrieves the physical path to the parent directory containing the provided class. For example, if a JAR file
 * contained a class org.something.clazz this method would return the parent directory of the JAR file.
 *
 * @param clazz the class to determine the parent directory of
 * @return the parent directory of the file containing the specified class.
 * @throws UnsupportedEncodingException thrown if UTF-8 is not supported.
 * @deprecated this should no longer be used.
 *//*w w w . j av  a2s .c o  m*/
@java.lang.Deprecated
public static File getPathToJar(Class clazz) throws UnsupportedEncodingException {
    final String filePath = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
    final String decodedPath = URLDecoder.decode(filePath, "UTF-8");
    final File jarPath = new File(decodedPath);
    return jarPath.getParentFile();
}

From source file:org.pepstock.jem.ant.tasks.StepJava.java

/**
 * Change the main class of the stepjava becuase this is necessary if it wants to apply
 * the JEm annotation to the main java class developed with business logic.
 * /*w w  w  .  java 2s.  c  o m*/
 * @throws NamingException if is not ableto get the right info from JNDI
 */
private void setCustomMainClass() throws NamingException {
    // sets here the annotations
    try {
        // if has got a classpath, change the main class with a JEM one
        if (super.getCommandLine().haveClasspath()) {
            Class<?> clazz = JavaMainClassLauncher.class;
            // gets where the class is located
            // becuase it must be added to classpath
            CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
            if (codeSource != null) {
                // gets URL
                URL url = codeSource.getLocation();
                if (url != null) {
                    // add at the ends of parameters the classname
                    super.createArg().setValue(getClassname());
                    // changes class name
                    super.setClassname(JavaMainClassLauncher.class.getName());
                    // adds URL to classpath
                    super.createClasspath()
                            .add(new Path(getProject(), FileUtils.toFile(url).getAbsolutePath()));
                }
            }
        } else {
            // if no classpath, can substitute here
            Class<?> clazz = Class.forName(getClassname());
            SetFields.applyByAnnotation(clazz);
        }
    } catch (ClassNotFoundException e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }
}

From source file:org.phenotips.variantstore.shared.ResourceManager.java

/**
 * Copy resources bundled with the application to a specified folder.
 *
 * @param source      the path of the resources relative to the resource folder
 * @param destination the destination//ww w  .  j  a  v a2  s. c o m
 * @param clazz       the class that owns the resource we want
 * @throws DatabaseException if an error occurs
 */
public static void copyResourcesToPath(final Path source, Path destination, Class<?> clazz)
        throws DatabaseException {
    Path dest = destination;
    // Check if storage dirs exists
    if (Files.isDirectory(dest)) {
        return;
    }

    // Make sure that we aren't double-nesting directories
    if (dest.endsWith(source)) {
        dest = dest.getParent();
    }

    if (clazz.getProtectionDomain().getCodeSource() == null) {
        throw new DatabaseException("This is running in a jar loaded from the system class loader. "
                + "Don't know how to handle this.");
    }
    // Windows adds leading `/` to the path resulting in
    // java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/...
    URL path = clazz.getProtectionDomain().getCodeSource().getLocation();
    Path resourcesPath;
    try {
        resourcesPath = Paths.get(path.toURI());
    } catch (URISyntaxException ex) {
        throw new DatabaseException("Incorrect resource path", ex);
    }

    try {

        // make destination folder
        Files.createDirectories(dest);

        // if we are running in a jar, get the resources from the jar
        if ("jar".equals(FilenameUtils.getExtension(resourcesPath.toString()))) {

            copyResourcesFromJar(resourcesPath, source, dest);

            // if running from an IDE or the filesystem, get the resources from the folder
        } else {

            copyResourcesFromFilesystem(resourcesPath.resolve(source), dest.resolve(source));

        }
    } catch (IOException e) {
        throw new DatabaseException("Error setting up variant store, unable to install resources.", e);
    }

}