Example usage for io.netty.handler.codec.http HttpMethod GET

List of usage examples for io.netty.handler.codec.http HttpMethod GET

Introduction

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

Prototype

HttpMethod GET

To view the source code for io.netty.handler.codec.http HttpMethod GET.

Click Source Link

Document

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

Usage

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

License:Open Source License

/**
 * Wraps the {@code request} in an implementation of {@link RestRequest} so that other layers can understand the
 * request./*from w  ww . ja v  a2s  . c om*/
 * <p/>
 * Note on content size: The content size is deduced in the following order:-
 * 1. From the {@link RestUtils.Headers#BLOB_SIZE} header.
 * 2. If 1 fails, from the {@link HttpHeaders.Names#CONTENT_LENGTH} header.
 * 3. If 2 fails, it is set to -1 which means that the content size is unknown.
 * If content size is set in the header (i.e. not -1), the actual content size should match that value. Otherwise, an
 * exception will be thrown.
 * @param request the {@link HttpRequest} that needs to be wrapped.
 * @param nettyMetrics the {@link NettyMetrics} instance to use.
 * @throws IllegalArgumentException if {@code request} is null.
 * @throws RestServiceException if the {@link HttpMethod} defined in {@code request} is not recognized as a
 *                                {@link RestMethod}.
 */
public NettyRequest(HttpRequest request, NettyMetrics nettyMetrics) throws RestServiceException {
    if (request == null) {
        throw new IllegalArgumentException("Received null HttpRequest");
    }
    restRequestMetricsTracker.nioMetricsTracker.markRequestReceived();
    HttpMethod httpMethod = request.getMethod();
    if (httpMethod == HttpMethod.GET) {
        restMethod = RestMethod.GET;
    } else if (httpMethod == HttpMethod.POST) {
        restMethod = RestMethod.POST;
    } else if (httpMethod == HttpMethod.DELETE) {
        restMethod = RestMethod.DELETE;
    } else if (httpMethod == HttpMethod.HEAD) {
        restMethod = RestMethod.HEAD;
    } else {
        nettyMetrics.unsupportedHttpMethodError.inc();
        throw new RestServiceException("http method not supported: " + httpMethod,
                RestServiceErrorCode.UnsupportedHttpMethod);
    }
    this.request = request;
    this.query = new QueryStringDecoder(request.getUri());
    this.nettyMetrics = nettyMetrics;

    if (HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE, null) != null) {
        size = Long.parseLong(HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE));
    } else {
        size = HttpHeaders.getContentLength(request, -1);
    }

    // query params.
    for (Map.Entry<String, List<String>> e : query.parameters().entrySet()) {
        StringBuilder value = null;
        if (e.getValue() != null) {
            StringBuilder combinedValues = combineVals(new StringBuilder(), e.getValue());
            if (combinedValues.length() > 0) {
                value = combinedValues;
            }
        }
        allArgs.put(e.getKey(), value);
    }

    Set<io.netty.handler.codec.http.Cookie> nettyCookies = null;
    // headers.
    for (Map.Entry<String, String> e : request.headers()) {
        StringBuilder sb;
        if (e.getKey().equals(HttpHeaders.Names.COOKIE)) {
            String value = e.getValue();
            if (value != null) {
                nettyCookies = CookieDecoder.decode(value);
            }
        } else {
            boolean valueNull = request.headers().get(e.getKey()) == null;
            if (!valueNull && allArgs.get(e.getKey()) == null) {
                sb = new StringBuilder(e.getValue());
                allArgs.put(e.getKey(), sb);
            } else if (!valueNull) {
                sb = (StringBuilder) allArgs.get(e.getKey());
                sb.append(MULTIPLE_HEADER_VALUE_DELIMITER).append(e.getValue());
            } else if (!allArgs.containsKey(e.getKey())) {
                allArgs.put(e.getKey(), null);
            }
        }
    }

    // turn all StringBuilders into String
    for (Map.Entry<String, Object> e : allArgs.entrySet()) {
        if (allArgs.get(e.getKey()) != null) {
            allArgs.put(e.getKey(), (e.getValue()).toString());
        }
    }
    // add cookies to the args as java cookies
    if (nettyCookies != null) {
        Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies);
        allArgs.put(RestUtils.Headers.COOKIE, cookies);
    }
    allArgsReadOnly = Collections.unmodifiableMap(allArgs);
}

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

License:Open Source License

/**
 * Tests conversion of {@link HttpRequest} to {@link NettyRequest} given good input.
 * @throws RestServiceException//  w w  w  .j  a  v a2s . c  o m
 */
@Test
public void conversionWithGoodInputTest() throws RestServiceException {
    // headers
    HttpHeaders headers = new DefaultHttpHeaders(false);
    headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextInt(Integer.MAX_VALUE));
    headers.add("headerKey", "headerValue1");
    headers.add("headerKey", "headerValue2");
    headers.add("overLoadedKey", "headerOverloadedValue");
    headers.add("paramNoValueInUriButValueInHeader", "paramValueInHeader");
    headers.add("headerNoValue", (Object) null);
    headers.add("headerNoValueButValueInUri", (Object) null);

    // params
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    List<String> values = new ArrayList<String>(2);
    values.add("paramValue1");
    values.add("paramValue2");
    params.put("paramKey", values);
    values = new ArrayList<String>(1);
    values.add("paramOverloadedValue");
    params.put("overLoadedKey", values);
    values = new ArrayList<String>(1);
    values.add("headerValueInUri");
    params.put("headerNoValueButValueInUri", values);
    params.put("paramNoValue", null);
    params.put("paramNoValueInUriButValueInHeader", null);

    StringBuilder uriAttachmentBuilder = new StringBuilder("?");
    for (Map.Entry<String, List<String>> param : params.entrySet()) {
        if (param.getValue() != null) {
            for (String value : param.getValue()) {
                uriAttachmentBuilder.append(param.getKey()).append("=").append(value).append("&");
            }
        } else {
            uriAttachmentBuilder.append(param.getKey()).append("&");
        }
    }
    uriAttachmentBuilder.deleteCharAt(uriAttachmentBuilder.length() - 1);
    String uriAttachment = uriAttachmentBuilder.toString();

    NettyRequest nettyRequest;
    String uri;
    Set<Cookie> cookies = new HashSet<Cookie>();
    Cookie httpCookie = new DefaultCookie("CookieKey1", "CookieValue1");
    cookies.add(httpCookie);
    httpCookie = new DefaultCookie("CookieKey2", "CookieValue2");
    cookies.add(httpCookie);
    headers.add(RestUtils.Headers.COOKIE, getCookiesHeaderValue(cookies));

    uri = "/GET" + uriAttachment;
    nettyRequest = createNettyRequest(HttpMethod.GET, uri, headers);
    validateRequest(nettyRequest, RestMethod.GET, uri, headers, params, cookies);
    closeRequestAndValidate(nettyRequest);

    uri = "/POST" + uriAttachment;
    nettyRequest = createNettyRequest(HttpMethod.POST, uri, headers);
    validateRequest(nettyRequest, RestMethod.POST, uri, headers, params, cookies);
    closeRequestAndValidate(nettyRequest);

    uri = "/DELETE" + uriAttachment;
    nettyRequest = createNettyRequest(HttpMethod.DELETE, uri, headers);
    validateRequest(nettyRequest, RestMethod.DELETE, uri, headers, params, cookies);
    closeRequestAndValidate(nettyRequest);

    uri = "/HEAD" + uriAttachment;
    nettyRequest = createNettyRequest(HttpMethod.HEAD, uri, headers);
    validateRequest(nettyRequest, RestMethod.HEAD, uri, headers, params, cookies);
    closeRequestAndValidate(nettyRequest);
}

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

License:Open Source License

/**
 * Tests different state transitions that can happen with {@link NettyRequest#addContent(HttpContent)} for GET
 * requests. Some transitions are valid and some should necessarily throw exceptions.
 * @throws RestServiceException//from   ww w.  jav  a2 s . co m
 */
@Test
public void addContentForGetTest() throws RestServiceException {
    byte[] content = RestTestUtils.getRandomBytes(16);
    // adding non LastHttpContent to nettyRequest
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.GET, "/", null);
    try {
        nettyRequest.addContent(new DefaultHttpContent(Unpooled.wrappedBuffer(content)));
        fail("GET requests should not accept non-LastHTTPContent");
    } catch (IllegalStateException e) {
        // expected. nothing to do.
    }

    // adding LastHttpContent with some content to nettyRequest
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", null);
    try {
        nettyRequest.addContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content)));
        fail("GET requests should not accept actual content in LastHTTPContent");
    } catch (IllegalStateException e) {
        // expected. nothing to do.
    }

    // should accept LastHttpContent just fine.
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", null);
    nettyRequest.addContent(new DefaultLastHttpContent());

    // should not accept LastHttpContent after close
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", null);
    nettyRequest.close();
    try {
        nettyRequest.addContent(new DefaultLastHttpContent());
        fail("Request channel has been closed, so addContent() should have thrown ClosedChannelException");
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.RequestChannelClosed,
                e.getErrorCode());
    }
}

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

License:Open Source License

@Test
public void keepAliveTest() throws RestServiceException {
    NettyRequest request = createNettyRequest(HttpMethod.GET, "/", null);
    // by default, keep-alive is true for HTTP 1.1
    assertTrue("Keep-alive not as expected", request.isKeepAlive());

    HttpHeaders headers = new DefaultHttpHeaders();
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request = createNettyRequest(HttpMethod.GET, "/", headers);
    assertTrue("Keep-alive not as expected", request.isKeepAlive());

    headers = new DefaultHttpHeaders();
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request = createNettyRequest(HttpMethod.GET, "/", headers);
    assertFalse("Keep-alive not as expected", request.isKeepAlive());
}

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

License:Open Source License

/**
 * Tests the {@link NettyRequest#getSize()} function to see that it respects priorities.
 * @throws RestServiceException/*from w w  w. jav a  2 s . c  o m*/
 */
@Test
public void sizeTest() throws RestServiceException {
    // no length headers provided.
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.GET, "/", null);
    assertEquals("Size not as expected", -1, nettyRequest.getSize());

    // deliberate mismatch to check priorities.
    int xAmbryBlobSize = 20;
    int contentLength = 10;

    // Content-Length header set
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", headers);
    assertEquals("Size not as expected", contentLength, nettyRequest.getSize());

    // xAmbryBlobSize set
    headers = new DefaultHttpHeaders();
    headers.add(RestUtils.Headers.BLOB_SIZE, xAmbryBlobSize);
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", headers);
    assertEquals("Size not as expected", xAmbryBlobSize, nettyRequest.getSize());

    // both set
    headers = new DefaultHttpHeaders();
    headers.add(RestUtils.Headers.BLOB_SIZE, xAmbryBlobSize);
    headers.add(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
    nettyRequest = createNettyRequest(HttpMethod.GET, "/", headers);
    assertEquals("Size not as expected", xAmbryBlobSize, nettyRequest.getSize());
}

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

License:Open Source License

/**
 * Checks the case where no body needs to be returned but just a
 * {@link RestResponseChannel#onResponseComplete(Exception)} is called on the server. This should return just
 * response metadata./*from  ww  w . ja  v a2  s .  c o  m*/
 */
@Test
public void noResponseBodyTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.GET,
            TestingUri.ImmediateResponseComplete.toString(), null);
    HttpHeaders.setKeepAlive(httpRequest, false);
    channel.writeInbound(httpRequest);
    // There should be a response.
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // Channel should be closed.
    assertFalse("Channel not closed on the server", channel.isActive());
}

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

License:Open Source License

/**
 * Tests behaviour of various functions of {@link NettyResponseChannel} under write failures.
 * @throws Exception//from w  w  w .  java 2 s  . co  m
 */
@Test
public void behaviourUnderWriteFailuresTest() throws Exception {
    onResponseCompleteUnderWriteFailureTest(TestingUri.ImmediateResponseComplete);
    onResponseCompleteUnderWriteFailureTest(TestingUri.OnResponseCompleteWithNonRestException);

    // writing to channel with a outbound handler that generates an Exception
    try {
        String content = "@@randomContent@@@";
        MockNettyMessageProcessor processor = new MockNettyMessageProcessor();
        ChannelOutboundHandler badOutboundHandler = new ExceptionOutboundHandler();
        EmbeddedChannel channel = new EmbeddedChannel(badOutboundHandler, processor);
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
        // channel gets closed because of write failure
        channel.writeInbound(createContent(content, true));
        fail("Callback for write would have thrown an Exception");
    } catch (Exception e) {
        assertEquals("Exception not as expected", ExceptionOutboundHandler.EXCEPTION_MESSAGE, e.getMessage());
    }

    // writing to channel with a outbound handler that generates an Error
    EmbeddedChannel channel = new EmbeddedChannel(new ErrorOutboundHandler(), new MockNettyMessageProcessor());
    try {
        channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET,
                TestingUri.WriteFailureWithThrowable.toString(), null));
    } catch (Error e) {
        assertEquals("Unexpected error", ErrorOutboundHandler.ERROR_MESSAGE, e.getMessage());
    }

    channel = createEmbeddedChannel();
    channel.writeInbound(
            RestTestUtils.createRequest(HttpMethod.GET, TestingUri.ResponseFailureMidway.toString(), null));
    assertFalse("Channel is not closed at the remote end", channel.isActive());
}

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

License:Open Source License

/**
 * Tests handling of content that is larger than write buffer size. In this test case, the write buffer low and high
 * watermarks are requested to be set to 1 and 2 respectively so the content will be written byte by byte into the
 * {@link NettyResponseChannel}. This does <b><i>not</i></b> test for the same situation in a async scenario since
 * {@link EmbeddedChannel} only provides blocking semantics.
 * @throws IOException/*w  w  w.jav a2  s . c om*/
 */
@Test
public void fillWriteBufferTest() throws IOException {
    String content = "@@randomContent@@@";
    String lastContent = "@@randomLastContent@@@";
    EmbeddedChannel channel = createEmbeddedChannel();
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.GET, TestingUri.FillWriteBuffer.toString(),
            null);
    HttpHeaders.setKeepAlive(httpRequest, false);
    channel.writeInbound(httpRequest);
    channel.writeInbound(createContent(content, false));
    channel.writeInbound(createContent(lastContent, true));

    // first outbound has to be response.
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // content echoed back.
    StringBuilder returnedContent = new StringBuilder();
    while (returnedContent.length() < content.length()) {
        returnedContent.append(RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    }
    assertEquals("Content does not match with expected content", content, returnedContent.toString());
    // last content echoed back.
    StringBuilder returnedLastContent = new StringBuilder();
    while (returnedLastContent.length() < lastContent.length()) {
        returnedLastContent.append(RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    }
    assertEquals("Content does not match with expected content", lastContent, returnedLastContent.toString());
    assertFalse("Channel not closed on the server", channel.isActive());
}

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

License:Open Source License

/**
 * Sends a request with certain headers that will copied into the response. Checks the response for those headers to
 * see that values match./*from w ww. j a  v a 2  s. c o  m*/
 * @throws ParseException
 */
@Test
public void headersPresenceTest() throws ParseException {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.CopyHeaders.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertFalse("Channel not closed on the server", channel.isActive());

    checkHeaders(request, response);
}

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

License:Open Source License

/**
 * Sends null input to {@link NettyResponseChannel#setHeader(String, Object)} (through
 * {@link MockNettyMessageProcessor}) and tests for reaction.
 *///  w w  w  .  j a v a2  s .com
@Test
public void nullHeadersSetTest() {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetNullHeader.toString());
    HttpHeaders.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.getStatus());
    assertFalse("Channel not closed on the server", channel.isActive());
}