Search in sources :

Example 66 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project camel by apache.

the class NettyHttpAccessHttpRequestAndResponseBeanTest method myTransformer.

/**
     * We can use both a netty http request and response type for transformation
     */
public static HttpResponse myTransformer(FullHttpRequest request) {
    String in = request.content().toString(Charset.forName("UTF-8"));
    String reply = "Bye " + in;
    request.content().release();
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, NettyConverter.toByteBuffer(reply.getBytes()));
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), reply.length());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 67 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project riposte by Nike-Inc.

the class ResponseSender method createActualResponseObjectForFirstChunk.

protected HttpResponse createActualResponseObjectForFirstChunk(ResponseInfo<?> responseInfo, ObjectMapper serializer, ChannelHandlerContext ctx) {
    HttpResponse actualResponseObject;
    HttpResponseStatus httpStatus = HttpResponseStatus.valueOf(responseInfo.getHttpStatusCodeWithDefault(DEFAULT_HTTP_STATUS_CODE));
    determineAndSetCharsetAndMimeTypeForResponseInfoIfNecessary(responseInfo);
    if (responseInfo.isChunkedResponse()) {
        // Chunked response. No content (yet).
        actualResponseObject = new DefaultHttpResponse(HTTP_1_1, httpStatus);
    } else {
        // Full response. There may or may not be content.
        if (responseInfo.getContentForFullResponse() == null) {
            // No content, so create a simple full response.
            actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus);
        } else {
            // There is content. If it's a raw byte buffer then use it as-is. Otherwise serialize it to a string
            //      using the provided serializer.
            Object content = responseInfo.getContentForFullResponse();
            ByteBuf bytesForResponse;
            if (content instanceof byte[])
                bytesForResponse = Unpooled.wrappedBuffer((byte[]) content);
            else {
                bytesForResponse = Unpooled.copiedBuffer(serializeOutput(responseInfo.getContentForFullResponse(), serializer, responseInfo, ctx), responseInfo.getDesiredContentWriterEncoding());
            }
            // Turn the serialized string to bytes for the response content, create the full response with content,
            //      and set the content type header.
            actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus, bytesForResponse);
        }
    }
    return actualResponseObject;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) ByteBuf(io.netty.buffer.ByteBuf)

Example 68 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project motan by weibocom.

the class YarMessageHandlerWarpper method handle.

@Override
public Object handle(Channel channel, Object message) {
    FullHttpRequest httpRequest = (FullHttpRequest) message;
    String uri = httpRequest.getUri();
    // should not be null
    int index = uri.indexOf("?");
    String requestPath = uri;
    Map<String, String> attachments = null;
    if (index > -1) {
        requestPath = uri.substring(0, index);
        if (index != uri.length() - 1) {
            attachments = getAttachMents(uri.substring(index + 1, uri.length()));
        }
    }
    YarResponse yarResponse = null;
    String packagerName = "JSON";
    try {
        ByteBuf buf = httpRequest.content();
        final byte[] contentBytes = new byte[buf.readableBytes()];
        buf.getBytes(0, contentBytes);
        YarRequest yarRequest = new AttachmentRequest(YarProtocol.buildRequest(contentBytes), attachments);
        yarRequest.setRequestPath(requestPath);
        yarResponse = (YarResponse) orgHandler.handle(channel, yarRequest);
    } catch (Exception e) {
        LoggerUtil.error("YarMessageHandlerWarpper handle yar request fail.", e);
        yarResponse = YarProtocolUtil.buildDefaultErrorResponse(e.getMessage(), packagerName);
    }
    byte[] responseBytes;
    try {
        responseBytes = YarProtocol.toProtocolBytes(yarResponse);
    } catch (IOException e) {
        throw new MotanFrameworkException("convert yar response to bytes fail.", e);
    }
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes));
    httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, httpResponse.content().readableBytes());
    if (HttpHeaders.isKeepAlive(httpRequest)) {
        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
    } else {
        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, Values.CLOSE);
    }
    return httpResponse;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) YarRequest(com.weibo.yar.YarRequest) YarResponse(com.weibo.yar.YarResponse) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) AttachmentRequest(com.weibo.api.motan.protocol.yar.AttachmentRequest)

Example 69 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project async-http-client by AsyncHttpClient.

the class HttpStaticFileServerHandler method sendRedirect.

private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
    response.headers().set(LOCATION, newUri);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 70 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project android by JetBrains.

the class GoogleCrashTest method checkServerReceivesPostedData.

@Ignore
@Test
public void checkServerReceivesPostedData() throws Exception {
    String expectedReportId = "deadcafe";
    Map<String, String> attributes = new ConcurrentHashMap<>();
    myTestServer.setResponseSupplier(httpRequest -> {
        if (httpRequest.method() != HttpMethod.POST) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        }
        HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest);
        try {
            for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) {
                if (httpData instanceof Attribute) {
                    Attribute attr = (Attribute) httpData;
                    attributes.put(attr.getName(), attr.getValue());
                }
            }
        } catch (IOException e) {
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        } finally {
            requestDecoder.destroy();
        }
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8)));
    });
    CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException).setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
    CompletableFuture<String> reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());
    // assert that the server get the expected data
    assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID));
    assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION));
    // Note: the exception message should have been elided
    assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE, attributes.get(GoogleCrash.KEY_EXCEPTION_INFO));
    List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02");
    report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build();
    attributes.clear();
    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());
    // check that the crash count and descriptions made through
    assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes")));
    assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc"));
    Path testData = Paths.get(AndroidTestBase.getTestDataPath());
    List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8);
    report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build();
    attributes.clear();
    reportId = myReporter.submit(report);
    assertEquals(expectedReportId, reportId.get());
    assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt"));
}
Also used : Path(java.nio.file.Path) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Attribute(io.netty.handler.codec.http.multipart.Attribute) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) IOException(java.io.IOException) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)72 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)44 ByteBuf (io.netty.buffer.ByteBuf)27 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)8 Test (org.junit.Test)7 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 ChannelFuture (io.netty.channel.ChannelFuture)4 IOException (java.io.IOException)4 Map (java.util.Map)4 HttpContent (io.netty.handler.codec.http.HttpContent)3 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)3 File (java.io.File)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)2