Example usage for io.netty.handler.codec.http HttpResponse getStatus

List of usage examples for io.netty.handler.codec.http HttpResponse getStatus

Introduction

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

Prototype

@Deprecated
HttpResponseStatus getStatus();

Source Link

Usage

From source file:HttpUploadClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }//w  ww.java 2  s.co  m
            }
        }

        if (response.getStatus().code() == 200 && response.headers()
                .contains(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED, true)) {
            readingChunks = true;
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        System.err.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                System.err.println("} END OF CHUNKED CONTENT");
            } else {
                System.err.println("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    assert msg instanceof FullHttpResponse;
    l.info(" Got a message from server !!! {}", msg);
    ++state;/*  w w  w  . j a  v  a  2 s.  c  om*/

    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.out.println("STATUS: " + response.getStatus());
        System.out.println("VERSION: " + response.getProtocolVersion());
        System.out.println();

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.out.println("HEADER: " + name + " = " + value);
                }
            }
            System.out.println();
        }

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.out.println("CHUNKED CONTENT {");
        } else {
            System.out.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.out.print(content.content().toString(CharsetUtil.UTF_8));
        System.out.flush();

        if (content instanceof LastHttpContent) {
            System.out.println("} END OF CONTENT");
        }
    }

    switch (state) {
    case 1:
        FullHttpResponse resp = (FullHttpResponse) msg;
        for (String cookiestr : resp.headers().getAll(HttpHeaders.Names.SET_COOKIE)) {
            Set<Cookie> tmp = CookieDecoder.decode(cookiestr);
            sessCookies = tmp;
        }
        //login( ctx.channel(), credential );
        pubEvent(ctx.channel(), event, (FullHttpResponse) msg);
        break;
    case 2:
        getEvents(ctx.channel(), (FullHttpResponse) msg);
        break;
    case 3:
        logout(ctx.channel());
        break;
    default:
        ctx.close();
        break;
    }
}

From source file:com.andrewkroh.cisco.xmlservices.XmlResponseChannelHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    IpPhone phone = ctx.channel().attr(phoneAttributeKey).get();

    if (msg instanceof HttpResponse && LOGGER.isDebugEnabled()) {
        HttpResponse response = (HttpResponse) msg;

        StringBuilder responseInfo = new StringBuilder();
        responseInfo.append("Source=");
        responseInfo.append(phone.getHostname());
        responseInfo.append(", ");
        responseInfo.append("Status=");
        responseInfo.append(response.getStatus());
        responseInfo.append(", ");
        responseInfo.append("Version=");
        responseInfo.append(response.getProtocolVersion());

        for (String name : response.headers().names()) {
            for (String value : response.headers().getAll(name)) {
                responseInfo.append(", ");
                responseInfo.append(name);
                responseInfo.append('=');
                responseInfo.append(value);
            }/*from   w ww .  j a  v  a 2 s .c  om*/
        }

        LOGGER.debug(responseInfo.toString());
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        SettableFuture<XmlPushResponse> responseFuture = ctx.channel().attr(responseAttributeKey).get();

        // The default charset for HTTP is ISO-8859-1. None
        // of the Cisco phones I've seen to date were actually
        // setting the charset so use the default. We could
        // improve here by checking the header for the value.
        String xmlContent = content.content().toString(CharsetUtil.ISO_8859_1);

        CiscoIPPhoneResponse xmlResponse = XmlMarshaller.unmarshal(xmlContent, CiscoIPPhoneResponse.class);
        responseFuture.set(new DefaultXmlPushResponse(phone, xmlResponse));

        // Cleanup:
        ctx.close();
        ctx.channel().close();
    }
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Writes response metadata to the channel if not already written previously and channel is active.
 * @param responseMetadata the {@link HttpResponse} that needs to be written.
 * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
 * @return {@code true} if response metadata was written to the channel in this call. {@code false} otherwise.
 *//*  www . j av a2  s. c o m*/
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
        GenericFutureListener<ChannelFuture> listener) {
    long writeProcessingStartTime = System.currentTimeMillis();
    boolean writtenThisTime = false;
    if (responseMetadataWriteInitiated.compareAndSet(false, true) && ctx.channel().isActive()) {
        // we do some manipulation here for chunking. According to the HTTP spec, we can have either a Content-Length
        // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not there, we add
        // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just explicitly specifying
        // this in the header.
        if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
            // This makes sure that we don't stomp on any existing transfer-encoding.
            HttpHeaders.setTransferEncodingChunked(responseMetadata);
        } else if (HttpHeaders.getContentLength(responseMetadata) == 0
                && !(responseMetadata instanceof FullHttpResponse)) {
            // if the Content-Length is 0, we can send a FullHttpResponse since there is no content expected.
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    responseMetadata.getStatus());
            fullHttpResponse.headers().set(responseMetadata.headers());
            responseMetadata = fullHttpResponse;
        }
        logger.trace("Sending response with status {} on channel {}", responseMetadata.getStatus(),
                ctx.channel());
        finalResponseMetadata = responseMetadata;
        ChannelPromise writePromise = ctx.newPromise().addListener(listener);
        ctx.writeAndFlush(responseMetadata, writePromise);
        writtenThisTime = true;
        long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
        nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
    }
    return writtenThisTime;
}

From source file:com.bloom.zerofs.rest.PublicAccessLogHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    long startTimeInMs = System.currentTimeMillis();
    boolean shouldReset = msg instanceof LastHttpContent;
    if (request != null) {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            logHeaders("Response", response, publicAccessLogger.getResponseHeaders());
            logMessage.append(", ");
            logMessage.append("status=").append(response.getStatus().code());
            logMessage.append(", ");
            if (HttpHeaders.isTransferEncodingChunked(response)) {
                responseFirstChunkStartTimeInMs = System.currentTimeMillis();
            } else {
                shouldReset = true;// w w w  .  j  a  va 2s. c  o  m
            }
        } else if (!(msg instanceof HttpContent)) {
            logger.error(
                    "Sending response that is not of type HttpResponse or HttpContent. Sending response to "
                            + ctx.channel().remoteAddress() + ". Request is of type " + msg.getClass()
                            + ". No action being taken other than logging this unexpected state.");
        }
        if (shouldReset) {
            logDurations();
            publicAccessLogger.logInfo(logMessage.toString());
            reset();
        }
    }
    nettyMetrics.publicAccessLogResponseProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
    super.write(ctx, msg, promise);
}

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

License:Open Source License

@Nonnull
@Override/*  w w w  .  j  a v a 2s .  co  m*/
public HttpResponse apply(@Nonnull HttpRequest req, @Nonnull HttpResponse res) {
    Objects.requireNonNull(req);
    Objects.requireNonNull(res);
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(content.length);
    buffer.writeBytes(content);
    HttpResponse r = new DefaultFullHttpResponse(res.getProtocolVersion(), res.getStatus(), buffer);
    for (Map.Entry<String, String> entry : res.headers()) {
        r.headers().add(entry.getKey(), entry.getValue());
    }
    r.headers().remove(CONTENT_LENGTH);
    r.headers().add(CONTENT_LENGTH, content.length);
    return r;
}

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

License:Open Source License

@Test
public void testApplyResponse() throws Exception {
    int code = 404;

    StatusCodeAction action = new StatusCodeAction(code);
    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());/*w w w.  j a  v a2 s .co  m*/
    assertThat(out.getStatus().code(), is(code));
}

From source file:com.couchbase.client.core.endpoint.config.ConfigHandler.java

License:Apache License

/**
 * Decodes a {@link BucketStreamingResponse}.
 *
 * @param ctx the handler context./*from   ww  w. j av a 2 s .c o  m*/
 * @param header the received header.
 * @return a initialized {@link CouchbaseResponse}.
 */
private CouchbaseResponse handleBucketStreamingResponse(final ChannelHandlerContext ctx,
        final HttpResponse header) {
    SocketAddress addr = ctx.channel().remoteAddress();
    String host = addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getHostName()
            : addr.toString();
    ResponseStatus status = ResponseStatusConverter.fromHttp(header.getStatus().code());

    Observable<String> scheduledObservable = null;
    if (status.isSuccess()) {
        streamingConfigObservable = BehaviorSubject.create();
        scheduledObservable = streamingConfigObservable.onBackpressureBuffer().observeOn(env().scheduler());
    }
    return new BucketStreamingResponse(scheduledObservable, host, status, currentRequest());
}

From source file:com.couchbase.client.io.QueryDecoder.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {
        currentEvent = queue.poll();//from ww w  .  j  a  va  2s.  c o m
        HttpResponse response = (HttpResponse) msg;
        if (response.getStatus().code() != 200) {
            setCurrentEventStatus(false, response.getStatus().toString());
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        contentBuffer.append(content.content().toString(CharsetUtil.UTF_8));

        if (msg instanceof LastHttpContent) {
            QueryResult result = decodeContentBuffer();
            setCurrentEventStatus(true, "Success");
            currentEvent.getFuture().set(result, currentStatus);
            currentEvent.getLatch().countDown();
            clearForNextEvent();
        }
    }
}

From source file:com.digisky.innerproxy.testclient.HttpSnoopClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    TestTimer.add("channelRead0()::37");
    TestTimer.print();//ww w. ja v a  2 s . c om
    System.out.println("http CLient received a package!");
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());
        System.err.println();

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
            System.err.println();
        }

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.err.print(content.content().toString(CharsetUtil.UTF_8));
        System.err.flush();

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }

}