Java Code Examples for org.eclipse.jetty.server.Server#setStopAtShutdown()

The following examples show how to use org.eclipse.jetty.server.Server#setStopAtShutdown() . 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: ApiWebSite.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
public static Server createServer(int port) throws MalformedURLException, URISyntaxException {
    Server server = new Server();
    server.setStopAtShutdown(true);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setReuseAddress(true);

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

    WebAppContext webContext = new WebAppContext("webapp", CONTEXT);
    webContext.setBaseResource(Resource.newResource(new URL(ApiWebSite.class.getResource("/webapp/WEB-INF"), ".")));
    webContext.setClassLoader(ApiWebSite.class.getClassLoader());

    server.setHandler(webContext);

    return server;
}
 
Example 2
Source File: JettyFactory.java    From base-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录.
 */
public static Server createServerInSource(int port, String contextPath) {
	Server server = new Server();
	// 设置在JVM退出时关闭Jetty的钩子。
	server.setStopAtShutdown(true);

	SelectChannelConnector connector = new SelectChannelConnector();
	connector.setPort(port);
	// 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
	connector.setReuseAddress(false);
	server.setConnectors(new Connector[] { connector });

	WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath);
	server.setHandler(webContext);

	return server;
}
 
Example 3
Source File: AmforeasJetty.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
protected void startServer (final AmforeasConfiguration conf) throws Exception {
    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(conf.getServerThreadsMin());
    threadPool.setMaxThreads(conf.getServerThreadsMax());

    final Server server = new Server(threadPool);

    setupJerseyServlet(conf, server);
    setupHTTPConnection(conf, server);
    setupHTTPSConnection(conf, server);


    server.start();
    server.setStopAtShutdown(true);
    server.join();
}
 
Example 4
Source File: PackageManagerCLITest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
  server = new Server();

  connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
  server.setStopAtShutdown(true);

  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setResourceBase(resourceDir);
  resourceHandler.setDirectoriesListed(true);

  HandlerList handlers = new HandlerList();
  handlers.setHandlers(new Handler[] {resourceHandler, new DefaultHandler()});
  server.setHandler(handlers);

  server.start();
}
 
Example 5
Source File: JettyWebappTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
  super.setUp();
  System.setProperty("solr.solr.home", SolrJettyTestBase.legacyExampleCollection1SolrHome());
  System.setProperty("tests.shardhandler.randomSeed", Long.toString(random().nextLong()));
  System.setProperty("solr.tests.doContainerStreamCloseAssert", "false");

  File dataDir = createTempDir().toFile();
  dataDir.mkdirs();

  System.setProperty("solr.data.dir", dataDir.getCanonicalPath());
  String path = ExternalPaths.WEBAPP_HOME;

  server = new Server(port);
  // insecure: only use for tests!!!!
  server.setSessionIdManager(new DefaultSessionIdManager(server, new Random(random().nextLong())));
  new WebAppContext(server, path, context );

  ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
  connector.setIdleTimeout(1000 * 60 * 60);
  connector.setPort(0);
  server.setConnectors(new Connector[]{connector});
  server.setStopAtShutdown( true );

  server.start();
  port = connector.getLocalPort();
}
 
Example 6
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux Execution API endpoint.
 * @return Jetty Server instance
 */
@Named("ExecutionAPIJettyServer")
@Provides
@Singleton
Server getExecutionAPIJettyServer(@Named("Execution.Node.Api.service.port") int port,
                         @Named("ExecutionAPIResourceConfig")ResourceConfig resourceConfig,
                         @Named("Execution.Node.Api.service.acceptors") int acceptorThreads,
                         @Named("Execution.Node.Api.service.selectors") int selectorThreads,
                         @Named("Execution.Node.Api.service.workers") int maxWorkerThreads,
                         ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(objectMapper);
    resourceConfig.register(provider);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    ServletContextHandler context = new ServletContextHandler(server, "/*");
    ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
    context.addServlet(servlet, "/*");

    final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
    handler.setHandler(context);
    server.setHandler(handler);

    server.setStopAtShutdown(true);
    return server;
}
 
Example 7
Source File: ContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux API endpoint.
 * @param port where the service is available.
 * @return Jetty Server instance
 */
@Named("APIJettyServer")
@Provides
@Singleton
Server getAPIJettyServer(@Named("Api.service.port") int port,
						 @Named("APIResourceConfig")ResourceConfig resourceConfig,
						 @Named("Api.service.acceptors") int acceptorThreads,
						 @Named("Api.service.selectors") int selectorThreads,
						 @Named("Api.service.workers") int maxWorkerThreads,
						 ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
	JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
	provider.setMapper(objectMapper);
	resourceConfig.register(provider);
	QueuedThreadPool threadPool = new QueuedThreadPool();
	threadPool.setMaxThreads(maxWorkerThreads);
	Server server = new Server(threadPool);
	ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
	http.setPort(port);
	server.addConnector(http);
	ServletContextHandler context = new ServletContextHandler(server, "/*");
	ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
	context.addServlet(servlet, "/*");

	final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
	handler.setHandler(context);
	server.setHandler(handler);

	server.setStopAtShutdown(true);
	return server;
}
 
Example 8
Source File: MockHttpApiRule.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Exception {
  handler = new MockHandler();
  server = new Server();
  final ServerConnector http = new ServerConnector(server);
  http.setHost("localhost");
  server.addConnector(http);
  server.setStopAtShutdown(true);
  server.setHandler(handler);
  server.setRequestLog(buildRequestLog());
  server.start();
}
 
Example 9
Source File: JettyWebServer.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private Server configureJettyServer() {
    LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(m_maxTaskQueue); 
    QueuedThreadPool threadPool = new QueuedThreadPool(m_maxconns, m_defaultMinThreads, m_defaultIdleTimeout, 
    		taskQueue);
    Server server = new Server(threadPool);
    server.setStopAtShutdown(true);
    return server;
}
 
Example 10
Source File: Commands.java    From allure2 with Apache License 2.0 5 votes vote down vote up
/**
 * Set up Jetty server to serve Allure Report.
 */
protected Server setUpServer(final String host, final int port, final Path reportDirectory) {
    final Server server = Objects.isNull(host)
            ? new Server(port)
            : new Server(new InetSocketAddress(host, port));
    final ResourceHandler handler = new ResourceHandler();
    handler.setRedirectWelcome(true);
    handler.setDirectoriesListed(true);
    handler.setResourceBase(reportDirectory.toAbsolutePath().toString());
    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{handler, new DefaultHandler()});
    server.setStopAtShutdown(true);
    server.setHandler(handlers);
    return server;
}
 
Example 11
Source File: EmbeddedHttpGitServer.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private Server createGitServer(int port) throws Exception {
    final Server server = new Server(port);

    final ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(new ServletHolder(createGitServlet()), "/*");

    server.start();
    server.setStopAtShutdown(true);

    LOGGER.info("Started serving local git repositories [" + this.repositories.values().stream().map(
        LazilyLoadedRepository::getName).collect(Collectors.toList()) + "] under http://localhost:" + port);
    return server;
}
 
Example 12
Source File: TestSpringWebApp.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop", name = "httpServer")
@Order(0)
public Server httpServer(ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[]{"/"});

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = new InetSocketAddress(SocketUtils.findAvailableTcpPort());

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{connector});
    server.setHandler(servlets);
    server.setStopAtShutdown(true);

    return server;
}
 
Example 13
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
Example 14
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ks.jks"));

    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            if (request.getAttribute("javax.servlet.request.X509Certificate") != null) {
                clientSerial = ((java.security.cert.X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate"))[0].getSerialNumber();
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 15
Source File: WebServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(WebServer webServer) throws Exception {

		/**
		 * 更新x_desktop的center指向
		 */
		updateCenterConfigJson();
		/**
		 * 更新 favicon.ico
		 */
		updateFavicon();
		/**
		 * 创建index.html
		 */
		createIndexPage();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(WEBSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(WEBSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		if (webServer.getSslEnable()) {
			addHttpsConnector(server, webServer.getPort());
		} else {
			addHttpConnector(server, webServer.getPort());
		}
		WebAppContext context = new WebAppContext();
		context.setContextPath("/");
		context.setBaseResource(Resource.newResource(new File(Config.base(), "servers/webServer")));
		// context.setResourceBase(".");
		context.setParentLoaderPriority(true);
		context.setExtractWAR(false);
		// context.setDefaultsDescriptor(new File(Config.base(),
		// "commons/webdefault_w.xml").getAbsolutePath());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "" + webServer.getDirAllowed());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		if (webServer.getCacheControlMaxAge() > 0) {
			context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl",
					"max-age=" + webServer.getCacheControlMaxAge());
		}
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "256000000");
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFileSize", "200000000");
		context.setWelcomeFiles(new String[] { "default.html", "index.html" });
		context.setGzipHandler(new GzipHandler());
		context.setParentLoaderPriority(true);
		context.getMimeTypes().addMimeMapping("wcss", "application/json");
		/* stat */
		if (webServer.getStatEnable()) {
			FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
			statFilterHolder.setInitParameter("exclusions", webServer.getStatExclusions());
			context.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
			ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
			statServletHolder.setInitParameter("sessionStatEnable", "false");
			context.addServlet(statServletHolder, "/druid/*");
		}
		/* stat end */
		server.setHandler(context);
		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);
		server.start();

		context.setMimeTypes(Config.mimeTypes());
		System.out.println("****************************************");
		System.out.println("* web server start completed.");
		System.out.println("* port: " + webServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 16
Source File: Main.java    From dexter with Apache License 2.0 4 votes vote down vote up
private void start() {
	// Start a Jetty server with some sensible(?) defaults
	try {
		Server srv = new Server();
		srv.setStopAtShutdown(true);

		// Allow 5 seconds to complete.
		// Adjust this to fit with your own webapp needs.
		// Remove this if you wish to shut down immediately (i.e. kill <pid>
		// or Ctrl+C).
		srv.setGracefulShutdown(5000);

		// Increase thread pool
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMaxThreads(100);
		srv.setThreadPool(threadPool);

		// Ensure using the non-blocking connector (NIO)
		Connector connector = new SelectChannelConnector();
		connector.setPort(port);
		connector.setMaxIdleTime(30000);
		srv.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();

		// Handle signout/signin in BigIP-cluster

		// Add the warFile (this jar)
		WebAppContext context = new WebAppContext(warFile, contextPath);
		context.setServer(srv);
		resetTempDirectory(context, currentDir);

		// Add the handlers
		HandlerList handlers = new HandlerList();
		handlers.addHandler(context);
		handlers.addHandler(new ShutdownHandler(srv, context, secret));
		handlers.addHandler(new BigIPNodeHandler(secret));
		srv.setHandler(handlers);

		srv.start();
		srv.join();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 17
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example 18
Source File: CAMutualAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 19
Source File: HMaster.java    From hbase with Apache License 2.0 4 votes vote down vote up
private int putUpJettyServer() throws IOException {
  if (!conf.getBoolean("hbase.master.infoserver.redirect", true)) {
    return -1;
  }
  final int infoPort = conf.getInt("hbase.master.info.port.orig",
    HConstants.DEFAULT_MASTER_INFOPORT);
  // -1 is for disabling info server, so no redirecting
  if (infoPort < 0 || infoServer == null) {
    return -1;
  }
  if(infoPort == infoServer.getPort()) {
    return infoPort;
  }
  final String addr = conf.get("hbase.master.info.bindAddress", "0.0.0.0");
  if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) {
    String msg =
        "Failed to start redirecting jetty server. Address " + addr
            + " does not belong to this host. Correct configuration parameter: "
            + "hbase.master.info.bindAddress";
    LOG.error(msg);
    throw new IOException(msg);
  }

  // TODO I'm pretty sure we could just add another binding to the InfoServer run by
  // the RegionServer and have it run the RedirectServlet instead of standing up
  // a second entire stack here.
  masterJettyServer = new Server();
  final ServerConnector connector = new ServerConnector(masterJettyServer);
  connector.setHost(addr);
  connector.setPort(infoPort);
  masterJettyServer.addConnector(connector);
  masterJettyServer.setStopAtShutdown(true);

  final String redirectHostname =
      StringUtils.isBlank(useThisHostnameInstead) ? null : useThisHostnameInstead;

  final RedirectServlet redirect = new RedirectServlet(infoServer, redirectHostname);
  final WebAppContext context = new WebAppContext(null, "/", null, null, null, null, WebAppContext.NO_SESSIONS);
  context.addServlet(new ServletHolder(redirect), "/*");
  context.setServer(masterJettyServer);

  try {
    masterJettyServer.start();
  } catch (Exception e) {
    throw new IOException("Failed to start redirecting jetty server", e);
  }
  return connector.getLocalPort();
}
 
Example 20
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors, sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(), new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException("HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}