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

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

Introduction

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

Prototype

HttpMethod POST

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

Click Source Link

Document

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

Usage

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

License:Open Source License

/**
 * Creates a {@link NettyMultipartRequest} with the given {@code headers} and {@code parts}.
 * @param headers the {@link HttpHeaders} that need to be added to the request.
 * @param parts the files that will form the parts of the request.
 * @return a {@link NettyMultipartRequest} containing all the {@code headers} and {@code parts}.
 * @throws Exception//w  w  w . ja v a  2 s. c o m
 */
private NettyMultipartRequest createRequest(HttpHeaders headers, InMemoryFile[] parts) throws Exception {
    HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    if (headers != null) {
        httpRequest.headers().set(headers);
    }
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, parts);
    NettyMultipartRequest request = new NettyMultipartRequest(encoder.finalizeRequest(), nettyMetrics);
    assertTrue("Request channel is not open", request.isOpen());
    while (!encoder.isEndOfInput()) {
        // Sending null for ctx because the encoder is OK with that.
        request.addContent(encoder.readChunk(null));
    }
    return request;
}

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  w w.j av  a  2s  . com
 * <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/*from w w  w  .  j a  v  a2  s.  com*/
 */
@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 for behavior of multiple operations after {@link NettyRequest#close()} has been called. Some should be ok to
 * do and some should throw exceptions.// w  ww.ja va2s .  c  om
 * @throws Exception
 */
@Test
public void operationsAfterCloseTest() throws Exception {
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    closeRequestAndValidate(nettyRequest);

    // operations that should be ok to do (does not include all operations).
    nettyRequest.close();

    // operations that will throw exceptions.
    AsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel();
    ReadIntoCallback callback = new ReadIntoCallback();
    try {
        nettyRequest.readInto(writeChannel, callback).get();
        fail("Request channel has been closed, so read should have thrown ClosedChannelException");
    } catch (ExecutionException e) {
        Exception exception = (Exception) Utils.getRootCause(e);
        assertTrue("Exception is not ClosedChannelException", exception instanceof ClosedChannelException);
        assertEquals("Exceptions of callback and future differ", exception.getMessage(),
                callback.exception.getMessage());
    }

    try {
        byte[] content = RestTestUtils.getRandomBytes(1024);
        nettyRequest.addContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content)));
        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

/**
 * Tests {@link NettyRequest#addContent(HttpContent)} and
 * {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} by creating a {@link NettyRequest}, adding a few
 * pieces of content to it and then reading from it to match the stream with the added content.
 * <p/>/*w ww .  ja va2s.c o m*/
 * The read happens at different points of time w.r.t content addition (before, during, after).
 * @throws Exception
 */
@Test
public void contentAddAndReadTest() throws Exception {
    // start reading before content added
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    List<HttpContent> httpContents = new ArrayList<HttpContent>();
    ByteBuffer content = generateContent(httpContents);
    ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel();
    ReadIntoCallback callback = new ReadIntoCallback();
    Future<Long> future = nettyRequest.readInto(writeChannel, callback);

    for (HttpContent httpContent : httpContents) {
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    readAndVerify(content.limit(), writeChannel, content);
    verifyRefCnts(httpContents);
    writeChannel.close();
    if (callback.exception != null) {
        throw callback.exception;
    }
    long futureBytesRead = future.get();
    assertEquals("Total bytes read does not match (callback)", content.limit(), callback.bytesRead);
    assertEquals("Total bytes read does not match (future)", content.limit(), futureBytesRead);
    closeRequestAndValidate(nettyRequest);

    // start reading in the middle of content add
    nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    httpContents = new ArrayList<HttpContent>();
    content = generateContent(httpContents);
    writeChannel = new ByteBufferAsyncWritableChannel();
    callback = new ReadIntoCallback();

    // add content initially
    int bytesToVerify = 0;
    int addedCount = 0;
    for (; addedCount < httpContents.size() / 2; addedCount++) {
        HttpContent httpContent = httpContents.get(addedCount);
        bytesToVerify += httpContent.content().readableBytes();
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    future = nettyRequest.readInto(writeChannel, callback);
    readAndVerify(bytesToVerify, writeChannel, content);

    // add some more content
    bytesToVerify = 0;
    for (; addedCount < httpContents.size(); addedCount++) {
        HttpContent httpContent = httpContents.get(addedCount);
        bytesToVerify += httpContent.content().readableBytes();
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    readAndVerify(bytesToVerify, writeChannel, content);
    verifyRefCnts(httpContents);
    writeChannel.close();
    if (callback.exception != null) {
        throw callback.exception;
    }
    futureBytesRead = future.get();
    assertEquals("Total bytes read does not match (callback)", content.limit(), callback.bytesRead);
    assertEquals("Total bytes read does not match (future)", content.limit(), futureBytesRead);
    closeRequestAndValidate(nettyRequest);

    // start reading after all content added
    nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    httpContents = new ArrayList<HttpContent>();
    content = generateContent(httpContents);
    writeChannel = new ByteBufferAsyncWritableChannel();
    callback = new ReadIntoCallback();

    for (HttpContent httpContent : httpContents) {
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    future = nettyRequest.readInto(writeChannel, callback);
    readAndVerify(content.limit(), writeChannel, content);
    verifyRefCnts(httpContents);
    writeChannel.close();
    if (callback.exception != null) {
        throw callback.exception;
    }
    futureBytesRead = future.get();
    assertEquals("Total bytes read does not match (callback)", content.limit(), callback.bytesRead);
    assertEquals("Total bytes read does not match (future)", content.limit(), futureBytesRead);
    closeRequestAndValidate(nettyRequest);
}

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

License:Open Source License

/**
 * Tests exception scenarios of {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} and behavior of
 * {@link NettyRequest} when {@link AsyncWritableChannel} instances fail.
 * @throws InterruptedException/*from w ww .  j  av a2 s. c  o  m*/
 * @throws IOException
 * @throws RestServiceException
 */
@Test
public void readIntoExceptionsTest() throws InterruptedException, IOException, RestServiceException {
    // try to call readInto twice.
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    AsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel();
    nettyRequest.readInto(writeChannel, null);

    try {
        nettyRequest.readInto(writeChannel, null);
        fail("Calling readInto twice should have failed");
    } catch (IllegalStateException e) {
        // expected. Nothing to do.
    }

    // write into a channel that throws exceptions
    // non RuntimeException
    nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    List<HttpContent> httpContents = new ArrayList<HttpContent>();
    generateContent(httpContents);
    assertTrue("Not enough content has been generated", httpContents.size() > 2);
    String expectedMsg = "@@expectedMsg@@";
    Exception exception = new Exception(expectedMsg);
    writeChannel = new BadAsyncWritableChannel(exception);
    ReadIntoCallback callback = new ReadIntoCallback();

    // add content initially
    int addedCount = 0;
    for (; addedCount < httpContents.size() / 2; addedCount++) {
        HttpContent httpContent = httpContents.get(addedCount);
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    Future<Long> future = nettyRequest.readInto(writeChannel, callback);

    // add some more content
    for (; addedCount < httpContents.size(); addedCount++) {
        HttpContent httpContent = httpContents.get(addedCount);
        nettyRequest.addContent(httpContent);
    }

    writeChannel.close();
    verifyRefCnts(httpContents);
    assertNotNull("Exception was not piped correctly", callback.exception);
    assertEquals("Exception message mismatch (callback)", expectedMsg, callback.exception.getMessage());
    try {
        future.get();
        fail("Future should have thrown exception");
    } catch (ExecutionException e) {
        assertEquals("Exception message mismatch (future)", expectedMsg, Utils.getRootCause(e).getMessage());
    }
    closeRequestAndValidate(nettyRequest);

    // RuntimeException
    // during readInto
    nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    httpContents = new ArrayList<HttpContent>();
    generateContent(httpContents);
    exception = new IllegalStateException(expectedMsg);
    writeChannel = new BadAsyncWritableChannel(exception);
    callback = new ReadIntoCallback();

    for (HttpContent httpContent : httpContents) {
        nettyRequest.addContent(httpContent);
        assertEquals("Reference count is not as expected", 2, httpContent.refCnt());
    }
    try {
        nettyRequest.readInto(writeChannel, callback);
        fail("readInto did not throw expected exception");
    } catch (Exception e) {
        assertEquals("Exception caught does not match expected exception", expectedMsg, e.getMessage());
    }
    writeChannel.close();
    closeRequestAndValidate(nettyRequest);
    verifyRefCnts(httpContents);

    // after readInto
    nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    httpContents = new ArrayList<HttpContent>();
    generateContent(httpContents);
    exception = new IllegalStateException(expectedMsg);
    writeChannel = new BadAsyncWritableChannel(exception);
    callback = new ReadIntoCallback();

    nettyRequest.readInto(writeChannel, callback);
    // add content
    HttpContent httpContent = httpContents.get(1);
    try {
        nettyRequest.addContent(httpContent);
        fail("addContent did not throw expected exception");
    } catch (Exception e) {
        assertEquals("Exception caught does not match expected exception", expectedMsg, e.getMessage());
    }
    writeChannel.close();
    closeRequestAndValidate(nettyRequest);
    verifyRefCnts(httpContents);
}

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

License:Open Source License

/**
 * Tests that {@link NettyRequest#close()} leaves any added {@link HttpContent} the way it was before it was added.
 * (i.e no reference count changes).// ww w .j  a  va2  s .c o m
 * @throws RestServiceException
 */
@Test
public void closeTest() throws RestServiceException {
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    Queue<HttpContent> httpContents = new LinkedBlockingQueue<HttpContent>();
    for (int i = 0; i < 5; i++) {
        ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(1024));
        HttpContent httpContent = new DefaultHttpContent(Unpooled.wrappedBuffer(content));
        nettyRequest.addContent(httpContent);
        httpContents.add(httpContent);
    }
    closeRequestAndValidate(nettyRequest);
    while (httpContents.peek() != null) {
        assertEquals("Reference count of http content has changed", 1, httpContents.poll().refCnt());
    }
}

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

License:Open Source License

/**
 * Tests for POST request that has no content.
 * @throws Exception/*  w ww. ja  v a 2 s. co  m*/
 */
@Test
public void zeroSizeContentTest() throws Exception {
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null);
    HttpContent httpContent = new DefaultLastHttpContent();

    nettyRequest.addContent(httpContent);
    assertEquals("Reference count is not as expected", 2, httpContent.refCnt());

    ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel();
    ReadIntoCallback callback = new ReadIntoCallback();
    Future<Long> future = nettyRequest.readInto(writeChannel, callback);
    assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining());
    writeChannel.resolveOldestChunk(null);
    closeRequestAndValidate(nettyRequest);
    writeChannel.close();
    assertEquals("Reference count of http content has changed", 1, httpContent.refCnt());
    if (callback.exception != null) {
        throw callback.exception;
    }
    long futureBytesRead = future.get();
    assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead);
    assertEquals("Total bytes read does not match (future)", 0, futureBytesRead);
}

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

License:Open Source License

/**
 * Tests reaction of NettyRequest when content size is less than the size specified in the headers.
 * @throws InterruptedException//from  w  ww.j a v a 2s.  com
 * @throws IOException
 * @throws RestServiceException
 */
private void sizeInHeaderMoreThanContentTest() throws InterruptedException, IOException, RestServiceException {
    List<HttpContent> httpContents = new ArrayList<HttpContent>();
    ByteBuffer content = generateContent(httpContents);
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, content.limit() + 1);
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", httpHeaders);
    doHeaderAndContentSizeMismatchTest(nettyRequest, httpContents);
}

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

License:Open Source License

/**
 * Tests reaction of NettyRequest when content size is more than the size specified in the headers.
 * @throws InterruptedException/*from  w w  w . j av  a  2s .  c  om*/
 * @throws IOException
 * @throws RestServiceException
 */
private void sizeInHeaderLessThanContentTest() throws InterruptedException, IOException, RestServiceException {
    List<HttpContent> httpContents = new ArrayList<HttpContent>();
    ByteBuffer content = generateContent(httpContents);
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    int lastHttpContentSize = httpContents.get(httpContents.size() - 1).content().readableBytes();
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, content.limit() - lastHttpContentSize - 1);
    NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", httpHeaders);
    doHeaderAndContentSizeMismatchTest(nettyRequest, httpContents);
}