Example usage for io.netty.handler.codec.http HttpHeaders getHeader

List of usage examples for io.netty.handler.codec.http HttpHeaders getHeader

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders getHeader.

Prototype

@Deprecated
public static String getHeader(HttpMessage message, CharSequence name) 

Source Link

Usage

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Verifies blob properties from output, to that sent in during input
 * @param expectedHeaders the expected headers in the response.
 * @param response the {@link HttpResponse} that contains the headers.
 *//*from  w  ww .j  a v  a 2  s.  c  om*/
private void verifyBlobProperties(HttpHeaders expectedHeaders, HttpResponse response) {
    assertEquals("Blob size does not match", Long.parseLong(expectedHeaders.get(RestUtils.Headers.BLOB_SIZE)),
            Long.parseLong(HttpHeaders.getHeader(response, RestUtils.Headers.BLOB_SIZE)));
    assertEquals(RestUtils.Headers.SERVICE_ID + " does not match",
            expectedHeaders.get(RestUtils.Headers.SERVICE_ID),
            HttpHeaders.getHeader(response, RestUtils.Headers.SERVICE_ID));
    assertEquals(RestUtils.Headers.PRIVATE + " does not match", expectedHeaders.get(RestUtils.Headers.PRIVATE),
            HttpHeaders.getHeader(response, RestUtils.Headers.PRIVATE));
    assertEquals(RestUtils.Headers.AMBRY_CONTENT_TYPE + " does not match",
            expectedHeaders.get(RestUtils.Headers.AMBRY_CONTENT_TYPE),
            HttpHeaders.getHeader(response, RestUtils.Headers.AMBRY_CONTENT_TYPE));
    assertTrue("No " + RestUtils.Headers.CREATION_TIME,
            HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
    if (Long.parseLong(expectedHeaders.get(RestUtils.Headers.TTL)) != Utils.Infinite_Time) {
        assertEquals(RestUtils.Headers.TTL + " does not match", expectedHeaders.get(RestUtils.Headers.TTL),
                HttpHeaders.getHeader(response, RestUtils.Headers.TTL));
    }
    if (expectedHeaders.contains(RestUtils.Headers.OWNER_ID)) {
        assertEquals(RestUtils.Headers.OWNER_ID + " does not match",
                expectedHeaders.get(RestUtils.Headers.OWNER_ID),
                HttpHeaders.getHeader(response, RestUtils.Headers.OWNER_ID));
    }
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Verifies User metadata headers from output, to that sent in during input
 * @param expectedHeaders the expected headers in the response.
 * @param response the {@link HttpResponse} which contains the headers of the response.
 * @param usermetadata if non-null, this is expected to come as the body.
 * @param content the content accompanying the response.
 *//*from w w w  .  ja  v a 2  s .  com*/
private void verifyUserMetadata(HttpHeaders expectedHeaders, HttpResponse response, byte[] usermetadata,
        Queue<HttpObject> content) {
    if (usermetadata == null) {
        assertEquals("Content-Length is not 0", 0, HttpHeaders.getContentLength(response));
        for (Map.Entry<String, String> header : expectedHeaders) {
            String key = header.getKey();
            if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) {
                assertEquals("Value for " + key + " does not match in user metadata", header.getValue(),
                        HttpHeaders.getHeader(response, key));
            }
        }
        for (Map.Entry<String, String> header : response.headers()) {
            String key = header.getKey();
            if (key.startsWith(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX)) {
                assertTrue("Key " + key + " does not exist in expected headers", expectedHeaders.contains(key));
            }
        }
        discardContent(content, 1);
    } else {
        assertEquals("Content-Length is not as expected", usermetadata.length,
                HttpHeaders.getContentLength(response));
        byte[] receivedMetadata = getContent(response, content).array();
        assertArrayEquals("User metadata does not match original", usermetadata, receivedMetadata);
    }
}

From source file:com.github.ambry.rest.EchoMethodHandler.java

License:Open Source License

private void updateHeaders(HttpResponse response, HttpRequest request, int contentLength) {
    HttpHeaders.setContentLength(response, contentLength);
    if (HttpHeaders.getHeader(request, RESPONSE_HEADER_KEY_1) != null) {
        HttpHeaders.setHeader(response, RESPONSE_HEADER_KEY_1,
                HttpHeaders.getHeader(request, RESPONSE_HEADER_KEY_1));
    }//from   w  ww .ja  v a 2 s.  c om
    if (HttpHeaders.getHeader(request, RESPONSE_HEADER_KEY_2) != null) {
        HttpHeaders.setHeader(response, RESPONSE_HEADER_KEY_2,
                HttpHeaders.getHeader(request, RESPONSE_HEADER_KEY_2));
    }
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Checks the headers in the response match those in the request.
 * @param request the {@link HttpRequest} with the original value of the headers.
 * @param response the {@link HttpResponse} that should have the same value for some headers in {@code request}.
 * @throws ParseException/* w ww .  j  a  v a 2 s. com*/
 */
private void checkHeaders(HttpRequest request, HttpResponse response) throws ParseException {
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertEquals(HttpHeaders.Names.CONTENT_TYPE + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_TYPE),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE));
    assertEquals(HttpHeaders.Names.CONTENT_LENGTH + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_LENGTH),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_LENGTH));
    assertEquals(HttpHeaders.Names.LOCATION + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.LOCATION),
            HttpHeaders.getHeader(response, HttpHeaders.Names.LOCATION));
    assertEquals(HttpHeaders.Names.LAST_MODIFIED + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.LAST_MODIFIED),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.LAST_MODIFIED));
    assertEquals(HttpHeaders.Names.EXPIRES + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.EXPIRES),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.EXPIRES));
    assertEquals(HttpHeaders.Names.CACHE_CONTROL + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.CACHE_CONTROL),
            HttpHeaders.getHeader(response, HttpHeaders.Names.CACHE_CONTROL));
    assertEquals(HttpHeaders.Names.PRAGMA + " does not match",
            HttpHeaders.getHeader(request, HttpHeaders.Names.PRAGMA),
            HttpHeaders.getHeader(response, HttpHeaders.Names.PRAGMA));
    assertEquals(HttpHeaders.Names.DATE + " does not match",
            HttpHeaders.getDateHeader(request, HttpHeaders.Names.DATE),
            HttpHeaders.getDateHeader(response, HttpHeaders.Names.DATE));
    assertEquals(MockNettyMessageProcessor.CUSTOM_HEADER_NAME + " does not match",
            HttpHeaders.getHeader(request, MockNettyMessageProcessor.CUSTOM_HEADER_NAME),
            HttpHeaders.getHeader(response, MockNettyMessageProcessor.CUSTOM_HEADER_NAME));
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Handles a {@link HttpRequest}. If content is awaited, handles some state maintenance. Else handles the request
 * according to a predefined flow based on the uri.
 * @param httpRequest the {@link HttpRequest} that needs to be handled.
 * @throws Exception/* ww  w .j a  v a2 s  .c  o  m*/
 */
private void handleRequest(HttpRequest httpRequest) throws Exception {
    request = new NettyRequest(httpRequest, nettyMetrics);
    restResponseChannel = new NettyResponseChannel(ctx, nettyMetrics);
    restResponseChannel.setRequest(request);
    restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, "text/plain; charset=UTF-8");
    TestingUri uri = TestingUri.getTestingURI(request.getUri());
    switch (uri) {
    case Close:
        restResponseChannel.close();
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case CopyHeaders:
        copyHeaders(httpRequest);
        restResponseChannel.onResponseComplete(null);
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case ImmediateResponseComplete:
        restResponseChannel.onResponseComplete(null);
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case FillWriteBuffer:
        ctx.channel().config().setWriteBufferLowWaterMark(1);
        ctx.channel().config().setWriteBufferHighWaterMark(2);
        break;
    case ModifyResponseMetadataAfterWrite:
        restResponseChannel.write(ByteBuffer.wrap(new byte[0]), null);
        restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, "text/plain; charset=UTF-8");
        break;
    case MultipleClose:
        restResponseChannel.onResponseComplete(null);
        assertFalse("Request channel is not closed", request.isOpen());
        restResponseChannel.close();
        restResponseChannel.close();
        break;
    case MultipleOnResponseComplete:
        restResponseChannel.onResponseComplete(null);
        assertFalse("Request channel is not closed", request.isOpen());
        restResponseChannel.onResponseComplete(null);
        break;
    case OnResponseCompleteWithRestException:
        String errorCodeStr = (String) request.getArgs().get(REST_SERVICE_ERROR_CODE_HEADER_NAME);
        RestServiceErrorCode errorCode = RestServiceErrorCode.valueOf(errorCodeStr);
        restResponseChannel.onResponseComplete(new RestServiceException(errorCodeStr, errorCode));
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case OnResponseCompleteWithNonRestException:
        restResponseChannel.onResponseComplete(
                new RuntimeException(TestingUri.OnResponseCompleteWithNonRestException.toString()));
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case ResponseFailureMidway:
        ChannelWriteCallback callback = new ChannelWriteCallback();
        callback.compareWithFuture(restResponseChannel
                .write(ByteBuffer.wrap(TestingUri.ResponseFailureMidway.toString().getBytes()), callback));
        assertNull("There shouldn't have been any exceptions on the first write", callback.exception);
        restResponseChannel.onResponseComplete(new Exception());
        // this should close the channel and the test will check for that.
        break;
    case SetNullHeader:
        setNullHeaders();
        break;
    case SetRequest:
        setRequestTest();
        break;
    case SetStatus:
        restResponseChannel
                .setStatus(ResponseStatus.valueOf(HttpHeaders.getHeader(httpRequest, STATUS_HEADER_NAME)));
        restResponseChannel.onResponseComplete(null);
        assertFalse("Request channel is not closed", request.isOpen());
        break;
    case WriteAfterClose:
        restResponseChannel.close();
        assertFalse("Request channel is not closed", request.isOpen());
        callback = new ChannelWriteCallback();
        callback.compareWithFuture(restResponseChannel
                .write(ByteBuffer.wrap(TestingUri.WriteAfterClose.toString().getBytes()), callback));
        if (callback.exception != null) {
            throw callback.exception;
        }
        break;
    case WriteFailureWithThrowable:
        callback = new ChannelWriteCallback();
        callback.compareWithFuture(restResponseChannel
                .write(ByteBuffer.wrap(TestingUri.WriteFailureWithThrowable.toString().getBytes()), callback));
        break;
    }
}

From source file:com.github.ambry.rest.NettyResponseChannelTest.java

License:Open Source License

/**
 * Copies headers from request to response.
 * @param httpRequest the {@link HttpRequest} to copy headers from.
 * @throws ParseException/*from   w w  w. ja va  2 s .co m*/
 * @throws RestServiceException
 */
private void copyHeaders(HttpRequest httpRequest) throws ParseException, RestServiceException {
    restResponseChannel.setStatus(ResponseStatus.Accepted);
    restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE,
            HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CONTENT_TYPE));
    restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH,
            Long.parseLong(HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CONTENT_LENGTH)));
    restResponseChannel.setHeader(RestUtils.Headers.LOCATION,
            HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.LOCATION));
    restResponseChannel.setHeader(RestUtils.Headers.LAST_MODIFIED,
            HttpHeaders.getDateHeader(httpRequest, HttpHeaders.Names.LAST_MODIFIED));
    restResponseChannel.setHeader(RestUtils.Headers.EXPIRES,
            HttpHeaders.getDateHeader(httpRequest, HttpHeaders.Names.EXPIRES));
    restResponseChannel.setHeader(RestUtils.Headers.CACHE_CONTROL,
            HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CACHE_CONTROL));
    restResponseChannel.setHeader(RestUtils.Headers.PRAGMA,
            HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.PRAGMA));
    restResponseChannel.setHeader(RestUtils.Headers.DATE,
            HttpHeaders.getDateHeader(httpRequest, HttpHeaders.Names.DATE));
    restResponseChannel.setHeader(CUSTOM_HEADER_NAME, HttpHeaders.getHeader(httpRequest, CUSTOM_HEADER_NAME));
}

From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureRequestContent(HttpRequest httpRequest, byte[] fullMessage, HarRequest harRequest) {
    if (fullMessage.length == 0) {
        return;/*w ww. j  a v  a 2 s  .com*/
    }

    String contentType = HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CONTENT_TYPE);
    if (contentType == null) {
        log.warn("No content type specified in request to {}. Content will be treated as {}",
                httpRequest.getUri(), BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE);
        contentType = BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE;
    }

    HarPostData postData = new HarPostData();
    harRequest.setPostData(postData);

    postData.setMimeType(contentType);

    final boolean urlEncoded = contentType.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);

    Charset charset;
    try {
        charset = BrowserMobHttpUtil.readCharsetInContentTypeHeader(contentType);
    } catch (UnsupportedCharsetException e) {
        log.warn(
                "Found unsupported character set in Content-Type header '{}' in HTTP request to {}. Content will not be captured in HAR.",
                contentType, httpRequest.getUri(), e);
        return;
    }

    if (charset == null) {
        // no charset specified, so use the default -- but log a message since this might not encode the data correctly
        charset = BrowserMobHttpUtil.DEFAULT_HTTP_CHARSET;
        log.debug("No charset specified; using charset {} to decode contents to {}", charset,
                httpRequest.getUri());
    }

    if (urlEncoded) {
        String textContents = BrowserMobHttpUtil.getContentAsString(fullMessage, charset);

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(textContents, charset, false);

        ImmutableList.Builder<HarPostDataParam> paramBuilder = ImmutableList.builder();

        for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) {
            for (String value : entry.getValue()) {
                paramBuilder.add(new HarPostDataParam(entry.getKey(), value));
            }
        }

        harRequest.getPostData().setParams(paramBuilder.build());
    } else {
        //TODO: implement capture of files and multipart form data

        // not URL encoded, so let's grab the body of the POST and capture that
        String postBody = BrowserMobHttpUtil.getContentAsString(fullMessage, charset);
        harRequest.getPostData().setText(postBody);
    }
}

From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureResponseContent(HttpResponse httpResponse, byte[] fullMessage, HarResponse harResponse) {
    // force binary if the content encoding is not supported
    boolean forceBinary = false;

    String contentType = HttpHeaders.getHeader(httpResponse, HttpHeaders.Names.CONTENT_TYPE);
    if (contentType == null) {
        log.warn("No content type specified in response from {}. Content will be treated as {}",
                originalRequest.getUri(), BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE);
        contentType = BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE;
    }//from   w ww . j  a va  2 s  . co  m

    if (responseCaptureFilter.isResponseCompressed() && !responseCaptureFilter.isDecompressionSuccessful()) {
        log.warn(
                "Unable to decompress content with encoding: {}. Contents will be encoded as base64 binary data.",
                responseCaptureFilter.getContentEncoding());
        forceBinary = true;
    }

    Charset charset;
    try {
        charset = BrowserMobHttpUtil.readCharsetInContentTypeHeader(contentType);
    } catch (UnsupportedCharsetException e) {
        log.warn(
                "Found unsupported character set in Content-Type header '{}' in HTTP response from {}. Content will not be captured in HAR.",
                contentType, originalRequest.getUri(), e);
        return;
    }

    if (charset == null) {
        // no charset specified, so use the default -- but log a message since this might not encode the data correctly
        charset = BrowserMobHttpUtil.DEFAULT_HTTP_CHARSET;
        log.debug("No charset specified; using charset {} to decode contents from {}", charset,
                originalRequest.getUri());
    }

    if (!forceBinary && BrowserMobHttpUtil.hasTextualContent(contentType)) {
        String text = BrowserMobHttpUtil.getContentAsString(fullMessage, charset);
        harResponse.getContent().setText(text);
    } else {
        harResponse.getContent().setText(DatatypeConverter.printBase64Binary(fullMessage));
        harResponse.getContent().setEncoding("base64");
    }

    harResponse.getContent().setSize(fullMessage.length);
}

From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureResponseMimeType(HttpResponse httpResponse, HarResponse harResponse) {
    String contentType = HttpHeaders.getHeader(httpResponse, HttpHeaders.Names.CONTENT_TYPE);
    // don't set the mimeType to null, since mimeType is a required field
    if (contentType != null) {
        harResponse.getContent().setMimeType(contentType);
    }//from ww w .j a va  2s . co m
}

From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureRedirectUrl(HttpResponse httpResponse, HarResponse harResponse) {
    String locationHeaderValue = HttpHeaders.getHeader(httpResponse, HttpHeaders.Names.LOCATION);
    if (locationHeaderValue != null) {
        harResponse.setRedirectURL(locationHeaderValue);
    }// w  w  w . j  a  v a  2s.  c  o m
}