Search in sources :

Example 16 with HttpContent

use of io.netty.handler.codec.http.HttpContent in project proxyee-down by monkeyWie.

the class HttpDownHandleInterceptFactory method create.

@Override
public HttpProxyIntercept create() {
    return new HttpProxyIntercept() {

        @Override
        public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception {
            HttpRequest httpRequest = pipeline.getHttpRequest();
            ProxyConfig proxyConfig = ContentManager.CONFIG.get().getSecProxyConfig();
            TaskInfo taskInfo = HttpDownUtil.getTaskInfo(httpRequest, httpResponse.headers(), proxyConfig, HttpDownConstant.clientSslContext, HttpDownConstant.clientLoopGroup);
            HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest, proxyConfig);
            ContentManager.DOWN.putBoot(httpDownInfo);
            httpResponse.setStatus(HttpResponseStatus.OK);
            httpResponse.headers().clear();
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
            byte[] content;
            if (HttpUtil.checkHead(httpRequest, HttpHeaderNames.HOST, "^.*\\.baidupcs\\.com.*$")) {
                content = "<script>window.close();</script>".getBytes();
            } else {
                content = "<script>window.history.go(-1);</script>".getBytes();
            }
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length);
            clientChannel.writeAndFlush(httpResponse);
            HttpContent httpContent = new DefaultLastHttpContent();
            httpContent.content().writeBytes(content);
            clientChannel.writeAndFlush(httpContent);
            clientChannel.close();
            httpDownDispatch.dispatch(httpDownInfo);
        }
    };
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) TaskInfo(lee.study.down.model.TaskInfo) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpProxyIntercept(lee.study.proxyee.intercept.HttpProxyIntercept) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) HttpDownInfo(lee.study.down.model.HttpDownInfo) HttpProxyInterceptPipeline(lee.study.proxyee.intercept.HttpProxyInterceptPipeline) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 17 with HttpContent

use of io.netty.handler.codec.http.HttpContent in project ambry by linkedin.

the class NettyMultipartRequest method readInto.

/**
 * {@inheritDoc}
 * @param asyncWritableChannel the {@link AsyncWritableChannel} to read the data into.
 * @param callback the {@link Callback} that will be invoked either when all the data in the channel has been emptied
 *                 into the {@code asyncWritableChannel} or if there is an exception in doing so. This can be null.
 * @return the {@link Future} that will eventually contain the result of the operation.
 * @throws IllegalStateException if an attempt is made to read the channel before calling {@link #prepare()} or if
 *                                this function is called more than once.
 */
@Override
public Future<Long> readInto(AsyncWritableChannel asyncWritableChannel, Callback<Long> callback) {
    if (callbackWrapper != null) {
        throw new IllegalStateException("ReadableStreamChannel cannot be read more than once");
    } else if (!readyForRead) {
        throw new IllegalStateException("The channel cannot be read yet");
    }
    callbackWrapper = new ReadIntoCallbackWrapper(callback);
    if (!isOpen()) {
        nettyMetrics.multipartRequestAlreadyClosedError.inc();
        callbackWrapper.invokeCallback(new ClosedChannelException());
    }
    HttpContent content = requestContents.poll();
    while (content != null) {
        try {
            writeContent(asyncWritableChannel, callbackWrapper, content);
        } finally {
            ReferenceCountUtil.release(content);
        }
        content = requestContents.poll();
    }
    return callbackWrapper.futureResult;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent)

Example 18 with HttpContent

use of io.netty.handler.codec.http.HttpContent in project ambry by linkedin.

the class NettyRequest method readInto.

@Override
public Future<Long> readInto(AsyncWritableChannel asyncWritableChannel, Callback<Long> callback) {
    ReadIntoCallbackWrapper tempWrapper = new ReadIntoCallbackWrapper(callback);
    contentLock.lock();
    try {
        if (!isOpen()) {
            nettyMetrics.requestAlreadyClosedError.inc();
            tempWrapper.invokeCallback(new ClosedChannelException());
        } else if (writeChannel != null) {
            throw new IllegalStateException("ReadableStreamChannel cannot be read more than once");
        }
        HttpContent content = requestContents.poll();
        while (content != null) {
            try {
                writeContent(asyncWritableChannel, tempWrapper, content);
            } finally {
                ReferenceCountUtil.release(content);
            }
            content = requestContents.poll();
        }
        callbackWrapper = tempWrapper;
        writeChannel = asyncWritableChannel;
    } finally {
        contentLock.unlock();
    }
    return tempWrapper.futureResult;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 19 with HttpContent

use of io.netty.handler.codec.http.HttpContent in project ambry by linkedin.

the class PublicAccessLogHandler method write.

@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.status().code());
            logMessage.append(", ");
            if (HttpUtil.isTransferEncodingChunked(response)) {
                responseFirstChunkStartTimeInMs = System.currentTimeMillis();
            } else {
                shouldReset = true;
            }
        } 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);
}
Also used : HttpResponse(io.netty.handler.codec.http.HttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Example 20 with HttpContent

use of io.netty.handler.codec.http.HttpContent in project ambry by linkedin.

the class NettyMessageProcessorTest method sendRequestCheckResponse.

/**
 * Sends the provided {@code httpRequest} and verifies that the response is an echo of the {@code restMethod}.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param restMethod the equivalent {@link RestMethod} for {@code httpMethod}. Used to check for correctness of
 *                   response.
 * @param isKeepAlive if the request needs to be keep-alive.
 * @throws IOException
 */
private void sendRequestCheckResponse(EmbeddedChannel channel, HttpMethod httpMethod, RestMethod restMethod, boolean isKeepAlive) throws IOException {
    long requestId = REQUEST_ID_GENERATOR.getAndIncrement();
    String uri = MockBlobStorageService.ECHO_REST_METHOD + requestId;
    HttpRequest httpRequest = RestTestUtils.createRequest(httpMethod, uri, null);
    HttpUtil.setKeepAlive(httpRequest, isKeepAlive);
    channel.writeInbound(httpRequest);
    channel.writeInbound(new DefaultLastHttpContent());
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
    // MockBlobStorageService echoes the RestMethod + request id.
    String expectedResponse = restMethod.toString() + requestId;
    assertEquals("Unexpected content", expectedResponse, RestTestUtils.getContentString((HttpContent) channel.readOutbound()));
    assertTrue("End marker was expected", channel.readOutbound() instanceof LastHttpContent);
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Aggregations

HttpContent (io.netty.handler.codec.http.HttpContent)146 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)110 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)56 Test (org.junit.Test)55 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)54 ByteBuf (io.netty.buffer.ByteBuf)39 HttpRequest (io.netty.handler.codec.http.HttpRequest)32 HttpResponse (io.netty.handler.codec.http.HttpResponse)30 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)29 ArrayList (java.util.ArrayList)29 HttpObject (io.netty.handler.codec.http.HttpObject)25 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)20 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 Channel (io.netty.channel.Channel)16 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)16 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 IOException (java.io.IOException)13 ByteBufferAsyncWritableChannel (com.github.ambry.commons.ByteBufferAsyncWritableChannel)10