Search in sources :

Example 11 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project openzaly by akaxincom.

the class HttpServerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        /**
         * http-request包含: <br>
         * 1.请求行 ,Method Request-URI Http-Version CRLF<br>
         * 2.消息头 <br>
         * 3.请求正文 <br>
         */
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
            if (!checkLegalRequest()) {
                logger.error("{} http request method error. please use post!", AkxProject.PLN);
                ctx.close();
                return;
            }
            String clientIp = request.headers().get(HttpConst.HTTP_H_FORWARDED);
            if (clientIp == null) {
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                clientIp = address.getAddress().getHostAddress();
            }
            if (!checkLegalClientIp(clientIp)) {
                logger.error("{} http request illegal IP={}.", AkxProject.PLN, clientIp);
                ctx.close();
                return;
            }
            logger.debug("{} request uri:{} clientIp={}", AkxProject.PLN, request.uri(), clientIp);
        }
        /**
         * HttpContent:表示HTTP实体正文和内容标头的基类 <br>
         * method.name=POST 传输消息体存在内容
         */
        if (msg instanceof LastHttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf httpByteBuf = content.content();
            if (httpByteBuf == null) {
                return;
            }
            if (!checkLegalRequest()) {
                ctx.close();
                return;
            }
            String clientIp = request.headers().get(HttpConst.HTTP_H_FORWARDED);
            String sitePluginId = request.headers().get(PluginConst.SITE_PLUGIN_ID);
            byte[] contentBytes = new byte[httpByteBuf.readableBytes()];
            httpByteBuf.readBytes(contentBytes);
            httpByteBuf.release();
            // 查询扩展的auth——key
            String authKey = PluginSession.getInstance().getPluginAuthKey(sitePluginId);
            if (StringUtils.isNotEmpty(authKey)) {
                // byte[] tsk = AESCrypto.generateTSKey(authKey);
                byte[] tsk = authKey.getBytes(CharsetCoding.ISO_8859_1);
                byte[] decContent = AESCrypto.decrypt(tsk, contentBytes);
                contentBytes = decContent;
            }
            PluginProto.ProxyPluginPackage pluginPackage = PluginProto.ProxyPluginPackage.parseFrom(contentBytes);
            Map<Integer, String> proxyHeader = pluginPackage.getPluginHeaderMap();
            String requestTime = proxyHeader.get(PluginProto.PluginHeaderKey.PLUGIN_TIMESTAMP_VALUE);
            long currentTime = System.currentTimeMillis();
            boolean timeOut = true;
            if (StringUtils.isNotEmpty(requestTime)) {
                long timeMills = Long.valueOf(requestTime);
                if (currentTime - timeMills < 10 * 1000l) {
                    timeOut = false;
                }
            }
            logger.debug("{} client={} http request timeOut={} currTime={} reqTime={}", AkxProject.PLN, clientIp, timeOut, currentTime, requestTime);
            if (!timeOut) {
                Command command = new Command();
                command.setField(PluginConst.PLUGIN_AUTH_KEY, authKey);
                if (proxyHeader != null) {
                    command.setSiteUserId(proxyHeader.get(PluginProto.PluginHeaderKey.CLIENT_SITE_USER_ID_VALUE));
                }
                command.setChannelContext(ctx);
                command.setUri(request.uri());
                command.setParams(Base64.getDecoder().decode(pluginPackage.getData()));
                command.setClientIp(clientIp);
                command.setStartTime(System.currentTimeMillis());
                logger.debug("{} client={} http server handler command={}", AkxProject.PLN, clientIp, command.toString());
                CommandResponse response = this.executor.execute(HttpUriAction.HTTP_ACTION.getUri(), command);
                LogUtils.requestResultLog(logger, command, response);
            } else {
                // 超时10s,认为此请求失效,直接断开连接
                ctx.close();
                logger.error("{} client={} http request error.timeOut={} currTime={} reqTime={}", AkxProject.PLN, clientIp, timeOut, currentTime, requestTime);
            }
        }
    } catch (Exception e) {
        ctx.close();
        logger.error(StringHelper.format("{} http request error.", AkxProject.PLN), e);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) InetSocketAddress(java.net.InetSocketAddress) PluginProto(com.akaxin.proto.core.PluginProto) CommandResponse(com.akaxin.common.command.CommandResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) Command(com.akaxin.common.command.Command) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 12 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project async-http-client by AsyncHttpClient.

the class AsyncHttpClientHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);
    try {
        if (attribute instanceof OnLastHttpContentCallback) {
            if (msg instanceof LastHttpContent) {
                ((OnLastHttpContentCallback) attribute).call();
            }
        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            future.touch();
            handleRead(channel, future, msg);
        } else if (attribute instanceof StreamedResponsePublisher) {
            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;
            publisher.future().touch();
            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.isReadable()) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content, false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.DISCARD) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute, msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : Channel(io.netty.channel.Channel) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart)

Example 13 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForMultiSubscribeRequestOnlyOneToSource.

@Test
public final void testTradeForMultiSubscribeRequestOnlyOneToSource() {
    final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    // trade.inboundHolder().setMaxBlockSize(-1);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber1 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber1);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber2 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber2);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber3 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber3);
    writeToInboundAndFlush(channel, request);
    writeToInboundAndFlush(channel, req_contents[0]);
    reqSubscriber1.assertValueCount(2);
    reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber2.assertValueCount(2);
    reqSubscriber2.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber3.assertValueCount(2);
    reqSubscriber3.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DisposableWrapper(org.jocean.idiom.DisposableWrapper) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) TestSubscriber(rx.observers.TestSubscriber) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Example 14 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForRequestAndContentsSourceAndDumpFullRequests.

@Test
public final void testTradeForRequestAndContentsSourceAndDumpFullRequests() throws IOException {
    final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    Observable.<HttpObject>concat(Observable.<HttpObject>just(request), Observable.<HttpObject>from(req_contents), Observable.<HttpObject>just(LastHttpContent.EMPTY_LAST_CONTENT)).map(obj -> writeToInboundAndFlush(channel, obj)).last().toBlocking().single().syncUninterruptibly();
    callByteBufHolderBuilderOnceAndAssertDumpContentAndRefCnt(trade.inbound().compose(RxNettys.message2fullreq(trade)).toBlocking().single().unwrap(), REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    callByteBufHolderBuilderOnceAndAssertDumpContentAndRefCnt(trade.inbound().compose(RxNettys.message2fullreq(trade)).toBlocking().single().unwrap(), REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpObject(io.netty.handler.codec.http.HttpObject) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Example 15 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForMultiSubscribeRequestOnlyOneToSource2.

// 3 subscriber subscribe inbound request at different time,
// so push with different httpobject
@Test
public final void testTradeForMultiSubscribeRequestOnlyOneToSource2() {
    final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    // trade.inboundHolder().setMaxBlockSize(-1);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber1 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber1);
    writeToInboundAndFlush(channel, request);
    reqSubscriber1.assertValueCount(1);
    reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request));
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber2 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber2);
    writeToInboundAndFlush(channel, req_contents[0]);
    reqSubscriber1.assertValueCount(2);
    reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber2.assertValueCount(2);
    reqSubscriber2.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber3 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber3);
    reqSubscriber1.assertValueCount(2);
    reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber2.assertValueCount(2);
    reqSubscriber2.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber3.assertValueCount(2);
    reqSubscriber3.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DisposableWrapper(org.jocean.idiom.DisposableWrapper) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) TestSubscriber(rx.observers.TestSubscriber) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Aggregations

HttpContent (io.netty.handler.codec.http.HttpContent)158 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)122 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)62 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)59 Test (org.junit.Test)59 ByteBuf (io.netty.buffer.ByteBuf)40 HttpResponse (io.netty.handler.codec.http.HttpResponse)37 HttpRequest (io.netty.handler.codec.http.HttpRequest)35 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)34 ArrayList (java.util.ArrayList)30 HttpObject (io.netty.handler.codec.http.HttpObject)28 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)24 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)20 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)17 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 Channel (io.netty.channel.Channel)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)15 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 IOException (java.io.IOException)13