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.zaizi.sensefy.api.SensefyResourceApplication.java

public static void main(String[] args) {
    SpringApplication.run(SensefyResourceApplication.class, args);
    int port = Integer.parseInt(System.getProperty("jetty.port", "8080"));
    int requestHeaderSize = Integer.parseInt(System.getProperty("jetty.header.size", "65536"));
    Server server = new Server(port);
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1);
    ProtectionDomain domain = SensefyResourceApplication.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    // Set request header size
    //   server.getConnectors()[0].setRequestHeaderSize(requestHeaderSize);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/api");
    webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
    webapp.setServer(server);//from  ww w.  j  av a 2  s  .c  om
    webapp.setWar(location.toExternalForm());

    // (Optional) Set the directory the war will extract to.
    // If not set, java.io.tmpdir will be used, which can cause problems
    // if the temp directory gets cleaned periodically.
    // Your build scripts should remove this directory between deployments
    // webapp.setTempDirectory(new File("/path/to/webapp-directory"));

    server.setHandler(webapp);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:alpine.embedded.EmbeddedJettyServer.java

public static void main(String[] args) throws Exception {

    final CliArgs cliArgs = new CliArgs(args);
    final String contextPath = cliArgs.switchValue("-context", "/");
    final String host = cliArgs.switchValue("-host", "0.0.0.0");
    final int port = cliArgs.switchIntegerValue("-port", 8080);

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();/*  w  w  w .ja  v  a2s  .c  o  m*/

    final Server server = new Server();
    final ServerConnector connector = new ServerConnector(server);
    connector.setHost(host);
    connector.setPort(port);
    server.setConnectors(new Connector[] { connector });

    final WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath(contextPath);
    context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
            ".*/[^/]*taglibs.*\\.jar$");
    context.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
    context.addBean(new ServletContainerInitializersStarter(context), true);

    // Prevent loading of logging classes
    context.getSystemClasspathPattern().add("org.apache.log4j.");
    context.getSystemClasspathPattern().add("org.slf4j.");
    context.getSystemClasspathPattern().add("org.apache.commons.logging.");

    final ProtectionDomain protectionDomain = EmbeddedJettyServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    context.setWar(location.toExternalForm());

    server.setHandler(context);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:org.zaizi.sensefy.ui.SensefySearchUiApplication.java

public static void main(String[] args) {
    // SpringApplication.run(SensefySearchUiApplication.class, args);

    SpringApplication.run(SensefySearchUiApplication.class, args);
    int port = Integer.parseInt(System.getProperty("jetty.port", "8080"));
    int requestHeaderSize = Integer.parseInt(System.getProperty("jetty.header.size", "65536"));
    Server server = new Server(port);
    ProtectionDomain domain = SensefySearchUiApplication.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    // Set request header size
    // server.getConnectors()[0].setRequestHeaderSize(requestHeaderSize);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/ui");
    webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
    webapp.setServer(server);//from   w w  w. j a v  a  2 s. c o m
    webapp.setWar(location.toExternalForm());

    // (Optional) Set the directory the war will extract to.
    // If not set, java.io.tmpdir will be used, which can cause problems
    // if the temp directory gets cleaned periodically.
    // Your build scripts should remove this directory between deployments
    // webapp.setTempDirectory(new File("/path/to/webapp-directory"));

    server.setHandler(webapp);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.zaizi.sensefy.auth.AuthServerApplication.java

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);

    int port = Integer.parseInt(System.getProperty("jetty.port", "8080"));
    int requestHeaderSize = Integer.parseInt(System.getProperty("jetty.header.size", "65536"));
    Server server = new Server(port);
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1);
    ProtectionDomain domain = AuthServerApplication.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    // Set request header size
    // server.getConnectors()[0].setRequestHeaderSize(requestHeaderSize);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/auth");
    webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
    webapp.setServer(server);//from  www .  j a v a  2 s . c o  m
    webapp.setWar(location.toExternalForm());

    // (Optional) Set the directory the war will extract to.
    // If not set, java.io.tmpdir will be used, which can cause problems
    // if the temp directory gets cleaned periodically.
    // Your build scripts should remove this directory between deployments
    // webapp.setTempDirectory(new File("/path/to/webapp-directory"));

    server.setHandler(webapp);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:RedPenRunner.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", "version", false, "print the version information and exit");

    OptionBuilder.withLongOpt("port");
    OptionBuilder.withDescription("port number");
    OptionBuilder.hasArg();//  ww  w.j  a  v  a  2 s  .c o  m
    OptionBuilder.withArgName("PORT");
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("stop key");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("STOP_KEY");
    options.addOption(OptionBuilder.create("k"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("CONFIG_FILE");
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("lang");
    OptionBuilder.withDescription("Language of error messages");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("LANGUAGE");
    options.addOption(OptionBuilder.create("L"));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(options);
        System.exit(-1);
    }

    int portNum = 8080;
    String language = "en";
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        System.exit(0);
    }
    if (commandLine.hasOption("p")) {
        portNum = Integer.parseInt(commandLine.getOptionValue("p"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (isPortTaken(portNum)) {
        System.err.println("port is taken...");
        System.exit(1);
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    final String contextPath = System.getProperty("redpen.home", "/");

    Server server = new Server(portNum);
    ProtectionDomain domain = RedPenRunner.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    HandlerList handlerList = new HandlerList();
    if (commandLine.hasOption("key")) {
        // Add Shutdown handler only when STOP_KEY is specified
        ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key"));
        handlerList.addHandler(shutdownHandler);
    }

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    if (location.toExternalForm().endsWith("redpen-server/target/classes/")) {
        // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources.
        webapp.setWar(location.toExternalForm() + "../redpen-server/");
    } else {
        webapp.setWar(location.toExternalForm());
    }
    if (commandLine.hasOption("c")) {
        webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c"));
    }

    handlerList.addHandler(webapp);
    server.setHandler(handlerList);

    server.start();
    server.join();
}

From source file:Main.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * //from  w  ww . j  av a 2s .c  o m
 * @param clazz
 *          the Class
 * @param results -
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the clazz
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n");
    results.append(clazz.getName());
    results.append("(");
    results.append(Integer.toHexString(clazz.hashCode()));
    results.append(").ClassLoader=");
    results.append(cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n..");
        results.append(parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n....");
            results.append(urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) {
        results.append("\n++++CodeSource: ");
        results.append(clazzCS);
    } else
        results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        Class iface = ifaces[i];
        results.append("\n++");
        results.append(iface);
        results.append("(");
        results.append(Integer.toHexString(iface.hashCode()));
        results.append(")");
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: ");
        results.append(loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            results.append("\n++++CodeSource: ");
            results.append(cs);
        } else
            results.append("\n++++Null CodeSource");
    }
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * //from   w w  w.j a  v  a2 s.co m
 * @param clazz
 *          the Class
 * @param results,
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class<?> clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n.." + parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n...." + urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null)
        results.append("\n++++CodeSource: " + clazzCS);
    else
        results.append("\n++++Null CodeSource");
    results.append("\nImplemented Interfaces:");
    Class<?>[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        results.append("\n++" + ifaces[i]);
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: " + loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null)
            results.append("\n++++CodeSource: " + cs);
        else
            results.append("\n++++Null CodeSource");
    }
}

From source file:org.duracloud.syncui.SyncUIDriver.java

/**
 * Note: The embedded Jetty server setup below is based on the example configuration in the Eclipse documentation:
 * https://www.eclipse.org/jetty/documentation/9.4.x/embedded-examples.html#embedded-webapp-jsp
 *//* ww w  .j a  va  2 s  . c  o m*/
private static void launchServer(final String url, final CloseableHttpClient client) {
    try {
        final JDialog dialog = new JDialog();
        dialog.setSize(new java.awt.Dimension(400, 75));
        dialog.setModalityType(ModalityType.MODELESS);
        dialog.setTitle("DuraCloud Sync");
        dialog.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        final JLabel label = new JLabel("Loading...");
        final JProgressBar progress = new JProgressBar();
        progress.setStringPainted(true);

        panel.add(label);
        panel.add(progress);
        dialog.add(panel);
        dialog.setVisible(true);

        port = SyncUIConfig.getPort();
        contextPath = SyncUIConfig.getContextPath();
        Server srv = new Server(port);

        // Setup JMX
        MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
        srv.addBean(mbContainer);

        ProtectionDomain protectionDomain = org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();

        log.debug("warfile: {}", warFile);
        WebAppContext context = new WebAppContext();
        context.setContextPath(contextPath);
        context.setWar(warFile);
        context.setExtractWAR(Boolean.TRUE);

        Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(srv);
        classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                "org.eclipse.jetty.annotations.AnnotationConfiguration");

        context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");

        srv.setHandler(context);

        new Thread(new Runnable() {
            @Override
            public void run() {
                createSysTray(url, srv);

                while (true) {
                    if (progress.getValue() < 100) {
                        progress.setValue(progress.getValue() + 3);
                    }

                    sleep(2000);
                    if (isAppRunning(url, client)) {
                        break;
                    }
                }

                progress.setValue(100);

                label.setText("Launching browser...");
                launchBrowser(url);
                dialog.setVisible(false);
            }
        }).start();

        srv.start();

        srv.join();
    } catch (Exception e) {
        log.error("Error launching server: " + e.getMessage(), e);
    }
}

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();
    }//from   ww w  .  j a  v a2 s.c o  m
    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:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Return file for the enclosing jar/*from   w ww  .j  av a 2 s . c  om*/
 *
 * @return
 *
 * @throws URISyntaxException
 */
private static File thisJarFile() {
    final ProtectionDomain protectionDomain = ExpandRunServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    try {
        return new File(location.toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}