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:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java

private static URL getSpringUrl() {

    final ProtectionDomain protectionDomain = RemoteInvocation.class.getProtectionDomain();
    String errorMessage = "creation of jar file failed for UNKNOWN reason";

    if (protectionDomain == null) {

        errorMessage = "class protection domain is null";

    } else {//  ww  w. j  a  v a2s.co m

        final CodeSource codeSource = protectionDomain.getCodeSource();

        if (codeSource == null) {

            errorMessage = "class code source is null";

        } else {

            final URL location = codeSource.getLocation();

            if (location == null) {

                errorMessage = "class code source location is null";

            } else {

                return location;

            }

        }

    }

    throw new UnsupportedOperationException(errorMessage);

}

From source file:Main.java

public Main() {
    Class cls = this.getClass();
    ProtectionDomain pDomain = cls.getProtectionDomain();
    CodeSource cSource = pDomain.getCodeSource();
    URL loc = cSource.getLocation();

}

From source file:net.seedboxer.jetty.DaemonServer.java

private void start() {
    // Start a Jetty server with some sensible(?) defaults
    try {/*from  www  .  j av a2  s .  co  m*/

        Server srv = new Server(port);
        srv.setStopAtShutdown(true);

        // Get the war-file
        ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
        String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

        // Add the warFile (this jar)
        WebAppContext context = new WebAppContext();
        context.setContextPath(CONTEXT_PATH);
        context.setWar(warFile);
        resetTempDirectory(context, currentDir);

        srv.setHandler(context);

        // Register shutdown hook
        registerShutdownHook(srv, context);

        srv.start();
        srv.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jp.gr.java_conf.schkit.utils.ApplicationInfo.java

private ApplicationInfo() {
    try {/*  www  .ja v  a  2  s  .co  m*/
        ProtectionDomain domain = this.getClass().getProtectionDomain();
        classLotation = domain.getCodeSource().getLocation();
        classLoader = (URLClassLoader) domain.getClassLoader();

        loadManifest();
        // setDirectories();
    } catch (Exception 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: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 ww .  j  a v a  2s  .  co m*/
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
    }
    return null;
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private void extractWarFile() {
    if (webAppBase != null && webAppBase.length() > 0) {
        ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
        URL location = protectionDomain.getCodeSource().getLocation();
        log.info("detected run JAR at " + location);

        if (!location.toExternalForm().startsWith("file:") || !location.toExternalForm().endsWith(".jar"))
            throw new IllegalArgumentException("invalid code location: " + location);

        try {//w  w  w.  j a  va2 s . c o  m
            ZipFile zipFile = new ZipFile(new File(location.toURI()));

            Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
            ZipEntry warEntry = null;
            while (entryEnum.hasMoreElements()) {
                ZipEntry entry = entryEnum.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(webAppBase) && entryName.endsWith(".war")) {
                    warEntry = entry;
                    break;
                }
            }

            if (warEntry == null)
                throw new RuntimeException("can't find JAR entry for " + webAppBase + "*.war");

            log.info("extracting WAR file " + warEntry.getName());

            // extract web app WAR to current directory
            InputStream inputStream = zipFile.getInputStream(warEntry);
            OutputStream outputStream = new FileOutputStream(new File(warEntry.getName()));
            byte buf[] = new byte[1024];
            int nread;
            while ((nread = inputStream.read(buf, 0, 1024)) > 0) {
                outputStream.write(buf, 0, nread);
            }
            outputStream.close();
            inputStream.close();
            zipFile.close();

            String launchContextRoot = contextRoot != null ? contextRoot : webAppBase;
            if (!launchContextRoot.startsWith("/"))
                launchContextRoot = "/" + launchContextRoot;

            log.info("launching WAR file " + warEntry.getName() + " at context root " + launchContextRoot);

            // add web app to Tomcat
            Context context = tomcat.addWebapp(launchContextRoot, warEntry.getName());
            if (context instanceof StandardContext)
                ((StandardContext) context).setUnpackWAR(false);
        } catch (Exception e) {
            throw new RuntimeException("error extracting WAR file", e);
        }
    }
}

From source file:com.ai.alm.launcher.Launcher.java

void startJetty() {
    String warFile;//from   ww  w  . j  a v a2 s. c o  m
    File workDir;
    try {
        // Get the war-file
        ProtectionDomain protectionDomain = Launcher.class.getProtectionDomain();
        warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();

        // Work directory
        File warDir = new File(protectionDomain.getCodeSource().getLocation().getPath());
        String currentDir = warDir.getParent();
        workDir = getTempDirectory(currentDir, warDir.getName());
    } catch (IOException exp) {
        err.println("error = " + exp.getMessage());
        exp.printStackTrace();
        return;
    }

    // Server
    final Server server = new Server();
    server.setStopAtShutdown(true);
    // Allow 5 seconds to complete.
    server.setGracefulShutdown(5000);
    // Increase thread pool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(100);
    server.setThreadPool(threadPool);

    // Ensure using the non-blocking connector (NIO)
    Connector connector = new SelectChannelConnector();
    connector.setHost(host);
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    server.setConnectors(new Connector[] { connector });

    // Add the warFile (this jar)
    // final WebAppContext context = new ThrowyWebAppContext(warFile, contextPath);
    final WebAppContext context = new WebAppContext(warFile, contextPath) {
        @Override
        protected void doStart() throws Exception {
            super.doStart();
            if (getUnavailableException() != null) {
                throw (Exception) getUnavailableException();
            }
        }
    };

    context.setServer(server);
    context.setTempDirectory(workDir);

    // Handles ping request
    final Date since = new Date();
    final AbstractHandler pingHandler = new AbstractHandler() {
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            if (!target.equals("/jetty-ping")) {
                return;
            }
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("since: " + since);
        }
    };

    // Shutdown Handler
    final AbstractHandler shutdownHandler = new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            if (!target.equals("/jetty-shutdown") || !request.getMethod().equals("POST")
                    || !secret.equals(request.getParameter("secret"))) {
                return;
            }
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("Stopping...");
            stopJetty(server, context);
        }
    };

    try {
        // Handler wrapper
        final HandlerWrapper handlerWrapper = (logsEnabled) ? new DetailedLoggingHandler()
                : new HandlerWrapper();
        handlerWrapper.setHandler(new HandlerList() {
            {
                setHandlers(new Handler[] { shutdownHandler, // shutdown
                        pingHandler, // Handle ping
                        context // Handle app
                });
            }
        });

        server.setHandler(handlerWrapper);

        // Add Lifecycle listener
        server.addLifeCycleListener(new LifeCycle.Listener() {
            @Override
            public void lifeCycleFailure(LifeCycle lc, Throwable th) {
                log.error("#==> error = {}", th.getMessage());
                err.println("#==> error = " + th.getMessage());
                th.printStackTrace();
            }

            @Override
            public void lifeCycleStarted(LifeCycle lc) {
                log.info(String.format("#==> Started jetty @ http://%s:%d/", host, port));
                out.println(String.format("#==> Started jetty @ http://%s:%d/", host, port));
            }

            @Override
            public void lifeCycleStarting(LifeCycle lc) {
                log.info(String.format("#==> Starting jetty @ http://%s:%d/ ...", host, port));
                out.println(String.format("#==> Starting jetty @ http://%s:%d/ ...", host, port));
            }

            @Override
            public void lifeCycleStopped(LifeCycle lc) {
                log.info(String.format("#==> Stopped jetty @ http://%s:%d/", host, port));
                out.println(String.format("#==> Stopped jetty @ http://%s:%d/", host, port));
            }

            @Override
            public void lifeCycleStopping(LifeCycle lc) {
                log.info(String.format("#==> Stopping jetty @ http://%s:%d/ ...", host, port));
                out.println(String.format("#==> Stopping jetty @ http://%s:%d/ ...", host, port));
            }

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

From source file:org.apache.phoenix.tracingwebapp.http.Main.java

@Override
public int run(String[] arg0) throws Exception {
    // logProcessInfo(getConf());
    final int port = getConf().getInt(TRACE_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT);
    BasicConfigurator.configure();/* www . ja v a  2  s  . c  om*/
    final String home = getConf().get(TRACE_SERVER_HTTP_JETTY_HOME_KEY, DEFAULT_HTTP_HOME);
    //setting up the embedded server
    ProtectionDomain domain = Main.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();
    String webappDirLocation = location.toString().split("target")[0] + "src/main/webapp";
    Server server = new Server(port);
    WebAppContext root = new WebAppContext();

    root.setContextPath(home);
    root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
    root.setResourceBase(webappDirLocation);
    root.setParentLoaderPriority(true);
    server.setHandler(root);

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

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();
}