Java 类io.netty.handler.codec.http.HttpVersion 实例源码

项目:xrpc    文件:Recipes.java   
/**
 * Returns a full HTTP response with the specified status, content type, and custom headers.
 *
 * <p>Headers should be specified as a map of strings. For example, to allow CORS, add the
 * following key and value: "access-control-allow-origin", "http://foo.example"
 *
 * <p>If content type or content length are passed in as custom headers, they will be ignored.
 * Instead, content type will be as specified by the parameter contentType and content length will
 * be the length of the parameter contentLength.
 */
public static FullHttpResponse newResponse(
    HttpResponseStatus status,
    ByteBuf payload,
    ContentType contentType,
    Map<String, String> customHeaders) {
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, payload);

  if (customHeaders != null) {
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
      response.headers().set(entry.getKey(), entry.getValue());
    }
  }

  response.headers().set(CONTENT_TYPE, contentType.value);
  response.headers().setInt(CONTENT_LENGTH, payload.readableBytes());

  return response;
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldHandlerRequestAndResponse() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    inboundChannel.write(req);

    assertEquals(1, inboundChannel.outboundMessages().size());

    Object outboundReq = inboundChannel.outboundMessages().poll();
    assertTrue(outboundReq instanceof ByteBuf);
    assertEquals("GET / HTTP/1.1\r\n\r\n", new String(readBytes((ByteBuf) outboundReq)));

    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    assertFalse(inboundChannel.writeInbound(resp));

    assertEquals(1, outboundChannel.outboundMessages().size());
    assertEquals(resp, outboundChannel.outboundMessages().poll());

    resp.release();
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldPendingRequests() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    // First request
    inboundChannel.write(req.retain());

    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);

    // Second request
    inboundChannel.write(req);

    // Should pending second request
    assertTrue(inboundChannel.outboundMessages().isEmpty());
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldClearPendingRequests() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    // First request
    inboundChannel.write(req.retain());

    assertEquals(1, req.refCnt());
    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);

    // Second request
    inboundChannel.write(req);

    assertEquals(1, req.refCnt());
    assertTrue(inboundChannel.outboundMessages().isEmpty());

    inboundChannel.close();

    assertEquals(0, req.refCnt());
}
项目:elasticsearch_my    文件:Netty4HttpChannelTests.java   
public void testReleaseOnSendToClosedChannel() {
    final Settings settings = Settings.builder().build();
    final NamedXContentRegistry registry = xContentRegistry();
    try (Netty4HttpServerTransport httpServerTransport =
                 new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, registry, new NullDispatcher())) {
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        final EmbeddedChannel embeddedChannel = new EmbeddedChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(registry, httpRequest, embeddedChannel);
        final HttpPipelinedRequest pipelinedRequest = randomBoolean() ? new HttpPipelinedRequest(request.request(), 1) : null;
        final Netty4HttpChannel channel =
                new Netty4HttpChannel(httpServerTransport, request, pipelinedRequest, randomBoolean(), threadPool.getThreadContext());
        final TestResponse response = new TestResponse(bigArrays);
        assertThat(response.content(), instanceOf(Releasable.class));
        embeddedChannel.close();
        channel.sendResponse(response);
        // ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released
    }
}
项目:elasticsearch_my    文件:Netty4HttpChannelTests.java   
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
    // construct request and send it over the transport layer
    try (Netty4HttpServerTransport httpServerTransport =
                 new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(),
                         new NullDispatcher())) {
        httpServerTransport.start();
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        if (originValue != null) {
            httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue);
        }
        httpRequest.headers().add(HttpHeaderNames.HOST, host);
        final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);

        Netty4HttpChannel channel =
                new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
        channel.sendResponse(new TestResponse());

        // get the response
        List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
        assertThat(writtenObjects.size(), is(1));
        return (FullHttpResponse) writtenObjects.get(0);
    }
}
项目:qonduit    文件:NonSslRedirectHandler.java   
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(Names.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
项目:qonduit    文件:BasicAuthLoginRequestHandlerTest.java   
@Test
public void testBasicAuthenticationFailure() throws Exception {
    Configuration config = TestConfiguration.createMinimalConfigurationForTest();

    BasicAuthLogin auth = new BasicAuthLogin();
    auth.setUsername("test");
    auth.setPassword("test2");
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
    request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth));

    TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Object result = results.iterator().next();
    Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass());

    BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config);
    CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext();
    handler.channelRead(ctx, result);
    Assert.assertNotNull(ctx.msg);
    Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse);
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg;
    Assert.assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
    Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE));
    Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE));
}
项目:ServiceCOLDCache    文件:NettyRequestProxyFilter.java   
protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
    String uri = req.getUri();
    if ("/version".equals(uri)) {
        if (HttpMethod.GET.equals(req.getMethod())) {
            JsonObject jsonObj = new JsonObject();
            jsonObj.addProperty("name", m_appConfig.getAppName());
            jsonObj.addProperty("version", m_appConfig.getAppVersion());
            byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
            DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(content));
            HttpHeaders.setKeepAlive(resp, false);
            HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE,
                    "application/json");
            HttpHeaders.setContentLength(resp, content.length);
            return resp;
        }
    }

    return RESPONSE_404;
}
项目:ServiceCOLDCache    文件:DebugClientHandlerTest.java   
@Test
public void testChannelRead0_debugOnResponse() {
    Mockito.when(LOGGER.isDebugEnabled()).thenReturn(true);
    Mockito.when(response.getStatus()).thenReturn(HttpResponseStatus.OK);
    Mockito.when(response.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
    Mockito.when(headers.isEmpty()).thenReturn(false);
    Set<String> headersSet = new HashSet<>();
    headersSet.add("no-cache");
    Mockito.when(headers.names()).thenReturn(headersSet);
    List<String> noCacheValues = new ArrayList<>();
    noCacheValues.add("private");
    Mockito.when(headers.getAll("no-cache")).thenReturn(noCacheValues);
    PowerMockito.mockStatic(HttpHeaders.class);
    BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(true);
    handler.channelRead0(ctx, response);
    Mockito.verify(LOGGER, Mockito.times(1)).debug("STATUS: " + HttpResponseStatus.OK);
    Mockito.verify(LOGGER, Mockito.times(1)).debug("VERSION: " + HttpVersion.HTTP_1_1);
    Mockito.verify(LOGGER, Mockito.times(1)).debug("HEADER: no-cache = private");
    Mockito.verify(LOGGER, Mockito.times(1)).debug("CHUNKED CONTENT {");


    BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(false);
    handler.channelRead0(ctx, response);
    Mockito.verify(LOGGER, Mockito.times(1)).debug("CONTENT {");
}
项目:java_learn    文件:WebSocketServerHandler.java   
private void handleHttpRequest(ChannelHandlerContext ctx,
        FullHttpRequest req) {
    if (!req.getDecoderResult().isSuccess()
            || (!"websocket".equals(req.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;
    }
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://localhost:7777/websocket", null, false);
    socketServerHandshaker = wsFactory.newHandshaker(req);
    if (socketServerHandshaker == null) {
        WebSocketServerHandshakerFactory
                .sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        socketServerHandshaker.handshake(ctx.channel(), req);
    }
}
项目:spring4-understanding    文件:Netty4ClientHttpRequest.java   
private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
    io.netty.handler.codec.http.HttpMethod nettyMethod =
            io.netty.handler.codec.http.HttpMethod.valueOf(this.method.name());

    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            nettyMethod, this.uri.toString(), this.body.buffer());

    nettyRequest.headers().set(HttpHeaders.HOST, uri.getHost());
    nettyRequest.headers().set(HttpHeaders.CONNECTION, io.netty.handler.codec.http.HttpHeaders.Values.CLOSE);

    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        nettyRequest.headers().add(entry.getKey(), entry.getValue());
    }

    return nettyRequest;
}
项目:little_mitm    文件:ClientToProxyConnection.java   
private void writeAuthenticationRequired(String realm) {
    String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n"
            + "<html><head>\n"
            + "<title>407 Proxy Authentication Required</title>\n"
            + "</head><body>\n"
            + "<h1>Proxy Authentication Required</h1>\n"
            + "<p>This server could not verify that you\n"
            + "are authorized to access the document\n"
            + "requested.  Either you supplied the wrong\n"
            + "credentials (e.g., bad password), or your\n"
            + "browser doesn't understand how to supply\n"
            + "the credentials required.</p>\n" + "</body></html>\n";
    DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1,
            HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED, body);
    HttpHeaders.setDate(response, new Date());
    response.headers().set("Proxy-Authenticate",
            "Basic realm=\"" + (realm == null ? "Restricted Files" : realm) + "\"");
    write(response);
}
项目:timely    文件:HttpSuggestRequestHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, SuggestRequest msg) throws Exception {
    byte[] buf = null;
    try {
        buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.suggest(msg));
    } catch (TimelyException e) {
        LOG.error(e.getMessage(), e);
        this.sendHttpError(ctx, e);
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
项目:timely    文件:HttpSearchLookupRequestHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, SearchLookupRequest msg) throws Exception {
    byte[] buf = null;
    try {
        buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.lookup(msg));
    } catch (TimelyException e) {
        LOG.error(e.getMessage(), e);
        this.sendHttpError(ctx, e);
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
项目:timely    文件:HttpQueryRequestHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, QueryRequest msg) throws Exception {
    byte[] buf;
    try {
        buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.query(msg));
    } catch (TimelyException e) {
        if (e.getMessage().contains("No matching tags")) {
            LOG.trace(e.getMessage());
        } else {
            LOG.error(e.getMessage(), e);
        }
        this.sendHttpError(ctx, e);
        return;
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(buf));
    response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
项目:timely    文件:NonSslRedirectHandler.java   
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(Names.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
项目:timely    文件:HttpRequestDecoderTest.java   
@Test
public void testLookupPostWithNoLimit() throws Exception {
    // @formatter:off
    String content = 
    "{\n" +
    "    \"metric\": \"sys.cpu.user\"\n" + 
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/search/lookup");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
    SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
    Assert.assertEquals("sys.cpu.user", lookup.getQuery());
    Assert.assertEquals(25, lookup.getLimit());
    Assert.assertEquals(0, lookup.getTags().size());
}
项目:timely    文件:HttpRequestDecoderTest.java   
@Test
public void testLookupPostWithLimit() throws Exception {
    // @formatter:off
    String content = 
    "{\n" +
    "    \"metric\": \"sys.cpu.user\",\n" +
    "    \"limit\": 3000\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/search/lookup");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
    SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
    Assert.assertEquals("sys.cpu.user", lookup.getQuery());
    Assert.assertEquals(3000, lookup.getLimit());
    Assert.assertEquals(0, lookup.getTags().size());
}
项目:timely    文件:HttpRequestDecoderTest.java   
@Test
public void testLookupURIWithLimitAndTags() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            "/api/search/lookup?m=sys.cpu.user{host=*}&limit=3000");
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
    SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
    Assert.assertEquals("sys.cpu.user", lookup.getQuery());
    Assert.assertEquals(3000, lookup.getLimit());
    Assert.assertEquals(1, lookup.getTags().size());
    Tag tag = lookup.getTags().iterator().next();
    Assert.assertEquals("host", tag.getKey());
    Assert.assertEquals("*", tag.getValue());
}
项目:reactor-netty    文件:HttpClientOperations.java   
HttpClientOperations(Channel channel,
        BiFunction<? super HttpClientResponse, ? super HttpClientRequest, ? extends Publisher<Void>> handler,
        ContextHandler<?> context) {
    super(channel, handler, context);
    this.isSecure = channel.pipeline()
                           .get(NettyPipeline.SslHandler) != null;
    String[] redirects = channel.attr(REDIRECT_ATTR_KEY)
                                .get();
    this.redirectedFrom = redirects == null ? EMPTY_REDIRECTIONS : redirects;
    this.nettyRequest =
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    this.requestHeaders = nettyRequest.headers();
    this.requestHeaders.set(HttpHeaderNames.USER_AGENT, HttpClient.USER_AGENT);
    this.inboundPrefetch = 16;
    chunkedTransfer(true);
}
项目:timely    文件:HttpRequestDecoderTest.java   
@Test
public void testSuggestPostWithValidType() throws Exception {
    // @formatter:off
    String content = 
    "{\n" +
    "    \"type\": \"metrics\"\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/suggest");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SuggestRequest.class, results.iterator().next().getClass());
    SuggestRequest suggest = (SuggestRequest) results.iterator().next();
    Assert.assertEquals("metrics", suggest.getType());
    Assert.assertFalse(suggest.getQuery().isPresent());
    Assert.assertEquals(25, suggest.getMax());
    suggest.validate();
}
项目:Camel    文件:NettyUseRawHttpResponseTest.java   
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("netty4-http:http://0.0.0.0:{{port}}/foo")
                .to("mock:input")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                                                                            NettyConverter.toByteBuffer("Bye World".getBytes()));
                        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 9);

                        exchange.getOut().setBody(response);
                    }
                });
        }
    };
}
项目:timely    文件:HttpRequestDecoderTest.java   
@Test
public void testSuggestPostWithValidTypeAndQueryAndMax() throws Exception {
    // @formatter:off
    String content = 
    "{\n" +
    "    \"type\": \"metrics\",\n" +
    "    \"q\": \"sys.cpu.user\",\n" +
    "    \"max\": 30\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/suggest");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SuggestRequest.class, results.iterator().next().getClass());
    SuggestRequest suggest = (SuggestRequest) results.iterator().next();
    Assert.assertEquals("metrics", suggest.getType());
    Assert.assertEquals("sys.cpu.user", suggest.getQuery().get());
    Assert.assertEquals(30, suggest.getMax());
    suggest.validate();
}
项目:flashback    文件:RecordedHttpRequestBuilderTest.java   
@Test
public void testBuildContent()
    throws Exception {
  HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "www.google.com");
  RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);

  String charset = "UTF-8";
  String str1 = "first content";
  HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent1);
  String str2 = "second content";
  HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(httpContent2);

  String lastStr = "Last chunk";
  HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
  recordedHttpRequestBuilder.appendHttpContent(lastContent);

  RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
  Assert
      .assertEquals((str1 + str2 + lastStr).getBytes(charset), recordedHttpRequest.getHttpBody().getContent(charset));
}
项目:nesty    文件:HttpContext.java   
public static HttpContext build(HttpRequestVisitor visitor) {
    HttpContext context = new HttpContext();
    context.remoteAddress = visitor.visitRemoteAddress();
    context.uri = visitor.visitURI();
    context.terms = visitor.visitTerms();
    context.requestMethod = visitor.visitHttpMethod();
    context.httpHeaders = visitor.visitHttpHeaders();
    context.httpParams = visitor.visitHttpParams();

    // TODO : if exclude GET or not ?
    //
    context.httpBody = visitor.visitHttpBody();

    if (visitor.visitHttpVersion() == HttpVersion.HTTP_1_1 &&
            HttpConstants.HEADER_CONNECTION_CLOSE.equals(context.httpHeaders.get(HttpConstants.HEADER_CONNECTION)))
        context.isKeepAlive = false;

    if (visitor.visitHttpVersion() == HttpVersion.HTTP_1_0 &&
            !HttpConstants.HEADER_CONNECTION_KEEPALIVE.equalsIgnoreCase(context.httpHeaders.get(HttpConstants.HEADER_CONNECTION)))
        context.isKeepAlive = false;

    return context;
}
项目:flashback    文件:NoMatchResponseGenerator.java   
public static FullHttpResponse generateNoMatchResponse(RecordedHttpRequest recordedHttpRequest) {
  StringBuilder bodyTextBuilder = new StringBuilder();
  bodyTextBuilder.append("No Matching Request\n").append("Incoming Request Method: ")
      .append(recordedHttpRequest.getMethod()).append("\n").append("Incoming Request URI: ")
      .append(recordedHttpRequest.getUri()).append("\n").append("Incoming Request Headers: ")
      .append(recordedHttpRequest.getHeaders()).append("\n");
  RecordedHttpBody incomingBody = recordedHttpRequest.getHttpBody();
  if (incomingBody != null) {
    if (incomingBody instanceof RecordedEncodedHttpBody) {
      incomingBody = ((RecordedEncodedHttpBody) incomingBody).getDecodedBody();
    }
    if (incomingBody instanceof RecordedStringHttpBody) {
      bodyTextBuilder.append("Incoming Request Body: ").append(((RecordedStringHttpBody) incomingBody).getContent());
    } else {
      bodyTextBuilder.append("Incoming Request Body: (binary content)");
    }
  }
  ByteBuf badRequestBody = Unpooled.wrappedBuffer(bodyTextBuilder.toString().getBytes(Charset.forName("UTF-8")));
  return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, badRequestBody);
}
项目:yar-java    文件:HttpServerHandler.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

    ByteBuf buf = msg.content();
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(0, bytes);

    YarRequest yarRequest = YarProtocol.buildRequest(bytes);
    YarResponse yarResponse = process(yarRequest);

    FullHttpResponse response =
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(YarProtocol
                    .toProtocolBytes(yarResponse)));
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    if (HttpHeaders.isKeepAlive(msg)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ctx.flush();
    ctx.close();
}
项目:riposte    文件:RequestInfoImplTest.java   
@Test
public void getMultipartParts_works_as_expected_with_known_valid_data() throws IOException {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    Whitebox.setInternalState(requestInfo, "isMultipart", true);
    Whitebox.setInternalState(requestInfo, "contentCharset", CharsetUtil.UTF_8);
    Whitebox.setInternalState(requestInfo, "protocolVersion", HttpVersion.HTTP_1_1);
    Whitebox.setInternalState(requestInfo, "method", HttpMethod.POST);
    requestInfo.isCompleteRequestWithAllChunks = true;
    requestInfo.rawContentBytes = KNOWN_MULTIPART_DATA_BODY.getBytes(CharsetUtil.UTF_8);
    requestInfo.getHeaders().set("Content-Type", KNOWN_MULTIPART_DATA_CONTENT_TYPE_HEADER);

    // when
    List<InterfaceHttpData> result = requestInfo.getMultipartParts();

    // then
    assertThat(result, notNullValue());
    assertThat(result.size(), is(1));
    InterfaceHttpData data = result.get(0);
    assertThat(data, instanceOf(FileUpload.class));
    FileUpload fileUploadData = (FileUpload)data;
    assertThat(fileUploadData.getName(), is(KNOWN_MULTIPART_DATA_NAME));
    assertThat(fileUploadData.getFilename(), is(KNOWN_MULTIPART_DATA_FILENAME));
    assertThat(fileUploadData.getString(CharsetUtil.UTF_8), is(KNOWN_MULTIPART_DATA_ATTR_UUID));
}
项目:riposte    文件:RequestInfoImplTest.java   
@Test
public void getMultipartParts_works_as_expected_with_known_empty_data() throws IOException {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    Whitebox.setInternalState(requestInfo, "isMultipart", true);
    Whitebox.setInternalState(requestInfo, "contentCharset", CharsetUtil.UTF_8);
    Whitebox.setInternalState(requestInfo, "protocolVersion", HttpVersion.HTTP_1_1);
    Whitebox.setInternalState(requestInfo, "method", HttpMethod.POST);
    requestInfo.isCompleteRequestWithAllChunks = true;
    requestInfo.rawContentBytes = null;
    requestInfo.getHeaders().set("Content-Type", KNOWN_MULTIPART_DATA_CONTENT_TYPE_HEADER);

    // when
    List<InterfaceHttpData> result = requestInfo.getMultipartParts();

    // then
    assertThat(result, notNullValue());
    assertThat(result.isEmpty(), is(true));
}
项目:riposte    文件:RequestInfoImplTest.java   
@Test(expected = IllegalStateException.class)
public void getMultipartParts_explodes_if_multipartData_had_been_released() throws IOException {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    Whitebox.setInternalState(requestInfo, "isMultipart", true);
    Whitebox.setInternalState(requestInfo, "contentCharset", CharsetUtil.UTF_8);
    Whitebox.setInternalState(requestInfo, "protocolVersion", HttpVersion.HTTP_1_1);
    Whitebox.setInternalState(requestInfo, "method", HttpMethod.POST);
    requestInfo.isCompleteRequestWithAllChunks = true;
    requestInfo.rawContentBytes = KNOWN_MULTIPART_DATA_BODY.getBytes(CharsetUtil.UTF_8);
    requestInfo.getHeaders().set("Content-Type", KNOWN_MULTIPART_DATA_CONTENT_TYPE_HEADER);
    List<InterfaceHttpData> result = requestInfo.getMultipartParts();
    assertThat(result, notNullValue());
    assertThat(result.size(), is(1));

    // expect
    requestInfo.releaseMultipartData();
    requestInfo.getMultipartParts();
    fail("Expected an error, but none was thrown");
}
项目:cosmic    文件:HttpUploadServerHandler.java   
private void writeResponse(final Channel channel, final HttpResponseStatus statusCode) {
    // Convert the response content to a ChannelBuffer.
    final ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    responseContent.setLength(0);
    // Decide whether to close the connection or not.
    final boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) ||
            request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION));
    // Build the response object.
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, statusCode, buf);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    if (!close) {
        // There's no need to add 'Content-Length' header if this is the last response.
        response.headers().set(CONTENT_LENGTH, buf.readableBytes());
    }
    // Write the response.
    final ChannelFuture future = channel.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}
项目:GitHub    文件:NettyHttpClient.java   
private void sendRequest(HttpUrl url) {
  start = System.nanoTime();
  total = 0;
  HttpRequest request = new DefaultFullHttpRequest(
      HttpVersion.HTTP_1_1, HttpMethod.GET, url.encodedPath());
  request.headers().set(HttpHeaders.Names.HOST, url.host());
  request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
  channel.writeAndFlush(request);
}
项目:GitHub    文件:NettyHttpClient.java   
private void sendRequest(HttpUrl url) {
  start = System.nanoTime();
  total = 0;
  HttpRequest request = new DefaultFullHttpRequest(
      HttpVersion.HTTP_1_1, HttpMethod.GET, url.encodedPath());
  request.headers().set(HttpHeaders.Names.HOST, url.host());
  request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
  channel.writeAndFlush(request);
}
项目:TFWebSock    文件:NettyHttpFileHandler.java   
public void sendRedirect(ChannelHandlerContext ctx, String newUri) {
   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
   response.headers().set(HttpHeaders.Names.LOCATION, newUri);

   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
项目:TFWebSock    文件:NettyHttpFileHandler.java   
public void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
   FullHttpResponse response = new DefaultFullHttpResponse(
         HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
   response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");

   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
项目:TFWebSock    文件:NettyHttpFileHandler.java   
/**
 * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
 *
 * @param ctx
 *            Context
 */
public void sendNotModified(ChannelHandlerContext ctx) {
   FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
   setDateHeader(response);

   // Close the connection as soon as the error message is sent.
   ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
项目:xrpc    文件:Recipes.java   
public static FullHttpRequest newFullRequest(
    HttpMethod method, String urlPath, ByteBuf payload, ContentType contentType) {
  FullHttpRequest request =
      new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, urlPath, payload);
  request.headers().set(CONTENT_TYPE, contentType.value);
  request.headers().setInt(CONTENT_LENGTH, payload.readableBytes());
  return request;
}
项目:Limitart    文件:HttpUtil.java   
public static void sendResponse(Channel channel, HttpResponseStatus resultCode, ContentTypes contentType,
        ByteBuf result, boolean isClose) {
    channel.eventLoop().execute(() -> {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, resultCode, result);
        response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType.getValue());
        response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes() + "");
        channel.writeAndFlush(response).addListener((ChannelFutureListener) arg0 -> {
            if (isClose) {
                arg0.channel().close();
            }
        });
    });
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldHandleRequestsAndResponses() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");

    // First request
    inboundChannel.write(req.retain());

    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);

    // First response
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    assertFalse(inboundChannel.writeInbound(resp));

    assertEquals(1, outboundChannel.outboundMessages().size());
    assertEquals(resp, outboundChannel.outboundMessages().poll());

    // Second request
    inboundChannel.write(req);

    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);

    // Second response
    assertFalse(inboundChannel.writeInbound(resp));

    assertEquals(1, outboundChannel.outboundMessages().size());
    assertEquals(resp, outboundChannel.outboundMessages().poll());

    resp.release();
}