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

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

Introduction

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

Prototype

@Deprecated
public static void setHeader(HttpMessage message, CharSequence name, Iterable<?> values) 

Source Link

Usage

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

public void post(URI uri, Object content, Map<String, String> headers, ResponseFuture responsefuture)
        throws Exception {

    if (m_shutDown.get()) {
        throw new IOException("IO has been Shutdown = ");

    }//from www . jav a2  s  . co m

    if (uri == null)
        throw new NullPointerException("uri is null or incorrect");

    if (!m_started.get()) {
        synchronized (this) {
            if (!m_started.get()) {
                start();
                m_started.set(true);
            }
        }
    }

    ByteBuf byteBuf = Unpooled.buffer(m_config.getInitialRequestBufferSize());
    ByteBufOutputStream outputStream = new ByteBufOutputStream(byteBuf);

    // transform to json
    try {
        m_mapper.writeValue(outputStream, content);
    } catch (JsonGenerationException e) {
        throw e;
    } catch (JsonMappingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        outputStream.close();
    }

    EmbeddedChannel encoder;
    String contenteEncoding;
    if ("gzip".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP, 1));
        contenteEncoding = "gzip";

    } else if ("deflate".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB, 1));
        contenteEncoding = "deflate";
    } else {
        encoder = null;
        contenteEncoding = null;
    }

    if (encoder != null) {
        encoder.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
        encoder.writeOutbound(byteBuf);
        encoder.finish();
        byteBuf = (ByteBuf) encoder.readOutbound();
        encoder.close();
    }

    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uri.toString(), byteBuf);
    if (contenteEncoding != null) {
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_ENCODING, contenteEncoding);
    }
    HttpHeaders.setHeader(request, HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate");
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json");
    HttpHeaders.setContentLength(request, byteBuf.readableBytes());

    if (isKeepAlive())
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONNECTION, "keep-alive");

    if (headers != null) {
        @SuppressWarnings("rawtypes")
        Iterator it = headers.entrySet().iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry pairs = (Map.Entry) it.next();
            HttpHeaders.setHeader(request, (String) pairs.getKey(), pairs.getValue());
        }
    }

    if (responsefuture != null) {
        RequestId reqid = RequestId.newRequestId();

        m_responseDispatcher.add(reqid, responsefuture);

        HttpHeaders.setHeader(request, "X_EBAY_REQ_ID", reqid.toString());
        // we expect this to be echoed in the response used for correlation.
    }

    if (m_dataQueue.size() < m_workQueueCapacity) {
        ProcessHttpWorkRequest workRequest = new ProcessHttpWorkRequest(this, uri, request);

        if (!m_dataQueue.offer(workRequest)) {
            if (responsefuture != null) {
                responsefuture.setFailure();
                m_responseDispatcher.remove(request.headers().get("X_EBAY_REQ_ID"));
            }
        }
    } else {
        throw new IOException("downstream Queue is full ");
    }

}

From source file:com.ebay.jetstream.http.netty.server.AbstractHttpRequest.java

License:MIT License

protected void postResponse(Channel channel, HttpRequest request, HttpResponse response) {

    boolean keepAlive = HttpHeaders.isKeepAlive(request);

    String reqid = request.headers().get("X_EBAY_REQ_ID");

    if (reqid != null && !reqid.isEmpty()) // if request contains
                                           // X_EBAY_REQ_ID we will echo it
                                           // back
        HttpHeaders.setHeader(response, "X_EBAY_REQ_ID", reqid);

    // we will echo back cookies for now in the response. Our request ID is
    // set as a cookie

    String contentLenHeader = response.headers().get(HttpHeaders.Names.CONTENT_LENGTH);
    if (contentLenHeader == null)
        HttpHeaders.setContentLength(response, 0);

    // Write the response.
    ChannelFuture future = channel.writeAndFlush(response);

    // Close the non-keep-alive connection after the write operation is
    // done.//from www.  j a  v a  2s .c o m
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java

License:MIT License

@Override
public void addCookie(Cookie arg0) {
    String cookieString = m_nettyhttpresp.headers().get(HttpHeaders.Names.COOKIE);
    Set<io.netty.handler.codec.http.Cookie> cookies;
    if (cookieString != null) {
        cookies = CookieDecoder.decode(cookieString);
        cookies.add(new io.netty.handler.codec.http.DefaultCookie(arg0.getName(), arg0.getValue()));
    } else {/*from   w  ww .j a  v a 2s  .c om*/
        cookies = new HashSet<io.netty.handler.codec.http.Cookie>();
        cookies.add(new io.netty.handler.codec.http.DefaultCookie(arg0.getName(), arg0.getValue()));
    }

    if (!cookies.isEmpty()) {
        // Reset the cookies if necessary.
        HttpHeaders.setHeader(m_nettyhttpresp, HttpHeaders.Names.SET_COOKIE,
                ServerCookieEncoder.encode(cookies));
    }
}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java

License:MIT License

@Override
public void setContentType(String arg0) {
    HttpHeaders.setHeader(m_nettyhttpresp, CONTENT_TYPE, arg0);

}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletResponse.java

License:MIT License

@Override
public void setHeader(String arg0, String arg1) {
    HttpHeaders.setHeader(m_nettyhttpresp, arg0, arg1);
}

From source file:com.ebay.jetstream.http.netty.server.KeepAliveHandler.java

License:MIT License

private void closeConnection(Object msg, ChannelPromise promise) {
    if (msg instanceof HttpResponse) {
        HttpHeaders.setHeader((HttpResponse) msg, HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    }//from  ww  w .j a v  a2 s.  co m
    promise.addListener(ChannelFutureListener.CLOSE);
}

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   www  . jav a2s. c o m
    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.NettyMessageProcessorTest.java

License:Open Source License

/**
 * Tests the case where raw bytes are POSTed as chunks.
 * @throws InterruptedException/*from  ww w  .  java 2s. com*/
 */
@Test
public void rawBytesPostTest() throws InterruptedException {
    Random random = new Random();
    // request also contains content.
    ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128));
    HttpRequest postRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/",
            Unpooled.wrappedBuffer(content));
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest");
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, content.remaining());
    postRequest = ReferenceCountUtil.retain(postRequest);
    ByteBuffer receivedContent = doPostTest(postRequest, null);
    compareContent(receivedContent, Collections.singletonList(content));

    // request and content separate.
    final int NUM_CONTENTS = 5;
    postRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null);
    List<ByteBuffer> contents = new ArrayList<ByteBuffer>(NUM_CONTENTS);
    int blobSize = 0;
    for (int i = 0; i < NUM_CONTENTS; i++) {
        ByteBuffer buffer = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128));
        blobSize += buffer.remaining();
        contents.add(i, buffer);
    }
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest");
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, blobSize);
    receivedContent = doPostTest(postRequest, contents);
    compareContent(receivedContent, contents);
}

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

License:Open Source License

/**
 * Tests the case where multipart upload is used.
 * @throws Exception/* ww  w .java  2  s . c  o  m*/
 */
@Test
public void multipartPostTest() throws Exception {
    Random random = new Random();
    ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128));
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null);
    HttpHeaders.setHeader(httpRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest");
    HttpHeaders.setHeader(httpRequest, RestUtils.Headers.BLOB_SIZE, content.remaining());
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, content);
    HttpRequest postRequest = encoder.finalizeRequest();
    List<ByteBuffer> contents = new ArrayList<ByteBuffer>();
    while (!encoder.isEndOfInput()) {
        // Sending null for ctx because the encoder is OK with that.
        contents.add(encoder.readChunk(null).content().nioBuffer());
    }
    ByteBuffer receivedContent = doPostTest(postRequest, contents);
    compareContent(receivedContent, Collections.singletonList(content));
}

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

License:Open Source License

/**
 * Does the post test by sending the request and content to {@link NettyMessageProcessor} through an
 * {@link EmbeddedChannel} and returns the data stored in the {@link InMemoryRouter} as a result of the post.
 * @param postRequest the POST request as a {@link HttpRequest}.
 * @param contentToSend the content to be sent as a part of the POST.
 * @return the data stored in the {@link InMemoryRouter} as a result of the POST.
 * @throws InterruptedException//from w  ww .  j a v  a 2s . co m
 */
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend)
        throws InterruptedException {
    EmbeddedChannel channel = createChannel();

    // POST
    notificationSystem.reset();
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream");
    HttpHeaders.setKeepAlive(postRequest, false);
    channel.writeInbound(postRequest);
    if (contentToSend != null) {
        for (ByteBuffer content : contentToSend) {
            channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content)));
        }
        channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    }
    if (!notificationSystem.operationCompleted.await(100, TimeUnit.MILLISECONDS)) {
        fail("Post did not succeed after 100ms. There is an error or timeout needs to increase");
    }
    assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn);
    return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob();
}