java类io.netty.handler.codec.http.HttpObject的实例源码

MockingFCMServerHandler.java 文件源码 项目:push-network-proxies 阅读 29 收藏 0 点赞 0 评论 0
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
        HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
        Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json");

    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);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
Http2FrontendHandler.java 文件源码 项目:nitmproxy 阅读 24 收藏 0 点赞 0 评论 0
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOGGER.info("[Client ({})] => [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);

    if (msg instanceof FullHttpRequest) {
        String streamId = ((HttpRequest) msg).headers().get(
                HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        if (streamId == null) {
            throw new IllegalStateException("No streamId");
        }
        streams.offer(streamId);
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handle message: " + msg.getClass());
    }

    outboundChannel.writeAndFlush(msg);
}
NettyRequestProxyFilter.java 文件源码 项目:ServiceCOLDCache 阅读 22 收藏 0 点赞 0 评论 0
private void debugRequestInfo(HttpObject httpObject, String key) {
    if (m_debugInfo && httpObject instanceof HttpRequest) {
        if (key != null) {
            LOGGER.debug("Cache Key: " + key);
        }
        if (httpObject instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest) httpObject;
            HttpHeaders headers = req.headers();
            LOGGER.debug("Headers:");
            for (Iterator<Entry<String, String>> it = headers.iterator(); it
                    .hasNext();) {
                Entry<String, String> entry = it.next();
                LOGGER.debug("\t" + entry.getKey() + ":\t"
                        + entry.getValue());
            }
            ByteBuf content = req.content();
            int length = content.readableBytes();
            LOGGER.debug("Content Length: " + length);
            if (length != 0) {
                LOGGER.debug("Content: "
                        + content.toString(Charset.forName("UTF-8")));
            }
        }
    }
}
HttpSnoopClientHandler.java 文件源码 项目:ServiceCOLDCache 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
        throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        LOGGER.info("Response status: " + response.getStatus());
        if (response.getStatus().equals(OK)) {
            LOGGER.info("Operation is successful");
        } else {
            LOGGER.error("Operation is failed");
        }
    }

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

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

    }

}
RequestInfoSetterHandlerTest.java 文件源码 项目:riposte 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void doChannelRead_checks_for_fully_send_responses_but_does_nothing_else_if_msg_is_not_HttpRequest_or_HttpContent() {
    // given
    HttpObject msgMock = mock(HttpObject.class);

    // when
    PipelineContinuationBehavior result = handler.doChannelRead(ctxMock, msgMock);

    // then
    verify(ctxMock).channel();
    verifyNoMoreInteractions(ctxMock);
    verify(stateMock).isResponseSendingLastChunkSent();
    verifyNoMoreInteractions(stateMock);
    verifyNoMoreInteractions(msgMock);
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
RoutingHandlerTest.java 文件源码 项目:riposte 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void doChannelRead_does_nothing_if_msg_is_not_HttpRequest() {
    // given
    String pathTemplate = "/some/path/with/{id}";
    Collection<String> pathTemplates = new ArrayList<String>() {{ add(pathTemplate); }};
    doReturn(pathTemplates).when(matcherMock).matchingPathTemplates();
    HttpObject msg = mock(HttpObject.class);

    // when
    PipelineContinuationBehavior result = handlerSpy.doChannelRead(ctxMock, msg);

    // then
    verify(handlerSpy).doChannelRead(ctxMock, msg);
    verifyNoMoreInteractions(handlerSpy);
    verifyNoMoreInteractions(requestInfoMock);
    verifyNoMoreInteractions(stateMock);
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
ComponentTestUtils.java 文件源码 项目:riposte 阅读 26 收藏 0 点赞 0 评论 0
public static Bootstrap createNettyHttpClientBootstrap() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup())
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     p.addLast(new HttpClientCodec());
                     p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                     p.addLast("clientResponseHandler", new SimpleChannelInboundHandler<HttpObject>() {
                         @Override
                         protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                             throw new RuntimeException("Client response handler was not setup before the call");
                         }
                     });
                 }
             });

    return bootstrap;
}
ComponentTestUtils.java 文件源码 项目:riposte 阅读 35 收藏 0 点赞 0 评论 0
public static CompletableFuture<NettyHttpClientResponse> setupNettyHttpClientResponseHandler(
    Channel ch, Consumer<ChannelPipeline> pipelineAdjuster
) {
    CompletableFuture<NettyHttpClientResponse> responseFromServerFuture = new CompletableFuture<>();
    ch.pipeline().replace("clientResponseHandler", "clientResponseHandler", new SimpleChannelInboundHandler<HttpObject>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
            throws Exception {
            if (msg instanceof FullHttpResponse) {
                // Store the proxyServer response for asserting on later.
                responseFromServerFuture.complete(new NettyHttpClientResponse((FullHttpResponse) msg));
            } else {
                // Should never happen.
                throw new RuntimeException("Received unexpected message type: " + msg.getClass());
            }
        }
    });

    if (pipelineAdjuster != null)
        pipelineAdjuster.accept(ch.pipeline());

    return responseFromServerFuture;
}
ClientRequestCaptureFilter.java 文件源码 项目:Dream-Catcher 阅读 27 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        this.httpRequest = (HttpRequest) httpObject;
    }

    if (httpObject instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) httpObject;

        storeRequestContent(httpContent);

        if (httpContent instanceof LastHttpContent) {
            LastHttpContent lastHttpContent = (LastHttpContent) httpContent;
            trailingHeaders = lastHttpContent .trailingHeaders();
        }
    }

    return null;
}
HttpsHostCaptureFilter.java 文件源码 项目:Dream-Catcher 阅读 28 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        if (ProxyUtils.isCONNECT(httpRequest)) {
            Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME));
            String hostAndPort = httpRequest.getUri();

            // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
            // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
            // would be unexpected.
            String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443);
            hostname.set(hostNoDefaultPort);
        }
    }

    return null;
}
BrowserMobHttpFilterChain.java 文件源码 项目:Dream-Catcher 阅读 25 收藏 0 点赞 0 评论 0
@Override
public HttpObject serverToProxyResponse(HttpObject httpObject) {
    HttpObject processedHttpObject = httpObject;

    for (HttpFilters filter : filters) {
        try {
            processedHttpObject = filter.serverToProxyResponse(processedHttpObject);
            if (processedHttpObject == null) {
                return null;
            }
        } catch (RuntimeException e) {
            log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e);
        }
    }

    return processedHttpObject;
}
BrowserMobHttpFilterChain.java 文件源码 项目:Dream-Catcher 阅读 32 收藏 0 点赞 0 评论 0
@Override
public HttpObject proxyToClientResponse(HttpObject httpObject) {
    HttpObject processedHttpObject = httpObject;
    for (HttpFilters filter : filters) {
        try {
            processedHttpObject = filter.proxyToClientResponse(processedHttpObject);
            if (processedHttpObject == null) {
                return null;
            }
        } catch (RuntimeException e) {
            log.warn("Filter in filter chain threw exception. Filter method may have been aborted.", e);
        }
    }

    return processedHttpObject;
}
BlacklistFilter.java 文件源码 项目:Dream-Catcher 阅读 25 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        String url = getFullUrl(httpRequest);

        for (BlacklistEntry entry : blacklistedUrls) {
            if (HttpMethod.CONNECT.equals(httpRequest.getMethod()) && entry.getHttpMethodPattern() == null) {
                // do not allow CONNECTs to be blacklisted unless a method pattern is explicitly specified
                continue;
            }

            if (entry.matches(url, httpRequest.getMethod().name())) {
                HttpResponseStatus status = HttpResponseStatus.valueOf(entry.getStatusCode());
                HttpResponse resp = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), status);
                HttpHeaders.setContentLength(resp, 0L);

                return resp;
            }
        }
    }

    return null;
}
AutoBasicAuthFilter.java 文件源码 项目:Dream-Catcher 阅读 26 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (credentialsByHostname.isEmpty()) {
        return null;
    }

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        // providing authorization during a CONNECT is generally not useful
        if (ProxyUtils.isCONNECT(httpRequest)) {
            return null;
        }

        String hostname = getHost(httpRequest);

        // if there is an entry in the credentials map matching this hostname, add the credentials to the request
        String base64CredentialsForHostname = credentialsByHostname.get(hostname);
        if (base64CredentialsForHostname != null) {
            httpRequest.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + base64CredentialsForHostname);
        }
    }

    return null;
}
DefaultProxyBase.java 文件源码 项目:vector 阅读 25 收藏 0 点赞 0 评论 0
@Override
@SuppressWarnings("unchecked")
public void start() {
    List<Handler<HttpObject>> httpHandlerList = (List<Handler<HttpObject>>) getHandlerList();
    DefaultHttpProxyServer.bootstrap()
            .withPort(port).withFiltersSource(new HttpFiltersSourceAdapter() {
        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    httpHandlerList.forEach(httpObjectHandler -> httpObjectHandler.client2Proxy(httpObject));
                    return null;
                }
            };
        }
    }).start();
}
ClientChannelHandler.java 文件源码 项目:flashback 阅读 27 收藏 0 点赞 0 评论 0
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject)
    throws Exception {
  // initial request
  if (LOG.isDebugEnabled()) {
    LOG.debug(String.format("%s: Reading from client %s", System.currentTimeMillis(), httpObject));
  }
  if (httpObject instanceof HttpRequest) {
    HttpRequest initialRequest = (HttpRequest) httpObject;
    if (_channelHandlerDelegate == null) {
      _channelHandlerDelegate =
          HandlerDelegateFactory.create(initialRequest, _channelMediator, _connectionFlowRegistry);
      _channelHandlerDelegate.onCreate();
    }
  }
  _channelHandlerDelegate.onRead(httpObject);
}
NettyClient_NoHttps.java 文件源码 项目:little_mitm 阅读 29 收藏 0 点赞 0 评论 0
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
        throws Exception {
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        RandomAccessFile output = null;
        FileChannel oc = null;
        try {
            output = new RandomAccessFile(file, "rw");
            oc = output.getChannel();
            oc.position(oc.size());
            ByteBuf buffer = content.content();
            for (int i = 0, len = buffer.nioBufferCount(); i < len; i++) {
                oc.write(buffer.nioBuffers()[i]);
            }
        } finally {
            IOUtils.closeQuietly(oc);
            IOUtils.closeQuietly(output);
        }
        if (content instanceof LastHttpContent) {
            ctx.close();
        }
    }
}
DirectRequestTest.java 文件源码 项目:little_mitm 阅读 23 收藏 0 点赞 0 评论 0
private void startProxyServerWithFilterAnsweringStatusCode(int statusCode) {
    final HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode);
    HttpFiltersSource filtersSource = new HttpFiltersSourceAdapter() {
        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    return new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
                }
            };
        }
    };

    proxyServer = DefaultHttpProxyServer.bootstrap()
            .withPort(0)
            .withFiltersSource(filtersSource)
            .start();
}
RecordController.java 文件源码 项目:flashback 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void handleReadFromClient(ChannelMediator channelMediator, HttpObject httpObject) {
  if (channelMediator == null) {
    throw new IllegalStateException("HRFC: ChannelMediator can't be null");
  }

  try {
    if (httpObject instanceof HttpRequest) {
      HttpRequest httpRequest = (HttpRequest) httpObject;
      _clientRequestBuilder.interpretHttpRequest(httpRequest);
      _clientRequestBuilder.addHeaders(httpRequest);
    }

    if (httpObject instanceof HttpContent) {
      _clientRequestBuilder.appendHttpContent((HttpContent) httpObject);
    }
  } catch (IOException e) {
    throw new RuntimeException("HRFC: Failed to record HttpContent", e);
  }

  channelMediator.writeToServer(httpObject);
}
HttpChannelHandlerDelegate.java 文件源码 项目:flashback 阅读 24 收藏 0 点赞 0 评论 0
@Override
public void onRead(HttpObject httpObject) {
  if (!_connectionFlowProcessor.isComplete()) {
    _channelReadCallback.write(httpObject);
    // Accroding to http://netty.io/wiki/reference-counted-objects.html
    // When an event loop reads data into a ByteBuf and triggers a channelRead() event with it,
    // it is the responsibility of the ChannelHandler in the corresponding pipeline to release the buffer.
    // Since this is the last ChannelHandler, it release the reference-counted after read. So we need to
    // retain to make sure it will not be released until we stored in scene.
    if(httpObject instanceof HttpContent){
      ((HttpContent)httpObject).retain();
    }
    return;
  }
  _channelMediator.readFromClientChannel(httpObject);
}
ProxyServerFilter.java 文件源码 项目:proxy-server 阅读 24 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        System.err.println("--->" + ((HttpRequest) httpObject).getUri());
    }

    return super.clientToProxyRequest(httpObject);
}
NettyHttpClient.java 文件源码 项目:GitHub 阅读 34 收藏 0 点赞 0 评论 0
@Override protected void channelRead0(
    ChannelHandlerContext context, HttpObject message) throws Exception {
  if (message instanceof HttpResponse) {
    receive((HttpResponse) message);
  }
  if (message instanceof HttpContent) {
    receive((HttpContent) message);
    if (message instanceof LastHttpContent) {
      release(this);
    }
  }
}
NettyHttpClient.java 文件源码 项目:GitHub 阅读 42 收藏 0 点赞 0 评论 0
@Override protected void channelRead0(
    ChannelHandlerContext context, HttpObject message) throws Exception {
  if (message instanceof HttpResponse) {
    receive((HttpResponse) message);
  }
  if (message instanceof HttpContent) {
    receive((HttpContent) message);
    if (message instanceof LastHttpContent) {
      release(this);
    }
  }
}
MockingFCMProxyServer.java 文件源码 项目:push-network-proxies 阅读 30 收藏 0 点赞 0 评论 0
public HttpProxyServer start() {

        return DefaultHttpProxyServer.bootstrap()
            .withAddress(new InetSocketAddress(host, port))
            .withFiltersSource(new HttpFiltersSourceAdapter() {

                @Override
                public HttpFilters filterRequest(HttpRequest originalRequest) {

                    return new HttpFiltersAdapter(originalRequest) {

                        final String mockedAddress = mockServer + ":" + mockPort;

                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                            final HttpRequest request = (HttpRequest) httpObject;

                            if (request.getUri().contains("google")) {
                                request.setUri(mockedAddress);
                            }

                            super.clientToProxyRequest(request);

                            return null;
                        }
                    };
                }
            }).start();
    }
Http1BackendHandler.java 文件源码 项目:nitmproxy 阅读 23 收藏 0 点赞 0 评论 0
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject)
        throws Exception {
    LOGGER.info("[Client ({})] <= [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                httpObject);

    outboundChannel.writeAndFlush(ReferenceCountUtil.retain(httpObject));

    if (httpObject instanceof HttpResponse) {
        currentRequest = null;
        delayOutboundHandler.next();
    }
}
Http1BackendHandler.java 文件源码 项目:nitmproxy 阅读 26 收藏 0 点赞 0 评论 0
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof FullHttpRequest) {
        LOGGER.info("[Client ({})] => [Server ({})] : (PENDING) {}",
                    connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                    msg);
        HttpRequest request = (HttpRequest) msg;
        pendings.offer(new RequestPromise(request, promise));
        next();
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handled message: " + msg.getClass());
    } else {
        ctx.write(msg, promise);
    }
}
Http2BackendHandler.java 文件源码 项目:nitmproxy 阅读 24 收藏 0 点赞 0 评论 0
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    LOGGER.info("[Client ({})] => [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);
    if (msg instanceof FullHttpRequest) {
        HttpMessage httpMessage = (HttpRequest) msg;
        httpMessage.headers().add(ExtensionHeaderNames.SCHEME.text(), "https");
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handle message: " + msg.getClass());
    }

    ctx.writeAndFlush(msg, promise);
}
ProxyServerFilter.java 文件源码 项目:proxy-server 阅读 26 收藏 0 点赞 0 评论 0
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        System.err.println("--->" + ((HttpRequest) httpObject).getUri());
    }

    return super.clientToProxyRequest(httpObject);
}
DebugClientHandler.java 文件源码 项目:ServiceCOLDCache 阅读 25 收藏 0 点赞 0 评论 0
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (LOGGER.isDebugEnabled()) {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            LOGGER.debug("STATUS: " + response.getStatus());
            LOGGER.debug("VERSION: " + response.getProtocolVersion());
            if (!response.headers().isEmpty()) {
                for (String name : response.headers().names()) {
                    for (String value : response.headers().getAll(name)) {
                        LOGGER.debug("HEADER: " + name + " = " + value);
                    }
                }
            }
            if (HttpHeaders.isTransferEncodingChunked(response)) {
                LOGGER.debug("CHUNKED CONTENT {");
            } else {
                LOGGER.debug("CONTENT {");
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            LOGGER.debug(content.content().toString(CharsetUtil.UTF_8));
            if (content instanceof LastHttpContent) {
                LOGGER.debug("} END OF CONTENT");
            }
        }
    }
}
DebugHttpFilter.java 文件源码 项目:ServiceCOLDCache 阅读 26 收藏 0 点赞 0 评论 0
@Override
public HttpObject serverToProxyResponse(HttpObject httpObject) {
    if (httpObject instanceof FullHttpResponse) {
        m_debugManager.debugResponse((FullHttpResponse) httpObject, this.m_ctx);
    }
    return httpObject;
}


问题


面经


文章

微信
公众号

扫码关注公众号