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

The following examples show how to use io.netty.handler.codec.http.HttpVersion. 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 File: ModelServerTest.java    From serve with 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 #2
Source File: TestShiroAuthenticator.java    From arcusplatform with 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 File: ChangePasswordRESTHandler.java    From arcusplatform with 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 #4
Source File: HandshakeHandlerTest.java    From socketio with 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 #5
Source File: HttpRequestDecoderTest.java    From timely with 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 #6
Source File: PublisherAdapterTest.java    From aws-sdk-java-v2 with 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 #7
Source File: RequestAdapterTest.java    From aws-sdk-java-v2 with 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 #8
Source File: Netty4ClientHttpRequest.java    From java-technology-stack with 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 #9
Source File: HttpController.java    From litchi with 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 #10
Source File: Http2FrameCodecTest.java    From netty-4.1.22 with 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 #11
Source File: RequestFromVertXTest.java    From wisdom with 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 #12
Source File: ModelServerTest.java    From serve with 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 #13
Source File: ViewHandlerTest.java    From couchbase-jvm-core with 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 #14
Source File: HttpSuggestRequestHandler.java    From timely with 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 #15
Source File: NettyRequestTest.java    From ambry with 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 File: NettyHttpResponse.java    From netstrap with 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 #17
Source File: EmbeddedChannelUnitTest.java    From tutorials with 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 #18
Source File: HttpRequestDecoderTest.java    From timely with 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 #19
Source File: Http1BackendHandlerTest.java    From nitmproxy with 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 #20
Source File: HttpResponse.java    From lannister with 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 #21
Source File: PublisherAdapterTest.java    From aws-sdk-java-v2 with 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 #22
Source File: RequestInfoImplTest.java    From riposte with 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 #23
Source File: ModelServerTest.java    From serve with 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 #24
Source File: Http1FilterUnitTest.java    From xio with 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 #25
Source File: StyxToNettyResponseTranslator.java    From styx with Apache License 2.0 5 votes vote down vote up
public HttpResponse toNettyResponse(LiveHttpResponse httpResponse) {
    io.netty.handler.codec.http.HttpVersion version = toNettyVersion(httpResponse.version());
    HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(httpResponse.status().code());

    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(version, httpResponseStatus, true);

    httpResponse.headers().forEach(httpHeader ->
            nettyResponse.headers().add(httpHeader.name(), httpHeader.value()));

    return nettyResponse;
}
 
Example #26
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testRegisterModelNotFound() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/models?url=InvalidUrl");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

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

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), "Model not found in model store: InvalidUrl");
}
 
Example #27
Source File: SessionLogRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
   String requestJson = httpRequest.content().toString(CharsetUtil.UTF_8);
   ClientMessage requestMessage = JSON.fromJson(requestJson, ClientMessage.class);
   ClientMessage responseMessage = handler.handle(requestMessage, session);
   FullHttpResponse httpResponse = new DefaultFullHttpResponse(
         HttpVersion.HTTP_1_1, 
         getStatus(responseMessage), 
         Unpooled.copiedBuffer(JSON.toJson(responseMessage), CharsetUtil.UTF_8)
   );
   httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, BridgeHeaders.CONTENT_TYPE_JSON_UTF8);
   return httpResponse;
}
 
Example #28
Source File: LittleProxyMitmProxy.java    From LittleProxy-mitm with 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 #29
Source File: HttpTestServer.java    From crate with Apache License 2.0 5 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest msg) throws UnsupportedEncodingException {
    String uri = msg.uri();
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    logger.debug("Got Request for " + uri);
    HttpResponseStatus status = fail ? HttpResponseStatus.BAD_REQUEST : HttpResponseStatus.OK;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        JsonGenerator generator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
        generator.writeStartObject();
        for (Map.Entry<String, List<String>> entry : decoder.parameters().entrySet()) {
            if (entry.getValue().size() == 1) {
                generator.writeStringField(entry.getKey(), URLDecoder.decode(entry.getValue().get(0), "UTF-8"));
            } else {
                generator.writeArrayFieldStart(entry.getKey());
                for (String value : entry.getValue()) {
                    generator.writeString(URLDecoder.decode(value, "UTF-8"));
                }
                generator.writeEndArray();
            }
        }
        generator.writeEndObject();
        generator.close();

    } catch (Exception ex) {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    ByteBuf byteBuf = Unpooled.wrappedBuffer(out.toByteArray());
    responses.add(out.toString(StandardCharsets.UTF_8.name()));

    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, byteBuf);
    ChannelFuture future = ctx.channel().writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #30
Source File: QueryHandlerV2Test.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecodeProfileInfo() throws Exception {
    String response = Resources.read("with_timings_profile.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    latch = new CountDownLatch(1);
    inbound.profileInfo().subscribe(
            new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    buf.release();
                }
            },
            new Action1<Throwable>() {
                @Override
                public void call(Throwable err) {
                    latch.countDown();
                }
            },
            new Action0() {
                @Override
                public void call() {
                    latch.countDown();
                }
            }
    );
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, invokeCounter1.get());
}