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.apache.sentry.binding.hive.authz.SentryConfigTool.java

/**
 * set the required system property to be read by HiveConf and AuthzConf
 * @throws Exception//w  w  w .  jav  a2 s  .  co  m
 */
public void setupConfig() throws Exception {
    System.out.println("Configuration: ");
    CodeSource src = SentryConfigTool.class.getProtectionDomain().getCodeSource();
    if (src != null) {
        System.out.println("Sentry package jar: " + src.getLocation());
    }

    if (getPolicyFile() != null) {
        System.setProperty(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar(), getPolicyFile());
    }
    System.setProperty(AuthzConfVars.SENTRY_TESTING_MODE.getVar(), "true");
    setHiveConf(new HiveConf(SessionState.class));
    getHiveConf().setVar(ConfVars.SEMANTIC_ANALYZER_HOOK, HiveAuthzBindingHook.class.getName());
    try {
        System.out.println("Hive config: " + getHiveConf().getHiveSiteLocation());
    } catch (NullPointerException e) {
        // Hack, hiveConf doesn't provide a reliable way check if it found a valid
        // hive-site
        throw new SentryConfigurationException("Didn't find a hive-site.xml");

    }

    if (getSentrySiteFile() != null) {
        getHiveConf().set(HiveAuthzConf.HIVE_SENTRY_CONF_URL, getSentrySiteFile());
    }

    setAuthzConf(HiveAuthzConf.getAuthzConf(getHiveConf()));
    System.out.println("Sentry config: " + getAuthzConf().getHiveAuthzSiteFile());
    System.out.println("Sentry Policy: " + getAuthzConf().get(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar()));
    System.out.println("Sentry server: " + getAuthzConf().get(AuthzConfVars.AUTHZ_SERVER_NAME.getVar()));

    setSentryProvider(getAuthorizationProvider());
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

/**
 * This is a copy of {@link URLClassLoader#getPermissions(CodeSource)}.
 *
 * Returns the permissions for the given codesource object.
 * The implementation of this method first calls super.getPermissions
 * and then adds permissions based on the URL of the codesource.
 * <p>// w  w w .j  ava2 s .  c om
 * If the protocol of this URL is "jar", then the permission granted
 * is based on the permission that is required by the URL of the Jar
 * file.
 * <p>
 * If the protocol is "file"
 * and the path specifies a file, then permission to read that
 * file is granted. If protocol is "file" and the path is
 * a directory, permission is granted to read all files
 * and (recursively) all files and subdirectories contained in
 * that directory.
 * <p>
 * If the protocol is not "file", then
 * to connect to and accept connections from the URL's host is granted.
 * @param codesource the codesource
 * @return the permissions granted to the codesource
 */
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
    final PermissionCollection perms = super.getPermissions(codesource);
    final URL url = codesource.getLocation();
    Permission p;
    URLConnection urlConnection;
    try {
        urlConnection = url.openConnection();
        p = urlConnection.getPermission();
    } catch (IOException ignored) {
        p = null;
        urlConnection = null;
    }
    if (p instanceof FilePermission) {
        // if the permission has a separator char on the end,
        // it means the codebase is a directory, and we need
        // to add an additional permission to read recursively
        String path = p.getName();
        if (path.endsWith(File.separator)) {
            path += "-";
            p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
        }
    } else if ((p == null) && (url.getProtocol().equals("file"))) {
        String path = url.getFile().replace('/', File.separatorChar);
        path = ParseUtil.decode(path);
        if (path.endsWith(File.separator)) {
            path += "-";
        }
        p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
    } else {
        URL locUrl = url;
        if (urlConnection instanceof JarURLConnection) {
            locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
        }
        final String host = locUrl.getHost();
        if (host != null && (host.length() > 0)) {
            p = new SocketPermission(host, SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION);
        }
    }
    // make sure the person that created this class loader
    // would have this permission

    if (p != null) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            final Permission fp = p;
            doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() throws SecurityException {
                    sm.checkPermission(fp);
                    return null;
                }
            }, _acc);
        }
        perms.add(p);
    }
    return perms;
}

From source file:org.spout.engine.SpoutClient.java

@Override
public void init(SpoutApplication args) {
    boolean inJar = false;

    try {//from  w ww  .ja va2s.  c o  m
        CodeSource cs = SpoutClient.class.getProtectionDomain().getCodeSource();
        inJar = cs.getLocation().toURI().getPath().endsWith(".jar");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    if (inJar) {
        unpackLwjgl();
    }

    ExecutorService executorBoss = Executors
            .newCachedThreadPool(new NamedThreadFactory("SpoutServer - Boss", true));
    ExecutorService executorWorker = Executors
            .newCachedThreadPool(new NamedThreadFactory("SpoutServer - Worker", true));
    ChannelFactory factory = new NioClientSocketChannelFactory(executorBoss, executorWorker);
    bootstrap.setFactory(factory);

    ChannelPipelineFactory pipelineFactory = new CommonPipelineFactory(this, true);
    bootstrap.setPipelineFactory(pipelineFactory);
    super.init(args);

    this.ccoverride = args.ccoverride;

    inputManager.bind(Keyboard.get(SpoutInputConfiguration.FORWARD.getString()), "forward");
    inputManager.bind(Keyboard.get(SpoutInputConfiguration.BACKWARD.getString()), "backward");
    inputManager.bind(Keyboard.get(SpoutInputConfiguration.LEFT.getString()), "left");
    inputManager.bind(Keyboard.get(SpoutInputConfiguration.RIGHT.getString()), "right");
    inputManager.bind(Keyboard.get(SpoutInputConfiguration.UP.getString()), "jump");
    inputManager.bind(Keyboard.get(SpoutInputConfiguration.DOWN.getString()), "crouch");
    inputManager.bind(Keyboard.KEY_F3, "debug_info");
    inputManager.bind(org.spout.api.input.Mouse.MOUSE_SCROLLDOWN, "select_down");
    inputManager.bind(org.spout.api.input.Mouse.MOUSE_SCROLLUP, "select_up");
    inputManager.bind(org.spout.api.input.Mouse.MOUSE_BUTTON0, "left_click");
    inputManager.bind(org.spout.api.input.Mouse.MOUSE_BUTTON1, "interact");
    inputManager.bind(org.spout.api.input.Mouse.MOUSE_BUTTON2, "fire_2");
}

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

/**
 * Read the file of the path.// w  w  w . j av  a2 s  .  c  om
 *
 * @param pathStr the file path to read.
 * @return the content of the file in path
 */
public String readFile(String pathStr) {
    String text = "";
    String name = pathStr.substring(pathStr.lastIndexOf("/") + 1, pathStr.length());
    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
            CodeSource src = ReportGenerator.class.getProtectionDomain().getCodeSource();
            if (src != null) {
                URL jar = src.getLocation();
                ZipInputStream zip;

                zip = new ZipInputStream(jar.openStream());
                ZipEntry zipFile;
                boolean found = false;
                while ((zipFile = zip.getNextEntry()) != null && !found) {
                    if (zipFile.getName().endsWith(name)) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(zip));
                        String line = br.readLine();
                        while (line != null) {
                            text += line + System.lineSeparator();
                            line = br.readLine();
                        }
                        found = true;
                    }
                    zip.closeEntry();
                }
            }
        }
    } 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:org.forgerock.openicf.maven.DocBookResourceMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {/* w w  w.jav a  2 s .  co  m*/
        getLog().info("Skipping DocBook generation");
        return;
    }

    if (!("pom".equalsIgnoreCase(project.getPackaging()))) {
        ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler();
        if (!"java".equals(artifactHandler.getLanguage())) {
            getLog().info(
                    "Not executing DocBook report as the project is not a Java classpath-capable package");
            return;
        }
    }

    try {

        if (!docbkxDirectory.exists()) {
            getLog().info("Not executing DocBook report as the project does not have DocBook source");
            return;
        }

        File rootDirectory = new File(buildDirectory,
                "openicf-docbkx/" + artifact.getArtifactId() + "-" + artifact.getVersion());
        try {
            FileUtils.mkdir(rootDirectory.getAbsolutePath());

            MavenResourcesExecution mre = new MavenResourcesExecution();
            mre.setMavenProject(getMavenProject());
            mre.setEscapeWindowsPaths(true);
            mre.setMavenSession(session);
            mre.setInjectProjectBuildFilters(true);

            List<FileUtils.FilterWrapper> filterWrappers = null;
            try {
                filterWrappers = fileFilter.getDefaultFilterWrappers(mre);
            } catch (MavenFilteringException e) {
                filterWrappers = Collections.emptyList();
            }

            if (docbkxDirectory.exists()) {
                final List<String> includes = FileUtils.getFileAndDirectoryNames(docbkxDirectory, "**",
                        StringUtils.join(DirectoryScanner.DEFAULTEXCLUDES, ",") + ",**/*.xml", true, false,
                        true, true);

                org.apache.commons.io.FileUtils.copyDirectory(docbkxDirectory, rootDirectory, new FileFilter() {
                    public boolean accept(File pathname) {
                        return includes.contains(pathname.getPath());
                    }
                });

                List<File> files = FileUtils.getFiles(docbkxDirectory, "**/*.xml", null);

                for (File file : files) {
                    try {
                        fileFilter.copyFile(file, new File(rootDirectory, file.getName()), true, filterWrappers,
                                getSourceEncoding());
                    } catch (MavenFilteringException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }
                }
            }

            File sharedRoot = rootDirectory.getParentFile();

            CodeSource src = getClass().getProtectionDomain().getCodeSource();
            if (src != null) {
                final ZipInputStream zip = new ZipInputStream(src.getLocation().openStream());
                ZipEntry entry = null;
                while ((entry = zip.getNextEntry()) != null) {
                    String name = entry.getName();
                    if (entry.getName().startsWith("shared")) {

                        File destination = new File(sharedRoot, name);
                        if (entry.isDirectory()) {
                            if (!destination.exists()) {
                                destination.mkdirs();
                            }
                        } else {
                            if (!destination.exists()) {
                                FileOutputStream output = null;
                                try {
                                    output = new FileOutputStream(destination);
                                    IOUtil.copy(zip, output);
                                } finally {
                                    IOUtil.close(output);
                                }
                            }
                        }
                    }
                }
                zip.closeEntry();
                zip.close();
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error copy DocBook resources.", e);
        }

        // Generate Config and Schema DocBook Chapter
        CurrentLocale.set(Locale.ENGLISH);
        ConnectorDocBuilder generator = new ConnectorDocBuilder(this);
        generator.executeReport();

        // Look at the content of the resourcesDirectory and create a
        // manifest
        // of the files
        // so that velocity can easily process any resources inside the JAR
        // that
        // need to be processed.

        if (attach) {
            RemoteResourcesBundle remoteResourcesBundle = new RemoteResourcesBundle();
            remoteResourcesBundle.setSourceEncoding(getSourceEncoding());

            DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedir(new File(buildDirectory, "openicf-docbkx/"));
            // scanner.setIncludes(new String[] { docFolder + "/**" });
            scanner.addDefaultExcludes();
            scanner.scan();

            List<String> includedFiles = Arrays.asList(scanner.getIncludedFiles());

            if (resourcesDirectory.exists()) {
                scanner = new DirectoryScanner();
                scanner.setBasedir(resourcesDirectory);
                if (includes != null && includes.length != 0) {
                    scanner.setIncludes(includes);
                } else {
                    scanner.setIncludes(DEFAULT_INCLUDES);
                }

                if (excludes != null && excludes.length != 0) {
                    scanner.setExcludes(excludes);
                }

                scanner.addDefaultExcludes();
                scanner.scan();
                includedFiles.addAll(Arrays.asList(scanner.getIncludedFiles()));
            }
            for (String resource : includedFiles) {
                remoteResourcesBundle.addRemoteResource(StringUtils.replace(resource, '\\', '/'));
            }

            RemoteResourcesBundleXpp3Writer w = new RemoteResourcesBundleXpp3Writer();

            try {
                File f = new File(buildDirectory,
                        "openicf-docbkx/" + BundleRemoteResourcesMojo.RESOURCES_MANIFEST);

                FileUtils.mkdir(f.getParentFile().getAbsolutePath());

                Writer writer = new FileWriter(f);

                w.write(writer, remoteResourcesBundle);
            } catch (IOException e) {
                throw new MojoExecutionException("Error creating remote resources manifest.", e);
            }

            File outputFile = generateArchive(new File(buildDirectory, "openicf-docbkx/"),
                    finalName + "-docbkx.jar");

            projectHelper.attachArtifact(project, "jar", "docbkx", outputFile);
        } else {
            getLog().info("NOT adding DocBook to attached artifacts list.");
        }
    } catch (ArchiverException e) {
        failOnError("ArchiverException: Error while creating archive", e);
    } catch (IOException e) {
        failOnError("IOException: Error while creating archive", e);
    } catch (RuntimeException e) {
        failOnError("RuntimeException: Error while creating archive", e);
    }
}

From source file:com.sikulix.core.SX.java

static void sxRunningAs() {
    CodeSource codeSrc = sxGlobalClassReference.getProtectionDomain().getCodeSource();
    String base = null;// w w w . j a v a 2 s .c  o m
    if (codeSrc != null && codeSrc.getLocation() != null) {
        base = Content.slashify(codeSrc.getLocation().getPath(), false);
    }
    appType = "from a jar";
    if (base != null) {
        fSxBaseJar = new File(base);
        String jn = fSxBaseJar.getName();
        fSxBase = fSxBaseJar.getParentFile();
        debug("sxRunningAs: runs as %s in: %s", jn, fSxBase.getAbsolutePath());
        if (jn.contains("classes")) {
            runningJar = false;
            fSxProject = fSxBase.getParentFile().getParentFile();
            debug("sxRunningAs: not jar - supposing Maven project: %s", fSxProject);
            appType = "in Maven project from classes";
            runningInProject = true;
        } else if ("target".equals(fSxBase.getName())) {
            fSxProject = fSxBase.getParentFile().getParentFile();
            debug("sxRunningAs: folder target detected - supposing Maven project: %s", fSxProject);
            appType = "in Maven project from some jar";
            runningInProject = true;
        } else {
            if (isWindows()) {
                if (jn.endsWith(".exe")) {
                    setSXASAPP(true);
                    runningJar = false;
                    appType = "as application .exe";
                }
            } else if (isMac()) {
                if (fSxBase.getAbsolutePath().contains("SikuliX.app/Content")) {
                    setSXASAPP(true);
                    appType = "as application .app";
                    if (!fSxBase.getAbsolutePath().startsWith("/Applications")) {
                        appType += " (not from /Applications folder)";
                    }
                }
            }
        }
    } else {
        terminate(1, "sxRunningAs: no valid Java context for SikuliX available "
                + "(java.security.CodeSource.getLocation() is null)");
    }
}

From source file:controller.CCInstance.java

public final String getCurrentFolder() {
    final CodeSource cs = ACCinaPDF.class.getProtectionDomain().getCodeSource();
    File f = null;/*from  w  ww.  j  a v  a 2  s . c om*/
    try {
        f = new File(cs.getLocation().toURI().getPath());
    } catch (URISyntaxException ex) {
        return null;
    }
    return f.getParentFile().getPath();
}

From source file:org.xmlsh.sh.shell.Shell.java

private static String tryFindHome() {
    getLogger().entry();/*from w  w  w .j  ava 2s.c om*/
    try {
        CodeSource cs = Shell.class.getProtectionDomain().getCodeSource();
        if (cs != null) {
            Path p = Paths.get(cs.getLocation().toURI());
            String sdir = null;
            while ((p = FileUtils.resolveLink(p)) != null) {
                while (p != null && !Files.isDirectory(p))
                    p = FileUtils.getParent(p);
                if (p == null)
                    break;

                if (sdir == null)
                    sdir = p.toString(); // first dir found

                Path parent = FileUtils.getParent(p);
                if (parent == null || parent == p || Files.isSameFile(parent, p))
                    break;
                p = parent;
                if (p != null) {
                    if (Files.isDirectory(p.resolve("modules")) || Files.isDirectory(p.resolve("lib")))
                        return getLogger().exit(p.toString());
                }
            }
            return getLogger().exit(sdir);
        }

    } catch (SecurityException | URISyntaxException | IOException e) {
        getLogger().catching(e);
    }

    return null;
}

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;/*from   w ww .  j  av  a 2  s  .co  m*/
    if (outputFileUri == null) {
        throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. ");
    }
    outputFolder = new File(outputFileUri.path());
    if (!outputFolder.exists()) {
        if (!outputFolder.mkdirs()) {
            throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath());
        }
    }

    File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT);
    if (!cssFolderOut.exists()) {
        if (!cssFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath());
        }
    }

    File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT);
    if (!jsFolderOut.exists()) {
        if (!jsFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath());
        }
    }

    File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT);
    if (!imgFolderOut.exists()) {
        if (!imgFolderOut.mkdirs()) {
            throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath());
        }
    }

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE),
            outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE);

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE);

    copyResourceFile(
            getClass()
                    .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE);

    ClassLoader classLoader = getClass().getClassLoader();
    CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource();
    URL codeSourceUrl = srcCode.getLocation();
    File codeSourseFile = new File(codeSourceUrl.getPath());

    if (codeSourseFile.isDirectory()) {
        File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile());
        File[] imgFiles = imgFolder.listFiles();
        if (imgFiles != null) {
            for (File imgFile : imgFiles) {
                InputStream inputStream = getClass()
                        .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK
                                + System.getProperty("file.separator") + imgFile.getName());
                copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName());
            }
        }
    } else if (codeSourseFile.getName().endsWith("jar")) {
        JarFile jarFile = new JarFile(codeSourseFile);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) {

                copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT,
                        entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, ""));
            }

        }
        jarFile.close();

    }

    return outputFolder;
}

From source file:org.jenkinsci.plugins.pipeline.maven.WithMavenStepExecution.java

private FilePath setupMavenSpy() throws IOException, InterruptedException {
    if (tempBinDir == null) {
        throw new IllegalStateException("tempBinDir not defined");
    }//from  w  w w .  j  av a2  s . c om

    // Mostly for testing / debugging in the IDE
    final String MAVEN_SPY_JAR_URL = "org.jenkinsci.plugins.pipeline.maven.mavenSpyJarUrl";
    String mavenSpyJarUrl = System.getProperty(MAVEN_SPY_JAR_URL);
    InputStream in;
    if (mavenSpyJarUrl == null) {
        String embeddedMavenSpyJarPath = "META-INF/lib/pipeline-maven-spy.jar";
        LOGGER.log(Level.FINE, "Load embedded maven spy jar '" + embeddedMavenSpyJarPath + "'");
        // Don't use Thread.currentThread().getContextClassLoader() as it doesn't show the resources of the plugin
        Class<WithMavenStepExecution> clazz = WithMavenStepExecution.class;
        ClassLoader classLoader = clazz.getClassLoader();
        LOGGER.log(Level.FINE, "Load " + embeddedMavenSpyJarPath + " using classloader "
                + classLoader.getClass() + ": " + classLoader);
        in = classLoader.getResourceAsStream(embeddedMavenSpyJarPath);
        if (in == null) {
            CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
            String msg = "Embedded maven spy jar not found at " + embeddedMavenSpyJarPath
                    + " in the pipeline-maven-plugin classpath. "
                    + "Maven Spy Jar URL can be defined with the system property: '" + MAVEN_SPY_JAR_URL + "'"
                    + "Classloader " + classLoader.getClass() + ": " + classLoader + ". " + "Class "
                    + clazz.getName() + " loaded from "
                    + (codeSource == null ? "#unknown#" : codeSource.getLocation());
            throw new IllegalStateException(msg);
        }
    } else {
        LOGGER.log(Level.FINE, "Load maven spy jar provided by system property '" + MAVEN_SPY_JAR_URL + "': "
                + mavenSpyJarUrl);
        in = new URL(mavenSpyJarUrl).openStream();
    }

    FilePath mavenSpyJarFilePath = tempBinDir.child("pipeline-maven-spy.jar");
    mavenSpyJarFilePath.copyFrom(in);
    return mavenSpyJarFilePath;
}