Java Code Examples for io.undertow.util.HeaderMap#getFirst()

The following examples show how to use io.undertow.util.HeaderMap#getFirst() . 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: RestHandler.java    From light with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getTokenUser(HeaderMap headerMap) throws Exception {

        Map<String, Object> user = null;

        String authorization = headerMap.getFirst("authorization");
        if (authorization != null) {
            String[] parts = authorization.split(" ");
            if (parts.length == 2) {
                String scheme = parts[0];
                String credentials = parts[1];

                Pattern pattern = Pattern.compile("^Bearer$", Pattern.CASE_INSENSITIVE);
                if (pattern.matcher(scheme).matches()) {
                    logger.debug("jwt = " + credentials);
                    user = JwtUtil.verifyJwt(credentials);
                }
            }
        }
        return user;
    }
 
Example 2
Source File: MultiPartParserDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void beginPart(final HeaderMap headers) {
    this.currentFileSize = 0;
    this.headers = headers;
    final String disposition = headers.getFirst(Headers.CONTENT_DISPOSITION);
    if (disposition != null) {
        if (disposition.startsWith("form-data")) {
            currentName = Headers.extractQuotedValueFromHeader(disposition, "name");
            fileName = Headers.extractQuotedValueFromHeaderWithEncoding(disposition, "filename");
            if (fileName != null) {
                try {
                    if (tempFileLocation != null) {
                        file = Files.createTempFile(tempFileLocation, "undertow", "upload");
                    } else {
                        file = Files.createTempFile("undertow", "upload");
                    }
                    createdFiles.add(file);
                    fileChannel = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
 
Example 3
Source File: StoredResponse.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String extractCharset(HeaderMap headers) {
    String contentType = headers.getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        String value = Headers.extractQuotedValueFromHeader(contentType, "charset");
        if (value != null) {
            return value;
        }
        //if it is text we default to ISO_8859_1
        if(contentType.startsWith("text/")) {
            return StandardCharsets.ISO_8859_1.displayName();
        }
        return null;
    }
    return null;
}
 
Example 4
Source File: HTTPHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
void linkContext(ActionLog actionLog, HeaderMap headers) {
    String client = headers.getFirst(HTTPHandler.HEADER_CLIENT);
    if (client != null) actionLog.clients = List.of(client);

    String refId = headers.getFirst(HTTPHandler.HEADER_REF_ID);
    if (refId != null) actionLog.refIds = List.of(refId);

    String correlationId = headers.getFirst(HTTPHandler.HEADER_CORRELATION_ID);
    if (correlationId != null) actionLog.correlationIds = List.of(correlationId);

    if ("true".equals(headers.getFirst(HEADER_TRACE)))
        actionLog.trace = true;
}
 
Example 5
Source File: Http2StreamSourceChannel.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
Http2StreamSourceChannel(Http2Channel framedChannel, PooledByteBuffer data, long frameDataRemaining, HeaderMap headers, int streamId) {
    super(framedChannel, data, frameDataRemaining);
    this.headers = headers;
    this.streamId = streamId;
    this.flowControlWindow = framedChannel.getInitialReceiveWindowSize();
    String contentLengthString = headers.getFirst(Headers.CONTENT_LENGTH);
    if(contentLengthString != null) {
        contentLengthRemaining = Long.parseLong(contentLengthString);
    } else {
        contentLengthRemaining = -1;
    }
}
 
Example 6
Source File: HTTPErrorHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private Response defaultErrorResponse(Throwable e, HttpServerExchange exchange, ActionLog actionLog) {
    HTTPStatus status = httpStatus(e);

    HeaderMap headers = exchange.getRequestHeaders();
    String accept = headers.getFirst(Headers.ACCEPT);

    if (accept != null && accept.contains(ContentType.APPLICATION_JSON.mediaType)) {
        String userAgent = headers.getFirst(Headers.USER_AGENT);
        return Response.bean(errorResponse(e, userAgent, actionLog.id)).status(status);
    } else {
        return Response.text(errorHTML(e, actionLog.id)).status(status).contentType(ContentType.TEXT_HTML);
    }
}
 
Example 7
Source File: WebSocketHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
public boolean checkWebSocket(HTTPMethod method, HeaderMap headers) {
    if (method == HTTPMethod.GET && headers.getFirst(Headers.SEC_WEB_SOCKET_KEY) != null) {
        String version = headers.getFirst(Headers.SEC_WEB_SOCKET_VERSION);
        if ("13".equals(version)) return true;  // only support latest ws version
        throw new BadRequestException("only support web socket version 13, version=" + version, "INVALID_HTTP_REQUEST");
    }
    return false;
}
 
Example 8
Source File: DomainUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Based on the current request represented by the HttpExchange construct a complete URL for the supplied path.
 *
 * @param exchange - The current HttpExchange
 * @param path - The path to include in the constructed URL
 * @return The constructed URL
 */
public static String constructUrl(final HttpServerExchange exchange, final String path) {
    final HeaderMap headers = exchange.getRequestHeaders();
    String host = headers.getFirst(HOST);
    String protocol = exchange.getConnection().getSslSessionInfo() != null ? "https" : "http";

    return protocol + "://" + host + path;
}
 
Example 9
Source File: SSLHeaderHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    HeaderMap requestHeaders = exchange.getRequestHeaders();
    final String sessionId = requestHeaders.getFirst(SSL_SESSION_ID);
    final String cipher = requestHeaders.getFirst(SSL_CIPHER);
    String clientCert = requestHeaders.getFirst(SSL_CLIENT_CERT);
    //the proxy client replaces \n with ' '
    if (clientCert != null && clientCert.length() > 28) {
        StringBuilder sb = new StringBuilder(clientCert.length() + 1);
        sb.append(Certificates.BEGIN_CERT);
        sb.append('\n');
        sb.append(clientCert.replace(' ', '\n').substring(28, clientCert.length() - 26));//core certificate data
        sb.append('\n');
        sb.append(Certificates.END_CERT);
        clientCert = sb.toString();
    }
    if (clientCert != null || sessionId != null || cipher != null) {
        try {
            SSLSessionInfo info = new BasicSSLSessionInfo(sessionId, cipher, clientCert);
            exchange.setRequestScheme(HTTPS);
            exchange.getConnection().setSslSessionInfo(info);
            exchange.addExchangeCompleteListener(CLEAR_SSL_LISTENER);
        } catch (java.security.cert.CertificateException | CertificateException e) {
            UndertowLogger.REQUEST_LOGGER.debugf(e, "Could not create certificate from header %s", clientCert);
        }
    }
    next.handleRequest(exchange);
}
 
Example 10
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String extractCharset(HeaderMap headers) {
    String contentType = headers.getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        String value = Headers.extractQuotedValueFromHeader(contentType, "charset");
        if (value != null) {
            return value;
        }
    }
    return ISO_8859_1;
}
 
Example 11
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
public void parse(RequestImpl request, HttpServerExchange exchange, ActionLog actionLog) throws Throwable {
    HeaderMap headers = exchange.getRequestHeaders();

    request.scheme = scheme(exchange.getRequestScheme(), headers.getFirst(Headers.X_FORWARDED_PROTO));
    request.hostName = hostName(exchange.getHostName(), headers.getFirst(Headers.X_FORWARDED_HOST));
    int requestPort = requestPort(headers.getFirst(Headers.HOST), request.scheme, exchange);
    request.port = port(requestPort, headers.getFirst(Headers.X_FORWARDED_PORT));

    String method = exchange.getRequestMethod().toString();
    actionLog.context("method", method);

    request.requestURL = requestURL(request, exchange);
    actionLog.context("request_url", request.requestURL);

    logHeaders(headers);
    parseClientIP(request, exchange, actionLog, headers.getFirst(Headers.X_FORWARDED_FOR)); // parse client ip after logging header, as ip in x-forwarded-for may be invalid
    parseCookies(request, exchange);

    request.method = httpMethod(method);    // parse method after logging header/etc, to gather more info in case we see unsupported method passed from internet

    logSiteHeaders(headers, actionLog);

    parseQueryParams(request, exchange.getQueryParameters());

    if (withBodyMethods.contains(request.method)) {
        String contentType = headers.getFirst(Headers.CONTENT_TYPE);
        request.contentType = contentType == null ? null : ContentType.parse(contentType);
        parseBody(request, exchange);
    }
}
 
Example 12
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
void logSiteHeaders(HeaderMap headers, ActionLog actionLog) {
    if (logSiteHeaders) {
        String userAgent = headers.getFirst(Headers.USER_AGENT);
        if (userAgent != null) actionLog.context("user_agent", userAgent);
        String referer = headers.getFirst(Headers.REFERER);
        if (referer != null) actionLog.context("referer", Strings.truncate(referer, 1000));     // referer passed from browser can be long
    }
}
 
Example 13
Source File: LogoutHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HeaderMap requestHeaders = exchange.getRequestHeaders();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    String referrer = responseHeaders.getFirst(REFERER);
    String protocol = exchange.getRequestScheme();
    String host = null;
    if (referrer != null) {
        try {
            URI uri = new URI(referrer);
            protocol = uri.getScheme();
            host = uri.getHost() + portPortion(protocol, uri.getPort());
        } catch (URISyntaxException e) {
        }
    }
    if (host == null) {
        host = requestHeaders.getFirst(HOST);
        if (host == null) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            return;
        }
    }

    /*
     * Main sequence of events:
     *
     * 1. Redirect to self using user:pass@host form of authority. This forces Safari to overwrite its cache. (Also
     * forces FF and Chrome, but not absolutely necessary) Set the exit flag as a state signal for step 3
     *
     * 2. Send 401 digest without a nonce stale marker, this will force FF and Chrome and likely other browsers to
     * assume an invalid (old) password. In the case of Opera, which doesn't invalidate under such a circumstance,
     * send an invalid realm. This will overwrite its auth cache, since it indexes it by host and not realm.
     *
     * 3. The credentials in 307 redirect wlll be transparently accepted and a final redirect to the console is
     * performed. Opera ignores these, so the user must hit escape which will use javascript to perform the redirect
     *
     * In the case of Internet Explorer, all of this will be bypassed and will simply redirect to the console. The console
     * MUST use a special javascript call before redirecting to logout.
     */
    String userAgent = requestHeaders.getFirst(USER_AGENT);
    boolean opera = userAgent != null && userAgent.contains("Opera");
    boolean win = !opera && userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"));

    String rawQuery = exchange.getQueryString();
    boolean exit = rawQuery != null && rawQuery.contains(EXIT);



    if (win) {
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } else {
        // Do the redirects to finish the logout
        String authorization = requestHeaders.getFirst(AUTHORIZATION);

        boolean digest = true;
        Map<String, Deque<String>> parameters = exchange.getQueryParameters();
        if (parameters.containsKey(MECHANISM)) {
            digest = !BASIC.equals(parameters.get(MECHANISM).getFirst());
        }
        if (authorization != null && authorization.length() > BASIC.length()
                && BASIC.equalsIgnoreCase(authorization.substring(0, BASIC.length()))) {
            digest = false;
            ByteBuffer decode = FlexBase64.decode(authorization.substring(6));
            authorization = new String(decode.array(), decode.arrayOffset(), decode.limit(), UTF_8);
        }

        if (authorization == null || !authorization.contains("enter-login-here")) {
            if (!exit) {
                responseHeaders.add(LOCATION, protocol + "://enter-login-here:blah@" + host + "/logout?" + EXIT + "&"
                        + MECHANISM + "=" + (digest ? DIGEST : BASIC));
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                return;
            }

            mechanism(opera, digest).sendChallenge(exchange, null);
            String reply = "<html><script type='text/javascript'>window.location=\"" + protocol + "://" + host
                    + "/\";</script></html>";
            exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
            exchange.getResponseSender().send(reply, IoCallback.END_EXCHANGE);
            return;
        }

        // Success, now back to the login screen
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    }
}
 
Example 14
Source File: EventBusToServerSentEvents.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected boolean reservationCheck(HttpServerExchange exchange) {
    HeaderMap requestHeaders = exchange.getRequestHeaders();
    String origin = requestHeaders.getFirst(CorsHeaders.ORIGIN);
    if (cors.getAllowedOrigins().contains("*") || cors.getAllowedOrigins().contains(origin)) {
        HeaderMap responseHeaders = exchange.getResponseHeaders();
        responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), origin);

        String value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_HEADERS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), value);
        }

        value = requestHeaders.getFirst(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD);
        if (value != null) {
            responseHeaders.put(new HttpString(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS), value);
        }
    }

    String uri = exchange.getRequestURI();
    if (uri.indexOf(path + "/") != 0) {
        exchange.setStatusCode(404);
        return false;
    }

    final String subscriptionId = uri.substring(path.length() + 1);
    if (subscriptionId.isEmpty()) {
        exchange.setStatusCode(404);
        return false;
    }

    EventReservationsHandler.Reservation reservation = eventReservationsHandler.existsReservation(subscriptionId);
    if (reservation == null) {
        exchange.setStatusCode(404);
        return false;
    }
    return true;
}
 
Example 15
Source File: GZipPredicate.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
boolean resolve(HeaderMap headers) {
    String contentType = headers.getFirst(Headers.CONTENT_TYPE);
    if (contentType == null || !gzipContentTypes.contains(contentType)) return false;
    String length = headers.getFirst(Headers.CONTENT_LENGTH);
    return length == null || Long.parseLong(length) > MIN_GZIP_LENGTH;
}
 
Example 16
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
static StreamSinkConduit createSinkConduit(final HttpServerExchange exchange) {
    DateUtils.addDateHeaderIfRequired(exchange);

    boolean headRequest = exchange.getRequestMethod().equals(Methods.HEAD);
    HttpServerConnection serverConnection = (HttpServerConnection) exchange.getConnection();

    HttpResponseConduit responseConduit = serverConnection.getResponseConduit();
    responseConduit.reset(exchange);
    StreamSinkConduit channel = responseConduit;
    if (headRequest) {
        //if this is a head request we add a head channel underneath the content encoding channel
        //this will just discard the data
        //we still go through with the rest of the logic, to make sure all headers are set correctly
        channel = new HeadStreamSinkConduit(channel, terminateResponseListener(exchange));
    } else if(!Connectors.isEntityBodyAllowed(exchange)) {
        //we are not allowed to send an entity body for some requests
        exchange.getResponseHeaders().remove(Headers.CONTENT_LENGTH);
        exchange.getResponseHeaders().remove(Headers.TRANSFER_ENCODING);
        channel = new HeadStreamSinkConduit(channel, terminateResponseListener(exchange));
        return channel;
    }

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    // test to see if we're still persistent
    String connection = responseHeaders.getFirst(Headers.CONNECTION);
    if (!exchange.isPersistent()) {
        responseHeaders.put(Headers.CONNECTION, Headers.CLOSE.toString());
    } else if (exchange.isPersistent() && connection != null) {
        if (HttpString.tryFromString(connection).equals(Headers.CLOSE)) {
            exchange.setPersistent(false);
        }
    } else if (exchange.getConnection().getUndertowOptions().get(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, true)) {
        responseHeaders.put(Headers.CONNECTION, Headers.KEEP_ALIVE.toString());
    }
    //according to the HTTP RFC we should ignore content length if a transfer coding is specified
    final String transferEncodingHeader = responseHeaders.getLast(Headers.TRANSFER_ENCODING);
    if(transferEncodingHeader == null) {
        final String contentLengthHeader = responseHeaders.getFirst(Headers.CONTENT_LENGTH);
        if (contentLengthHeader != null) {
            StreamSinkConduit res = handleFixedLength(exchange, headRequest, channel, responseHeaders, contentLengthHeader, serverConnection);
            if (res != null) {
                return res;
            }
        }
    } else {
        responseHeaders.remove(Headers.CONTENT_LENGTH); //if there is a transfer-encoding header we remove content length if present
    }
    return handleResponseConduit(exchange, headRequest, channel, responseHeaders, terminateResponseListener(exchange), transferEncodingHeader);
}
 
Example 17
Source File: HttpTransferEncoding.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void setupRequest(final HttpServerExchange exchange) {
    final HeaderMap requestHeaders = exchange.getRequestHeaders();
    final String connectionHeader = requestHeaders.getFirst(Headers.CONNECTION);
    final String transferEncodingHeader = requestHeaders.getLast(Headers.TRANSFER_ENCODING);
    final String contentLengthHeader = requestHeaders.getFirst(Headers.CONTENT_LENGTH);

    final HttpServerConnection connection = (HttpServerConnection) exchange.getConnection();
    //if we are already using the pipelineing buffer add it to the exchange
    PipeliningBufferingStreamSinkConduit pipeliningBuffer = connection.getPipelineBuffer();
    if (pipeliningBuffer != null) {
        pipeliningBuffer.setupPipelineBuffer(exchange);
    }
    ConduitStreamSourceChannel sourceChannel = connection.getChannel().getSourceChannel();
    sourceChannel.setConduit(connection.getReadDataStreamSourceConduit());

    boolean persistentConnection = persistentConnection(exchange, connectionHeader);

    if (transferEncodingHeader == null && contentLengthHeader == null) {
        if (persistentConnection
                && connection.getExtraBytes() != null
                && pipeliningBuffer == null
                && connection.getUndertowOptions().get(UndertowOptions.BUFFER_PIPELINED_DATA, false)) {
            pipeliningBuffer = new PipeliningBufferingStreamSinkConduit(connection.getOriginalSinkConduit(), connection.getByteBufferPool());
            connection.setPipelineBuffer(pipeliningBuffer);
            pipeliningBuffer.setupPipelineBuffer(exchange);
        }
        // no content - immediately start the next request, returning an empty stream for this one
        Connectors.terminateRequest(exchange);
    } else {
        persistentConnection = handleRequestEncoding(exchange, transferEncodingHeader, contentLengthHeader, connection, pipeliningBuffer, persistentConnection);
    }

    exchange.setPersistent(persistentConnection);

    if (!exchange.isRequestComplete() || connection.getExtraBytes() != null) {
        //if there is more data we suspend reads
        sourceChannel.setReadListener(null);
        sourceChannel.suspendReads();
    }

}
 
Example 18
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public String getHeader(final HttpString name) {
    HeaderMap headers = exchange.getRequestHeaders();
    return headers.getFirst(name);
}
 
Example 19
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String getHeader(final String name) {
    HeaderMap headers = exchange.getRequestHeaders();
    return headers.getFirst(name);
}
 
Example 20
Source File: ProcessorLocalStatusCode.java    From galeb with Apache License 2.0 4 votes vote down vote up
String extractXGalebErrorHeader(final HeaderMap responseHeaders) {
    final String headerGalebError = responseHeaders != null ? responseHeaders.getFirst(X_GALEB_ERROR) : null;
    return headerGalebError != null ? headerGalebError : UNKNOWN_TARGET;
}