Example usage for io.netty.handler.codec.http DefaultFullHttpResponse content

List of usage examples for io.netty.handler.codec.http DefaultFullHttpResponse content

Introduction

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

Prototype

ByteBuf content

To view the source code for io.netty.handler.codec.http DefaultFullHttpResponse content.

Click Source Link

Usage

From source file:books.netty.protocol.http.xml.codec.HttpXmlResponseDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, DefaultFullHttpResponse msg, List<Object> out)
        throws Exception {
    HttpXmlResponse resHttpXmlResponse = new HttpXmlResponse(msg, decode0(ctx, msg.content()));
    out.add(resHttpXmlResponse);/*from   w  w  w.  jav  a2  s  .  com*/
}

From source file:com.buildria.mocking.builder.action.BodyActionTest.java

License:Open Source License

@Test
public void testApplyResponseUTF8() throws Exception {
    Object content = person;//from  w  ww.  j a va  2s  .c  o  m

    List<Action> actions = new ArrayList<>();
    actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-8"));

    Action action = new BodyAction(content, actions);
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p");
    HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpResponse out = action.apply(req, res);

    assertThat(out, notNullValue());

    assertThat(out, instanceOf(DefaultFullHttpResponse.class));
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) out;
    ByteBuf buf = response.content();
    byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes();

    assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length));

    ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_8);
    ObjectSerializer serializer = ObjectSerializerFactory.create(ctx);
    byte[] expected = serializer.serialize(person);

    assertThat(json, is(expected));
}

From source file:com.buildria.mocking.builder.action.BodyActionTest.java

License:Open Source License

@Test
public void testApplyResponseUTF16BE() throws Exception {
    Object content = person;//  w w w  .ja  va  2 s. c o  m

    List<Action> actions = new ArrayList<>();
    actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-16BE"));

    Action action = new BodyAction(content, actions);
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p");
    HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpResponse out = action.apply(req, res);

    assertThat(out, notNullValue());

    assertThat(out, instanceOf(DefaultFullHttpResponse.class));
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) out;
    ByteBuf buf = response.content();
    byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes();

    assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length));

    ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_16BE);
    ObjectSerializer serializer = ObjectSerializerFactory.create(ctx);
    byte[] expected = serializer.serialize(person);

    assertThat(json, is(expected));
}

From source file:com.buildria.mocking.builder.action.RawBodyActionTest.java

License:Open Source License

@Test
public void testApplyResponse() throws Exception {
    byte[] content = "content".getBytes();

    Action action = new RawBodyAction(content);
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p");
    HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    res.headers().add(ACCEPT, "application/xml");
    HttpResponse out = action.apply(req, res);

    assertThat(out, notNullValue());/*from ww w. ja  v  a 2 s  .  c  om*/
    assertThat(out.headers().get(CONTENT_LENGTH), is("7"));
    assertThat(out.headers().get(ACCEPT), is("application/xml"));

    assertThat(out, instanceOf(DefaultFullHttpResponse.class));
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) out;
    ByteBuf buf = response.content();

    byte[] actual = new byte[buf.readableBytes()];
    buf.readBytes(actual);
    assertThat(actual, is(content));
}

From source file:com.example.http.hello.HttpHelloServerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    log.info("request coming[{}, hash: {}]: {}", current, hasher.hashCode(), msg);
    current = counter.incrementAndGet();
    if (msg instanceof HttpRequest) {
        final HttpRequest request = (HttpRequest) msg;
        if (HttpUtil.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        }//from  w ww . ja  v  a  2s. com

        final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        final boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:com.rackspacecloud.blueflood.http.DefaultHandler.java

License:Apache License

public static void sendResponse(ChannelHandlerContext channel, FullHttpRequest request, String messageBody,
        HttpResponseStatus status, Map<String, String> headers) {

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    if (headers != null && !headers.keySet().isEmpty()) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String headerKey = itr.next();
            response.headers().add(headerKey, headers.get(headerKey));
        }//from www. ja  v  a  2  s .c o m
    }

    final Timer.Context sendResponseTimerContext = sendResponseTimer.time();
    try {
        if (messageBody != null && !messageBody.isEmpty()) {
            response.content().writeBytes(Unpooled.copiedBuffer(messageBody, Constants.DEFAULT_CHARSET));
        }

        HttpResponder.respond(channel, request, response);
        Tracker.getInstance().trackResponse(request, response);
    } finally {
        sendResponseTimerContext.stop();
    }
}

From source file:com.soho.framework.server.netty.http.HttpServletHandler.java

License:Apache License

protected void handleHttpServletRequest(ChannelHandlerContext ctx, HttpRequest request, FilterChainImpl chain)
        throws Exception {
    // ?//from w w w.ja v  a 2 s.  c  om
    interceptOnRequestReceived(ctx, request);

    // Netty HTTP?Servlet
    HttpServletRequestImpl req = buildHttpServletRequest(request, chain);

    // Netty HTTP??Servlet?
    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    HttpServletResponseImpl resp = buildHttpServletResponse(response);

    // 
    chain.doFilter(req, resp);

    // ?
    interceptOnRequestSuccessed(ctx, request, response);

    resp.getWriter().flush();

    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // -
        // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // ?
    if (req.isAsyncSupported() && req.isAsyncStarted()) {
        ctx.fireChannelRead(resp);
    } else {
        // write response...
        ChannelFuture future = ctx.channel().writeAndFlush(response);

        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:com.yeetor.androidcontrol.WSSocketHandler.java

License:Open Source License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req,
        DefaultFullHttpResponse res) {
    // /*from  w  w  w  .  java  2  s  . co m*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
    }
    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.yeetor.server.HttpServer.java

License:Open Source License

public HttpResponse doDefaultResponse(ChannelHandlerContext ctx, HttpRequest request, byte[] data,
        String contentType) {/*from w  w  w. j a v a2s  . c  om*/
    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add("Content-Type", contentType);
    response.content().writeBytes(data);
    response.headers().add("Content-Length", data.length);
    return response;
}

From source file:etcd.client.HttpClientTest.java

License:Open Source License

@Test
public void httpClient() throws Exception {
    final ServerList serverList = new ServerList();
    serverList.addServer(URI.create("http://localhost:2001"), true);
    final HttpClient httpClient = new HttpClient(new NioEventLoopGroup(), Runnable::run, serverList, false);
    final CountDownLatch latch = new CountDownLatch(1);
    httpClient.send(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v2/keys/"),
            (response) -> {/*from  www  .ja  v  a  2s .c om*/
                final DefaultFullHttpResponse httpResponse = response.getHttpResponse();
                final ByteBuf contentBuffer = httpResponse.content();
                System.out.println(contentBuffer.toString(Charset.defaultCharset()));
                latch.countDown();
            });
    assertTrue(latch.await(500, TimeUnit.MILLISECONDS), "Failed to get valid response from server.");
}