下面列出了怎么用org.eclipse.jetty.server.handler.HandlerCollection的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
});
}
};
}
@Override
public void configure() throws Exception {
server.addEventListener(mbeans());
server.addConnector(plainConnector());
ContextHandlerCollection handlers = new ContextHandlerCollection();
deploymentManager.setContexts(handlers);
createWebAppContext();
JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler();
webAppContext.setErrorHandler(errorHandler);
webAppContext.setGzipHandler(gzipHandler());
server.addBean(errorHandler);
server.addBean(deploymentManager);
HandlerCollection serverLevelHandlers = new HandlerCollection();
serverLevelHandlers.setHandlers(new Handler[]{handlers});
server.setHandler(serverLevelHandlers);
performCustomConfiguration();
server.setStopAtShutdown(true);
}
/**
* @param registry Prometheus CollectorRegistry to register the default exporters.
* @param httpPort The port the Server runs on.
* @return a Jetty Server with Prometheus' default exporters registered.
*/
public static Server serverWithStatisticsCollection(CollectorRegistry registry, int httpPort) {
Server server = new Server(httpPort);
new StandardExports().register(registry);
new MemoryPoolsExports().register(registry);
new GarbageCollectorExports().register(registry);
new ThreadExports().register(registry);
new ClassLoadingExports().register(registry);
new VersionInfoExports().register(registry);
HandlerCollection handlers = new HandlerCollection();
StatisticsHandler statisticsHandler = new StatisticsHandler();
statisticsHandler.setServer(server);
handlers.addHandler(statisticsHandler);
new JettyStatisticsCollector(statisticsHandler).register(registry);
server.setHandler(handlers);
return server;
}
@Before
public void setUp() throws Exception {
server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
handlers.setHandlers(new Handler[]{context});
StatisticsHandler stats = new StatisticsHandler();
stats.setHandler(handlers);
server.setHandler(stats);
// register collector
new JettyStatisticsCollector(stats).register();
server.setHandler(stats);
server.start();
}
private static void initServer(Properties properties) throws Exception {
Integer port = Integer.valueOf(properties.getProperty("server.port"));
String host = properties.getProperty("server.host");
Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
String clientSecret = properties.getProperty("client.secret");
HandlerCollection handlers = new HandlerCollection();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());
VkApiClient vk = new VkApiClient(new HttpTransportClient());
handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});
Server server = new Server(port);
server.setHandler(handlers);
server.start();
server.join();
}
private static void initServer(Properties properties) throws Exception {
Integer port = Integer.valueOf(properties.getProperty("server.port"));
String host = properties.getProperty("server.host");
Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
String clientSecret = properties.getProperty("client.secret");
HandlerCollection handlers = new HandlerCollection();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());
VkApiClient vk = new VkApiClient(new HttpTransportClient());
handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});
Server server = new Server(port);
server.setHandler(handlers);
server.start();
server.join();
}
public static Server initJetty(final String bindAddress, final int port,
final LogWriterI18n log) throws Exception {
final Server jettyServer = new Server();
// Add a handler collection here, so that each new context adds itself
// to this collection.
jettyServer.setHandler(new HandlerCollection());
// bind on address and port
setAddressAndPort(jettyServer, bindAddress, port);
if (bindAddress != null && !bindAddress.isEmpty()) {
JettyHelper.bindAddress = bindAddress;
}
JettyHelper.port = port;
return jettyServer;
}
/**
* 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;
}
public void start() throws Exception {
RequestLogHandler requestLogHandler = new RequestLogHandler();
Slf4jRequestLog requestLog = new Slf4jRequestLog();
requestLog.setExtended(true);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
requestLog.setLogLatency(true);
requestLogHandler.setRequestLog(requestLog);
handlers.add(0, new ContextHandlerCollection());
handlers.add(requestLogHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
server.setHandler(handlerCollection);
server.start();
log.info("Server started at end point {}", getServiceUri());
}
public void start() throws PulsarServerException {
log.info("Starting web socket proxy at port {}", conf.getWebServicePort().get());
RequestLogHandler requestLogHandler = new RequestLogHandler();
Slf4jRequestLog requestLog = new Slf4jRequestLog();
requestLog.setExtended(true);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
requestLog.setLogLatency(true);
requestLogHandler.setRequestLog(requestLog);
handlers.add(0, new ContextHandlerCollection());
handlers.add(requestLogHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
server.setHandler(handlerCollection);
try {
server.start();
} catch (Exception e) {
throw new PulsarServerException(e);
}
}
public static Server initJetty(final String bindAddress, final int port,
final LogWriterI18n log) throws Exception {
final Server jettyServer = new Server();
// Add a handler collection here, so that each new context adds itself
// to this collection.
jettyServer.setHandler(new HandlerCollection());
// bind on address and port
setAddressAndPort(jettyServer, bindAddress, port);
if (bindAddress != null && !bindAddress.isEmpty()) {
JettyHelper.bindAddress = bindAddress;
}
JettyHelper.port = port;
return jettyServer;
}
public static void main(String[] args) throws Exception {
URI baseUri = UriBuilder.fromUri("http://localhost").port(SERVER_PORT)
.build();
ResourceConfig config = new ResourceConfig(Calculator.class);
Server server = JettyHttpContainerFactory.createServer(baseUri, config,
false);
ContextHandler contextHandler = new ContextHandler("/rest");
contextHandler.setHandler(server.getHandler());
ProtectionDomain protectionDomain = EmbeddedServer.class
.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setWelcomeFiles(new String[] { "index.html" });
resourceHandler.setResourceBase(location.toExternalForm());
System.out.println(location.toExternalForm());
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[] { resourceHandler,
contextHandler, new DefaultHandler() });
server.setHandler(handlerCollection);
server.start();
server.join();
}
private static HandlerCollection createHandlers(
final GatewayConfig config,
final GatewayServices services,
final ContextHandlerCollection contexts) {
HandlerCollection handlers = new HandlerCollection();
RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog(new AccessHandler());
TraceHandler traceHandler = new TraceHandler();
traceHandler.setHandler(contexts);
traceHandler.setTracedBodyFilter(System.getProperty("org.apache.knox.gateway.trace.body.status.filter"));
CorrelationHandler correlationHandler = new CorrelationHandler();
correlationHandler.setHandler(traceHandler);
DefaultTopologyHandler defaultTopoHandler = new DefaultTopologyHandler(config, services, contexts);
handlers.setHandlers(new Handler[]{correlationHandler, defaultTopoHandler, logHandler});
return handlers;
}
/**
* Creates a server which delegates the request handling to both a logging
* handler and to a web application, in this order.
*
* @return a server
*/
public static Server createMultiHandlerServer() {
Server server = createBaseServer();
// Creates the handlers and adds them to the server.
HandlerCollection handlers = new HandlerCollection();
String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
handlers.addHandler(customRequestHandler);
Handler loggingRequestHandler = new LoggingRequestHandler();
handlers.addHandler(loggingRequestHandler);
server.setHandler(handlers);
return server;
}
public static void main( String[] args )
throws Exception
{
Server server = new Server( 8080 );
WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );
ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
server.join();
}
public static void main( String[] args )
throws Exception
{
Server server = new Server( 8080 );
WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );
ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );
server.setHandler( handlers );
server.start();
server.join();
}
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();
}
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/RubySpringSupport.war");
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
server.setHandler(handlers);
server.start();
System.out.println("Server ready...");
server.join();
}
protected void run() {
server = new org.eclipse.jetty.server.Server(PORT);
WebAppContext webappcontext = new WebAppContext();
String contextPath = null;
try {
contextPath = getClass().getResource(RESOURCE_PATH).toURI().getPath();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
webappcontext.setContextPath("/");
webappcontext.setWar(contextPath);
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
server.setHandler(handlers);
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void run() {
//System.out.println("Starting Server");
server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath("/");
webappcontext.setBaseResource(Resource.newClassPathResource("/webapp"));
server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void run() {
server = new org.eclipse.jetty.server.Server(port);
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath(contextPath);
webappcontext.setBaseResource(Resource.newClassPathResource(resourcePath));
server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));
try {
configureServer(server);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void run() {
server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath("/digestauth");
webappcontext.setBaseResource(Resource.newClassPathResource("/digestauth"));
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
server.setHandler(handlers);
try {
configureServer();
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
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();
}
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();
}
protected void run() {
server = new org.eclipse.jetty.server.Server(port);
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath(contextPath);
webappcontext.setBaseResource(Resource.newClassPathResource(resourcePath));
server.setHandler(new HandlerCollection(webappcontext, new DefaultHandler()));
try {
configureServer(server);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public WebServer(@NotNull SharedContext context, @NotNull Server server, @Nullable URL baseUrl, @NotNull EncryptionFactory tokenFactory) throws URISyntaxException {
this.context = context;
this.server = server;
this.baseUrl = baseUrl == null ? null : baseUrl.toURI();
this.tokenFactory = tokenFactory;
final ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/");
handler = contextHandler.getServletHandler();
final RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog((request, response) -> {
final User user = (User) request.getAttribute(User.class.getName());
final String username = (user == null || user.isAnonymous()) ? "" : user.getUsername();
log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), username, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason());
});
final HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(contextHandler);
handlers.addHandler(logHandler);
server.setHandler(handlers);
}
private void finalizeHandlerCollection(HandlerCollection handlers, HandlerCollection wsHandlers) {
/* DefaultHandler must come last eo ensure all contexts
* have a chance to handle a request first */
handlers.addHandler(new DefaultHandler());
/* Needed for graceful shutdown as per `setStopTimeout` documentation */
StatisticsHandler statsHandler = new StatisticsHandler();
statsHandler.setHandler(handlers);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[]{
statsHandler,
wsHandlers
});
super.setHandler(wrapWithGzipHandler(contexts));
}
private void createServer(final Map<String, String> sslProperties) {
jetty = new Server();
// create the unsecure connector
createConnector();
// create the secure connector if sslProperties are specified
if (sslProperties != null) {
createSecureConnector(sslProperties);
}
jetty.setHandler(new HandlerCollection(true));
}
public void clearHandlers() {
HandlerCollection hc = (HandlerCollection) jetty.getHandler();
Handler[] ha = hc.getHandlers();
if (ha != null) {
for (Handler h : ha) {
hc.removeHandler(h);
}
}
}
private void createServer(final Map<String, String> sslProperties) {
jetty = new Server();
// create the unsecure connector
createConnector();
// create the secure connector if sslProperties are specified
if (sslProperties != null) {
createSecureConnector(sslProperties);
}
jetty.setHandler(new HandlerCollection(true));
}