Example usage for java.security CodeSource getLocation

List of usage examples for java.security CodeSource getLocation

Introduction

In this page you can find the example usage for java.security CodeSource getLocation.

Prototype

public final URL getLocation() 

Source Link

Document

Returns the location associated with this CodeSource.

Usage

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *///  www.j  a v a  2s .  c om
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:org.openanzo.client.cli.CommandLineInterface.java

private static String determineVersion() throws URISyntaxException, IOException {
    String version = null;/*from  ww w.  j  a v  a  2  s  .  c  o  m*/
    if (CommandLineInterface.class.getProtectionDomain() != null
            && CommandLineInterface.class.getProtectionDomain().getCodeSource() != null
            && CommandLineInterface.class.getProtectionDomain().getCodeSource().getLocation() != null) {
        ProtectionDomain domain = CommandLineInterface.class.getProtectionDomain();
        CodeSource source = domain.getCodeSource();
        URL location = source.getLocation();
        if (location != null) {
            File file = new File(location.toURI());
            if (file.exists()) {
                JarFile jar = new JarFile(file);
                version = jar.getManifest().getMainAttributes().getValue("Bundle-Version");
                if (version == null) {
                    version = jar.getManifest().getMainAttributes().getValue("Implementation-Build");
                }
            }
        }
    }
    if (version == null) {
        version = CommandLineInterface.class.getPackage().getImplementationVersion();
    }
    return version;
}

From source file:msearch.tool.MSFunktionen.java

public static String getPathJar() {
    // liefert den Pfad der Programmdatei mit File.separator am Schluss
    String pFilePath = "pFile";
    File propFile = new File(pFilePath);
    if (!propFile.exists()) {
        try {//  www .  j  a  v a 2s. c om
            CodeSource cS = Main.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(cS.getLocation().toURI().getPath());
            String jarDir = jarFile.getParentFile().getPath();
            propFile = new File(jarDir + File.separator + pFilePath);
        } catch (Exception ex) {
        }
    }
    String s = propFile.getAbsolutePath().replace(pFilePath, "");
    if (!s.endsWith(File.separator)) {
        s = s + File.separator;
    }
    return s;
}

From source file:jenkins.security.ClassFilterImpl.java

/**
 * Tries to determine what JAR file a given class was loaded from.
 * The location is an opaque string suitable only for comparison to others.
 * Similar to {@link Which#jarFile(Class)} but potentially faster, and more tolerant of unknown URL formats.
 * @param c some class/*from   w  w w.  j  ava 2 s  . c  om*/
 * @return something typically like {@code file://plugins/structs/WEB-INF/lib/structs-1.10.jar};
 *         or null for classes in the Java Platform, some generated classes, etc.
 */
private static @CheckForNull String codeSource(@Nonnull Class<?> c) {
    CodeSource cs = c.getProtectionDomain().getCodeSource();
    if (cs == null) {
        return null;
    }
    URL loc = cs.getLocation();
    if (loc == null) {
        return null;
    }
    String r = loc.toString();
    if (r.endsWith(".class")) {
        // JENKINS-49147: Tomcat bug. Now do the more expensive check
        String suffix = c.getName().replace('.', '/') + ".class";
        if (r.endsWith(suffix)) {
            r = r.substring(0, r.length() - suffix.length());
        }
    }
    if (r.startsWith("jar:file:/") && r.endsWith(".jar!/")) {
        // JENKINS-49543: also an old behavior of Tomcat. Legal enough, but unexpected by isLocationWhitelisted.
        r = r.substring(4, r.length() - 2);
    }
    return r;
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static File locateBootstrapperFile() {
    ProtectionDomain protectionDomain = Bootstrapper.class.getProtectionDomain();
    if (protectionDomain == null) {
        JOptionPane.showMessageDialog(null,
                "Error: Could not locate Bootstrapper. (ProtectionDomain was null)");
        throw new RuntimeException();
    }// w w w  .  j  a v  a  2  s. c  om
    CodeSource codeSource = protectionDomain.getCodeSource();
    if (codeSource == null) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (CodeSource was null)");
        throw new RuntimeException();
    }
    URL url = codeSource.getLocation();
    if (url == null) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (Location was null)");
        throw new RuntimeException();
    }
    try {
        URI uri = url.toURI();
        File file = new File(uri.getPath());
        if (file.isDirectory()) {
            if (!Boolean.getBoolean("com.heliosdecompiler.isDebugging")) {
                JOptionPane.showMessageDialog(null,
                        "Error: Could not locate Bootstrapper. (File is directory)");
                throw new RuntimeException(file.getAbsolutePath());
            } else {
                System.out.println(
                        "Warning: Could not locate bootstrapper but com.heliosdecompiler.isDebugging was set to true");
            }
        } else if (!file.exists()) {
            JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File does not exist)");
            throw new RuntimeException();
        } else if (!file.canRead()) {
            JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (File is not readable)");
            throw new RuntimeException();
        }
        return file;
    } catch (URISyntaxException e) {
        JOptionPane.showMessageDialog(null, "Error: Could not locate Bootstrapper. (URISyntaxException)");
        throw new RuntimeException();
    }
}

From source file:org.sipfoundry.sipxconfig.test.TestHelper.java

/**
* The directory that is part of the classpath that a class was loaded from
*//*w  w  w. java  2 s. c  om*/
public static String getClasspathDirectory(Class testClass) {
    // create file on classpath
    CodeSource code = testClass.getProtectionDomain().getCodeSource();
    URL classpathUrl = code.getLocation();
    File classpathDir = new File(classpathUrl.getFile());

    return classpathDir.getAbsolutePath();
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static File findLibraryFolder(File minecraftHome) {
    if (LIBRARY_DIRECTORY_OVERRIDE != null) {
        FMLLog.log.error("System variable set to override Library Directory: {}", LIBRARY_DIRECTORY_OVERRIDE);
        return new File(LIBRARY_DIRECTORY_OVERRIDE);
    }//from ww w .j a  v  a 2 s.  c o m

    CodeSource source = ArtifactVersion.class.getProtectionDomain().getCodeSource();
    if (source == null) {
        FMLLog.log.error("Unable to determine codesource for {}. Using default libraries directory.",
                ArtifactVersion.class.getName());
        return new File(minecraftHome, "libraries");
    }

    try {
        File apache = new File(source.getLocation().toURI());
        if (apache.isFile())
            apache = apache.getParentFile(); //Get to a directory, this *should* always be the case...
        apache = apache.getParentFile(); //Skip the version folder. In case we ever update the version, I don't want to edit this code again.
        String comp = apache.getAbsolutePath().toLowerCase(Locale.ENGLISH).replace('\\', '/');
        if (!comp.endsWith("/"))
            comp += '/';

        if (!comp.endsWith("/org/apache/maven/maven-artifact/")) {
            FMLLog.log.error(
                    "Apache Maven library folder was not in the format expected. Using default libraries directory.");
            FMLLog.log.error("Full: {}", new File(source.getLocation().toURI()));
            FMLLog.log.error("Trimmed: {}", comp);
            return new File(minecraftHome, "libraries");
        }
        //     maven-artifact  /maven          /apache         /org            /libraries
        return apache.getParentFile().getParentFile().getParentFile().getParentFile();
    } catch (URISyntaxException e) {
        FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                "Unable to determine file for {}. Using default libraries directory.",
                ArtifactVersion.class.getName()), e);
    }

    return new File(minecraftHome, "libraries"); //Everything else failed, return the default.
}

From source file:net.ftb.util.OSUtils.java

/**
 * Gets the default installation path for the current OS.
 * @return a string containing the default install path for the current OS.
 *///  w  w w  .j a  v a2  s . c o  m
public static String getDefInstallPath() {
    switch (getCurrentOS()) {
    case WINDOWS:
        String defaultLocation = "c:\\ftb";
        File testFile = new File(defaultLocation);
        // existing directory and we can write
        if (testFile.canWrite()) {
            return defaultLocation;
        }

        // We can create default directory
        if (testFile.getParentFile().canWrite()) {
            return defaultLocation;
        }
        Logger.logWarn(
                "Can't use default installation location. Using current location of the launcher executable.");

    case MACOSX:
        return System.getProperty("user.home") + "/ftb";
    case UNIX:
        return System.getProperty("user.home") + "/ftb";
    default:
        try {
            CodeSource codeSource = LaunchFrame.class.getProtectionDomain().getCodeSource();
            File jarFile;
            jarFile = new File(codeSource.getLocation().toURI().getPath());
            return jarFile.getParentFile().getPath();
        } catch (URISyntaxException e) {
            Logger.logError("Unexcepted error", e);
        }

        return System.getProperty("user.home") + System.getProperty("path.separator") + "FTB";
    }
}

From source file:org.jbpm.bpel.tools.WscompileTool.java

/**
 * Gets the directory, JAR file or remote URL from which the given class was loaded.
 * @param c the class to be located/* w  w w. j a  v  a 2 s .co  m*/
 * @return the location from which the class was loaded, or <code>null</code> if the origin of
 * the class is unknown
 */
private static String getLocation(Class c) {
    CodeSource codeSource = c.getProtectionDomain().getCodeSource();
    if (codeSource == null) {
        /*
         * The code source of a domain may be null. This is the case for classes included in the Java
         * platform. For example, the javax.xml.soap package is part of Java SE 6. Not much more can
         * be done here, so we just tell the caller the location is unknown.
         * 
         * Thanks to Bernd Ruecker of Camunda GmbH for catching this one.
         */
        return null;
    }
    URL url = codeSource.getLocation();

    if ("jar".equals(url.getProtocol())) {
        try {
            JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
            url = urlConnection.getJarFileURL();
        } catch (IOException e) {
            log.debug("could not open connection to " + url, e);
        }
    }

    if (!"file".equals(url.getProtocol()))
        return url.toString();

    String fileName = url.getFile();
    try {
        fileName = URLDecoder.decode(fileName, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.debug("UTF-8 not supported", e);
    }
    return new File(fileName).getAbsolutePath();
}

From source file:org.mule.util.ClassUtils.java

public static URL getClassPathRoot(Class clazz) {
    CodeSource cs = clazz.getProtectionDomain().getCodeSource();
    return (cs != null ? cs.getLocation() : null);
}