Example usage for java.security ProtectionDomain getCodeSource

List of usage examples for java.security ProtectionDomain getCodeSource

Introduction

In this page you can find the example usage for java.security ProtectionDomain getCodeSource.

Prototype

public final CodeSource getCodeSource() 

Source Link

Document

Returns the CodeSource of this domain.

Usage

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);
        }//from w w  w. j a va2s.  c om
        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)./*w w w .  j a  v  a 2  s .c  o 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.openanzo.client.cli.AnzoConsole.java

AnzoConsole() {
    try {//from  w w w.  jav  a  2  s  . c o m
        dcw = CommandLineInterface.DEFAULT_CONSOLE;
        if (dcw.cr != null) {
            dcw.cr.setBellEnabled(true);
            dcw.cr.setPrompt("Anzo>");
            dcw.cr.setHistoryEnabled(true);
        }
        dcw.writeOutput(
                "Anzo Command Line Client. \nCopyright (c) 2009 Cambridge Semantics Inc and others. All rights reserved.");
        String version = null;
        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() && file.getName().toLowerCase().endsWith(".jar")) {
                    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();
        }
        dcw.writeOutput("Version: " + ((version == null) ? "Unknown" : version));
        dcw.writeOutput("Type help for usage");

        HashMap<String, Completer> completers = new HashMap<String, Completer>();
        completers.put("exit", new NullCompleter());
        completers.put("quit", new NullCompleter());
        completers.put("connect", new NullCompleter());
        completers.put("disconnect", new NullCompleter());
        completers.put("trace", new StringsCompleter("on", "off"));
        Options global = CommandLineInterface.getGlobalOptions();
        for (SubCommand sc : CommandLineInterface.subcommands) {
            String command = sc.getName();
            ArrayList<String> subcommands = new ArrayList<String>();
            for (Object o : sc.getOptions().getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            for (Object o : global.getOptions()) {
                Option options = (Option) o;
                subcommands.add("-" + options.getOpt());
                subcommands.add("--" + options.getLongOpt());
            }
            completers.put(command, new StringsCompleter(subcommands));
        }
        if (dcw.cr != null) {
            dcw.cr.addCompleter(new CLICompleter(completers));
        }
        boolean showStackTrace = false;
        while (true) {
            String command = dcw.readLine("Anzo>");
            if (command != null) {
                if (EXIT.toLowerCase().equals(command.trim().toLowerCase())
                        || QUIT.toLowerCase().equals(command.trim().toLowerCase())) {
                    if (context != null && context.client != null && context.client.isConnected()) {
                        context.client.disconnect();
                        context.client.close();
                        dcw.writeOutput("Disonnected from:" + context.host);
                    }
                    System.exit(0);
                }
                String arguments[] = stringToArgs(command);
                try {
                    if (arguments.length > 0) {
                        String subcommand = arguments[0];
                        if ("connect".equals(subcommand.toLowerCase())) {
                            Options options = new Options();
                            CommandLineInterface.appendGlobalOptions(options);
                            CommandLineParser parser = new PosixParser();
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            CommandLine cl = parser.parse(options, subcommandArgs);
                            if (context == null) {
                                context = CommandLineInterface.createContext(dcw, cl, options, arguments);
                            }
                            if (!context.client.isConnected()) {
                                context.client.connect();
                                dcw.writeOutput("Connected to:" + context.host);
                            }
                        } else if ("disconnect".equals(subcommand.toLowerCase())) {
                            if (context != null && context.client != null && context.client.isConnected()) {
                                context.client.disconnect();
                                context.client.close();
                                dcw.writeOutput("Disonnected from:" + context.host);
                            } else {
                                dcw.writeOutput("Not connected to:" + context.host);
                            }
                            context = null;
                        } else if ("trace".equals(subcommand.toLowerCase())) {
                            String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1,
                                    arguments.length);
                            if (subcommandArgs.length == 0) {
                                dcw.writeOutput("Show Stack Trace:" + showStackTrace);
                            } else {
                                String flag = subcommandArgs[0];
                                if (flag.equals("on"))
                                    showStackTrace = true;
                                else if (flag.equals("off"))
                                    showStackTrace = false;
                                else
                                    showStackTrace = Boolean.parseBoolean(flag);
                            }
                            if (context != null) {
                                context.showTrace = showStackTrace;
                            }
                        } else if ("version".equals(subcommand.toLowerCase())) {
                            String header = CommandLineInterface.generateVersionHeader();
                            dcw.writeOutput(header);

                        } else {
                            CommandLineInterface.processCommand(context, false, arguments);
                        }
                    }
                } catch (AnzoException e) {
                    if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) {
                        dcw.writeError("Connection failed.");
                        if (showStackTrace)
                            dcw.printException(e, showStackTrace);
                    } else {
                        dcw.printException(e, showStackTrace);
                    }
                } catch (AnzoRuntimeException e) {
                    dcw.printException(e, showStackTrace);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

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

private static String determineVersion() throws URISyntaxException, IOException {
    String version = null;//  w w  w .  j a  v  a2s. 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: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//from   w  w w.j  a v  a 2s . c  om
 *
 * @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.owasp.dependencycheck.utils.Settings.java

/**
 * Attempts to retrieve the folder containing the Jar file containing the
 * Settings class.//  www  .j a  va  2 s. c om
 *
 * @return a File object
 */
private File getJarPath() {
    String decodedPath = ".";
    String jarPath = "";
    final ProtectionDomain domain = Settings.class.getProtectionDomain();
    if (domain != null && domain.getCodeSource() != null && domain.getCodeSource().getLocation() != null) {
        jarPath = Settings.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    }
    try {
        decodedPath = URLDecoder.decode(jarPath, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        LOGGER.trace("", ex);
    }

    final File path = new File(decodedPath);
    if (path.getName().toLowerCase().endsWith(".jar")) {
        return path.getParentFile();
    } else {
        return new File(".");
    }
}

From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java

protected final Archive createArchive() {
    try {//from  w  w w.  j av  a2 s.c o  m
        ProtectionDomain protectionDomain = getClass().getProtectionDomain();
        CodeSource codeSource = protectionDomain.getCodeSource();
        URI location;
        location = (codeSource == null ? null : codeSource.getLocation().toURI());
        String path = (location == null ? null : location.getSchemeSpecificPart());
        if (path == null) {
            throw new IllegalStateException("Unable to determine code source archive");
        }
        File root = new File(path);
        if (!root.exists()) {
            throw new IllegalStateException("Unable to determine code source archive from " + root);
        }
        return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
    } catch (Exception e) {
        throw new IllegalStateException("Cannt create local archive", e);
    }
}

From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java

/**
 * Gets the URI of the jar file this class is in.
 *
 * @return URI of jar file this class is in
 * @throws URISyntaxException/*from   w ww. j a  v a  2s.  c om*/
 */
private URI getJarURI() throws URISyntaxException {
    final ProtectionDomain domain;
    final CodeSource source;
    final URL url;
    final URI uri;

    domain = this.getClass().getProtectionDomain();
    source = domain.getCodeSource();
    url = source.getLocation();
    uri = url.toURI();

    return (uri);
}

From source file:pt.ua.tm.neji.web.server.Server.java

/**
 * Initialize the server./*from   ww  w .j  av a 2  s  .  c o  m*/
 *
 * @param context    context
 * @param port       port
 * @param numThreads number of threads
 * @throws NejiException
 */
public void initialize(Context context, int port, int numThreads) throws NejiException {

    this.context = context;
    this.numThreads = numThreads;
    this.executor = Executors.newFixedThreadPool(numThreads);

    // Get services
    for (Service s : db.getServices()) {
        serviceMap.put(s.getName(), s);
    }

    // Start a Jetty server with some sensible defaults
    setStopAtShutdown(true);

    // Increase thread pool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(1);
    threadPool.setMaxThreads(100);
    threadPool.setDetailedDump(false);
    setThreadPool(threadPool);

    // HTTPS
    SslSelectChannelConnector sslconector = new SslSelectChannelConnector();
    sslconector.setKeystore(ServerConfiguration.getInstance().getHttpsKeystoreFile());
    sslconector.setKeyPassword(ServerConfiguration.getInstance().getHttpsKeystorePassword());

    sslconector.setTruststore(ServerConfiguration.getInstance().getHttpsTruststoreFile());
    sslconector.setTrustPassword(ServerConfiguration.getInstance().getHttpsTruststorePassword());

    sslconector.setAcceptors(4);
    sslconector.setMaxIdleTime(30000);
    sslconector.setPort(port);
    setConnectors(new Connector[] { sslconector });

    // Gets the war-file
    ProtectionDomain protectionDomain = WebMain.class.getProtectionDomain();
    String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();

    String contextPath = System.getProperty("jetty.contextPath", "/");
    String serverDescriptorPath = File.separator + "WEB-INF" + File.separator + "web.xml";

    // Web context configuration
    WebAppContext webContext = new WebAppContext();
    webContext.setContextPath(contextPath);
    webContext.setWar(warFile);
    webContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    setStopAtShutdown(true);
    webContext.setDescriptor(serverDescriptorPath);
    webContext.addServlet(new ServletHolder(new JSPServlet()), "/contextadd");

    // Adds the configured context to the handlers
    HandlerList handlers = new HandlerList();
    handlers.addHandler(webContext);
    setHandler(handlers);

    // Authentication        
    try {
        JDBCLoginService loginService = new JDBCLoginService("LoginRealm");
        loginService.setConfig("loginRealm.properties");
        addBean(loginService);
    } catch (IOException ex) {
        throw new NejiException("There was a problem initialazing the jetty authentication mechanism.");
    }

    addLifeCycleListener(this);
    this.initialized = true;
}