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

The following examples show how to use org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory. These examples are extracted from open source projects. 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
@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 2
Source Project: DataSphereStudio   Source File: DSSSpringApplication.java    License: 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 3
Source Project: joinfaces   Source File: WebFragmentRegistrationBean.java    License: 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 4
Source Project: joinfaces   Source File: JettyAutoConfiguration.java    License: 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 5
Source Project: tutorials   Source File: JettyWebServerConfiguration.java    License: 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 6
Source Project: flower   Source File: AggregateApplication.java    License: 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 7
@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 8
@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 9
@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 10
Source Project: java-trader   Source File: TraderUMainConfiguration.java    License: 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 11
Source Project: java-trader   Source File: TraderMainConfiguration.java    License: 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 12
Source Project: redis-manager   Source File: SystemConfig.java    License: 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 13
Source Project: nifi-registry   Source File: JettyITServerCustomizer.java    License: 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 14
Source Project: joinfaces   Source File: JettyAutoConfigurationIT.java    License: 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 Project: ambari-logsearch   Source File: LogSearchServletConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public ServletWebServerFactory webServerFactory() {
  return new JettyServletWebServerFactory();
}
 
Example 16
Source Project: nifi-registry   Source File: IntegrationTestBase.java    License: 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 Project: joinfaces   Source File: TldListenerRegistrationBean.java    License: 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 Project: joinfaces   Source File: JettyTestConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {
	return new JettyServletWebServerFactory();
}
 
Example 19
Source Project: para   Source File: ParaServer.java    License: 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
/**
 * Creates a {@link JettyServletWebServerFactory}.
 *
 * @return a {@link JettyServletWebServerFactory}.
 */
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {
    return new JettyServletWebServerFactory();
}