org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory Java Examples

The following examples show how to use org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory. 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: DSSSpringApplication.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettyFactoryCustomizer() {
    return new WebServerFactoryCustomizer<JettyServletWebServerFactory>() {
        public void customize(JettyServletWebServerFactory jettyServletWebServerFactory) {
            jettyServletWebServerFactory.addServerCustomizers(new JettyServerCustomizer() {
                public void customize(Server server) {
                    Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
                    final WebAppContext webApp = (WebAppContext) childHandlersByClass[0];
                    FilterHolder filterHolder = new FilterHolder(CharacterEncodingFilter.class);
                    filterHolder.setInitParameter("encoding", Configuration.BDP_ENCODING().getValue());
                    filterHolder.setInitParameter("forceEncoding", "true");
                    webApp.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));
                    BDPJettyServerHelper.setupRestApiContextHandler(webApp);
                    if(ServerConfiguration.BDP_SERVER_SOCKET_MODE().getValue()) {
                        BDPJettyServerHelper.setupControllerServer(webApp);
                    }
                    if(!ServerConfiguration.BDP_SERVER_DISTINCT_MODE().getValue()) {
                        BDPJettyServerHelper.setupWebAppContext(webApp);
                    }
                }
            });
        }
    };
}
 
Example #2
Source File: JettyWebServerConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Customise the Jetty web server to automatically decompress requests.
 */
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {

    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    factory.addServerCustomizers(server -> {

        GzipHandler gzipHandler = new GzipHandler();
        // Enable request decompression
        gzipHandler.setInflateBufferSize(MIN_BYTES);
        gzipHandler.setHandler(server.getHandler());

        HandlerCollection handlerCollection = new HandlerCollection(gzipHandler);
        server.setHandler(handlerCollection);
    });

    return factory;
}
 
Example #3
Source File: JettyAutoConfiguration.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jsfJettyFactoryCustomizer() {
	return factory -> factory.addServerCustomizers(new JettyServerCustomizer() {
		@Override
		@SneakyThrows(IOException.class)
		public void customize(Server server) {
			Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
			final WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

			String classPathResourceString = JettyAutoConfiguration.this.jettyProperties.getClassPathResource();

			webAppContext.setBaseResource(new ResourceCollection(
				Resource.newResource(new ClassPathResource(classPathResourceString).getURI()),
				webAppContext.getBaseResource()));

			log.info("Setting Jetty classLoader to {} directory", classPathResourceString);
		}
	});
}
 
Example #4
Source File: WebFragmentRegistrationBean.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(ConfigurableServletWebServerFactory factory) {

	if (factory instanceof TomcatServletWebServerFactory) {
		((TomcatServletWebServerFactory) factory).addContextCustomizers(new TomcatListenerAdder(this.listeners));
	}
	else if (factory instanceof JettyServletWebServerFactory) {
		((JettyServletWebServerFactory) factory).addConfigurations(new JettyListenerAdder(this.listeners));
	}
	else if (factory instanceof UndertowServletWebServerFactory) {
		((UndertowServletWebServerFactory) factory).addDeploymentInfoCustomizers(new UndertowListenerAdder(this.listeners));
	}
	else {
		log.warn("Unkown WebServerFactory implementation: {}", factory.getClass());
		factory.addInitializers(servletContext -> this.listeners.forEach(servletContext::addListener));
	}

	factory.addInitializers(servletContext -> this.contextParams.forEach(servletContext::setInitParameter));

	this.errorPages.forEach(factory::addErrorPages);
}
 
Example #5
Source File: WebContainerAccessLogAutoConfiguration.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer accessWebServerFactoryCustomizer() {
    return factory -> {
        if (factory instanceof JettyServletWebServerFactory) {
            ((JettyServletWebServerFactory) factory).addServerCustomizers((JettyServerCustomizer) server -> {
                HandlerCollection handlers = new HandlerCollection();
                for (Handler handler : server.getHandlers()) {
                    handlers.addHandler(handler);
                }
                RequestLogHandler reqLogs = new RequestLogHandler();
                Slf4jRequestLog requestLog = new Slf4jRequestLog();
                requestLog.setLoggerName("access-log");
                requestLog.setLogLatency(false);

                reqLogs.setRequestLog(requestLog);
                handlers.addHandler(reqLogs);
                server.setHandler(handlers);
            });
        }
    };
}
 
Example #6
Source File: BeanConfiguration.java    From sagemaker-sparkml-serving-container with Apache License 2.0 5 votes vote down vote up
@Bean
public JettyServletWebServerFactory provideJettyServletWebServerFactory() {
    final JettyServletWebServerFactory jettyServlet = new JettyServletWebServerFactory(
        new Integer(this.getHttpListenerPort()));
    final List<JettyServerCustomizer> serverCustomizerList = Lists.newArrayList();
    final JettyServerCustomizer serverCustomizer = server -> {
        final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
        threadPool.setMinThreads(SystemUtils.getNumberOfThreads(MIN_CORE_TO_THREAD_RATIO));
        threadPool.setMaxThreads(SystemUtils.getNumberOfThreads(MAX_CORE_TO_THREAD_RATIO));
    };
    serverCustomizerList.add(serverCustomizer);
    jettyServlet.setServerCustomizers(serverCustomizerList);
    return jettyServlet;
}
 
Example #7
Source File: BeanConfigurationTest.java    From sagemaker-sparkml-serving-container with Apache License 2.0 5 votes vote down vote up
@Test
public void testJettyServletWebServerFactoryNotNull() {
    JettyServletWebServerFactory jettyServletTest = configuration.provideJettyServletWebServerFactory();
    final String listenerPort =
        (System.getenv("SAGEMAKER_BIND_TO_PORT") != null) ? System.getenv("SAGEMAKER_BIND_TO_PORT") : "8080";
    Assert.assertEquals((int) new Integer(listenerPort), jettyServletTest.getPort());
    Assert.assertNotNull(jettyServletTest.getServerCustomizers());
}
 
Example #8
Source File: TraderUMainConfiguration.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    int port = ConfigUtil.getInt("/BasisService/web.httpPort", 10080);
    factory.setPort(port);
    factory.setContextPath("");
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
    factory.setSelectors(1);
    factory.setAcceptors(1);
    factory.setThreadPool(new ExecutorThreadPool(executorService()));
    return factory;
}
 
Example #9
Source File: TraderMainConfiguration.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    int port = ConfigUtil.getInt("/BasisService/web.httpPort", 10080);
    factory.setPort(port);
    factory.setContextPath("");
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
    factory.setSelectors(1);
    factory.setAcceptors(1);
    factory.setThreadPool(new ExecutorThreadPool(executorService()));
    return factory;
}
 
Example #10
Source File: SystemConfig.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * for vue history mode
 *
 * @return
 */
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index"));
    return factory;
}
 
Example #11
Source File: JettyITServerCustomizer.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(final JettyServletWebServerFactory factory) {
    LOGGER.info("Customizing Jetty server for integration tests...");

    factory.addServerCustomizers((server) -> {
        final Ssl sslProperties = serverProperties.getSsl();
        if (sslProperties != null) {
            createSslContextFactory(sslProperties);
            ServerConnector con = (ServerConnector) server.getConnectors()[0];
            int existingConnectorPort = con.getLocalPort();

            // create the http configuration
            final HttpConfiguration httpConfiguration = new HttpConfiguration();
            httpConfiguration.setRequestHeaderSize(HEADER_BUFFER_SIZE);
            httpConfiguration.setResponseHeaderSize(HEADER_BUFFER_SIZE);

            // add some secure config
            final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
            httpsConfiguration.setSecureScheme("https");
            httpsConfiguration.setSecurePort(existingConnectorPort);
            httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

            // build the connector with the endpoint identification algorithm set to null
            final ServerConnector httpsConnector = new ServerConnector(server,
                    new SslConnectionFactory(createSslContextFactory(sslProperties), "http/1.1"),
                    new HttpConnectionFactory(httpsConfiguration));
            server.removeConnector(con);
            server.addConnector(httpsConnector);
        }
    });

    LOGGER.info("JettyServer is customized");
}
 
Example #12
Source File: LogSearchWebServerCustomizer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(JettyServletWebServerFactory webServerFactory) {
  serverProperties.getServlet().getSession().setTimeout(Duration.ofMinutes(logSearchHttpConfig.getSessionTimeout()));
  serverProperties.getServlet().getSession().getCookie().setName(LOGSEARCH_SESSION_ID);

  if ("https".equals(logSearchHttpConfig.getProtocol())) {
    sslConfigurer.ensureStorePasswords();
    sslConfigurer.loadKeystore();
    webServerFactory.addServerCustomizers((JettyServerCustomizer) server -> {
      SslContextFactory sslContextFactory = sslConfigurer.getSslContextFactory();
      ServerConnector sslConnector = new ServerConnector(server, sslContextFactory);
      sslConnector.setPort(logSearchHttpConfig.getHttpsPort());
      server.setConnectors(new Connector[]{sslConnector});
    });
  } else {
    webServerFactory.setPort(logSearchHttpConfig.getHttpPort());
  }
  if (logSearchHttpConfig.isUseAccessLogs()) {
    webServerFactory.addServerCustomizers((JettyServerCustomizer) server -> {
      LoggerContext context = (LoggerContext) LogManager.getContext(false);
      Configuration configuration = context.getConfiguration();
      String logDir = configuration.getStrSubstitutor().getVariableResolver().lookup("log-path");
      String logFileNameSuffix = "logsearch-jetty-yyyy_mm_dd.request.log";
      String logFileName = logDir == null ? logFileNameSuffix : Paths.get(logDir, logFileNameSuffix).toString();
      NCSARequestLog requestLog = new NCSARequestLog(logFileName);
      requestLog.setAppend(true);
      requestLog.setExtended(false);
      requestLog.setLogTimeZone("GMT");
      server.setRequestLog(requestLog);
    });
  }
}
 
Example #13
Source File: AggregateApplication.java    From flower with Apache License 2.0 5 votes vote down vote up
/**
 * 使用jetty运行,不写该方法则默认使用tomcat运行 关于端口配置: application.yml
 * 是spring-boot启动的配置,其优先级高于以下端口配置; 如果需要在代码中自定义端口,请勿在application.xml文件中配置端口;
 */
@Bean
public JettyServletWebServerFactory servletContainer() {
  int port = 8080;
  Map<String, String> map = System.getenv();
  String envPort = map.get("PORT0");
  if (envPort != null && !envPort.isEmpty()) {
    port = Integer.valueOf(envPort);
  }
  return new JettyServletWebServerFactory(port);
}
 
Example #14
Source File: JettyAutoConfigurationIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
public void customize() {
	JettyServletWebServerFactory factory = new JettyServletWebServerFactory();

	this.jettyAutoConfiguration.jsfJettyFactoryCustomizer().customize(factory);

	Server server = ((JettyWebServer) factory.getWebServer()).getServer();

	Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
	WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

	assertThat(webAppContext.getBaseResource().getResource("testJetty.txt").exists())
		.isTrue();
}
 
Example #15
Source File: LogSearchServletConfig.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletWebServerFactory webServerFactory() {
  return new JettyServletWebServerFactory();
}
 
Example #16
Source File: IntegrationTestBase.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Bean
public JettyServletWebServerFactory jettyEmbeddedServletContainerFactory() {
    JettyServletWebServerFactory jettyContainerFactory = new JettyServletWebServerFactory();
    jettyContainerFactory.setContextPath(CONTEXT_PATH);
    return jettyContainerFactory;
}
 
Example #17
Source File: TldListenerRegistrationBean.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Override
public void customize(AbstractServletWebServerFactory factory) {
	if (factory instanceof JettyServletWebServerFactory || factory instanceof UndertowServletWebServerFactory) {
		factory.addInitializers(servletContext -> this.listeners.forEach(servletContext::addListener));
	}
}
 
Example #18
Source File: JettyTestConfiguration.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {
	return new JettyServletWebServerFactory();
}
 
Example #19
Source File: ParaServer.java    From para with Apache License 2.0 4 votes vote down vote up
/**
 * @return Jetty config bean
 */
@Bean
public ServletWebServerFactory jettyConfigBean() {
	JettyServletWebServerFactory jef = new JettyServletWebServerFactory();
	jef.addServerCustomizers((JettyServerCustomizer) (Server server) -> {
		if (Config.getConfigBoolean("access_log_enabled", true)) {
			// enable access log via Logback
			HandlerCollection handlers = new HandlerCollection();
			for (Handler handler : server.getHandlers()) {
				handlers.addHandler(handler);
			}
			RequestLogHandler reqLogs = new RequestLogHandler();
			reqLogs.setServer(server);
			RequestLogImpl rli = new RequestLogImpl();
			rli.setResource("/logback-access.xml");
			rli.setQuiet(true);
			rli.start();
			reqLogs.setRequestLog(rli);
			handlers.addHandler(reqLogs);
			server.setHandler(handlers);
		}

		for (Connector y : server.getConnectors()) {
			for (ConnectionFactory cf : y.getConnectionFactories()) {
				if (cf instanceof HttpConnectionFactory) {
					HttpConnectionFactory dcf = (HttpConnectionFactory) cf;
					// support for X-Forwarded-Proto
					// redirect back to https if original request uses it
					if (Config.IN_PRODUCTION) {
						ForwardedRequestCustomizer frc = new ForwardedRequestCustomizer() {
							public void customize(Connector connector, HttpConfiguration config, Request request) {
								super.customize(connector, config, request);
								String cfProto = request.getHeader("CloudFront-Forwarded-Proto");
								if (StringUtils.equalsIgnoreCase(cfProto, config.getSecureScheme())) {
									request.setScheme(cfProto);
									request.setSecure(true);
								}
							}
						};
						HttpConfiguration httpConfiguration = dcf.getHttpConfiguration();
						httpConfiguration.addCustomizer(frc);
					}
					// Disable Jetty version header
					dcf.getHttpConfiguration().setSendServerVersion(false);
					// Increase idle timeout
					dcf.getHttpConfiguration().setIdleTimeout(TimeUnit.MINUTES.toMillis(5));
				}
			}
		}
	});
	String contextPath = Config.getConfigParam("context_path", "");
	if (StringUtils.length(contextPath) > 1 && contextPath.charAt(0) == '/') {
		jef.setContextPath(contextPath);
	}
	jef.setPort(getServerPort());
	logger.info("Listening on port {}...", jef.getPort());
	return jef;
}
 
Example #20
Source File: JettyServletWebServerConfiguration.java    From logback-access-spring-boot-starter with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link JettyServletWebServerFactory}.
 *
 * @return a {@link JettyServletWebServerFactory}.
 */
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {
    return new JettyServletWebServerFactory();
}