io.undertow.server.HttpHandler Java Examples
The following examples show how to use
io.undertow.server.HttpHandler.
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: CustomHandlers.java From StubbornJava with MIT License | 6 votes |
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); }; }
Example #2
Source File: FilterHandler.java From lams with GNU General Public License v2.0 | 6 votes |
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; }
Example #3
Source File: ServletInitialHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
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; } }); }
Example #4
Source File: NameVirtualHostHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: PredicatesHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
@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); } }; } }; }
Example #6
Source File: ResponseValidatorTest.java From light-rest-4j with Apache License 2.0 | 6 votes |
@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(); } }
Example #7
Source File: ProteusHandler.java From proteus with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: MultiPartParserDefinition.java From quarkus-http with Apache License 2.0 | 6 votes |
@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); }
Example #9
Source File: PredicatesHandler.java From lams with GNU General Public License v2.0 | 6 votes |
@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); } }; } }; }
Example #10
Source File: FixedLengthRequestTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@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); } } }); }
Example #11
Source File: LotsOfHeadersRequestTestCase.java From quarkus-http with Apache License 2.0 | 6 votes |
@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); } } } }); }
Example #12
Source File: CustomHandlers.java From StubbornJava with MIT License | 5 votes |
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); }
Example #13
Source File: DeploymentManagerImpl.java From lams with GNU General Public License v2.0 | 5 votes |
private HttpHandler handleDevelopmentModePersistentSessions(HttpHandler next, final DeploymentInfo deploymentInfo, final SessionManager sessionManager, final ServletContextImpl servletContext) { final SessionPersistenceManager sessionPersistenceManager = deploymentInfo.getSessionPersistenceManager(); if (sessionPersistenceManager != null) { SessionRestoringHandler handler = new SessionRestoringHandler(deployment.getDeploymentInfo().getDeploymentName(), sessionManager, servletContext, next, sessionPersistenceManager); deployment.addLifecycleObjects(handler); return handler; } return next; }
Example #14
Source File: LearningPushHandler.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public HandlerWrapper build(Map<String, Object> config) { final int maxAge = config.containsKey("max-age") ? (Integer)config.get("max-age") : DEFAULT_MAX_CACHE_AGE; final int maxEntries = config.containsKey("max-entries") ? (Integer)config.get("max-entries") : DEFAULT_MAX_CACHE_ENTRIES; return new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { return new LearningPushHandler(maxEntries, maxAge, handler); } }; }
Example #15
Source File: RequestLimitingHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
/** * 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; }
Example #16
Source File: PageRoutes.java From StubbornJava with MIT License | 5 votes |
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); }; }
Example #17
Source File: Http2ServerConnection.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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())); }
Example #18
Source File: DelayedHandlerExample.java From StubbornJava with MIT License | 5 votes |
private static HttpHandler getRouter() { // Handler using Thread.sleep for a blocking delay HttpHandler sleepHandler = (exchange) -> { log.debug("In sleep handler"); Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS); Exchange.body().sendText(exchange, "ok"); }; // Custom handler using XnioExecutor.executeAfter // internals for a non blocking delay DelayedExecutionHandler delayedHandler = DiagnosticHandlers.fixedDelay( (exchange) -> { log.debug("In delayed handler"); Exchange.body().sendText(exchange, "ok"); }, 1L, TimeUnit.SECONDS); HttpHandler routes = new RoutingHandler() .get("/sleep", sleepHandler) .get("/dispatch/sleep", new BlockingHandler(sleepHandler)) .get("/delay", delayedHandler) .get("/dispatch/delay", new BlockingHandler(delayedHandler)) .setFallbackHandler(RoutingHandlers::notFoundHandler); return CustomHandlers.accessLog(routes, LoggerFactory.getLogger("Access Log")); }
Example #19
Source File: OpenApiHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@BeforeClass public static void setUp() { if(server == null) { logger.info("starting server"); HttpHandler handler = getTestHandler(); OpenApiHandler openApiHandler = new OpenApiHandler(); openApiHandler.setNext(handler); handler = openApiHandler; server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(handler) .build(); server.start(); } }
Example #20
Source File: TestWrapper.java From proteus with Apache License 2.0 | 5 votes |
@Override public HttpHandler wrap(HttpHandler handler) { return exchange -> { log.debug("Test wrapper"); exchange.putAttachment(DEBUG_TEST_KEY,wrapperValue); handler.handleRequest(exchange); }; }
Example #21
Source File: SessionAttachmentHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
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; }
Example #22
Source File: TestClassWrapper.java From proteus with Apache License 2.0 | 5 votes |
@Override public HttpHandler wrap(HttpHandler handler) { return exchange -> { handler.handleRequest(exchange); }; }
Example #23
Source File: PredicatesHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public HttpHandler wrap(HttpHandler handler) { PredicatesHandler h = new PredicatesHandler(handler, outerHandler); for(PredicatedHandler pred : handlers) { h.addPredicatedHandler(pred.getPredicate(), pred.getHandler()); } return h; }
Example #24
Source File: UndertowBootstrap.java From termd with Apache License 2.0 | 5 votes |
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); }
Example #25
Source File: ChunkedResponseTrailersTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
@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); } }); }
Example #26
Source File: ChunkedRequestTrailersTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
@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); } } }); }
Example #27
Source File: MultipartFormDataParserTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
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); } } }; }
Example #28
Source File: QueryParametersTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
@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()); } }); }
Example #29
Source File: WebServer.java From metamodel-membrane with Apache License 2.0 | 5 votes |
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(); } }); }
Example #30
Source File: AccessLogHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
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; }