Java Code Examples for io.undertow.util.Headers
The following examples show how to use
io.undertow.util.Headers.
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
Source Project: skywalking Author: apache File: Application.java License: Apache License 2.0 | 6 votes |
private static void undertow() { Undertow server = Undertow.builder().addHttpListener(8080, "0.0.0.0").setHandler(exchange -> { if (CASE_URL.equals(exchange.getRequestPath())) { exchange.dispatch(() -> { try { visit("http://localhost:8081/undertow-routing-scenario/case/undertow?send=httpHandler"); } catch (IOException e) { e.printStackTrace(); } }); } exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender().send("Success"); }).build(); Runtime.getRuntime().addShutdownHook(new Thread(server::stop)); server.start(); }
Example #2
Source Project: lams Author: lamsfoundation File: ChunkedStreamSinkConduit.java License: GNU General Public License v2.0 | 6 votes |
@Override public void terminateWrites() throws IOException { if(anyAreSet(state, FLAG_WRITES_SHUTDOWN)) { return; } if (this.chunkleft != 0) { UndertowLogger.REQUEST_IO_LOGGER.debugf("Channel closed mid-chunk"); next.truncateWrites(); } if (!anyAreSet(state, FLAG_FIRST_DATA_WRITTEN)) { //if no data was actually sent we just remove the transfer encoding header, and set content length 0 //TODO: is this the best way to do it? //todo: should we make this behaviour configurable? responseHeaders.put(Headers.CONTENT_LENGTH, "0"); //according to the spec we don't actually need this, but better to be safe responseHeaders.remove(Headers.TRANSFER_ENCODING); state |= FLAG_NEXT_SHUTDOWN | FLAG_WRITES_SHUTDOWN; if(anyAreSet(state, CONF_FLAG_PASS_CLOSE)) { next.terminateWrites(); } } else { createLastChunk(false); state |= FLAG_WRITES_SHUTDOWN; } }
Example #3
Source Project: lams Author: lamsfoundation File: Hybi07Handshake.java License: GNU General Public License v2.0 | 6 votes |
protected void handshakeInternal(final WebSocketHttpExchange exchange) { String origin = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING); if (origin != null) { exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING, origin); } selectSubprotocol(exchange); selectExtensions(exchange); exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange)); final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING); try { final String solution = solve(key); exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution); performUpgrade(exchange); } catch (NoSuchAlgorithmException e) { IoUtils.safeClose(exchange); exchange.endExchange(); return; } }
Example #4
Source Project: FrameworkBenchmarks Author: TechEmpower File: QueriesPostgresqlGetHandler.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { int queries = Helper.getQueries(exchange); World[] worlds = new World[queries]; try (Connection connection = ds.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM World WHERE id = ?")) { for (int i = 0; i < worlds.length; i++) { statement.setInt(1, randomWorld()); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); int id = resultSet.getInt("id"); int randomNumber = resultSet.getInt("randomNumber"); worlds[i] = new World(id, randomNumber); } } } writer.reset(); writer.serialize(worlds); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(ByteBuffer.wrap(writer.toByteArray())); }
Example #5
Source Project: light-rest-4j Author: networknt File: RequestValidator.java License: Apache License 2.0 | 6 votes |
/** * Validate the request against the given API operation * @param requestPath normalised path * @param exchange The HttpServerExchange to validate * @param openApiOperation OpenAPI operation * @return A validation report containing validation errors */ public Status validateRequest(final NormalisedPath requestPath, HttpServerExchange exchange, OpenApiOperation openApiOperation) { requireNonNull(requestPath, "A request path is required"); requireNonNull(exchange, "An exchange is required"); requireNonNull(openApiOperation, "An OpenAPI operation is required"); Status status = validateRequestParameters(exchange, requestPath, openApiOperation); if(status != null) return status; String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE); if (contentType==null || contentType.startsWith("application/json")) { Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY); // skip the body validation if body parser is not in the request chain. if(body == null && ValidatorHandler.config.skipBodyValidation) return null; status = validateRequestBody(body, openApiOperation); } return status; }
Example #6
Source Project: lams Author: lamsfoundation File: BlockingSenderImpl.java License: GNU General Public License v2.0 | 6 votes |
@Override public void send(final String data, final Charset charset, final IoCallback callback) { byte[] bytes = data.getBytes(charset); if (inCall) { queue(new ByteBuffer[]{ByteBuffer.wrap(bytes)}, callback); return; }else { long responseContentLength = exchange.getResponseContentLength(); if(responseContentLength > 0 && bytes.length > responseContentLength) { callback.onException(exchange, this, UndertowLogger.ROOT_LOGGER.dataLargerThanContentLength(bytes.length, responseContentLength)); return; } if (!exchange.isResponseStarted() && callback == IoCallback.END_EXCHANGE) { if (responseContentLength == -1 && !exchange.getResponseHeaders().contains(Headers.TRANSFER_ENCODING)) { exchange.setResponseContentLength(bytes.length); } } } try { outputStream.write(bytes); invokeOnComplete(callback); } catch (IOException e) { callback.onException(exchange, this, e); } }
Example #7
Source Project: hawkular-apm Author: hawkular File: ApacheHttpClientITest.java License: Apache License 2.0 | 6 votes |
@Override public void init() { server = Undertow.builder() .addHttpListener(8180, "localhost") .setHandler(path().addPrefixPath("sayHello", new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if (!exchange.getRequestHeaders().contains(Constants.HAWKULAR_APM_TRACEID)) { exchange.setResponseCode(400); } else if (!exchange.getRequestHeaders().contains("test-fault")) { if (!exchange.getRequestHeaders().contains("test-no-data")) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender().send(HELLO_WORLD); } } else { exchange.setResponseCode(401); } } })).build(); server.start(); super.init(); }
Example #8
Source Project: core-ng-project Author: neowu File: RequestParser.java License: Apache License 2.0 | 6 votes |
private void parseForm(RequestImpl request, HttpServerExchange exchange) throws IOException { FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA); if (formData == null) return; for (String name : formData) { FormData.FormValue value = formData.getFirst(name); if (value.isFileItem()) { String fileName = value.getFileName(); if (!Strings.isBlank(fileName)) { // browser passes blank file name if not choose file in form FormData.FileItem item = value.getFileItem(); logger.debug("[request:file] {}={}, size={}", name, fileName, item.getFileSize()); request.files.put(name, new MultipartFile(item.getFile(), fileName, value.getHeaders().getFirst(Headers.CONTENT_TYPE))); } } else { logger.debug("[request:form] {}={}", name, new FieldLogParam(name, value.getValue())); request.formParams.put(name, value.getValue()); } } }
Example #9
Source Project: lams Author: lamsfoundation File: AllowedContentEncodings.java License: GNU General Public License v2.0 | 6 votes |
@Override public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) { if (exchange.getResponseHeaders().contains(Headers.CONTENT_ENCODING)) { //already encoded return factory.create(); } //if this is a zero length response we don't want to encode if (exchange.getResponseContentLength() != 0 && exchange.getStatusCode() != StatusCodes.NO_CONTENT && exchange.getStatusCode() != StatusCodes.NOT_MODIFIED) { EncodingMapping encoding = getEncoding(); if (encoding != null) { exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoding.getName()); if (exchange.getRequestMethod().equals(Methods.HEAD)) { //we don't create an actual encoder for HEAD requests, but we set the header return factory.create(); } else { return encoding.getEncoding().getResponseWrapper().wrap(factory, exchange); } } } return factory.create(); }
Example #10
Source Project: light-4j Author: networknt File: LightHttpHandler.java License: Apache License 2.0 | 6 votes |
/** * There are situations that the downstream service returns an error status response and we just * want to bubble up to the caller and eventually to the original caller. * * @param exchange HttpServerExchange * @param status error status */ default void setExchangeStatus(HttpServerExchange exchange, Status status) { exchange.setStatusCode(status.getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\")); exchange.getResponseSender().send(status.toString()); StackTraceElement[] elements = Thread.currentThread().getStackTrace(); logger.error(status.toString() + " at " + elements[2].getClassName() + "." + elements[2].getMethodName() + "(" + elements[2].getFileName() + ":" + elements[2].getLineNumber() + ")"); // In normal case, the auditInfo shouldn't be null as it is created by OpenApiHandler with // endpoint and openapiOperation available. This handler will enrich the auditInfo. @SuppressWarnings("unchecked") Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO); if(auditInfo == null) { auditInfo = new HashMap<>(); exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo); } // save info for auditing purposes in case of an error if(auditOnError) auditInfo.put(Constants.STATUS, status); if(auditStackTrace) { auditInfo.put(Constants.STACK_TRACE, Arrays.toString(elements)); } }
Example #11
Source Project: lams Author: lamsfoundation File: HttpClientConnection.java License: GNU General Public License v2.0 | 6 votes |
protected void doHttp2Upgrade() { try { StreamConnection connectedStreamChannel = this.performUpgrade(); Http2Channel http2Channel = new Http2Channel(connectedStreamChannel, null, bufferPool, null, true, true, options); Http2ClientConnection http2ClientConnection = new Http2ClientConnection(http2Channel, currentRequest.getResponseCallback(), currentRequest.getRequest(), currentRequest.getRequest().getRequestHeaders().getFirst(Headers.HOST), clientStatistics, false); http2ClientConnection.getCloseSetter().set(new ChannelListener<ClientConnection>() { @Override public void handleEvent(ClientConnection channel) { ChannelListeners.invokeChannelListener(HttpClientConnection.this, HttpClientConnection.this.closeSetter.get()); } }); http2Delegate = http2ClientConnection; connectedStreamChannel.getSourceChannel().wakeupReads(); //make sure the read listener is immediately invoked, as it may not happen if data is pushed back currentRequest = null; pendingResponse = null; } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); safeClose(this); } }
Example #12
Source Project: wildfly-core Author: wildfly File: DomainUtil.java License: GNU Lesser General Public License v2.1 | 6 votes |
public static void writeResponse(final HttpServerExchange exchange, final int status, ModelNode response, OperationParameter operationParameter) { exchange.setStatusCode(status); final HeaderMap responseHeaders = exchange.getResponseHeaders(); final String contentType = operationParameter.isEncode() ? Common.APPLICATION_DMR_ENCODED : Common.APPLICATION_JSON; responseHeaders.put(Headers.CONTENT_TYPE, contentType + "; charset=" + Common.UTF_8); writeCacheHeaders(exchange, status, operationParameter); if (operationParameter.isGet() && status == 200) { // For GET request the response is purely the model nodes result. The outcome // is not send as part of the response but expressed with the HTTP status code. response = response.get(RESULT); } try { byte[] data = getResponseBytes(response, operationParameter); responseHeaders.put(Headers.CONTENT_LENGTH, data.length); exchange.getResponseSender().send(ByteBuffer.wrap(data)); } catch (IOException e) { throw new RuntimeException(e); } }
Example #13
Source Project: light-oauth2 Author: networknt File: Oauth2ServiceGetHandler.java License: Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services"); Deque<String> serviceIdDeque = exchange.getQueryParameters().get("serviceId"); String serviceId = serviceIdDeque == null? "%" : serviceIdDeque.getFirst() + "%"; int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1; Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize"); int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst()); LikePredicate likePredicate = new LikePredicate("serviceId", serviceId); PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ServiceComparator(), pageSize); pagingPredicate.setPage(page); Collection<Service> values = services.values(pagingPredicate); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values)); processAudit(exchange); }
Example #14
Source Project: keycloak Author: keycloak File: SimpleUndertowLoadBalancer.java License: Apache License 2.0 | 6 votes |
private HttpHandler createHandler() throws Exception { // TODO: configurable options if needed String[] sessionIds = {AUTH_SESSION_ID, AUTH_SESSION_ID + LEGACY_COOKIE}; int connectionsPerThread = 20; int problemServerRetry = 5; // In case of unavailable node, we will try to ping him every 5 seconds to check if it's back int maxTime = 3600000; // 1 hour for proxy request timeout, so we can debug the backend keycloak servers int requestQueueSize = 10; int cachedConnectionsPerThread = 10; int connectionIdleTimeout = 60; int maxRetryAttempts = backendNodes.size() - 1; lb = new CustomLoadBalancingClient(exchange -> exchange.getRequestHeaders().contains(Headers.UPGRADE), maxRetryAttempts) .setConnectionsPerThread(connectionsPerThread) .setMaxQueueSize(requestQueueSize) .setSoftMaxConnectionsPerThread(cachedConnectionsPerThread) .setTtl(connectionIdleTimeout) .setProblemServerRetry(problemServerRetry); for (String id : sessionIds) { lb.addSessionCookieName(id); } return new ProxyHandler(lb, maxTime, ResponseCodeHandler.HANDLE_404); }
Example #15
Source Project: lams Author: lamsfoundation File: HttpTransferEncoding.java License: GNU General Public License v2.0 | 6 votes |
private static StreamSinkConduit handleFixedLength(HttpServerExchange exchange, boolean headRequest, StreamSinkConduit channel, HeaderMap responseHeaders, String contentLengthHeader, HttpServerConnection connection) { try { final long contentLength = parsePositiveLong(contentLengthHeader); if (headRequest) { return channel; } // fixed-length response ServerFixedLengthStreamSinkConduit fixed = connection.getFixedLengthStreamSinkConduit(); fixed.reset(contentLength, exchange); return fixed; } catch (NumberFormatException e) { //we just fix it for them responseHeaders.remove(Headers.CONTENT_LENGTH); } return null; }
Example #16
Source Project: lams Author: lamsfoundation File: HttpTransferEncoding.java License: GNU General Public License v2.0 | 6 votes |
private static StreamSinkConduit handleExplicitTransferEncoding(HttpServerExchange exchange, StreamSinkConduit channel, ConduitListener<StreamSinkConduit> finishListener, HeaderMap responseHeaders, String transferEncodingHeader, boolean headRequest) { HttpString transferEncoding = new HttpString(transferEncodingHeader); if (transferEncoding.equals(Headers.CHUNKED)) { if (headRequest) { return channel; } Boolean preChunked = exchange.getAttachment(HttpAttachments.PRE_CHUNKED_RESPONSE); if(preChunked != null && preChunked) { return new PreChunkedStreamSinkConduit(channel, finishListener, exchange); } else { return new ChunkedStreamSinkConduit(channel, exchange.getConnection().getByteBufferPool(), true, !exchange.isPersistent(), responseHeaders, finishListener, exchange); } } else { if (headRequest) { return channel; } log.trace("Cancelling persistence because response is identity with no content length"); // make it not persistent - very unfortunate for the next request handler really... exchange.setPersistent(false); responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString()); return new FinishableStreamSinkConduit(channel, terminateResponseListener(exchange)); } }
Example #17
Source Project: light-rest-4j Author: networknt File: ResponseValidator.java License: Apache License 2.0 | 6 votes |
private Status validateHeaders(HttpServerExchange exchange, OpenApiOperation operation, String statusCode) { Optional<Response> response = Optional.ofNullable(operation.getOperation().getResponse(statusCode)); if(response.isPresent()) { Map<String, Header> headerMap = response.get().getHeaders(); Optional<Status> optional = headerMap.entrySet() .stream() //based on OpenAPI specification, ignore "Content-Type" header //If a response header is defined with the name "Content-Type", it SHALL be ignored. - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject .filter(entry -> !Headers.CONTENT_TYPE_STRING.equals(entry.getKey())) .map(p -> validateHeader(exchange, p.getKey(), p.getValue())) .filter(s -> s != null) .findFirst(); if(optional.isPresent()) { return optional.get(); } } return null; }
Example #18
Source Project: light-4j Author: networknt File: Http2Client.java License: Apache License 2.0 | 6 votes |
/** * Add Authorization Code grant token the caller app gets from OAuth2 server and inject OpenTracing context * * This is the method called from client like web server that want to have Tracer context pass through. * * @param request the http request * @param token the bearer token * @param tracer the OpenTracing tracer */ public void addAuthTokenTrace(ClientRequest request, String token, Tracer tracer) { if(token != null && !token.startsWith("Bearer ")) { if(token.toUpperCase().startsWith("BEARER ")) { // other cases of Bearer token = "Bearer " + token.substring(7); } else { token = "Bearer " + token; } } request.getRequestHeaders().put(Headers.AUTHORIZATION, token); if(tracer != null && tracer.activeSpan() != null) { Tags.SPAN_KIND.set(tracer.activeSpan(), Tags.SPAN_KIND_CLIENT); Tags.HTTP_METHOD.set(tracer.activeSpan(), request.getMethod().toString()); Tags.HTTP_URL.set(tracer.activeSpan(), request.getPath()); tracer.inject(tracer.activeSpan().context(), Format.Builtin.HTTP_HEADERS, new ClientRequestCarrier(request)); } }
Example #19
Source Project: light-4j Author: networknt File: ConsulClientImpl.java License: Apache License 2.0 | 6 votes |
/** * send to consul, init or reconnect if necessary * @param method http method to use * @param path path to send to consul * @param token token to put in header * @param json request body to send * @return AtomicReference<ClientResponse> response */ AtomicReference<ClientResponse> send (HttpString method, String path, String token, String json) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ClientResponse> reference = new AtomicReference<>(); if (needsToCreateConnection()) { this.connection = createConnection(); } ClientRequest request = new ClientRequest().setMethod(method).setPath(path); request.getRequestHeaders().put(Headers.HOST, "localhost"); if (token != null) request.getRequestHeaders().put(HttpStringConstants.CONSUL_TOKEN, token); logger.trace("The request sent to consul: {} = request header: {}, request body is empty", uri.toString(), request.toString()); if(StringUtils.isBlank(json)) { connection.sendRequest(request, client.createClientCallback(reference, latch)); } else { request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked"); connection.sendRequest(request, client.createClientCallback(reference, latch, json)); } latch.await(); reqCounter.getAndIncrement(); logger.trace("The response got from consul: {} = {}", uri.toString(), reference.get().toString()); return reference; }
Example #20
Source Project: lams Author: lamsfoundation File: NameVirtualHostHandler.java License: GNU General Public License v2.0 | 6 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { final String hostHeader = exchange.getRequestHeaders().getFirst(Headers.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 #21
Source Project: lams Author: lamsfoundation File: CachedHttpRequest.java License: GNU General Public License v2.0 | 6 votes |
public CachedHttpRequest(final HttpServerExchange exchange) { this.path = exchange.getRequestPath(); this.etag = ETagUtils.getETag(exchange); this.contentLocation = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LOCATION); this.language = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LANGUAGE); this.contentType = exchange.getResponseHeaders().getFirst(Headers.CONTENT_TYPE); String lmString = exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED); if (lmString == null) { this.lastModified = null; } else { this.lastModified = DateUtils.parseDate(lmString); } //the content encoding can be decided dynamically, based on the current state of the request //as the decision to compress generally depends on size and mime type final AllowedContentEncodings encoding = exchange.getAttachment(AllowedContentEncodings.ATTACHMENT_KEY); if(encoding != null) { this.contentEncoding = encoding.getCurrentContentEncoding(); } else { this.contentEncoding = exchange.getResponseHeaders().getFirst(Headers.CONTENT_ENCODING); } this.responseCode = exchange.getStatusCode(); }
Example #22
Source Project: quarkus-http Author: quarkusio File: HelloWorldServer.java License: Apache License 2.0 | 5 votes |
public static void main(final String[] args) { Undertow server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.writeAsync("Hello World"); } }).build(); server.start(); }
Example #23
Source Project: quarkus-http Author: quarkusio File: Http2Server.java License: Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws Exception { String version = System.getProperty("java.version"); System.out.println("Java version " + version); if(version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8 ) { System.out.println("This example requires Java 1.8 or later"); System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's"); System.out.println("See section 9.2.2 of the HTTP2 specification for details"); System.exit(1); } String bindAddress = System.getProperty("bind.address", "localhost"); SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore")); Undertow server = Undertow.builder() .setServerOption(UndertowOptions.ENABLE_HTTP2, true) .addHttpListener(8080, bindAddress) .addHttpsListener(8443, bindAddress, sslContext) .setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100)) .setDirectoryListingEnabled(true), new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath()); exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT); } }), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build(); server.start(); SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore")); LoadBalancingProxyClient proxy = new LoadBalancingProxyClient() .addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), UndertowOptionMap.create(UndertowOptions.ENABLE_HTTP2, true)) .setConnectionsPerThread(20); Undertow reverseProxy = Undertow.builder() .setServerOption(UndertowOptions.ENABLE_HTTP2, true) .addHttpListener(8081, bindAddress) .addHttpsListener(8444, bindAddress, sslContext) .setHandler(ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime( 30000).build()) .build(); reverseProxy.start(); }
Example #24
Source Project: jbang Author: jbangdev File: undertow.java License: MIT License | 5 votes |
public static void main(String args[]) { var server = Undertow.builder().addHttpListener(8080, "localhost").setHandler((exchange) -> { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender().send("Hello World"); }).build(); server.start(); }
Example #25
Source Project: light-oauth2 Author: networknt File: Oauth2SigningPostHandler.java License: Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { ObjectMapper mapper = Config.getInstance().getMapper(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); // check authorization header for basic authentication Client client = authenticateClient(exchange); if(client != null) { String jwt; Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY); SignRequest sr = Config.getInstance().getMapper().convertValue(body, SignRequest.class); int expires = sr.getExpires(); try { // assume that the custom_claim is in format of json map string. Map<String, Object> customClaim = sr.getPayload(); jwt = JwtIssuer.getJwt(mockCcClaims(client.getClientId(), expires, customClaim)); } catch (Exception e) { logger.error("Exception:", e); throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage())); } Map<String, Object> resMap = new HashMap<>(); resMap.put("access_token", jwt); resMap.put("token_type", "bearer"); resMap.put("expires_in", expires); exchange.getResponseSender().send(mapper.writeValueAsString(resMap)); } processAudit(exchange); }
Example #26
Source Project: PYX-Reloaded Author: devgianlu File: CustomResourceHandler.java License: Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { super.handleRequest(exchange); HeaderMap headers = exchange.getResponseHeaders(); if (cacheEnabled) headers.add(Headers.CACHE_CONTROL, "private, no-cache"); else headers.add(Headers.CACHE_CONTROL, "private, no-store, no-cache"); }
Example #27
Source Project: oxygen Author: justlive1 File: UndertowWebServer.java License: Apache License 2.0 | 5 votes |
private boolean gzipEnabled(final HttpServerExchange value) { if (undertowConf.isGzipEnabled()) { final String length = value.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH); if (length == null) { return false; } return Long.parseLong(length) > undertowConf.getGzipMinLength(); } return false; }
Example #28
Source Project: proteus Author: noboomu File: MaxRequestContentLengthPredicate.java License: Apache License 2.0 | 5 votes |
@Override public boolean resolve(final HttpServerExchange value) { final String length = value.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH); if (length == null) { return false; } return Long.parseLong(length) > maxSize; }
Example #29
Source Project: proteus Author: noboomu File: ServerFallbackHandler.java License: Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { final int statusCode = 404; exchange.setStatusCode(statusCode); final String responseBody; final String reason = StatusCodes.getReason(statusCode); if (ServerPredicates.ACCEPT_JSON_PREDICATE.resolve(exchange)) { responseBody = objectMapper.writeValueAsString(new Message(statusCode, reason)); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_JSON); } else if (ServerPredicates.ACCEPT_XML_PREDICATE.resolve(exchange)) { responseBody = xmlMapper.writeValueAsString(new Message(statusCode, reason)); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_XML); } else if (ServerPredicates.ACCEPT_HTML_PREDICATE.resolve(exchange)) { responseBody = "<html><head><title>Error</title></head><body>" + statusCode + " - " + reason + "</body></html>"; exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.TEXT_HTML); } else { responseBody = statusCode + " - " + reason; exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.TEXT_PLAIN); } exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + responseBody.length()); exchange.getResponseSender().send(responseBody); }
Example #30
Source Project: galeb Author: galeb File: PoolHandler.java License: Apache License 2.0 | 5 votes |
private HttpHandler healthcheckPoolHandler() { return exchange -> { logger.warn("detected header " + CHECK_RULE_HEADER); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseHeaders().put(Headers.SERVER, "GALEB"); exchange.getResponseHeaders().put(HttpString.tryFromString(X_POOL_NAME_HEADER), pool.getName()); exchange.getResponseSender().send("POOL_REACHABLE"); }; }