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

The following examples show how to use org.eclipse.jetty.webapp.WebAppContext#setWar() . 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: JAXRSClientServerWebSocketSpringWebAppTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static void startServers(String port) throws Exception {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(port));

    WebAppContext webappcontext = new WebAppContext();
    String contextPath = null;
    try {
        contextPath = JAXRSClientServerWebSocketSpringWebAppTest.class
            .getResource("/jaxrs_websocket").toURI().getPath();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    webappcontext.setContextPath("/webapp");

    webappcontext.setWar(contextPath);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
}
 
Example 2
Source File: Spring3WebMvcTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  server = new Server(0);

  final WebAppContext webAppContext = new WebAppContext();
  webAppContext.setServer(server);
  webAppContext.setContextPath("/");
  webAppContext.setWar("src/test/webapp");

  server.setHandler(webAppContext);
  server.start();

  // jetty starts on random port
  final int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
  url = "http://localhost:" + port;
}
 
Example 3
Source File: TestServer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TestServer() {
	System.clearProperty("DEBUG");

	jetty = new Server();

	ServerConnector conn = new ServerConnector(jetty);
	conn.setHost(HOST);
	conn.setPort(PORT);
	jetty.addConnector(conn);

	WebAppContext webapp = new WebAppContext();
	webapp.addSystemClass("org.slf4j.");
	webapp.addSystemClass("ch.qos.logback.");
	webapp.setContextPath(RDF4J_CONTEXT);
	// warPath configured in pom.xml maven-war-plugin configuration
	webapp.setWar("./target/rdf4j-server");
	jetty.setHandler(webapp);
}
 
Example 4
Source File: Start.java    From javasimon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) {
	Server server = new Server(8080);

	WebAppContext bb = new WebAppContext();
	bb.setServer(server);
	bb.setContextPath("/");
	bb.setWar("src/main/webapp");

	server.setHandler(bb);

	try {
		System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
		server.start();
		//noinspection ResultOfMethodCallIgnored
		System.in.read();
		System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
		server.stop();
		server.join();
	} catch (Exception e) {
		e.printStackTrace();
		System.exit(1);
	}
}
 
Example 5
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    System.out.println("Starting Server");

    /**
     * Important: This code simply starts up a servlet container and adds
     * the web application in src/webapp to it. Normally you would be using
     * Jetty or Tomcat and have the webapp packaged as a WAR. This is simply
     * as a convenience so you do not need to configure your servlet
     * container to see CXF in action!
     */
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9002);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    webappcontext.setWar("target/JAXRSSpringSecurity.war");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

    server.setHandler(handlers);
    server.start();
    System.out.println("Server ready...");
    server.join();
}
 
Example 6
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the WebApplication for Swagger-ui
 *
 * @return WebAppContext with swagger ui context
 */
private static WebAppContext setupWebAppSwagger(ExplorerConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    File webapp = new File(conf.getString(ExplorerConfiguration.ConfVars.EXPLORER_API_WAR));

    if (webapp.isDirectory()) {
        webApp.setResourceBase(webapp.getPath());
    } else {
        webApp.setWar(webapp.getAbsolutePath());
    }
    webApp.setContextPath("/docs");
    webApp.setParentLoaderPriority(true);
    // Bind swagger-ui to the path HOST/docs
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/docs/*");
    return webApp;
}
 
Example 7
Source File: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private WebAppContext createDeployedApplicationInstance(File workDirectory,
		String deployedApplicationPath) {
	WebAppContext deployedApplication = new WebAppContext();
	deployedApplication.setContextPath(this.getContextPath());
	deployedApplication.setWar(deployedApplicationPath);
	deployedApplication.setAttribute("javax.servlet.context.tempdir",
			workDirectory.getAbsolutePath());
	deployedApplication
			.setAttribute(
					"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
					".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$");
	deployedApplication.setAttribute(
			"org.eclipse.jetty.containerInitializers", jspInitializers());
	deployedApplication.setAttribute(InstanceManager.class.getName(),
			new SimpleInstanceManager());
	deployedApplication.addBean(new ServletContainerInitializersStarter(
			deployedApplication), true);
	// webapp.setClassLoader(new URLClassLoader(new
	// URL[0],App.class.getClassLoader()));
	deployedApplication.addServlet(jspServletHolder(), "*.jsp");
	return deployedApplication;
}
 
Example 8
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 9
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 10
Source File: HTTPMemServer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public HTTPMemServer() {
	System.clearProperty("DEBUG");

	jetty = new Server(PORT);

	WebAppContext webapp = new WebAppContext();
	webapp.setContextPath(RDF4J_CONTEXT);
	// warPath configured in pom.xml maven-war-plugin configuration
	webapp.setWar("./target/rdf4j-server");
	jetty.setHandler(webapp);
}
 
Example 11
Source File: RestTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public WebAppContext deployWebApp(String contextPath, File warFile) {
   WebAppContext webapp = new WebAppContext();
   if (contextPath.startsWith("/")) {
      webapp.setContextPath(contextPath);
   } else {
      webapp.setContextPath("/" + contextPath);
   }
   webapp.setWar(warFile.getAbsolutePath());

   handlers.addHandler(webapp);
   return webapp;
}
 
Example 12
Source File: ContainerStarter.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Method for starting the Jetty server with the ATS Agent webapp.
 * @return the started server.
 * @throws IOException
 */
private static Server startServer() throws IOException {

    addAppender();

    final int agentPort = getAgentDefaultPort();
    log.info("Starting ATS agent at port: " + agentPort);

    final String jettyHome = getJettyHome();

    logSystemInformation(jettyHome);

    // start the server
    Connector connector = new SelectChannelConnector();
    connector.setPort(agentPort);

    Server server = new Server();
    server.setConnectors(new Connector[]{ connector });

    WebAppContext webApp = new WebAppContext();
    webApp.setContextPath("/agentapp");
    webApp.setWar(jettyHome + "/webapp/agentapp.war");
    webApp.setAttribute("org.eclipse.jetty.webapp.basetempdir",
                        getJettyWorkDir(jettyHome));

    server.setHandler(webApp);
    server.setStopAtShutdown(true);

    setExtraClasspath(webApp, jettyHome);

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

    log.info("ATS agent started");
    return server;
}
 
Example 13
Source File: BaseSecurityTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
protected void startEmbeddedServer(Server server) throws Exception {
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(getWarPath());
    server.setHandler(webapp);

    server.start();
}
 
Example 14
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 15
Source File: VmRuntimeWebAppDeployer.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
  
  Resource resource = Resource.newResource(webapp);
  File file = resource.getFile();
  if (!resource.exists())
      throw new IllegalStateException("WebApp resouce does not exist "+resource);

  String lcName=file.getName().toLowerCase(Locale.ENGLISH);

  if (lcName.endsWith(".xml")) {
      XmlConfiguration xmlc = new XmlConfiguration(resource.getURI().toURL());
      xmlc.getIdMap().put("Server", contexts.getServer());
      xmlc.getProperties().put("jetty.home",System.getProperty("jetty.home","."));
      xmlc.getProperties().put("jetty.base",System.getProperty("jetty.base","."));
      xmlc.getProperties().put("jetty.webapp",file.getCanonicalPath());
      xmlc.getProperties().put("jetty.webapps",file.getParentFile().getCanonicalPath());
      xmlc.getProperties().putAll(properties);
      handler = (ContextHandler)xmlc.configure();
  } else {
    WebAppContext wac=new WebAppContext();
    wac.setWar(webapp);
    wac.setContextPath("/");
  }
  
  contexts.addHandler(handler);
  if (contexts.isRunning())
    handler.start();
}
 
Example 16
Source File: WebAppContextProvider.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * Serve given WAR at the given pathSpec; if not yet started, it is simply remembered until start;
 * if server already running, the context for this WAR is started.
 * @return the context created and added as a handler (and possibly already started if server is
 * started, so be careful with any changes you make to it!)
 */
public WebAppContext get(ManagementContext managementContext, Map<String, Object> attributes, boolean ignoreFailures) {
    checkNotNull(managementContext, "managementContext");
    checkNotNull(attributes, "attributes");
    boolean isRoot = pathSpec.isEmpty();

    final WebAppContext context = new WebAppContext();
    // use a unique session ID to prevent interference with other web apps on same server (esp for localhost);
    // note however this is only run for the legacy launcher
    // TODO would be nice if the various karaf startups rename the session cookie property (from JSESSIONID)
    // as the default is likely to conflict with other java-based servers (esp on localhost);
    // this can be done e.g. on ServletContext.getSessionCookieConfig(), but will be needed for REST and for JS (static) bundles
    // low priority however, if you /etc/hosts a localhost-brooklyn and use that it will stop conflicting
    context.setInitParameter(SessionHandler.__SessionCookieProperty, SessionHandler.__DefaultSessionCookie + "_" + "BROOKLYN" + Identifiers.makeRandomId(6));
    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, managementContext);
    for (Map.Entry<String, Object> attributeEntry : attributes.entrySet()) {
        context.setAttribute(attributeEntry.getKey(), attributeEntry.getValue());
    }

    try {
        final CustomResourceLocator locator = new CustomResourceLocator(managementContext.getConfig(), ResourceUtils.create(this));
        final InputStream resource = locator.getResourceFromUrl(warUrl);
        final String warName = isRoot ? "ROOT" : ("embedded-" + pathSpec);
        File tmpWarFile = Os.writeToTempFile(resource, warName, ".war");
        context.setWar(tmpWarFile.getAbsolutePath());
    } catch (Exception e) {
        LOG.warn("Failed to deploy webapp " + pathSpec + " from " + warUrl
                + (ignoreFailures ? "; launching run without WAR" : " (rethrowing)")
                + ": " + Exceptions.collapseText(e));
        if (!ignoreFailures) {
            throw new IllegalStateException("Failed to deploy webapp " + pathSpec + " from " + warUrl + ": " + Exceptions.collapseText(e), e);
        }
        LOG.debug("Detail on failure to deploy webapp: " + e, e);
        context.setWar("/dev/null");
    }

    context.setContextPath("/" + pathSpec);
    context.setParentLoaderPriority(true);

    return context;
}
 
Example 17
Source File: EmbeddedJetty.java    From junit-servers with MIT License 4 votes vote down vote up
/**
 * Build web app context used to launch server.
 * May be override by subclasses.
 *
 * @throws Exception May be thrown by web app context initialization (will be wrapped later).
 */
private WebAppContext createdWebAppContext() throws Exception {
	final String path = configuration.getPath();
	final String webapp = configuration.getWebapp();
	final String classpath = configuration.getClasspath();
	final ClassLoader parentClassLoader = configuration.getParentClassLoader();
	final String overrideDescriptor = configuration.getOverrideDescriptor();
	final Resource baseResource = configuration.getBaseResource();
	final String containerJarPattern = configuration.getContainerJarPattern();
	final String webInfJarPattern = configuration.getWebInfJarPattern();

	final WebAppContext ctx = new WebAppContext();

	if (containerJarPattern != null) {
		log.debug("Setting jetty 'containerJarPattern' attribute: {}", containerJarPattern);
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerJarPattern);
	}
	else if (Java.isPostJdk9()) {
		// Fix to make TLD scanning works with Java >= 9
		log.debug("Setting default jetty 'containerJarPattern' for JRE >= 9: {}");
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar");
	}

	if (webInfJarPattern != null) {
		log.debug("Setting jetty 'WebInfJarPattern' attribute: {}", webInfJarPattern);
		ctx.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfJarPattern);
	}

	final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader();
	final ClassLoader classLoader;

	if (parentClassLoader != null) {
		log.debug("Overriding jetty parent classloader");
		classLoader = new CompositeClassLoader(parentClassLoader, systemClassLoader);
	}
	else {
		log.debug("Using current thread classloader as jetty parent classloader");
		classLoader = systemClassLoader;
	}

	log.debug("Set jetty classloader");
	ctx.setClassLoader(classLoader);

	log.debug("Set jetty context path to: {}", path);
	ctx.setContextPath(path);

	if (baseResource == null) {
		// use default base resource
		log.debug("Initializing default jetty base resource from: {}", webapp);
		ctx.setBaseResource(newResource(webapp));
	}
	else {
		log.debug("Initializing jetty base resource from: {}", baseResource);
		ctx.setBaseResource(baseResource);
	}

	if (overrideDescriptor != null) {
		log.debug("Set jetty descriptor: {}", overrideDescriptor);
		ctx.setOverrideDescriptor(overrideDescriptor);
	}

	log.debug("Initializing jetty configuration classes");
	ctx.setConfigurations(new Configuration[] {
		new WebInfConfiguration(),
		new WebXmlConfiguration(),
		new AnnotationConfiguration(),
		new JettyWebXmlConfiguration(),
		new MetaInfConfiguration(),
		new FragmentConfiguration()
	});

	if (isNotBlank(classpath)) {
		log.debug("Adding jetty container resource: {}", classpath);

		// Fix to scan Spring WebApplicationInitializer
		// This will add compiled classes to jetty classpath
		// See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration
		// And more precisely: http://stackoverflow.com/a/18449506/1215828
		final File classes = new File(classpath);
		final PathResource containerResources = new PathResource(classes.toURI());
		ctx.getMetaData().addContainerResource(containerResources);
	}

	ctx.setParentLoaderPriority(true);
	ctx.setWar(webapp);
	ctx.setServer(server);

	// Add server context
	server.setHandler(ctx);

	return ctx;
}
 
Example 18
Source File: EmbeddedJettyServer.java    From Alpine with Apache License 2.0 4 votes vote down vote up
public static void main(final 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();

    final Server server = new Server();
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer( new org.eclipse.jetty.server.ForwardedRequestCustomizer() ); // Add support for X-Forwarded headers

    final HttpConnectionFactory connectionFactory = new HttpConnectionFactory( httpConfig );
    final ServerConnector connector = new ServerConnector(server, connectionFactory);
    connector.setHost(host);
    connector.setPort(port);
    disableServerVersionHeader(connector);
    server.setConnectors(new Connector[]{connector});

    final WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath(contextPath);
    context.setErrorHandler(new ErrorHandler());
    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    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);
    server.addBean(new ErrorHandler());
    try {
        server.start();
        addJettyShutdownHook(server);
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
 
Example 19
Source File: JettyServer.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"resource", "boxing"})
public static Server newServer(int jettyPort, String jettyWebAppDir, JettyServiceSetting jettyServiceSetting) throws Exception {

    if (jettyPort == 0 || jettyWebAppDir == null) {
        throw new IllegalArgumentException("Jetty port and resource dir may not be empty");
    }

    // server setup
    Server server = new Server();
    server.addBean(new ScheduledExecutorScheduler());
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);


    // http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e19050
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);


    //setup handlers according to the jetty settings
    HandlerCollection handlerCollection = new HandlerCollection();

    if (jettyServiceSetting == JettyServiceSetting.ARTIFACTORY || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // The WebAppContext is the entity that controls the environment in
        // which a web application lives and breathes. In this example the
        // context path is being set to "/" so it is suitable for serving root
        // context requests and then we see it setting the location of the war.
        // A whole host of other configurations are available, ranging from
        // configuring to support annotation scanning in the webapp (through
        // PlusConfiguration) to choosing where the webapp will unpack itself.
        WebAppContext webapp = new WebAppContext();
        File warFile = new File(jettyWebAppDir + File.separator + "artifactory.war");
        webapp.setContextPath("/artifactory");
        webapp.setWar(warFile.getAbsolutePath());

        // A WebAppContext is a ContextHandler as well so it needs to be set to
        // the server so it is aware of where to send the appropriate requests.
        handlerCollection.addHandler(webapp);

    }

    if (jettyServiceSetting == JettyServiceSetting.VIP || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // Serve resource files which reside in the jettyWebAppDir
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        resourceHandler.setResourceBase(jettyWebAppDir);

        handlerCollection.addHandler(resourceHandler);
    }

    server.setHandler(handlerCollection);


    // http configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSendServerVersion(true);

    // HTTP connector
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(jettyPort);
    server.addConnector(http);

    // start server
    server.start();

    LOG.info("Started jetty server on port: {}, resource dir: {} ", jettyPort, jettyWebAppDir);
    return server;
}
 
Example 20
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpService start() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), ROOT_WAR_PATH);

    try {
        if (httpsEnabled) {
            //by default the server is configured with a http connector, this needs to be removed since we are going
            //to provide https
            for (Connector c: server.getConnectors()) {
                server.removeConnector(c);
            }

            InputStream keyStoreStream = ResourceUtils.create(this).getResourceFromUrl(SERVER_KEYSTORE);
            KeyStore keyStore;
            try {
                keyStore = SecureKeys.newKeyStore(keyStoreStream, "password");
            } finally {
                keyStoreStream.close();
            }

            // manually create like seen in XMLs at http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(keyStore);
            sslContextFactory.setTrustAll(true);
            sslContextFactory.setKeyStorePassword("password");

            HttpConfiguration sslHttpConfig = new HttpConfiguration();
            sslHttpConfig.setSecureScheme("https");
            sslHttpConfig.setSecurePort(actualPort);

            ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(sslHttpConfig));
            httpsConnector.setPort(actualPort);

            server.addConnector(httpsConnector);
        }

        addShutdownHook();

        File tmpWarFile = Os.writeToTempFile(
                ResourceUtils.create(this).getResourceFromUrl(ROOT_WAR_URL), 
                "TestHttpService", 
                ".war");
        
        WebAppContext context = new WebAppContext();
        context.setWar(tmpWarFile.getAbsolutePath());
        context.setContextPath("/");
        context.setParentLoaderPriority(true);

        if (securityHandler.isPresent()) {
            context.setSecurityHandler(securityHandler.get());
        }

        server.setHandler(context);
        server.start();

        log.info("Started test HttpService at "+getUrl());
        
    } catch (Exception e) {
        try {
            shutdown();
        } catch (Exception e2) {
            log.warn("Error shutting down HttpService while recovering from earlier error (re-throwing earlier error)", e2);
            throw e;
        }
    }

    return this;
}