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.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.covito.kit.utility.ClassUtil.java

public static URL getClassLocation(final String clsName) {
    if (clsName == null) {
        return null;
    }/*  ww w .ja v  a  2 s  . c om*/
    Class cls = null;
    try {
        cls = Class.forName(clsName);
    } catch (Exception e) {
        return null;
    }
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    // java.lang.Class contract does not specify if 'pd' can ever be null;
    // it is not the case for Sun's implementations, but guard against null
    // just in case:
    if (pd != null) {
        final CodeSource cs = pd.getCodeSource();
        // 'cs' can be null depending on the classloader behavior:
        if (cs != null)
            result = cs.getLocation();
        if (result != null) {
            // Convert a code source location into a full class file
            // location
            // for some common cases:
            if ("file".equals(result.getProtocol())) {
                try {
                    if (result.toExternalForm().endsWith(".jar") || result.toExternalForm().endsWith(".zip"))
                        result = new URL(
                                "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
                    else if (new File(result.getFile()).isDirectory()) {
                        result = new URL(result, clsAsResource);
                    }
                } catch (MalformedURLException ignore) {
                }
            }
        }
    }
    if (result == null) {
        // Try to find 'cls' definition as a resource; this is not
        // documentd to be legal, but Sun's implementations seem to //allow
        // this:
        final ClassLoader clsLoader = cls.getClassLoader();
        result = clsLoader != null ? clsLoader.getResource(clsAsResource)
                : ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
}

From source file:org.devtoolbox.errorhandling.impl.OnErrorFileMoverTest.java

public @Before void setUp() throws IOException {

    unitUnderTest = new OnErrorFileMover();

    java.security.ProtectionDomain pd = OnErrorFileMoverTest.class.getProtectionDomain();
    java.security.CodeSource cs = pd.getCodeSource();
    java.net.URL url = cs.getLocation();
    java.io.File f = new File(url.getFile());
    rootFolderPath = f.getAbsolutePath();

    FileUtils.deleteDirectory(new File(rootFolderPath + fileSeparator + processingFolderPath));
    FileUtils.deleteDirectory(new File(rootFolderPath + fileSeparator + errorFolderPath));
    FileUtils.copyFile(new java.io.File("src/test/resources/org/devtoolbox/errorhandling/" + fileName),
            new java.io.File(rootFolderPath + fileSeparator + processingFolderPath + fileSeparator + fileName));
}

From source file:org.diffkit.common.DKRuntime.java

private URL getClassLocation() {
    ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    return codeSource.getLocation();
}

From source file:org.eclipse.jetty.Starter.java

private static void startServer(String hostname, int port) {
    InetSocketAddress inetAddress = new InetSocketAddress(hostname, port);
    Server server = new Server(inetAddress);

    WebAppContext context = new WebAppContext();
    context.setServer(server);//from w  w  w. j a  va  2s . co m
    context.setContextPath("/");

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

    server.setHandler(context);
    try {
        server.start();
        System.out.println("Visit http://" + inetAddress.getHostName() + ":" + port);
        System.out.println("Press any key to stop server!");
        System.in.read();
        server.stop();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(100);
    }
}

From source file:org.esigate.server.EsigateServer.java

/**
 * Create and start server./*from w w  w  . j  a v  a 2 s. c  om*/
 *
 * @throws Exception
 *             when server cannot be started.
 */
public static void start() throws Exception {
    MetricRegistry registry = new MetricRegistry();

    QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
    threadPool.setName("esigate");
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);

    srv = new Server(threadPool);
    srv.setStopAtShutdown(true);
    srv.setStopTimeout(5000);

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(outputBufferSize);
    httpConfig.setSendServerVersion(false);
    Timer processTime = registry.timer("processTime");

    try (ServerConnector connector = new InstrumentedServerConnector("main", EsigateServer.port, srv, registry,
            new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime));
            ServerConnector controlConnector = new ServerConnector(srv)) {

        // Main connector
        connector.setIdleTimeout(EsigateServer.idleTimeout);
        connector.setSoLingerTime(-1);
        connector.setName("main");
        connector.setAcceptQueueSize(200);

        // Control connector
        controlConnector.setHost("127.0.0.1");
        controlConnector.setPort(EsigateServer.controlPort);
        controlConnector.setName("control");

        srv.setConnectors(new Connector[] { connector, controlConnector });
        // War
        ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
        String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

        File workDir = resetTempDirectory(currentDir);

        WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath);
        context.setServer(srv);
        context.setTempDirectory(workDir);

        // Add extra classpath (allows to add extensions).
        if (EsigateServer.extraClasspath != null) {
            context.setExtraClasspath(EsigateServer.extraClasspath);
        }

        // Add the handlers
        HandlerCollection handlers = new HandlerList();
        // control handler must be the first one.
        // Work in progress, currently disabled.
        handlers.addHandler(new ControlHandler(registry));
        InstrumentedHandler ih = new InstrumentedHandler(registry);
        ih.setName("main");
        ih.setHandler(context);
        handlers.addHandler(ih);

        srv.setHandler(handlers);
        srv.start();
        srv.join();

    }

}

From source file:org.ff4j.web.console.server.JettyEmbeddedServer.java

/**
 * Start Jetty.//from  w w w .  jav a2  s  .c o m
 */
public void start() {
    try {

        // Setup Threadpool
        QueuedThreadPool threadPool = new QueuedThreadPool(512);

        // Setup Jetty Server instance
        Server server = new Server(threadPool);
        server.setStopAtShutdown(true);
        server.setStopTimeout(5000);

        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        connector.setIdleTimeout(30000);
        server.setConnectors(new Connector[] { connector });

        // Get the war-file
        ProtectionDomain protectionDomain = Main.class.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(warFile, contextPath);
        context.setServer(server);
        cleanTempDirectory(context, currentDir);

        // Add the handlers
        HandlerList handlers = new HandlerList();
        handlers.addHandler(context);
        handlers.addHandler(new ShutdownHandler(server, context));
        server.setHandler(handlers);
        server.start();
        server.join();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.java.plugin.standard.StandardPluginClassLoader.java

private static URL getClassBaseUrl(final Class cls) {
    ProtectionDomain pd = cls.getProtectionDomain();
    if (pd != null) {
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            return cs.getLocation();
        }/*  ww  w. ja va  2  s . c om*/
    }
    return null;
}

From source file:org.jumpmind.metl.StartWebServer.java

public static void runWebServer() throws Exception {

    disableJettyLogging();/*from  www.j av a  2 s.c  om*/

    System.out.println(IOUtils.toString(StartWebServer.class.getResource("/Metl.asciiart")));

    Server server = new Server(PORT);

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

    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);

    ProtectionDomain protectionDomain = StartWebServer.class.getProtectionDomain();
    URL location = protectionDomain.getCodeSource().getLocation();
    File locationDir = new File(location.getFile()).getParentFile();

    WebAppContext webapp = new WebAppContext();

    //        HashSessionManager sessionManager = new HashSessionManager();
    //        File storeDir = new File(locationDir, "sessions");
    //        storeDir.mkdirs();
    //        sessionManager.setStoreDirectory(storeDir);
    //        sessionManager.setLazyLoad(true);
    //        sessionManager.setSavePeriod(5);
    //        sessionManager.setDeleteUnrestorableSessions(true);        
    //        SessionHandler sessionHandler = new SessionHandler(sessionManager);
    //        webapp.setSessionHandler(sessionHandler);

    webapp.setContextPath("/metl");
    webapp.setWar(location.toExternalForm());
    webapp.addAliasCheck(new AllowSymLinkAliasChecker());

    File pluginsDir = new File(locationDir, "plugins");
    pluginsDir.mkdirs();
    StringBuilder extraClasspath = new StringBuilder();
    File[] files = pluginsDir.listFiles();
    Arrays.sort(files);
    for (File file : files) {
        if (file.isFile() && file.getName().endsWith(".jar")) {
            extraClasspath.append(file.toURI().toURL().toExternalForm()).append(",");
        }
    }
    webapp.setExtraClasspath(extraClasspath.toString());

    server.setHandler(webapp);

    ServerContainer webSocketServer = WebSocketServerContainerInitializer.configureContext(webapp);
    webSocketServer.setDefaultMaxSessionIdleTimeout(10000000);

    server.start();

    if (extraClasspath.length() > 0) {
        getLogger().info("Adding extra classpath of: " + extraClasspath.toString());
    }
    getLogger().info("To use Metl, navigate to http://localhost:" + PORT + "/metl");

    server.join();
}

From source file:org.jumpmind.metl.Wrapper.java

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

    String configFileName = "metl_service.conf";
    ProtectionDomain protectionDomain = Wrapper.class.getProtectionDomain();
    String jarFileName = protectionDomain.getCodeSource().getLocation().getFile();

    String appHomeDir = getConfigDir(true);

    File configFile = new File(appHomeDir, configFileName);
    if (!configFile.exists()) {
        try {/*  w  ww  .j a  va 2s .  c om*/
            String propContent = IOUtils
                    .toString(Wrapper.class.getClassLoader().getResourceAsStream(configFileName));
            propContent = propContent.replace("$(metl.war)", jarFileName);
            propContent = propContent.replace("$(java.io.tmpdir)", appHomeDir + File.separator + "tmp");
            propContent = propContent.replace("$(metl.home.dir)", appHomeDir);
            FileUtils.write(configFile, propContent);
        } catch (Exception e) {
            System.out.println("Unable to write config file for service wrapper." + e.getMessage());
            System.exit(-1);
        }
    }
    System.out.println("Calling WrapperHelper with parameters:  applHomeDir==>" + appHomeDir
            + ", configFile ==>" + appHomeDir + "/" + configFileName + " jarfile==> " + jarFileName);
    WrapperHelper.run(args, appHomeDir, appHomeDir + File.separator + configFileName, jarFileName);
}