io.undertow.util.Headers Java Examples

The following examples show how to use io.undertow.util.Headers. 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: ApacheHttpClientITest.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: Oauth2ServiceGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: SimpleUndertowLoadBalancer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #5
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source File: Hybi07Handshake.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: QueriesPostgresqlGetHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #9
Source File: HttpClientConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: LightHttpHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: Http2Client.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #13
Source File: ChunkedStreamSinkConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #14
Source File: AllowedContentEncodings.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #15
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: CachedHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #17
Source File: NameVirtualHostHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #18
Source File: Application.java    From skywalking with Apache License 2.0 6 votes vote down vote up
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 #19
Source File: BlockingSenderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #20
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #21
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #22
Source File: UndertowHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void sendError(int code, String message) {
    exchange.setResponseCode(code);
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
    try {
        exchange.getOutputStream().write(message.getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    exchange.endExchange();
}
 
Example #23
Source File: JwtMockHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(
            Headers.CONTENT_TYPE, "application/json");

    Map<String, Object> resMap = new HashMap<>();
    resMap.put("access_token", JwtIssuer.getJwt(mockClaims()));
    resMap.put("token_type", "bearer");
    resMap.put("expires_in", 600);
    exchange.getResponseSender().send(ByteBuffer.wrap(
            Config.getInstance().getMapper().writeValueAsBytes(
                    resMap)));
}
 
Example #24
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private void logHeaders(HeaderMap headers) {
    for (HeaderValues header : headers) {
        HttpString name = header.getHeaderName();
        if (!Headers.COOKIE.equals(name)) {
            logger.debug("[request:header] {}={}", name, new HeaderLogParam(name, header));
        }
    }
}
 
Example #25
Source File: HttpServerConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected StreamSinkConduit getSinkConduit(HttpServerExchange exchange, StreamSinkConduit conduit) {
    if(exchange.getRequestMethod().equals(Methods.CONNECT) && !connectHandled) {
        //make sure that any unhandled CONNECT requests result in a connection close
        exchange.setPersistent(false);
        exchange.getResponseHeaders().put(Headers.CONNECTION, "close");
    }
    return HttpTransferEncoding.createSinkConduit(exchange);
}
 
Example #26
Source File: DirectoryUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serve static resource for the directory listing
 *
 * @param exchange The exchange
 * @return true if resources were served
 */
public static boolean sendRequestedBlobs(HttpServerExchange exchange) {
    ByteBuffer buffer = null;
    String type = null;
    String etag = null;
    String quotedEtag = null;
    if ("css".equals(exchange.getQueryString())) {
        buffer = Blobs.FILE_CSS_BUFFER.duplicate();
        type = "text/css";
        etag = Blobs.FILE_CSS_ETAG;
        quotedEtag = Blobs.FILE_CSS_ETAG_QUOTED;
    } else if ("js".equals(exchange.getQueryString())) {
        buffer = Blobs.FILE_JS_BUFFER.duplicate();
        type = "application/javascript";
        etag = Blobs.FILE_JS_ETAG;
        quotedEtag = Blobs.FILE_JS_ETAG_QUOTED;
    }

    if (buffer != null) {

        if(!ETagUtils.handleIfNoneMatch(exchange, new ETag(false, etag), false)) {
            exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
            return true;
        }

        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(buffer.limit()));
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, type);
        exchange.getResponseHeaders().put(Headers.ETAG, quotedEtag);
        if (Methods.HEAD.equals(exchange.getRequestMethod())) {
            exchange.endExchange();
            return true;
        }
        exchange.getResponseSender().send(buffer);

        return true;
    }

    return false;
}
 
Example #27
Source File: RequestParserTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void logSiteHeaders() {
    var headers = new HeaderMap();
    headers.put(Headers.REFERER, "http://localhost");
    headers.put(Headers.USER_AGENT, "Mozilla/5.0");
    var actionLog = new ActionLog(null);

    parser.logSiteHeaders(headers, actionLog);
    assertThat(actionLog.context).doesNotContainKeys("user_agent", "referer");

    parser.logSiteHeaders = true;
    parser.logSiteHeaders(headers, actionLog);
    assertThat(actionLog.context).containsKeys("user_agent", "referer");
}
 
Example #28
Source File: PreCompressedResourceSupplier.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource getResource(HttpServerExchange exchange, String path) throws IOException {
    Resource originalResource = resourceManager.getResource(path);
    if(exchange.getRequestHeaders().contains(Headers.RANGE)) {
        //we don't use serve pre compressed resources for range requests
        return originalResource;
    }
    Resource resource = getEncodedResource(exchange, path, originalResource);
    if(resource == null) {
        return originalResource;
    }
    return resource;
}
 
Example #29
Source File: BodyHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Check the header starts with application/json and parse it into map or list
 * based on the first character "{" or "[". Otherwise, check the header starts
 * with application/x-www-form-urlencoded or multipart/form-data and parse it
 * into formdata
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // parse the body to map or list if content type is application/json
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        if (exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        exchange.startBlocking();
        try {
            if (contentType.startsWith("application/json")) {
                InputStream inputStream = exchange.getInputStream();
                String unparsedRequestBody = StringUtils.inputStreamToString(inputStream, StandardCharsets.UTF_8);
                // attach the unparsed request body into exchange if the cacheRequestBody is enabled in body.yml
                if (config.isCacheRequestBody()) {
                    exchange.putAttachment(REQUEST_BODY_STRING, unparsedRequestBody);
                }
                // attach the parsed request body into exchange if the body parser is enabled
                attachJsonBody(exchange, unparsedRequestBody);
            } else if (contentType.startsWith("multipart/form-data") || contentType.startsWith("application/x-www-form-urlencoded")) {
                // attach the parsed request body into exchange if the body parser is enabled
                attachFormDataBody(exchange);
            }
        } catch (IOException e) {
            logger.error("IOException: ", e);
            setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, contentType);
            return;
        }
    }
    Handler.next(exchange, next);
}
 
Example #30
Source File: ForwardedHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    HeaderValues forwarded = exchange.getRequestHeaders().get(Headers.FORWARDED);
    if (forwarded != null) {
        Map<Token, String> values = new HashMap<>();
        for (String val : forwarded) {
            parseHeader(val, values);
        }
        String host = values.get(Token.HOST);
        String proto = values.get(Token.PROTO);
        String by = values.get(Token.BY);
        String forVal = values.get(Token.FOR);

        if (host != null) {
            exchange.getRequestHeaders().put(Headers.HOST, host);
            exchange.setDestinationAddress(InetSocketAddress.createUnresolved(exchange.getHostName(), exchange.getHostPort()));
        } else if (by != null) {
            //we only use 'by' if the host is null
            InetSocketAddress destAddress = parseAddress(by);
            if (destAddress != null) {
                exchange.setDestinationAddress(destAddress);
            }
        }
        if (proto != null) {
            exchange.setRequestScheme(proto);
        }
        if (forVal != null) {
            InetSocketAddress sourceAddress = parseAddress(forVal);
            if (sourceAddress != null) {
                exchange.setSourceAddress(sourceAddress);
            }
        }
    }


    next.handleRequest(exchange);
}