下面列出了怎么用org.eclipse.jetty.server.handler.HandlerWrapper的API类实例代码及写法,或者点击链接到github查看源代码。
JettyServiceConfig(@Nullable String hostname,
@Nullable Boolean dumpAfterStart, @Nullable Boolean dumpBeforeStop,
@Nullable Long stopTimeoutMillis,
@Nullable Handler handler, @Nullable RequestLog requestLog,
@Nullable Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory,
Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers,
List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners,
List<Consumer<? super Server>> configurators) {
this.hostname = hostname;
this.dumpAfterStart = dumpAfterStart;
this.dumpBeforeStop = dumpBeforeStop;
this.stopTimeoutMillis = stopTimeoutMillis;
this.handler = handler;
this.requestLog = requestLog;
this.sessionIdManagerFactory = sessionIdManagerFactory;
this.attrs = Collections.unmodifiableMap(attrs);
this.beans = Collections.unmodifiableList(beans);
this.handlerWrappers = Collections.unmodifiableList(handlerWrappers);
this.eventListeners = Collections.unmodifiableList(eventListeners);
this.lifeCycleListeners = Collections.unmodifiableList(lifeCycleListeners);
this.configurators = Collections.unmodifiableList(configurators);
}
static String toString(
Object holder, @Nullable String hostname, @Nullable Boolean dumpAfterStart,
@Nullable Boolean dumpBeforeStop, @Nullable Long stopTimeout,
@Nullable Handler handler, @Nullable RequestLog requestLog,
@Nullable Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory,
Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers,
List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners,
List<Consumer<? super Server>> configurators) {
return MoreObjects.toStringHelper(holder)
.add("hostname", hostname)
.add("dumpAfterStart", dumpAfterStart)
.add("dumpBeforeStop", dumpBeforeStop)
.add("stopTimeoutMillis", stopTimeout)
.add("handler", handler)
.add("requestLog", requestLog)
.add("sessionIdManagerFactory", sessionIdManagerFactory)
.add("attrs", attrs)
.add("beans", beans)
.add("handlerWrappers", handlerWrappers)
.add("eventListeners", eventListeners)
.add("lifeCycleListeners", lifeCycleListeners)
.add("configurators", configurators)
.toString();
}
@BeforeEach
void beforeEach() throws Exception {
server.insertHandler(new HandlerWrapper() {
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
switch (request.getPathInfo()) {
case "/errorUnchecked":
throw new RuntimeException("big boom");
case "/error":
response.setStatus(500);
case "/ok":
baseRequest.setHandled(true);
}
}
});
server.setConnectors(new Connector[]{connector});
server.start();
httpClient.setFollowRedirects(false);
httpClient.getRequestListeners().add(JettyClientMetrics
.builder(registry, result -> result.getRequest().getURI().getPath()).build());
httpClient.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
@Override
public void lifeCycleStopped(LifeCycle event) {
singleRequestLatch.countDown();
}
});
httpClient.start();
}
@Override
protected HandlerWrapper injectJettyHandlers(HandlerWrapper chain) {
metricRegistry = new MetricRegistry();
com.codahale.metrics.jetty9.InstrumentedHandler metrics
= new com.codahale.metrics.jetty9.InstrumentedHandler(
metricRegistry);
metrics.setHandler(chain);
return metrics;
}
@Test
public void shouldSetHeadersAndBaseDirectory() throws IOException {
assertThat(handler.getContextPath(), is("/go/assets"));
assertThat(((HandlerWrapper) handler.getHandler()).getHandler() instanceof AssetsContextHandler.AssetsHandler, is(true));
AssetsContextHandler.AssetsHandler assetsHandler = (AssetsContextHandler.AssetsHandler) ((HandlerWrapper) handler.getHandler()).getHandler();
ResourceHandler resourceHandler = (ResourceHandler) ReflectionUtil.getField(assetsHandler, "resourceHandler");
assertThat(resourceHandler.getCacheControl(), is("max-age=31536000,public"));
assertThat(resourceHandler.getResourceBase(), isSameFileAs(new File("WEB-INF/rails.root/public/assets").toPath().toAbsolutePath().toUri().toString()));
}
@Test
public void shouldNotHandleForRails4DevelopmentMode() throws IOException, ServletException {
when(systemEnvironment.useCompressedJs()).thenReturn(false);
String target = "/go/assets/junk";
Request request = mock(Request.class);
HttpServletResponse response = mock(HttpServletResponse.class);
Request baseRequest = mock(Request.class);
ResourceHandler resourceHandler = mock(ResourceHandler.class);
ReflectionUtil.setField(((HandlerWrapper) handler.getHandler()).getHandler(), "resourceHandler", resourceHandler);
handler.getHandler().handle(target, baseRequest, request, response);
verify(resourceHandler, never()).handle(any(String.class), any(Request.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
private WebAppContext getWebAppContext(Handler... handlers) {
for (Handler handler : handlers) {
if (handler instanceof WebAppContext) {
return (WebAppContext) handler;
} else if (handler instanceof HandlerList) {
return getWebAppContext(((HandlerList) handler).getHandlers());
} else if (handler instanceof HandlerCollection) {
return getWebAppContext(((HandlerCollection) handler).getHandlers());
} else if (handler instanceof HandlerWrapper) {
return getWebAppContext(((HandlerWrapper) handler).getHandlers());
}
}
throw new RuntimeException("No WebAppContext found in Jetty server handlers");
}
@Override
public void setHandler(Handler handler) {
if (getHandler() != null && getHandler() instanceof HandlerWrapper) {
HandlerWrapper wrappedHandler = (HandlerWrapper) getHandler();
wrappedHandler.setHandler(handler);
} else {
super.setHandler(handler);
}
}
/**
* This is usually needed if you want to have a running server during many tests invocation.
*
* Creates and starts a web server on the default {@link #PORT}.
* The given resourceBase is used to be the ROOT directory that serves the default context.
* <p><b>Don't forget to stop the returned Server after the test</b>
*
* @param port the port to which the server is bound
* @param resourceBase the base of resources for the default context
* @param classpath additional classpath entries to add (may be null)
* @param servlets map of {String, Class} pairs: String is the path spec, while class is the class
* @param handler wrapper for handler (can be null)
* @return the newly created server
* @throws Exception if an error occurs
*/
public static Server createWebServer(final int port, final String resourceBase, final String[] classpath,
final Map<String, Class<? extends Servlet>> servlets, final HandlerWrapper handler) throws Exception {
final Server server = buildServer(port);
final WebAppContext context = new WebAppContext();
context.setContextPath("/");
context.setResourceBase(resourceBase);
if (servlets != null) {
for (final Map.Entry<String, Class<? extends Servlet>> entry : servlets.entrySet()) {
final String pathSpec = entry.getKey();
final Class<? extends Servlet> servlet = entry.getValue();
context.addServlet(servlet, pathSpec);
// disable defaults if someone likes to register his own root servlet
if ("/".equals(pathSpec)) {
context.setDefaultsDescriptor(null);
context.addServlet(DefaultServlet.class, "/favicon.ico");
}
}
}
final WebAppClassLoader loader = new WebAppClassLoader(context);
if (classpath != null) {
for (final String path : classpath) {
loader.addClassPath(path);
}
}
context.setClassLoader(loader);
if (handler != null) {
handler.setHandler(context);
server.setHandler(handler);
}
else {
server.setHandler(context);
}
tryStart(port, server);
return server;
}
/** descendants may inject own handler chaining it to the given root
* and then returning that own one*/
protected HandlerWrapper injectJettyHandlers(HandlerWrapper chain) {
return chain;
}
List<HandlerWrapper> handlerWrappers() {
return handlerWrappers;
}
/**
* Starts the web server on the default {@link #PORT}.
* The given resourceBase is used to be the ROOT directory that serves the default context.
* <p><b>Don't forget to stop the returned Server after the test</b>
*
* @param resourceBase the base of resources for the default context
* @param classpath additional classpath entries to add (may be null)
* @param servlets map of {String, Class} pairs: String is the path spec, while class is the class
* @param handler wrapper for handler (can be null)
* @throws Exception if the test fails
*/
protected void startWebServer(final String resourceBase, final String[] classpath,
final Map<String, Class<? extends Servlet>> servlets, final HandlerWrapper handler) throws Exception {
stopWebServers();
LAST_TEST_UsesMockWebConnection_ = Boolean.FALSE;
STATIC_SERVER_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServerStarter"));
STATIC_SERVER_ = WebServerTestCase.createWebServer(PORT, resourceBase, classpath, servlets, handler);
}