下面列出了javax.servlet.annotation.WebInitParam#io.undertow.server.HttpHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@BeforeClass
public static void setup() {
Assume.assumeFalse(DefaultServer.isH2upgrade());
final BlockingHandler blockingHandler = new BlockingHandler();
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
Collection<String> headers = exchange.getRequestHeaderNames();
for (String header : headers) {
for (String val : exchange.getRequestHeaders(header)) {
exchange.setResponseHeader(header, val);
}
}
}
});
}
@Override
public HandlerWrapper build(Map<String, Object> config) {
return new HandlerWrapper() {
@Override
public HttpHandler wrap(final HttpHandler handler) {
return new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Integer restarts = exchange.getAttachment(RESTART_COUNT);
if(restarts == null) {
restarts = 1;
} else {
restarts++;
}
exchange.putAttachment(RESTART_COUNT, restarts);
if(restarts > MAX_RESTARTS) {
throw UndertowLogger.ROOT_LOGGER.maxRestartsExceeded(MAX_RESTARTS);
}
exchange.putAttachment(RESTART, true);
}
};
}
};
}
public synchronized ProteusHandler add(HttpString method, String template, Predicate predicate, HttpHandler handler)
{
PathTemplateMatcher<RoutingMatch> matcher = matches.get(method);
if (matcher == null) {
matches.put(method, matcher = new PathTemplateMatcher<>());
}
RoutingMatch res = matcher.get(template);
if (res == null) {
matcher.add(template, res = new RoutingMatch());
}
if (allMethodsMatcher.get(template) == null) {
allMethodsMatcher.add(template, res);
}
res.predicatedHandlers.add(new HandlerHolder(predicate, handler));
return this;
}
public FilterHandler(final Map<DispatcherType, List<ManagedFilter>> filters, final boolean allowNonStandardWrappers, final HttpHandler next) {
this.allowNonStandardWrappers = allowNonStandardWrappers;
this.next = next;
this.filters = new EnumMap<>(filters);
Map<DispatcherType, Boolean> asyncSupported = new EnumMap<>(DispatcherType.class);
for(Map.Entry<DispatcherType, List<ManagedFilter>> entry : filters.entrySet()) {
boolean supported = true;
for(ManagedFilter i : entry.getValue()) {
if(!i.getFilterInfo().isAsyncSupported()) {
supported = false;
break;
}
}
asyncSupported.put(entry.getKey(), supported);
}
this.asyncSupported = asyncSupported;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String hostHeader = exchange.getRequestHeader(HttpHeaderNames.HOST);
if (hostHeader != null) {
String host;
if (hostHeader.contains(":")) { //header can be in host:port format
host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
} else {
host = hostHeader;
}
//most hosts will be lowercase, so we do the host
HttpHandler handler = hosts.get(host);
if (handler != null) {
handler.handleRequest(exchange);
return;
}
//do a cache insensitive match
handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
if (handler != null) {
handler.handleRequest(exchange);
return;
}
}
defaultHandler.handleRequest(exchange);
}
public ServletInitialHandler(final ServletPathMatches paths, final HttpHandler next, final Deployment deployment, final ServletContextImpl servletContext) {
this.next = next;
this.servletContext = servletContext;
this.paths = paths;
this.listeners = servletContext.getDeployment().getApplicationListeners();
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
//handle request can use doPrivilidged
//we need to make sure this is not abused
sm.checkPermission(PERMISSION);
}
ExceptionHandler handler = servletContext.getDeployment().getDeploymentInfo().getExceptionHandler();
if (handler != null) {
this.exceptionHandler = handler;
} else {
this.exceptionHandler = LoggingExceptionHandler.DEFAULT;
}
this.firstRequestHandler = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Object, ServletRequestContext>() {
@Override
public Object call(HttpServerExchange exchange, ServletRequestContext context) throws Exception {
handleFirstRequest(exchange, context);
return null;
}
});
}
@Before
public void setUp() {
if(server == null) {
logger.info("starting server");
TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
HttpHandler handler = Handlers.routing()
.add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
ValidatorHandler validatorHandler = new ValidatorHandler();
validatorHandler.setNext(handler);
handler = validatorHandler;
BodyHandler bodyHandler = new BodyHandler();
bodyHandler.setNext(handler);
handler = bodyHandler;
OpenApiHandler openApiHandler = new OpenApiHandler();
openApiHandler.setNext(handler);
handler = openApiHandler;
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(handler)
.build();
server.start();
}
}
public static HttpHandler loadBalancerHttpToHttps(HttpHandler next) {
return (HttpServerExchange exchange) -> {
HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
log.debug("non https switching to https {}", currentUrl.host());
HttpUrl newUrl = currentUrl.newBuilder()
.scheme("https")
.port(443)
.build();
exchange.setStatusCode(301);
exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
exchange.endExchange();
return;
}
next.handleRequest(exchange);
};
}
@BeforeClass
public static void setup() {
final BlockingHandler blockingHandler = new BlockingHandler();
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
try {
final OutputStream outputStream = exchange.getOutputStream();
final InputStream inputStream = exchange.getInputStream();
String m = HttpClientUtils.readResponse(inputStream);
Assert.assertEquals(message, m);
inputStream.close();
outputStream.close();
} catch (IOException e) {
exchange.setResponseHeader(HttpHeaderNames.CONNECTION, "close");
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
throw new RuntimeException(e);
}
}
});
}
@Override
public void parse(final HttpHandler handler) throws Exception {
if (exchange.getAttachment(FORM_DATA) != null) {
handler.handleRequest(exchange);
return;
}
this.handler = handler;
//we need to delegate to a thread pool
//as we parse with blocking operations
NonBlockingParseTask task;
if (executor == null) {
task = new NonBlockingParseTask(exchange.getWorker());
} else {
task = new NonBlockingParseTask(executor);
}
exchange.dispatch(executor, task);
}
@Override
public HandlerWrapper build(Map<String, Object> config) {
return new HandlerWrapper() {
@Override
public HttpHandler wrap(final HttpHandler handler) {
return new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Integer restarts = exchange.getAttachment(RESTART_COUNT);
if(restarts == null) {
restarts = 1;
} else {
restarts++;
}
exchange.putAttachment(RESTART_COUNT, restarts);
if(restarts > MAX_RESTARTS) {
throw UndertowLogger.ROOT_LOGGER.maxRestartsExceeded(MAX_RESTARTS);
}
exchange.putAttachment(RESTART, true);
}
};
}
};
}
@BeforeClass
public static void setup() {
final BlockingHandler blockingHandler = new BlockingHandler();
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
for (Map.Entry<String, Deque<String>> entry : exchange.getQueryParameters().entrySet()) {
exchange.setResponseHeader(entry.getKey(), entry.getValue().getFirst());
}
}
});
}
@Override
public HandlerWrapper build(Map<String, Object> config) {
return new HandlerWrapper() {
@Override
public HttpHandler wrap(HttpHandler handler) {
return new RequestEncodingHandler(handler)
.addEncoding("deflate", InflatingStreamSourceConduit.WRAPPER);
}
};
}
/**
* Construct a new instance. This version takes a {@link RequestLimit} directly which may be shared with other
* handlers.
*
* @param requestLimit the request limit information.
* @param nextHandler the next handler
*/
public RequestLimitingHandler(RequestLimit requestLimit, HttpHandler nextHandler) {
if (nextHandler == null) {
throw new IllegalArgumentException("nextHandler is null");
}
this.requestLimit = requestLimit;
this.nextHandler = nextHandler;
}
/**
* Channel that is used when the request is already half closed
* @param channel
* @param undertowOptions
* @param bufferSize
* @param rootHandler
*/
public Http2ServerConnection(Http2Channel channel, Http2DataStreamSinkChannel sinkChannel, OptionMap undertowOptions, int bufferSize, HttpHandler rootHandler) {
this.channel = channel;
this.rootHandler = rootHandler;
this.requestChannel = null;
this.undertowOptions = undertowOptions;
this.bufferSize = bufferSize;
responseChannel = sinkChannel;
originalSinkConduit = new StreamSinkChannelWrappingConduit(responseChannel);
originalSourceConduit = new StreamSourceChannelWrappingConduit(requestChannel);
this.conduitStreamSinkChannel = new ConduitStreamSinkChannel(responseChannel, originalSinkConduit);
this.conduitStreamSourceChannel = new ConduitStreamSourceChannel(Configurable.EMPTY, new EmptyStreamSourceConduit(getIoThread()));
}
@Override
public HandlerWrapper build(Map<String, Object> config) {
return new HandlerWrapper() {
@Override
public HttpHandler wrap(HttpHandler handler) {
return new StoredResponseHandler(handler);
}
};
}
public static HttpHandler redirector(HttpHandler next) {
return (HttpServerExchange exchange) -> {
HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
String host = currentUrl.host();
boolean redirect = false;
Builder newUrlBuilder = currentUrl.newBuilder();
if (host.equals("stubbornjava.com")) {
host = "www." + host;
newUrlBuilder.host(host);
redirect = true;
logger.debug("Host {} does not start with www redirecting to {}", currentUrl.host(), host);
}
if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
logger.debug("non https switching to https", currentUrl.host(), host);
newUrlBuilder.scheme("https")
.port(443);
redirect = true;
}
if (redirect) {
HttpUrl newUrl = newUrlBuilder.build();
exchange.setStatusCode(301);
exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
exchange.endExchange();
return;
}
next.handleRequest(exchange);
};
}
public WSServer(GraphBuilder p_builder, int p_port) {
this.builder = p_builder;
this.port = p_port;
peers = new HashSet<WebSocketChannel>();
handlers = new HashMap<String, HttpHandler>();
handlers.put(PREFIX, Handlers.websocket(this));
}
public static HttpHandler gzip(HttpHandler next) {
return new EncodingHandler(new ContentEncodingRepository()
.addEncodingHandler("gzip",
// This 1000 is a priority, not exactly sure what it does.
new GzipEncodingProvider(), 1000,
// Anything under a content-length of 20 will not be gzipped
Predicates.truePredicate()
//Predicates.maxContentSize(20) // https://issues.jboss.org/browse/UNDERTOW-1234
))
.setNext(next);
}
@Override
public HttpHandler wrap(HttpHandler handler)
{
return exchange -> {
handler.handleRequest(exchange);
};
}
public void bootstrap(final Consumer<Boolean> completionHandler) {
server = Undertow.builder()
.addHttpListener(port, host)
.setHandler(new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
UndertowBootstrap.this.handleWebSocketRequests(exchange);
}
})
.build();
server.start();
completionHandler.accept(true);
}
private static HttpHandler createHandler() {
return new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final FormDataParser parser = FormParserFactory.builder().build().createParser(exchange);
try {
FormData data = parser.parseBlocking();
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
if (data.getFirst("formValue").getValue().equals("myValue")) {
FormData.FormValue file = data.getFirst("file");
if (file.isFile()) {
if (file.getPath() != null) {
if (new String(Files.readAllBytes(file.getPath())).startsWith("file contents")) {
exchange.setStatusCode(StatusCodes.OK);
}
}
}
}
exchange.endExchange();
} catch (Throwable e) {
e.printStackTrace();
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.endExchange();
} finally {
IoUtils.safeClose(parser);
}
}
};
}
@BeforeClass
public static void setup (){
DefaultServer.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("{");
Iterator<Map.Entry<String,Deque<String>>> iterator = exchange.getQueryParameters().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Deque<String>> qp = iterator.next();
sb.append(qp.getKey());
sb.append("=>");
if(qp.getValue().size() == 1) {
sb.append(qp.getValue().getFirst());
} else {
sb.append("[");
for(Iterator<String> i = qp.getValue().iterator(); i.hasNext(); ) {
String val = i.next();
sb.append(val);
if(i.hasNext()) {
sb.append(",");
}
}
sb.append("]");
}
if(iterator.hasNext()) {
sb.append(",");
}
}
sb.append("}");
exchange.writeAsync(sb.toString());
}
});
}
public static void startServer(int port, boolean enableCors) throws Exception {
final DeploymentInfo deployment = Servlets.deployment().setClassLoader(WebServer.class.getClassLoader());
deployment.setContextPath("");
deployment.setDeploymentName("membrane");
deployment.addInitParameter("contextConfigLocation", "classpath:context/application-context.xml");
deployment.setResourceManager(new FileResourceManager(new File("."), 0));
deployment.addListener(Servlets.listener(ContextLoaderListener.class));
deployment.addListener(Servlets.listener(RequestContextListener.class));
deployment.addServlet(Servlets.servlet("dispatcher", DispatcherServlet.class).addMapping("/*")
.addInitParam("contextConfigLocation", "classpath:context/dispatcher-servlet.xml"));
deployment.addFilter(Servlets.filter(CharacterEncodingFilter.class).addInitParam("forceEncoding", "true")
.addInitParam("encoding", "UTF-8"));
final DeploymentManager manager = Servlets.defaultContainer().addDeployment(deployment);
manager.deploy();
final HttpHandler handler;
if (enableCors) {
CorsHandlers corsHandlers = new CorsHandlers();
handler = corsHandlers.allowOrigin(manager.start());
} else {
handler = manager.start();
}
final Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0").setHandler(handler).build();
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// graceful shutdown of everything
server.stop();
try {
manager.stop();
} catch (ServletException e) {
}
manager.undeploy();
}
});
}
public AccessLogHandler(final HttpHandler next, final AccessLogReceiver accessLogReceiver, String formatString, final ExchangeAttribute attribute, Predicate predicate) {
this.next = next;
this.accessLogReceiver = accessLogReceiver;
this.predicate = predicate;
this.formatString = handleCommonNames(formatString);
this.tokens = attribute;
}
@BeforeClass
public static void setup() {
final BlockingHandler blockingHandler = new BlockingHandler();
existing = DefaultServer.getUndertowOptions();
DefaultServer.setUndertowOptions(UndertowOptionMap.create(UndertowOptions.ALWAYS_SET_DATE, false));
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
try {
final OutputStream outputStream = exchange.getOutputStream();
final InputStream inputStream = exchange.getInputStream();
String m = HttpClientUtils.readResponse(inputStream);
Assert.assertEquals("abcdefghi", m);
HttpHeaders headers = exchange.getAttachment(HttpAttachments.REQUEST_TRAILERS);
for (Map.Entry<String, String> header : headers) {
for (String val : headers.getAll(header.getKey())) {
outputStream.write(header.getKey().getBytes(StandardCharsets.UTF_8));
outputStream.write(": ".getBytes());
outputStream.write(val.getBytes());
outputStream.write("\r\n".getBytes());
}
}
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
}
@BeforeClass
public static void setup() {
final BlockingHandler blockingHandler = new BlockingHandler();
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
HttpHeaders trailers = new DefaultHttpHeaders();
exchange.putAttachment(HttpAttachments.RESPONSE_TRAILERS, trailers);
trailers.set("foo", "fooVal");
trailers.set("bar", "barVal");
exchange.writeAsync(message);
}
});
}
@Override
public HttpHandler wrap(HttpHandler handler) {
PredicatesHandler h = new PredicatesHandler(handler, outerHandler);
for(PredicatedHandler pred : handlers) {
h.addPredicatedHandler(pred.getPredicate(), pred.getHandler());
}
return h;
}
public SessionAttachmentHandler(final HttpHandler next, final SessionManager sessionManager, final SessionConfig sessionConfig) {
this.sessionConfig = sessionConfig;
if (sessionManager == null) {
throw UndertowMessages.MESSAGES.sessionManagerMustNotBeNull();
}
this.next = next;
this.sessionManager = sessionManager;
}
@Override
public HttpHandler wrap(HttpHandler handler)
{
return exchange -> {
log.debug("Test wrapper");
exchange.putAttachment(DEBUG_TEST_KEY,wrapperValue);
handler.handleRequest(exchange);
};
}