Java Code Examples for io.netty.handler.codec.http.HttpVersion

The following examples show how to use io.netty.handler.codec.http.HttpVersion. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: socketio   Author: scalecube   File: HandshakeHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelRead() throws Exception {
  HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/socket.io/1/");

  LastOutboundHandler lastOutboundHandler = new LastOutboundHandler();
  EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler, handshakeHandler);
  channel.writeInbound(request);
  Object outboundMessage = lastOutboundHandler.getOutboundMessages().poll();
  assertTrue(outboundMessage instanceof FullHttpResponse);
  FullHttpResponse res = (FullHttpResponse) outboundMessage;
  assertEquals(HttpVersion.HTTP_1_1, res.protocolVersion());
  assertEquals(HttpResponseStatus.OK, res.status());
  ByteBuf content = res.content();
  assertTrue(content.toString(CharsetUtil.UTF_8).endsWith("60:60:websocket,flashsocket,xhr-polling,jsonp-polling"));
  channel.finish();
}
 
Example #2
Source Project: arcusplatform   Author: arcus-smart-home   File: TestShiroAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHandoffInvalidToken() throws Exception {
   EasyMock
      .expect(appHandoffDao.validate("token"))
      .andReturn(Optional.empty());
   
   replay();
   
   DefaultFullHttpRequest request = new DefaultFullHttpRequest(
         HttpVersion.HTTP_1_1, 
         HttpMethod.POST, 
         "http://localhost/client",
         Unpooled.wrappedBuffer("{token:\"token\"}".getBytes("UTF-8"))
   );
   
   FullHttpResponse response = authenticator.authenticateRequest(channel, request);
   assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
   assertCookieCleared(response);
   
   verify();
}
 
Example #3
Source Project: litchi   Author: phantacix   File: HttpController.java    License: Apache License 2.0 6 votes vote down vote up
public void writeFile(String fileName, String text) {
	ByteBuf content = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8);
	HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
	response.headers().set("Pragma", "Pragma");
	response.headers().set("Expires", "0");
	response.headers().set("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
	response.headers().set("Content-Type", "application/download");
	response.headers().set("Content-Disposition", "attachment;filename=" + fileName);
	response.headers().set("Content-Transfer-Encoding", "binary");
	
	if (enableCookies) {
		for (Map.Entry<String, Cookie> entry : cookieMaps.entrySet()) {
			response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(entry.getValue()));
		}
	}
	
	// 跨域支持
	response.headers().add("Access-Control-Allow-Origin", "*");
	response.headers().add("Access-Control-Allow-Methods", "POST");
	HttpUtil.setContentLength(response, content.readableBytes());
	channel.writeAndFlush(response); //.addListener(ChannelFutureListener.CLOSE);
}
 
Example #4
Source Project: couchbase-jvm-core   Author: couchbase   File: ViewHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseErrorWithEmptyRows() throws Exception {
    String response = Resources.read("error_empty_rows.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk1 = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    ViewQueryRequest requestMock = mock(ViewQueryRequest.class);
    queue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk1);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    ViewQueryResponse inbound = (ViewQueryResponse) firedEvents.get(0);
    assertTrue(inbound.status().isSuccess());

    assertEquals(0, countAndRelease(inbound.rows()));

    String error = inbound.error().toBlocking().single();
    Map<String, Object> parsed = DefaultObjectMapper.readValueAsMap(error);
    assertEquals(1, parsed.size());
    assertNotNull(parsed.get("errors"));
}
 
Example #5
Source Project: nitmproxy   Author: chhsiao90   File: Http1BackendHandlerTest.java    License: MIT License 6 votes vote down vote up
@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();
}
 
Example #6
Source Project: aws-sdk-java-v2   Author: aws   File: PublisherAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void successfulStreaming_shouldNotInvokeChannelRead() {
    Flowable<HttpContent> testPublisher = Flowable.just(fullHttpResponse);

    StreamedHttpResponse streamedHttpResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1,
                                                                                HttpResponseStatus.ACCEPTED,
                                                                                testPublisher);



    ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedHttpResponse,
                                                                                             ctx,
                                                                                             requestContext,
                                                                                             executeFuture
    );
    TestSubscriber subscriber = new TestSubscriber();

    publisherAdapter.subscribe(subscriber);

    verify(ctx, times(0)).read();
    verify(ctx, times(0)).close();
    assertThat(subscriber.isCompleted).isEqualTo(true);
    verify(channelPool).release(channel);
    executeFuture.join();
    assertThat(executeFuture).isCompleted();
}
 
Example #7
Source Project: riposte   Author: Nike-Inc   File: RequestInfoImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void getMultipartParts_explodes_if_multipartData_had_been_released() {
    // 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");
}
 
Example #8
Source Project: serve   Author: pytorch   File: ModelServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testLegacyPredict"})
public void testPredictionsInvalidRequestSize() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");

    req.content().writeZero(11485760);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_OCTET_STREAM);
    channel.writeAndFlush(req);

    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getHttpStatus(), HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
}
 
Example #9
Source Project: xio   Author: xjdr   File: Http1FilterUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeniedRule() throws UnknownHostException {
  List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>();
  HashMultimap<String, String> headers = HashMultimap.create();
  headers.put("User-Agent", "Bad-actor: 1.0");
  Http1DeterministicRuleEngineConfig.Rule bad =
      new Http1DeterministicRuleEngineConfig.Rule(
          HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
  blacklist.add(bad);
  Http1Filter http1Filter =
      new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist)));
  EmbeddedChannel chDeny = new EmbeddedChannel(http1Filter);
  DefaultHttpRequest request =
      new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure");
  request.headers().set("User-Agent", "Bad-actor: 1.0");
  chDeny.writeInbound(request);
  chDeny.runPendingTasks();
  assertFalse(chDeny.isActive());
  assertFalse(chDeny.isOpen());
}
 
Example #10
Source Project: serve   Author: pytorch   File: ModelServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testMetricManager"})
public void testInvalidRootRequest() throws InterruptedException {
    Channel channel = TestUtils.connect(false, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.METHOD_NOT_ALLOWED.code());
    Assert.assertEquals(resp.getMessage(), ERROR_METHOD_NOT_ALLOWED);
}
 
Example #11
Source Project: lannister   Author: anyflow   File: HttpResponse.java    License: Apache License 2.0 6 votes vote down vote up
public static HttpResponse createServerDefault(String requestCookie) {
	HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());

	ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");

	if (requestCookie == null) { return ret; }

	Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
	if (cookies.isEmpty()) { return ret; }

	// Reset the cookies if necessary.
	for (Cookie cookie : cookies) {
		ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
	}

	return ret;
}
 
Example #12
Source Project: timely   Author: NationalSecurityAgency   File: HttpRequestDecoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuggestPostWithValidTypeAndQuery() throws Exception {
// @formatter:off
    String content =
    "{\n" +
    "    \"type\": \"metrics\",\n" +
    "    \"q\": \"sys.cpu.user\"\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(25, suggest.getMax());
    suggest.validate();
}
 
Example #13
Source Project: tutorials   Author: eugenp   File: EmbeddedChannelUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenTwoChannelHandlers_testPipeline() {

	final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
			"/calculate?a=10&b=5");
	httpRequest.headers().add("Operator", "Add");

	EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());

	channel.pipeline().addFirst(new HttpMessageHandler()).addLast(new CalculatorOperationHandler());

	// send HTTP request to server and check that the message is on the inbound pipeline
	assertThat(channel.writeInbound(httpRequest)).isTrue();

	long inboundChannelResponse = channel.readInbound();
	assertThat(inboundChannelResponse).isEqualTo(15);

	// we should have an outbound message in the form of a HTTP response
	assertThat(channel.outboundMessages().size()).isEqualTo(1);
	// Object response = channel.readOutbound();

	FullHttpResponse httpResponse = channel.readOutbound();
	String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
	assertThat(httpResponseContent).isEqualTo("15");
}
 
Example #14
Source Project: netstrap   Author: minghu-zhang   File: NettyHttpResponse.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置keep-alive
 */
public HttpResponse keepAlive(HttpVersion httpVersion, Map<String, String> header) {

    String connection = header.getOrDefault(HeaderPublicKey.CONNECTION, Keepalive.CLOSE_ALIVE).toLowerCase();

    //设置keep-alive
    if ((httpVersion.equals(HttpVersion.HTTP_1_1) && !connection.equals(Keepalive.CLOSE_ALIVE))) {
        setKeepAlive(true);
    } else if (httpVersion.equals(HttpVersion.HTTP_1_0) && connection.equals(Keepalive.KEEP_ALIVE)) {
        setKeepAlive(true);
    }

    if (isKeepAlive()) {
        addHeader(HeaderPublicKey.CONNECTION, Keepalive.KEEP_ALIVE);
    }

    return this;
}
 
Example #15
Source Project: ambry   Author: linkedin   File: NettyRequestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link NettyRequest} with the given parameters.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri the URI desired.
 * @param headers {@link HttpHeaders} that need to be a part of the request.
 * @param channel the {@link Channel} that the request arrived over.
 * @return {@link NettyRequest} encapsulating a {@link HttpRequest} with the given parameters.
 * @throws RestServiceException if the {@code httpMethod} is not recognized by {@link NettyRequest}.
 */
private NettyRequest createNettyRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, Channel channel)
    throws RestServiceException {
  MetricRegistry metricRegistry = new MetricRegistry();
  RestRequestMetricsTracker.setDefaults(metricRegistry);
  HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, false);
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  NettyRequest nettyRequest =
      new NettyRequest(httpRequest, channel, new NettyMetrics(metricRegistry), BLACKLISTED_QUERY_PARAM_SET);
  assertEquals("Auto-read is in an invalid state",
      (!httpMethod.equals(HttpMethod.POST) && !httpMethod.equals(HttpMethod.PUT))
          || NettyRequest.bufferWatermark <= 0, channel.config().isAutoRead());
  return nettyRequest;
}
 
Example #16
Source Project: timely   Author: NationalSecurityAgency   File: HttpSuggestRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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(HttpHeaderNames.CONTENT_TYPE, Constants.JSON_TYPE);
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    sendResponse(ctx, response);
}
 
Example #17
Source Project: wisdom   Author: wisdom-framework   File: RequestFromVertXTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLanguageOrder() throws Exception {
    HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    req.headers().set(HeaderNames.ACCEPT_LANGUAGE, "da, en-gb;q=0.8, en;q=0.7");
    RequestFromVertx request = new RequestFromVertx(create(req));
    assertThat(request.languages()).containsExactly(
            new Locale("da"),
            new Locale("en", "gb"),
            new Locale("en")
    );

    req.headers().set(HeaderNames.ACCEPT_LANGUAGE, "da, en-gb;q=0.7, en;q=0.9");
    request = new RequestFromVertx(create(req));
    assertThat(request.languages()).containsExactly(
            new Locale("da"),
            new Locale("en"),
            new Locale("en", "gb")
    );
}
 
Example #18
Source Project: serve   Author: pytorch   File: ModelServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testRegisterModelHttpError"})
public void testRegisterModelInvalidPath() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=..%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), "Relative path is not allowed in url: ../fake.mar");
}
 
Example #19
Source Project: aws-sdk-java-v2   Author: aws   File: PublisherAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    executeFuture = new CompletableFuture<>();
    fullHttpResponse = mock(DefaultHttpContent.class);

    when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT));
    requestContext = new RequestContext(channelPool,
                                        eventLoopGroup,
                                        AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
                                        null);

    channel = new MockChannel();
    channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
    channel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
    channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
    when(ctx.channel()).thenReturn(channel);

    nettyResponseHandler = ResponseHandler.getInstance();
    DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class);
    when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE);
    when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED);
    when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
    nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse);
}
 
Example #20
Source Project: timely   Author: NationalSecurityAgency   File: HttpRequestDecoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #21
Source Project: aws-sdk-java-v2   Author: aws   File: RequestAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void adapt_h1Request_requestIsCorrect() {
    SdkHttpRequest request = SdkHttpRequest.builder()
            .uri(URI.create("http://localhost:12345/foo/bar/baz"))
            .putRawQueryParameter("foo", "bar")
            .putRawQueryParameter("bar", "baz")
            .putHeader("header1", "header1val")
            .putHeader("header2", "header2val")
            .method(SdkHttpMethod.GET)
            .build();

    HttpRequest adapted = h1Adapter.adapt(request);

    assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET"));
    assertThat(adapted.uri()).isEqualTo("/foo/bar/baz?foo=bar&bar=baz");
    assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1);
    assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345");
    assertThat(adapted.headers().getAll("header1")).containsExactly("header1val");
    assertThat(adapted.headers().getAll("header2")).containsExactly("header2val");
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: Netty4ClientHttpRequest.java    License: MIT License 6 votes vote down vote up
private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
	io.netty.handler.codec.http.HttpMethod nettyMethod =
			io.netty.handler.codec.http.HttpMethod.valueOf(this.method.name());

	String authority = this.uri.getRawAuthority();
	String path = this.uri.toString().substring(this.uri.toString().indexOf(authority) + authority.length());
	FullHttpRequest nettyRequest = new DefaultFullHttpRequest(
			HttpVersion.HTTP_1_1, nettyMethod, path, this.body.buffer());

	nettyRequest.headers().set(HttpHeaders.HOST, this.uri.getHost() + ":" + getPort(this.uri));
	nettyRequest.headers().set(HttpHeaders.CONNECTION, "close");
	headers.forEach((headerName, headerValues) -> nettyRequest.headers().add(headerName, headerValues));
	if (!nettyRequest.headers().contains(HttpHeaders.CONTENT_LENGTH) && this.body.buffer().readableBytes() > 0) {
		nettyRequest.headers().set(HttpHeaders.CONTENT_LENGTH, this.body.buffer().readableBytes());
	}

	return nettyRequest;
}
 
Example #23
Source Project: netty-4.1.22   Author: tianheframe   File: Http2FrameCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void upgradeEventNoRefCntError() throws Exception {
    frameListener.onHeadersRead(http2HandlerCtx, Http2CodecUtil.HTTP_UPGRADE_STREAM_ID, request, 31, false);

    // Using reflect as the constructor is package-private and the class is final.
    Constructor<UpgradeEvent> constructor =
            UpgradeEvent.class.getDeclaredConstructor(CharSequence.class, FullHttpRequest.class);

    // Check if we could make it accessible which may fail on java9.
    Assume.assumeTrue(ReflectionUtil.trySetAccessible(constructor, true) == null);

    HttpServerUpgradeHandler.UpgradeEvent upgradeEvent = constructor.newInstance(
            "HTTP/2", new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
    channel.pipeline().fireUserEventTriggered(upgradeEvent);
    assertEquals(1, upgradeEvent.refCnt());
}
 
Example #24
Source Project: arcusplatform   Author: arcus-smart-home   File: ChangePasswordRESTHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
   String json = request.content().toString(CharsetUtil.UTF_8);
   ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);

   ClientMessage.Builder responseBuilder = ClientMessage.builder().withCorrelationId(clientMessage.getCorrelationId()).withSource(Address.platformService(PlatformConstants.SERVICE_PEOPLE).getRepresentation());
   Pair<MessageBody, HttpResponseStatus> responseTuple;

   try {
      responseTuple = handleChangePassword(clientMessage, ctx);
   } catch (Exception e) {
      responseTuple = new ImmutablePair<MessageBody, HttpResponseStatus>(Errors.fromException(e), HttpResponseStatus.INTERNAL_SERVER_ERROR);
   }

   ClientMessage responseMessage = responseBuilder.withPayload(responseTuple.getLeft()).create();
   FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseTuple.getRight(), Unpooled.copiedBuffer(JSON.toJson(responseMessage), CharsetUtil.UTF_8));
   httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, BridgeHeaders.CONTENT_TYPE_JSON_UTF8);
   return httpResponse;
}
 
Example #25
Source Project: LittleProxy-mitm   Author: ganskef   File: LittleProxyMitmProxy.java    License: Apache License 2.0 5 votes vote down vote up
private HttpResponse createOfflineResponse() {
    ByteBuf buffer = Unpooled.wrappedBuffer("Offline response".getBytes());
    HttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);
    HttpHeaders.setContentLength(response, buffer.readableBytes());
    HttpHeaders.setHeader(response, HttpHeaders.Names.CONTENT_TYPE,
            "text/html");
    return response;
}
 
Example #26
Source Project: dubbo-2.6.5   Author: tianheframe   File: HttpProcessHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_200(String result) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(result.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example #27
Source Project: dubbo-2.6.5   Author: tianheframe   File: HttpProcessHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static final FullHttpResponse http_500(String errorMessage) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR
            , Unpooled.wrappedBuffer(errorMessage.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
 
Example #28
Source Project: xio   Author: xjdr   File: ThriftMarshaller.java    License: Apache License 2.0 5 votes vote down vote up
private Http1Version build(HttpVersion version) {
  if (version != null) {
    if (version.equals(HttpVersion.HTTP_1_0)) {
      return Http1Version.HTTP_1_0;
    } else if (version.equals(HttpVersion.HTTP_1_1)) {
      return Http1Version.HTTP_1_1;
    }
  }
  return null;
}
 
Example #29
Source Project: netty-4.1.22   Author: tianheframe   File: HttpPostRequestDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipartRequestWithFieldInvalidCharset() throws Exception {
    final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
        "http://localhost");
    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    // Force to use memory-based data.
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
    final String aData = "some data would be here. the data should be long enough that it " +
        "will be longer than the original buffer length of 256 bytes in " +
        "the HttpPostRequestDecoder in order to trigger the issue. Some more " +
        "data just to be on the safe side.";
    final String body =
        "--" + boundary + "\r\n" +
            "Content-Disposition: form-data; name=\"root\"\r\n" +
            "Content-Type: text/plain; charset=ABCD\r\n" +
            "\r\n" +
            aData +
            "\r\n" +
            "--" + boundary + "--\r\n";

    req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
    // Create decoder instance to test.
    try {
        new HttpPostRequestDecoder(inMemoryFactory, req);
        fail("Was expecting an ErrorDataDecoderException");
    } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
        assertTrue(e.getCause() instanceof UnsupportedCharsetException);
    } finally {
        req.release();
    }
}
 
Example #30
Source Project: netty-4.1.22   Author: tianheframe   File: Http2ClientInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    DefaultFullHttpRequest upgradeRequest =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    ctx.writeAndFlush(upgradeRequest);

    ctx.fireChannelActive();

    // Done with this handler, remove it from the pipeline.
    ctx.pipeline().remove(this);

    configureEndOfPipeline(ctx.pipeline());
}