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

The following examples show how to use io.netty.handler.codec.http.DefaultFullHttpRequest. 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: HttpToHttp2ConnectionHandlerTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoSchemeRequestTargetHandled() throws Exception {
    bootstrapEnv(2, 1, 0);
    final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
    final HttpHeaders httpHeaders = request.headers();
    httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
    httpHeaders.set(HttpHeaderNames.HOST, "localhost");
    ChannelPromise writePromise = newPromise();
    ChannelFuture writeFuture = clientChannel.writeAndFlush(request, writePromise);

    assertTrue(writePromise.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(writePromise.isDone());
    assertFalse(writePromise.isSuccess());
    assertTrue(writeFuture.isDone());
    assertFalse(writeFuture.isSuccess());
}
 
Example #2
Source File: HttpProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    final String host = NetUtil.toSocketAddressString(raddr);
    FullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
            host,
            Unpooled.EMPTY_BUFFER, false);

    req.headers().set(HttpHeaderNames.HOST, host);

    if (authorization != null) {
        req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
    }

    if (headers != null) {
        req.headers().add(headers);
    }

    return req;
}
 
Example #3
Source File: TestUtils.java    From serve with Apache License 2.0 6 votes vote down vote up
public static void scaleModel(
        Channel channel, String modelName, String version, int minWorker, boolean sync) {
    String requestURL = "/models/" + modelName;

    if (version != null) {
        requestURL += "/" + version;
    }

    requestURL += "?min_worker=" + minWorker;

    if (sync) {
        requestURL += "&synchronous=true";
    }

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, requestURL);
    channel.writeAndFlush(req);
}
 
Example #4
Source File: HttpClient.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean sendAsyncRequest(ResponseListener listener, String url, OneM2mRequest reqMessage) {
	
	try {
		URI uri = new URI(url);
		String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
		int port = uri.getPort();
		if(port == -1) port = 80;
		
		DefaultFullHttpRequest request = makeHttpMessage(host, reqMessage);

		log.debug("sendAsyncRequest");
		bootstrap.connect(host, port).addListener(new ConnectListner(request, mHttpClientListener, listener));
		
		return true;
		
	} catch (Exception e) {
		log.error("sendAsyncRequest", e);
	}
	
	return false;
}
 
Example #5
Source File: HttpAuthUpstreamHandlerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotNoHbaConfig() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);

    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
    request.headers().add("X-Real-Ip", "10.1.0.100");

    ch.writeInbound(request);
    ch.releaseInbound();
    assertFalse(handler.authorized());

    assertUnauthorized(
        ch.readOutbound(),
        "No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\"\n");
}
 
Example #6
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 #7
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeEmptyFullRequestWithTrailers() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(false));
    FullHttpRequest request = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.PUT, "/hello/world");

    HttpHeaders trailers = request.trailingHeaders();
    trailers.set("key", "value");
    assertTrue(ch.writeOutbound(request));

    Http2HeadersFrame headersFrame = ch.readOutbound();
    Http2Headers headers = headersFrame.headers();

    assertThat(headers.scheme().toString(), is("http"));
    assertThat(headers.method().toString(), is("PUT"));
    assertThat(headers.path().toString(), is("/hello/world"));
    assertFalse(headersFrame.isEndStream());

    Http2HeadersFrame trailersFrame = ch.readOutbound();
    assertThat(trailersFrame.headers().get("key").toString(), is("value"));
    assertTrue(trailersFrame.isEndStream());

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #8
Source File: HttpServerHandlerTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertChannelReadStartSuccess() {
    scalingConfiguration.getRuleConfiguration().setSourceDatasource("ds_0: !!" + YamlDataSourceConfiguration.class.getName() + "\n  "
            + "dataSourceClassName: com.zaxxer.hikari.HikariDataSource\n  props:\n    "
            + "jdbcUrl: jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL\n    username: root\n    password: 'password'\n    connectionTimeout: 30000\n    "
            + "idleTimeout: 60000\n    maxLifetime: 1800000\n    maxPoolSize: 50\n    minPoolSize: 1\n    maintenanceIntervalMilliseconds: 30000\n    readOnly: false\n");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setUrl("jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setName("root");
    scalingConfiguration.getRuleConfiguration().getDestinationDataSources().setPassword("password");
    ByteBuf byteBuf = Unpooled.copiedBuffer(GSON.toJson(scalingConfiguration), CharsetUtil.UTF_8);
    fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/scaling/job/start", byteBuf);
    httpServerHandler.channelRead0(channelHandlerContext, fullHttpRequest);
    ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(channelHandlerContext).writeAndFlush(argumentCaptor.capture());
    FullHttpResponse fullHttpResponse = (FullHttpResponse) argumentCaptor.getValue();
    assertTrue(fullHttpResponse.content().toString(CharsetUtil.UTF_8).contains("{\"success\":true"));
}
 
Example #9
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictionsValidRequestSize(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");

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

    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
}
 
Example #10
Source File: HttpProtoProtocolTest.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeHttpRequest() throws Exception {
    ServiceManager serviceManager = ServiceManager.getInstance();
    serviceManager.registerService(new EchoServiceImpl(), null);

    ByteBuf content = Unpooled.wrappedBuffer(encodeBody(
            Echo.EchoRequest.newBuilder().setMessage("hello").build()));

    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "/example.EchoService/Echo", content);
    httpRequest.headers().set("log-id", 1);
    httpRequest.setUri("/example.EchoService/Echo");
    httpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/proto; charset=utf-8");
    httpRequest.headers().set("key", "value");

    Request request = protocol.decodeRequest(httpRequest);
    assertEquals("example.EchoService", request.getRpcMethodInfo().getServiceName());
    assertEquals("Echo", request.getRpcMethodInfo().getMethodName());
    assertEquals(EchoService.class.getMethods()[0], request.getTargetMethod());
    assertEquals(EchoServiceImpl.class, request.getTarget().getClass());
    assertEquals(request.getKvAttachment().get("key"), "value");
}
 
Example #11
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 #12
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 #13
Source File: ResetPasswordRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private FullHttpResponse login(String email, String password, ChannelHandlerContext ctx) throws Exception {
   FullHttpRequest fakeLogin = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
   fakeLogin.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");

   String params = new StringBuilder("password=")
      .append(URLEncoder.encode(password, CharsetUtil.UTF_8.name()))
      .append("&")
      .append("user=")
      .append(URLEncoder.encode(email, CharsetUtil.UTF_8.name()))
      .toString();

   ByteBuf buffer = Unpooled.copiedBuffer(params, CharsetUtil.UTF_8);

   fakeLogin.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
   fakeLogin.content().clear().writeBytes(buffer);
   return authenticator.authenticateRequest(ctx.channel(), fakeLogin);
}
 
Example #14
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testRegisterModelHttpError() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

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

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

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
    Assert.assertEquals(
            resp.getMessage(),
            "Failed to download model from: https://localhost:8443/fake.mar, code: 404");
}
 
Example #15
Source File: NettyToStyxRequestDecoderTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleNettyCookies() {
    HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://foo.com/");
    request.headers().set(HOST, "http://foo.com/");
    request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=xxxxx-xxx-xxx-xxx-xxxxxxx");

    NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
            .uniqueIdSupplier(uniqueIdSupplier)
            .build();

    LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty())
            .build();

    LiveHttpRequest expected = new LiveHttpRequest.Builder(
            HttpMethod.GET, "http://foo.com/")
            .cookies(
                    requestCookie("ABC01", "\"1\""),
                    requestCookie("ABC02", "1"),
                    requestCookie("guid", "xxxxx-xxx-xxx-xxx-xxxxxxx")
            )
            .build();
    assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies())));
}
 
Example #16
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 #17
Source File: TestBindClientContextHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testBindUnknownSession() throws Exception {
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andThrow(new UnknownSessionException());
   replay();

   DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/client");
   DefaultHttpHeaders.addHeader(request, "Cookie", "irisAuthToken=test;");
   handler.channelRead(context, request);
   
   
   // an authenticated Client should have been bound
   ClientFactory factory = ServiceLocator.getInstance(ClientFactory.class);
   Client client = factory.get(channel);
   assertNotNull(client);
   assertFalse(client.isAuthenticated());
   assertEquals(null, client.getSessionId());

   verify();
}
 
Example #18
Source File: EmbeddedChannelUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
	EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());

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

	// the HttpMessageHandler does not handle the exception and throws it down the pipeline
       assertThatThrownBy(() -> {
           channel.writeInbound(wrongHttpRequest);
       }).isInstanceOf(IllegalArgumentException.class)
         .hasMessage("Operation not defined");

	// the outbound message is a HTTP response with the status code 500
	FullHttpResponse errorHttpResponse = channel.readOutbound();
	String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
	assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
	assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
 
Example #19
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testRegisterModelMalformedUrl"})
public void testRegisterModelConnectionFailed() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=http%3A%2F%2Flocalhost%3A18888%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.BAD_REQUEST.code());
    Assert.assertEquals(
            resp.getMessage(),
            "Failed to download model from: http://localhost:18888/fake.mar");
}
 
Example #20
Source File: RequestFromVertXTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testMediaType() throws Exception {
    HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    req.headers().set(HeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp," +
            "*/*;q=0.8");
    RequestFromVertx request = new RequestFromVertx(create(req));
    assertThat(request.mediaType().toString()).isEqualTo("text/html");

    req.headers().set(HeaderNames.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    assertThat(request.mediaType().toString()).isEqualTo("application/xhtml+xml");

    req.headers().set(HeaderNames.ACCEPT, "application/xhtml+xml;q=0.1,application/xml;q=0.9;charset=utf-8,*/*;q=0.8");
    assertThat(request.mediaType().withoutParameters().toString()).isEqualTo("application/xml");

    req.headers().clear();
    assertThat(request.mediaType()).isEqualTo(MediaType.ANY_TEXT_TYPE);
    req.headers().set(HeaderNames.ACCEPT, "*/*");
    assertThat(request.mediaType()).isEqualTo(MediaType.ANY_TEXT_TYPE);

    req.headers().set(HeaderNames.ACCEPT, "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5");
    assertThat(request.mediaTypes()).containsExactly(
            MediaType.parse("text/html").withParameter("level", "1"),
            MediaType.parse("text/html").withParameter("q", "0.7"),
            MediaType.parse("*/*").withParameter("q", "0.5"),
            MediaType.parse("text/html").withParameter("level", "2").withParameter("q", "0.4"),
            MediaType.parse("text/*").withParameter("q", "0.3")
    );
}
 
Example #21
Source File: HttpAuthUpstreamHandlerTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnauthorizedUser() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);

    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");

    ch.writeInbound(request);
    ch.releaseInbound();

    assertFalse(handler.authorized());
    assertUnauthorized(ch.readOutbound(), "trust authentication failed for user \"crate\"\n");
}
 
Example #22
Source File: ViewHandlerTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProduceValidUrlIfShortKeysAndNoOtherQueryParam() {
    String urlEncodedKeys = "%5B%221%22%2C%222%22%2C%223%22%5D";
    String keys = "[\"1\",\"2\",\"3\"]";
    String query = "";
    ViewQueryRequest request = new ViewQueryRequest("design", "view", true, query, keys, "bucket", "password");
    channel.writeOutbound(request);
    DefaultFullHttpRequest outbound = (DefaultFullHttpRequest) channel.readOutbound();
    String failMsg = outbound.getUri();
    assertEquals(HttpMethod.GET, outbound.getMethod());
    assertTrue(failMsg, outbound.getUri().endsWith("?keys=" + urlEncodedKeys));
    String content = outbound.content().toString(CharsetUtil.UTF_8);
    assertTrue(content.isEmpty());
    ReferenceCountUtil.releaseLater(outbound); //NO-OP since content is empty but still...
}
 
Example #23
Source File: RevokeAccessTokenUnit.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(UnitRequest msg, Handler<UnitResponse> handler) throws Exception {
    JSONObject json = new JSONObject() {{
        put("client_id", msg.getString("client_id"));
        put("access_token", msg.getString("access_token"));
    }};
    String body = json.toJSONString(),
            uri = msg.getContext().getUri();
    ByteBuf byteBuffer = Unpooled.wrappedBuffer(body.getBytes());
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, byteBuffer);
    OAuthService.auth.revokeToken(request).subscribe(
            message -> handler.handle(UnitResponse.createSuccess(message)),
            exception -> handler.handle(UnitResponse.createException(exception))
    );
}
 
Example #24
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testPredictionsJson(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    channel.writeAndFlush(req);

    latch.await();
    Assert.assertEquals(result, "OK");
}
 
Example #25
Source File: TestUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static FullHttpRequest makeHttpPostRequest(String content, String host, String path) {
  ByteBuf buf = Unpooled.wrappedBuffer(content.getBytes(US_ASCII));
  FullHttpRequest request =
      new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path, buf);
  request
      .headers()
      .set("user-agent", "Proxy")
      .set("host", host)
      .setInt("content-length", buf.readableBytes());
  return request;
}
 
Example #26
Source File: GetAllScopesUnit.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(UnitRequest msg, Handler<UnitResponse> handler) throws Exception {
    StringBuffer uriBuffer = new StringBuffer(msg.getContext().getUri());
    if (null != msg.getString("client_id")) {
        uriBuffer.append("?client_id=").append(msg.getString("client_id"));
    }
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriBuffer.toString());
    Single.just(OAuthService.getScopeService().getScopes(request)).subscribe(
            message -> handler.handle(UnitResponse.createSuccess(message)),
            exception -> handler.handle(UnitResponse.createException(exception))
    );
}
 
Example #27
Source File: ConfigHandler.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    if (msg instanceof RestApiRequest) {
        return encodeRestApiRequest(ctx, (RestApiRequest) msg);
    }
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;
    } else if (msg instanceof UpsertUserRequest) {
      httpMethod = HttpMethod.PUT;
    } else if (msg instanceof RemoveBucketRequest || msg instanceof RemoveUserRequest) {
        httpMethod = HttpMethod.DELETE;
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpsertUserRequest) {
        content = Unpooled.copiedBuffer(((UpsertUserRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof InsertBucketRequest || msg instanceof UpdateBucketRequest || msg instanceof UpsertUserRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.username(), msg.password());
    return request;
}
 
Example #28
Source File: HttpRequestDecoderTest.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test(expected = JsonMappingException.class)
public void testLookupPostWithNoArgs() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/search/lookup");
    addCookie(request);
    decoder.decode(null, request, results);
}
 
Example #29
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testPing(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/ping");
    channel.writeAndFlush(req);
    latch.await();

    StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
    Assert.assertEquals(resp.getStatus(), "Healthy");
    Assert.assertTrue(headers.contains("x-request-id"));
}
 
Example #30
Source File: HttpObjectEncoderBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
    byte[] bytes = new byte[256];
    content = Unpooled.buffer(bytes.length);
    content.writeBytes(bytes);
    ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
    HttpHeaders headersWithChunked = new DefaultHttpHeaders(false);
    headersWithChunked.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    HttpHeaders headersWithContentLength = new DefaultHttpHeaders(false);
    headersWithContentLength.add(HttpHeaderNames.CONTENT_LENGTH, testContent.readableBytes());

    fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", testContent,
            headersWithContentLength, EmptyHttpHeaders.INSTANCE);
    contentLengthRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index",
            headersWithContentLength);
    chunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", headersWithChunked);
    lastContent = new DefaultLastHttpContent(testContent, false);

    encoder = new HttpRequestEncoder();
    context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
            UnpooledByteBufAllocator.DEFAULT, encoder) {
        @Override
        protected void handleException(Throwable t) {
            handleUnexpectedException(t);
        }
    };
}