Java Code Examples for org.eclipse.jetty.webapp.WebAppContext#setTempDirectory()

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setTempDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JettyWebServer.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void configWebapp(WebAppContext webapp, JettyConf jettyConf)
    throws URISyntaxException, IOException {
  webapp.setContextPath(contextPath);
  webapp.setVirtualHosts(jettyConf.getVirtualHosts());
  webapp.setMaxFormContentSize(jettyConf.getMaxFormContentSize());
  webapp.setMaxFormKeys(jettyConf.getMaxFormKeys());
  webapp.setParentLoaderPriority(true);
  webapp.setConfigurationDiscovered(jettyConf.isConfigurationDiscovered());
  webapp.setTempDirectory(new File(FileUtils.tempBaseDir(), "jetty-temp"));
  URL url = getClass().getResource(Strings.SLASH);
  if (url != null) {
    webapp.setResourceBase(url.toURI().toASCIIString());
  } else {
    // run in jar
    File dir = new File(FileUtils.tempBaseDir(), "jetty-jsp");
    webapp.setResourceBase(dir.getAbsolutePath());
    if (dir.exists() || dir.mkdirs()) {
      copyJspFiles(dir);
    }
  }
  webapp.addServlet(new ServletHolder("jsp", JettyJspServlet.class), "*.jsp");
  webapp.setConfigurations(new Configuration[]{new AnnotationConfiguration()});
}
 
Example 2
Source File: GatewayServer.java    From knox with Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext( Topology topology, File warFile, String warPath ) {
  String topoName = topology.getName();
  WebAppContext context = new WebAppContext();
  String contextPath;
  contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName, warPath );
  context.setContextPath( contextPath );
  SessionCookieConfig sessionCookieConfig = context.getServletContext().getSessionCookieConfig();
  sessionCookieConfig.setName(KNOXSESSIONCOOKIENAME);
  context.setWar( warFile.getAbsolutePath() );
  context.setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName );
  context.setAttribute( "org.apache.knox.gateway.frontend.uri", getFrontendUri( context, config ) );
  context.setAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config );
  // Add support for JSPs.
  context.setAttribute(
      "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
      ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
  context.setTempDirectory( FileUtils.getFile( warFile, "META-INF", "temp" ) );
  context.setErrorHandler( createErrorHandler() );
  context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
  ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
  context.setClassLoader(jspClassLoader);
  return context;
}
 
Example 3
Source File: VarOneServer.java    From varOne with MIT License 6 votes vote down vote up
private static WebAppContext setupWebAppContext(VarOneConfiguration conf) {
	WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(conf.getServerContextPath());
    File warPath = new File(conf.getString(ConfVars.VARONE_WAR));
    if (warPath.isDirectory()) {
      webApp.setResourceBase(warPath.getPath());
      webApp.setParentLoaderPriority(true);
    } else {
      // use packaged WAR
      webApp.setWar(warPath.getAbsolutePath());
      File warTempDirectory = new File(conf.getRelativeDir(ConfVars.VARONE_WAR_TEMPDIR));
      warTempDirectory.mkdir();
      LOG.info("VarOneServer Webapp path: {}" + warTempDirectory.getPath());
      webApp.setTempDirectory(warTempDirectory);
    }
    // Explicit bind to root
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    return webApp;
}
 
Example 4
Source File: GatewayServer.java    From hadoop-mini-clusters with Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext(Topology topology, File warFile, String warPath) throws IOException, ZipException, TransformerException, SAXException, ParserConfigurationException {
        String topoName = topology.getName();
        WebAppContext context = new WebAppContext();
        String contextPath;
        contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin(config.getGatewayPath(), topoName, warPath);
        context.setContextPath(contextPath);
        context.setWar(warFile.getAbsolutePath());
        context.setAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName);
        context.setAttribute("org.apache.knox.gateway.frontend.uri", getFrontendUri(context, config));
        context.setAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config);
//        // Add support for JSPs.
//        context.setAttribute(
//                "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
//                ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
        context.setTempDirectory(FileUtils.getFile(warFile, "META-INF", "temp"));
        context.setErrorHandler(createErrorHandler());
        return context;
    }
 
Example 5
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
    AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap.<String, String>builder()
      .put("acceptRanges", "true")
      .put("dirAllowed", "false")
      .put("gzip", "true")
      .put("useFileMappedBuffer", "true")
      .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 6
Source File: NiFiTestServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private WebAppContext createWebAppContext(String webappRoot, String contextPath) {
    webappContext = new WebAppContext();
    webappContext.setContextPath(contextPath);
    webappContext.setWar(webappRoot);
    webappContext.setLogUrlOnStart(true);
    webappContext.setTempDirectory(new File("target/jetty"));
    return webappContext;
}
 
Example 7
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
                                                 AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap. <String, String> builder()
                                   .put("acceptRanges", "true")
                                   .put("dirAllowed", "false")
                                   .put("gzip", "true")
                                   .put("useFileMappedBuffer", "true")
                                   .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 8
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
                                                 AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap. <String, String> builder()
                                   .put("acceptRanges", "true")
                                   .put("dirAllowed", "false")
                                   .put("gzip", "true")
                                   .put("useFileMappedBuffer", "true")
                                   .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 9
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(
    ContextHandlerCollection contexts, ZeppelinConfiguration conf, String warPath, String contextPath) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(contextPath);
  LOG.info("warPath is: {}", warPath);
  File warFile = new File(warPath);
  if (warFile.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warFile.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warFile.getAbsolutePath());
    webApp.setExtractWAR(false);
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR) + contextPath);
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  contexts.addHandler(webApp);

  webApp.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class));

  webApp.setInitParameter(
      "org.eclipse.jetty.servlet.Default.dirAllowed",
      Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED)));
  return webApp;
}
 
Example 10
Source File: JettyHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static Server addWebApplication(final Server jetty,
    final String webAppContext, final String warFilePath) throws IOException {
  WebAppContext webapp = new WebAppContext();
  webapp.setContextPath(webAppContext);
  webapp.setWar(warFilePath);
  webapp.setParentLoaderPriority(false);

  File tmpPath = new File(getWebAppBaseDirectory(webAppContext));
  Files.createDirectories(tmpPath.toPath());
  webapp.setTempDirectory(tmpPath);

  ((HandlerCollection) jetty.getHandler()).addHandler(webapp);

  return jetty;
}
 
Example 11
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static WebAppContext createWebAppContext(Builder b,
                                                 AccessControlList adminsAcl, final String appDir) {
  WebAppContext ctx = new WebAppContext();
  ctx.setDefaultsDescriptor(null);
  ServletHolder holder = new ServletHolder(new DefaultServlet());
  Map<String, String> params = ImmutableMap. <String, String> builder()
      .put("acceptRanges", "true")
      .put("dirAllowed", "false")
      .put("gzip", "true")
      .put("useFileMappedBuffer", "true")
      .build();
  holder.setInitParameters(params);
  ctx.setWelcomeFiles(new String[] {"index.html"});
  ctx.addServlet(holder, "/");
  ctx.setDisplayName(b.name);
  ctx.setContextPath("/");
  ctx.setWar(appDir + "/" + b.name);
  String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY);
  if (tempDirectory != null && !tempDirectory.isEmpty()) {
    ctx.setTempDirectory(new File(tempDirectory));
    ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory);
  }
  ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf);
  ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl);
  addNoCacheFilter(ctx);
  return ctx;
}
 
Example 12
Source File: JettyHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static Server addWebApplication(final Server jetty,
    final String webAppContext, final String warFilePath) throws IOException {
  WebAppContext webapp = new WebAppContext();
  webapp.setContextPath(webAppContext);
  webapp.setWar(warFilePath);
  webapp.setParentLoaderPriority(false);

  File tmpPath = new File(getWebAppBaseDirectory(webAppContext));
  Files.createDirectories(tmpPath.toPath());
  webapp.setTempDirectory(tmpPath);

  ((HandlerCollection) jetty.getHandler()).addHandler(webapp);

  return jetty;
}
 
Example 13
Source File: EmbeddedServer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public EmbeddedServer(String host, int port, String contextPath, String warPath) {

		jetty = new Server();

		ServerConnector conn = new ServerConnector(jetty);
		conn.setHost(host);
		conn.setPort(port);
		jetty.addConnector(conn);

		WebAppContext webapp = new WebAppContext();
		webapp.setContextPath(contextPath);
		webapp.setTempDirectory(new File("temp/webapp/"));
		webapp.setWar(warPath);
		jetty.setHandler(webapp);
	}
 
Example 14
Source File: JettyServer.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private static WebAppContext loadWar(final File warFile, final String contextPath, final ClassLoader parentClassLoader) throws IOException {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // instruction jetty to examine these jars for tlds, web-fragments, etc
    webappContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    File tempDir = Paths.get(C2_SERVER_HOME, "tmp", warFile.getName()).toFile();
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}
 
Example 15
Source File: NiFiTestServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private WebAppContext createWebAppContext(String webappRoot, String contextPath) {
    webappContext = new WebAppContext();
    webappContext.setContextPath(contextPath);
    webappContext.setWar(webappRoot);
    webappContext.setLogUrlOnStart(true);
    webappContext.setTempDirectory(new File("target/jetty"));
    return webappContext;
}
 
Example 16
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(HandlerList handlers,
    SubmarineConfiguration conf) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath("/");
  File warPath = new File(conf.getString(SubmarineConfVars.ConfVars.WORKBENCH_WEB_WAR));
  LOG.info("workbench web war file path is {}.",
      conf.getString(SubmarineConfVars.ConfVars.WORKBENCH_WEB_WAR));
  if (warPath.isDirectory()) {
    // Development mode, read from FS
    webApp.setResourceBase(warPath.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warPath.getAbsolutePath());
    File warTempDirectory = new File("webapps");
    warTempDirectory.mkdir();
    webApp.setTempDirectory(warTempDirectory);
  }

  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/");
  // When requesting the workbench page, the content of index.html needs to be returned,
  // otherwise a 404 error will be displayed
  // NOTE: If you modify the workbench directory in the front-end URL,
  // you need to modify the `/workbench/*` here.
  webApp.addServlet(new ServletHolder(RefreshServlet.class), "/user/*");
  webApp.addServlet(new ServletHolder(RefreshServlet.class), "/workbench/*");

  handlers.setHandlers(new Handler[] { webApp });

  return webApp;
}
 
Example 17
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private WebAppContext loadWar(final File warFile, final String contextPath, final URL[] additionalResources)
        throws IOException {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    final File webWorkingDirectory = properties.getWebWorkingDirectory();
    final File tempDir = new File(webWorkingDirectory, warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    // add HTTP security headers to all responses
    final String ALL_PATHS = "/*";
    ArrayList<Class<? extends Filter>> filters = new ArrayList<>(Arrays.asList(XFrameOptionsFilter.class, ContentSecurityPolicyFilter.class, XSSProtectionFilter.class));
    if(properties.isHTTPSConfigured()) {
        filters.add(StrictTransportSecurityFilter.class);
    }

    filters.forEach( (filter) -> addFilters(filter, ALL_PATHS, webappContext));

    // start out assuming the system ClassLoader will be the parent, but if additional resources were specified then
    // inject a new ClassLoader in between the system and webapp ClassLoaders that contains the additional resources
    ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
    if (additionalResources != null && additionalResources.length > 0) {
        URLClassLoader additionalClassLoader = new URLClassLoader(additionalResources, ClassLoader.getSystemClassLoader());
        parentClassLoader = additionalClassLoader;
    }

    webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}
 
Example 18
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private WebAppContext loadWar(final File warFile, final String contextPath, final ClassLoader parentClassLoader) {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // instruction jetty to examine these jars for tlds, web-fragments, etc
    webappContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);

    // get the temp directory for this webapp
    File tempDir = new File(props.getWebWorkingDirectory(), warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    try {
        // configure the class loader - webappClassLoader -> jetty nar -> web app's nar -> ...
        webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));
    } catch (final IOException ioe) {
        startUpFailure(ioe);
    }

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}
 
Example 19
Source File: EsigateServer.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Create and start server.
 * 
 * @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);
        if (StringUtils.isNoneEmpty(sessionCookieName)) {
            context.getSessionHandler().getSessionCookieConfig().setName(sessionCookieName);
        }
        // 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();

    }

}
 
Example 20
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private WebAppContext loadWar(final File warFile, final String contextPath, final ClassLoader parentClassLoader) {
    final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath);
    webappContext.setContextPath(contextPath);
    webappContext.setDisplayName(contextPath);

    // instruction jetty to examine these jars for tlds, web-fragments, etc
    webappContext.setAttribute(CONTAINER_INCLUDE_PATTERN_KEY, CONTAINER_INCLUDE_PATTERN_VALUE);

    // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib
    List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses()));
    serverClasses.remove("org.slf4j.");
    webappContext.setServerClasses(serverClasses.toArray(new String[0]));
    webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML);
    webappContext.getMimeTypes().addMimeMapping("ttf", "font/ttf");

    // get the temp directory for this webapp
    File tempDir = new File(props.getWebWorkingDirectory(), warFile.getName());
    if (tempDir.exists() && !tempDir.isDirectory()) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory");
    } else if (!tempDir.exists()) {
        final boolean made = tempDir.mkdirs();
        if (!made) {
            throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created");
        }
    }
    if (!(tempDir.canRead() && tempDir.canWrite())) {
        throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege");
    }

    // configure the temp dir
    webappContext.setTempDirectory(tempDir);

    // configure the max form size (3x the default)
    webappContext.setMaxFormContentSize(600000);

    // add HTTP security headers to all responses
    final String ALL_PATHS = "/*";
    ArrayList<Class<? extends Filter>> filters =
            new ArrayList<>(Arrays.asList(
                    XFrameOptionsFilter.class,
                    ContentSecurityPolicyFilter.class,
                    XSSProtectionFilter.class,
                    XContentTypeOptionsFilter.class));

    if(props.isHTTPSConfigured()) {
        filters.add(StrictTransportSecurityFilter.class);
    }
    filters.forEach( (filter) -> addFilters(filter, ALL_PATHS, webappContext));
    addFiltersWithProps(ALL_PATHS, webappContext);

    try {
        // configure the class loader - webappClassLoader -> jetty nar -> web app's nar -> ...
        webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext));
    } catch (final IOException ioe) {
        startUpFailure(ioe);
    }

    logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath);
    return webappContext;
}