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:org.springframework.boot.web.servlet.server.DocumentRoot.java

File getCodeSourceArchive(CodeSource codeSource) {
    try {//w  ww  .j  av  a2s  . c  om
        URL location = (codeSource != null) ? codeSource.getLocation() : null;
        if (location == null) {
            return null;
        }
        String path;
        URLConnection connection = location.openConnection();
        if (connection instanceof JarURLConnection) {
            path = ((JarURLConnection) connection).getJarFile().getName();
        } else {
            path = location.toURI().getPath();
        }
        int index = path.indexOf("!/");
        if (index != -1) {
            path = path.substring(0, index);
        }
        return new File(path);
    } catch (Exception ex) {
        return null;
    }
}

From source file:codes.thischwa.c5c.impl.JarFilemanagerMessageResolver.java

@Override
public void setServletContext(ServletContext servletContext) {
    ObjectMapper mapper = new ObjectMapper();
    try {/*from w ww  .j a v  a2s .c o  m*/
        if (JarPathResolver.insideJar(getMessagesFolderPath())) {
            CodeSource src = JarFilemanagerMessageResolver.class.getProtectionDomain().getCodeSource();
            URI uri = src.getLocation().toURI();
            logger.info("Message folder is inside jar: {}", uri);

            try (FileSystem jarFS = FileSystems.newFileSystem(uri, new HashMap<String, String>())) {
                if (jarFS.getRootDirectories().iterator().hasNext()) {
                    Path rootDirectory = jarFS.getRootDirectories().iterator().next();

                    Path langFolder = rootDirectory.resolve(getMessagesFolderPath());
                    if (langFolder != null) {
                        try (DirectoryStream<Path> langFolderStream = Files.newDirectoryStream(langFolder,
                                JS_FILE_MASK)) {
                            for (Path langFile : langFolderStream) {
                                String lang = langFile.getFileName().toString();
                                InputStream is = Files.newInputStream(langFile);
                                Map<String, String> langData = mapper.readValue(is,
                                        new TypeReference<HashMap<String, String>>() {
                                        });
                                collectLangData(lang, langData);
                            }
                        }
                    } else {
                        throw new RuntimeException("Folder in jar " + langFolder + " does not exists.");
                    }
                }
            }
        } else {
            File messageFolder = JarPathResolver.getFolder(getMessagesFolderPath());
            logger.info("Message folder resolved to: {}", messageFolder);

            if (messageFolder == null || !messageFolder.exists()) {
                throw new RuntimeException("Folder " + getMessagesFolderPath() + " does not exist");
            }

            for (File file : messageFolder.listFiles(jsFilter)) {
                String lang = FilenameUtils.getBaseName(file.getName());
                Map<String, String> langData = mapper.readValue(file,
                        new TypeReference<HashMap<String, String>>() {
                        });
                collectLangData(lang, langData);
            }
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

public static String getCodeBase(Class<?> cls) {
    if (cls == null)
        return null;
    ProtectionDomain domain = cls.getProtectionDomain();
    if (domain == null)
        return null;
    CodeSource source = domain.getCodeSource();
    if (source == null)
        return null;
    URL location = source.getLocation();
    if (location == null)
        return null;
    return location.getFile();
}

From source file:net.famzangl.minecraft.minebot.settings.MinebotDirectoryCreator.java

public File createDirectory(File dir) throws IOException {
    CodeSource src = MinebotDirectoryCreator.class.getProtectionDomain().getCodeSource();
    if (src != null) {
        URL jar = src.getLocation();
        if (jar.getFile().endsWith("class") && !jar.getFile().contains(".jar!")) {
            System.out.println("WARNING: Using the dev directory for settings.");
            // We are in a dev enviroment.
            return new File(new File(jar.getFile()).getParentFile(), "minebot");
        }// w  ww.  j av a2  s.  c  o  m
        if (dir.isFile()) {
            dir.delete();
        }

        dir.mkdirs();
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        try {
            ZipEntry zipEntry;
            while ((zipEntry = zip.getNextEntry()) != null) {
                String name = zipEntry.getName();
                if (name.startsWith(BASE)) {
                    String[] localName = name.substring(BASE.length()).split("/");
                    File currentDir = dir;
                    for (int i = 0; i < localName.length; i++) {
                        currentDir = new File(currentDir, localName[i]);
                        currentDir.mkdir();
                    }
                    File copyTo = new File(currentDir, localName[localName.length - 1]);
                    extract(zip, copyTo);
                }
            }
        } finally {
            zip.close();
        }
        return dir;
    } else {
        throw new IOException("Could not find minebot directory to extract.");
    }
}

From source file:com.heliosdecompiler.helios.controller.UpdateController.java

public File getHeliosLocation() {
    ProtectionDomain pd = getClass().getProtectionDomain();
    if (pd != null) {
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            URL location = cs.getLocation();
            if (location != null) {
                try {
                    File file = new File(location.toURI().getPath());
                    if (file.isFile()) {
                        return file;
                    }/*w  w  w .  j  ava  2  s  .co m*/
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
    }
    return null;
}

From source file:de.lmu.ifi.dbs.jfeaturelib.utils.PackageScanner.java

List<String> getNames(Package inPackage)
        throws UnsupportedEncodingException, URISyntaxException, ZipException, IOException {
    List<String> binaryNames = new ArrayList<>();

    String packagePath = inPackage.getName();
    packagePath = packagePath.replace('.', '/');

    // During tests, this points to the classes/ directory, later, this points to the jar
    CodeSource src = PackageScanner.class.getProtectionDomain().getCodeSource();
    URL location = src.getLocation();
    // test case//from  w  ww. j  a  v  a  2s  .  com
    File dirOrJar = new File(location.toURI());
    if (dirOrJar.isDirectory()) {
        // +1 to include the slash after the directory name
        int basePathLength = dirOrJar.toString().length() + 1;
        File packageDir = new File(dirOrJar, packagePath);

        // list all .class files in this package directory
        for (File file : packageDir.listFiles((FilenameFilter) new SuffixFileFilter(".class"))) {
            // strip the leading directory
            String binaryName = file.getPath().substring(basePathLength);
            binaryName = pathToBinary(binaryName);
            binaryNames.add(binaryName);
        }

    } else {
        try (ZipFile jar = new ZipFile(dirOrJar)) {
            for (Enumeration entries = jar.entries(); entries.hasMoreElements();) {
                String binaryName = ((ZipEntry) entries.nextElement()).getName();
                if (!binaryName.endsWith(".class")) { // we only need classes
                    continue;
                }
                if (binaryName.startsWith(packagePath)) {
                    binaryName = pathToBinary(binaryName);
                    binaryNames.add(binaryName);
                }
            }
        }
    }

    return binaryNames;
}

From source file:org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory.java

private File getCodeSourceArchive() {
    try {/*from   w  w  w  .j  ava 2s. c  o  m*/
        CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
        URL location = (codeSource == null ? null : codeSource.getLocation());
        if (location == null) {
            return null;
        }
        String path = location.getPath();
        URLConnection connection = location.openConnection();
        if (connection instanceof JarURLConnection) {
            path = ((JarURLConnection) connection).getJarFile().getName();
        }
        if (path.indexOf("!/") != -1) {
            path = path.substring(0, path.indexOf("!/"));
        }
        return new File(path);
    } catch (IOException ex) {
        return null;
    }
}

From source file:org.apache.struts2.JSPLoader.java

protected String getJarUrl(Class clazz) {
    ProtectionDomain protectionDomain = clazz.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URL loc = codeSource.getLocation();
    File file = FileUtils.toFile(loc);
    return file.getAbsolutePath();
}

From source file:com.izforge.izpack.installer.multiunpacker.MultiVolumeUnpacker.java

/**
 * Tries to return a sensible default media path for multi-volume installations.
 * <p/>/*  www . ja va  2 s  .co  m*/
 * This returns:
 * <ul>
 * <li>the directory the installer is located in; or </li>
 * <li>the user directory, if the installer location can't be determined</li>
 * </ul>
 *
 * @return the default media path. May be <tt>null</tt>
 */
private String getDefaultMediaPath() {
    String result = null;
    try {
        CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
        if (codeSource != null) {
            URI uri = codeSource.getLocation().toURI();
            if ("file".equals(uri.getScheme())) {
                File dir = new File(uri.getSchemeSpecificPart()).getAbsoluteFile();
                if (dir.getName().endsWith(".jar")) {
                    dir = dir.getParentFile();
                }
                result = dir.getPath();
            }
        }
    } catch (URISyntaxException exception) {
        // ignore
    }
    if (result == null) {
        result = System.getProperty("user.dir");
    }
    return result;
}

From source file:biz.dfch.j.graylog2.plugin.filter.dfchBizExecScript.java

public dfchBizExecScript() throws IOException, URISyntaxException {
    try {//from   w  ww . ja  v a 2  s.c om
        LOG.debug(String.format("*** [%d] %s: Initialising plugin ...\r\n", Thread.currentThread().getId(),
                DF_PLUGIN_NAME));

        // get config file
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URI uri = codeSource.getLocation().toURI();

        // String path = uri.getSchemeSpecificPart();
        // path would contain absolute path including jar file name with extension
        // String path = FilenameUtils.getPath(uri.getPath());
        // path would contain relative path (no leadig '/' and no jar file name

        String path = FilenameUtils.getPath(uri.getPath());
        if (!path.startsWith("/")) {
            path = String.format("/%s", path);
        }
        String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart());
        if (null == baseName || baseName.isEmpty()) {
            baseName = this.getClass().getPackage().getName();
        }

        // get config values
        configurationFileName = FilenameUtils.concat(path, baseName + ".conf");
        JSONParser jsonParser = new JSONParser();
        Object object = jsonParser.parse(new FileReader(configurationFileName));

        JSONObject jsonObject = (JSONObject) object;
        String scriptEngine = (String) jsonObject.get(DF_SCRIPT_ENGINE);
        String scriptPathAndName = (String) jsonObject.get(DF_SCRIPT_PATH_AND_NAME);
        if (null == scriptPathAndName || scriptPathAndName.isEmpty()) {
            scriptPathAndName = FilenameUtils.concat(path, (String) jsonObject.get(DF_SCRIPT_NAME));
        }
        Boolean scriptCacheContents = (Boolean) jsonObject.get(DF_SCRIPT_CACHE_CONTENTS);
        Boolean scriptDisplayOutput = (Boolean) jsonObject.get(DF_SCRIPT_DISPLAY_OUTPUT);
        String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY);
        Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE);
        Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED);

        // set configuration
        Map<String, Object> map = new HashMap<>();
        map.put(DF_SCRIPT_ENGINE, scriptEngine);
        map.put(DF_SCRIPT_PATH_AND_NAME, scriptPathAndName);
        map.put(DF_SCRIPT_DISPLAY_OUTPUT, scriptDisplayOutput);
        map.put(DF_SCRIPT_CACHE_CONTENTS, scriptCacheContents);
        map.put(DF_PLUGIN_PRIORITY, pluginPriority);
        map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage);
        map.put(DF_PLUGIN_DISABLED, pluginDisabled);

        initialize(new Configuration(map));
    } catch (IOException ex) {
        LOG.error(String.format("*** [%d] %s: Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n",
                Thread.currentThread().getId(), DF_PLUGIN_NAME, ex.getMessage()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled.");
        ex.printStackTrace();
    } catch (Exception ex) {
        LOG.error(String.format("*** [%d] %s: Initialising plugin FAILED. Filter will be disabled.\r\n",
                Thread.currentThread().getId(), DF_PLUGIN_NAME));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled.");
        ex.printStackTrace();
    }
}