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.struts2.osgi.BaseOsgiHost.java

protected String getJarUrl(Class clazz) {
    ProtectionDomain protectionDomain = clazz.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URL loc = codeSource.getLocation();
    return loc.toString();
}

From source file:org.eclim.eclipse.EclimClasspathInitializer.java

private IClasspathEntry[] computeClasspathEntries(IJavaProject javaProject) {
    final ArrayList<IClasspathEntry> list = new ArrayList<IClasspathEntry>();
    try {// w  w  w .j av  a2  s.  c o m
        final LinkedHashSet<String> bundleNames = new LinkedHashSet<String>();
        final ArrayList<String> jarPaths = new ArrayList<String>();
        final String projectPath = ProjectUtils.getPath(javaProject.getProject());

        new File(projectPath).list(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                if (name.startsWith("org.eclim")) {
                    // first pull bundle dependencies from the manifest
                    File manifest = new File(dir.getPath() + '/' + name + "/META-INF/MANIFEST.MF");
                    if (manifest.exists()) {
                        FileInputStream fin = null;
                        try {
                            fin = new FileInputStream(manifest);
                            HashMap<String, String> headers = new HashMap<String, String>();
                            ManifestElement.parseBundleManifest(fin, headers);
                            String requiredBundles = headers.get("Require-Bundle");
                            for (String bname : requiredBundles.split(",\\s*")) {
                                if (bname.startsWith("org.eclim")) {
                                    continue;
                                }
                                bundleNames.add(bname);
                            }
                        } catch (Exception e) {
                            logger.error("Failed to load manifest: " + manifest, e);
                        } finally {
                            IOUtils.closeQuietly(fin);
                        }
                    }

                    // then look for plugin jar files
                    File lib = new File(dir.getPath() + '/' + name + "/lib");
                    if (lib.exists()) {
                        for (String jar : lib.list()) {
                            if (jar.endsWith(".jar")) {
                                jarPaths.add(name + "/lib/" + jar);
                            }
                        }
                    }
                }
                return false;
            }
        });

        // load platform dependent swt jar
        CodeSource source = SWT.class.getProtectionDomain().getCodeSource();
        if (source != null) {
            URL swt = source.getLocation();
            if (swt != null) {
                logger.debug("adding swt to classpath: {}", swt.getPath());
                Path path = new Path(swt.getPath());
                list.add(JavaCore.newLibraryEntry(path, sourcePath(path), null, null, attributes(path), false));
            }
        }

        for (String name : bundleNames) {
            logger.debug("adding bundle to classpath: {}", name);
            try {
                Bundle bundle = Platform.getBundle(name);
                if (bundle != null) {
                    String pathName = FileLocator.getBundleFile(bundle).getPath();
                    Path path = new Path(pathName);
                    list.add(JavaCore.newLibraryEntry(path, sourcePath(path), null, null, attributes(path),
                            false));

                    if (path.toFile().isDirectory()) {
                        listFiles(path.toFile(), new FileFilter() {
                            public boolean accept(File file) {
                                if (file.getName().endsWith(".jar")) {
                                    list.add(JavaCore.newLibraryEntry(new Path(file.getPath()), null, null,
                                            null, null, false));
                                } else if (file.isDirectory()) {
                                    listFiles(file, this);
                                }
                                return false;
                            }
                        });
                    }
                }
            } catch (IOException ioe) {
                logger.error("Failed to locate bundle: " + name, ioe);
            }
        }

        // some plugins need access to nested libraries extracted at build time,
        // handle adding those jars to the classpath here.
        listFiles(new File(projectPath + "/build/temp/lib"), new FileFilter() {
            public boolean accept(File file) {
                if (file.getName().endsWith(".jar")) {
                    String jar = file.getPath().replace(projectPath, "");
                    if (jar.startsWith("/")) {
                        jar = jar.substring(1);
                    }
                    jarPaths.add(jar);
                }
                if (file.isDirectory()) {
                    listFiles(file, this);
                }
                return false;
            }
        });

        for (String jarPath : jarPaths) {
            logger.debug("adding jar to classpath: {}", jarPath);
            list.add(JavaCore.newLibraryEntry(new Path(projectPath + '/' + jarPath), null, null, null, null,
                    false));
        }
    } catch (Exception e) {
        logger.error("Failed to load eclim classpath container", e);
    }
    return (IClasspathEntry[]) list.toArray(new IClasspathEntry[list.size()]);
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * List dir file paths.//from  w w w . j  av  a 2 s .  c om
 *
 * @param directory directory
 * @return List of file paths
 * @throws IOException IOException
 */
public List<Path> listDirFilePaths(String directory) throws IOException {
    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    List<Path> paths = new ArrayList<>();

    try {
        if (src != null) {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            ZipEntry zipEntry;

            while ((zipEntry = zip.getNextEntry()) != null) {
                String entryName = zipEntry.getName();
                if (entryName.startsWith(directory + "/")) {
                    paths.add(Paths.get("/" + entryName));
                }
            }
        }
    } catch (IOException e) {
        throw e;
    }

    return paths;
}

From source file:com.seeburger.vfs2.util.VFSClassLoader.java

/**
 * Calls super.getPermissions both for the code source and also
 * adds the permissions granted to the parent layers.
 * @param cs the CodeSource.//www.ja v a  2s . com
 * @return The PermissionCollections.
 */
@Override
protected PermissionCollection getPermissions(final CodeSource cs) {
    try {
        final String url = cs.getLocation().toString();
        FileObject file = lookupFileObject(url);
        if (file == null) {
            return super.getPermissions(cs);
        }

        FileObject parentLayer = file.getFileSystem().getParentLayer();
        if (parentLayer == null) {
            return super.getPermissions(cs);
        }

        Permissions combi = new Permissions();
        PermissionCollection permCollect = super.getPermissions(cs);
        copyPermissions(permCollect, combi);

        for (FileObject parent = parentLayer; parent != null; parent = parent.getFileSystem()
                .getParentLayer()) {
            final CodeSource parentcs = new CodeSource(parent.getURL(), parent.getContent().getCertificates());
            permCollect = super.getPermissions(parentcs);
            copyPermissions(permCollect, combi);
        }

        return combi;
    } catch (final FileSystemException fse) {
        throw new SecurityException(fse.getMessage());
    }
}

From source file:org.pepstock.jem.springbatch.tasks.utilities.MainLauncherTasklet.java

/**
 * Loads java class from className and for classpath
 * @param className classname to be loaded
 * @return class object loaded from classpath
 * @throws IOException if any error occurs
 * @throws ClassNotFoundException if any error occurs
 *//*  ww  w .jav  a  2  s.c o  m*/
private Class<?> loadCustomClass(String classNam) throws IOException, ClassNotFoundException {
    // CLASSPATH has been set therefore it an try to load the plugin by
    // a custom classloader
    // collection of all file of classpath
    Collection<File> files = new LinkedList<File>();

    for (String classPathFile : classPath) {
        classPathFile = FilenameUtils.normalize(classPathFile, true);
        // checks if a item contains more than 1 path
        String[] paths = null;
        if (classPathFile.contains(File.pathSeparator)) {
            // substitute variables if there are and split
            paths = StringUtils.split(JobsProperties.getInstance().replacePlaceHolders(classPathFile),
                    File.pathSeparator);
        } else if (classPathFile.contains(";")) {
            // substitute variables if there are and split
            paths = StringUtils.split(JobsProperties.getInstance().replacePlaceHolders(classPathFile), ";");
        } else {
            // substitute variables if there are and assign
            paths = new String[] { JobsProperties.getInstance().replacePlaceHolders(classPathFile) };
        }
        if (paths != null) {
            for (String path : paths) {
                // creates the file
                File file = new File(path);
                // if file ends with * could be only this folder or all folders
                // in cascade
                if (path.endsWith(ClassLoaderUtil.ALL_FOLDER)) {
                    // checks if is all folders in cascade
                    boolean cascade = path.endsWith(ClassLoaderUtil.ALL_FOLDER_IN_CASCADE);
                    // gets the parent and asks for all JAR files
                    File parent = file.getParentFile();
                    Collection<File> newFiles = FileUtils.listFiles(parent,
                            ClassLoaderUtil.EXTENSIONS.toArray(new String[0]), cascade);
                    // loads to the collection
                    files.addAll(newFiles);
                } else if (file.isDirectory() && file.exists()) {
                    // if here, we have a directory
                    // adds the directory to collection
                    files.add(file);
                } else if (file.isFile() && file.exists()) {
                    // if here, a file has been indicated
                    // adds the directory to collection
                    files.add(file);
                }
            }
        }
    }
    // checks if the collection is empty.
    // if yes, all classpath definiton is wrong and no files have been
    // loaded
    if (!files.isEmpty()) {
        // gets where the class is located
        // because it must be added to classpath
        CodeSource codeSource = JavaMainClassLauncher.class.getProtectionDomain().getCodeSource();
        if (codeSource != null) {
            // gets URL
            URL url = codeSource.getLocation();
            if (url != null) {
                // adds URL to classpath
                files.add(FileUtils.toFile(url));
            }
        }
        // exports files in URLs, for our classloader
        final URL[] urls = FileUtils.toURLs(files.toArray(new File[files.size()]));
        // loads a our classloader by access controller
        ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return new ReverseURLClassLoader(urls, MainLauncherTasklet.class.getClassLoader(), false);
            }
        });
        // loads the plugin from classloader
        return loader.loadClass(className);
    } else {
        throw new IOException(UtilMessage.JEMB009E.toMessage().getMessage());
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 *
 * @see java.security.SecureClassLoader#getPermissions(
 *     java.security.CodeSource)//from   ww w .j a va 2  s . c om
 */
protected PermissionCollection getPermissions(CodeSource codesource) {
    boolean isAcceptable = false;
    if (!CHECKED.containsKey(codesource.getLocation())) {
        Certificate[] certs = codesource.getCertificates();
        if (certs == null || certs.length == 0) {
            JOptionPane.showMessageDialog(null, "The jar at " + codesource.getLocation() + " is not signed!",
                    "Security Error", JOptionPane.ERROR_MESSAGE);
            isAcceptable = false;
        } else {
            isAcceptable = true;
            for (int i = 0; (i < certs.length) && isAcceptable; i++) {
                if (!verifyCertificate((X509Certificate) certs[i])) {
                    isAcceptable = false;
                }
            }
        }
        CHECKED.put(codesource.getLocation(), isAcceptable);
    } else {
        isAcceptable = CHECKED.get(codesource.getLocation());
    }

    Permissions permissions = new Permissions();
    if (isAcceptable) {
        permissions.add(new AllPermission());
        return permissions;
    }
    throw new SecurityException("Access denied to " + codesource.getLocation());
}

From source file:se.trixon.jota.client.Client.java

public boolean serverStart() throws URISyntaxException, IOException, NotBoundException {
    boolean serverProbablyStarted = false;
    Xlog.timedOut(Dict.SERVER_START.toString());

    StringBuilder java = new StringBuilder();
    java.append(System.getProperty("java.home")).append(SystemUtils.FILE_SEPARATOR).append("bin")
            .append(SystemUtils.FILE_SEPARATOR).append("java");

    if (SystemUtils.IS_OS_WINDOWS) {
        java.append(".exe");
    }//  w w w .  j  a  va 2s. c om

    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    File jarFile = new File(codeSource.getLocation().toURI().getPath());
    if (jarFile.getAbsolutePath().endsWith(".jar")) {
        ArrayList<String> command = new ArrayList<>();
        command.add(java.toString());
        command.add("-cp");
        command.add(jarFile.getAbsolutePath());
        command.add("Server");
        command.add("--port");
        command.add(String.valueOf(mOptions.getAutostartServerPort()));

        Xlog.timedOut(StringUtils.join(command, " "));
        ProcessBuilder processBuilder = new ProcessBuilder(command).inheritIO();
        processBuilder.start();

        try {
            Thread.sleep(mOptions.getAutostartServerConnectDelay());
        } catch (InterruptedException ex) {
            Xlog.timedErr(ex.getLocalizedMessage());
        }

        serverProbablyStarted = true;
    } else {
        Xlog.timedErr(mBundle.getString("autostart_info"));
    }

    return serverProbablyStarted;
}

From source file:org.apache.accumulo.cluster.standalone.StandaloneClusterControl.java

String getJarFromClass(Class<?> clz) {
    CodeSource source = clz.getProtectionDomain().getCodeSource();
    if (null == source) {
        throw new RuntimeException("Could not get CodeSource for class");
    }/*from www  .  j  ava  2 s . c  o  m*/
    URL jarUrl = source.getLocation();
    String jar = jarUrl.getPath();
    if (!jar.endsWith(".jar")) {
        throw new RuntimeException("Need to have a jar to run mapreduce: " + jar);
    }
    return jar;
}

From source file:org.craftercms.social.migration.controllers.MainController.java

protected void extractBuildInScripts(String application, ListView lstToAdd) throws MigrationException {
    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    List<String> list = new ArrayList<String>();
    byte[] buffer = new byte[1024];
    if (src != null) {
        try {/*from   w  w  w  .j  ava2 s .c o  m*/
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            ZipEntry ze = zip.getNextEntry();
            if (ze == null) {
                //Running from IDE or Exploded Jar no need to extract!
                log.debug("Loading files from FS ");
                loadScripts(getClass().getResource("/" + application).getFile(), lstToAdd);
            } else {
                while (ze != null) {
                    String entryName = ze.getName();
                    if (entryName.startsWith(application) && entryName.endsWith(".js")) {
                        log.debug("Extracting {} ", entryName);
                        final File extractFile = Paths.get(Paths
                                .get(MigrationTool.systemProperties
                                        .getString("crafter" + "" + ".migration.profile.scripts"))
                                .toFile().getParent(), entryName).toFile();
                        if (!extractFile.exists()) {
                            extractFile.createNewFile();
                            FileOutputStream fos = new FileOutputStream(extractFile);
                            int len;
                            while ((len = zip.read(buffer)) > 0) {
                                fos.write(buffer, 0, len);
                            }
                            fos.close();

                        }
                    }
                    ze = zip.getNextEntry();
                }
            }
        } catch (IOException ex) {
            log.debug("Unable to load build in scripts", ex);
        }
    } else {
        loadBuildInScripts(application, lstToAdd);
    }
}

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.
 * /*from w ww  .ja  v  a  2s.  c  om*/
 * @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);
    }
}