Java Code Examples for io.netty.handler.codec.http.HttpMethod#PUT

The following examples show how to use io.netty.handler.codec.http.HttpMethod#PUT . 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: 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 2
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Tests keep-alive for different HTTP methods and error statuses.
 */
@Test
public void keepAliveTest() {
  HttpMethod[] HTTP_METHODS = {HttpMethod.POST, HttpMethod.PUT, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE};
  EmbeddedChannel channel = createEmbeddedChannel();
  for (HttpMethod httpMethod : HTTP_METHODS) {
    for (RestServiceErrorCode errorCode : RestServiceErrorCode.values()) {
      channel = doKeepAliveTest(channel, httpMethod, errorCode, getExpectedHttpResponseStatus(errorCode), 0, null);
    }
    channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, null);
    channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, true);
    channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, false);
  }
  // special test for put because the keep alive depends on content size (0 already tested above)
  channel = doKeepAliveTest(channel, HttpMethod.PUT, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 1, null);
  channel = doKeepAliveTest(channel, HttpMethod.PUT, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 100, null);
  channel.close();
}
 
Example 3
Source File: SnapshotTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testSecondModelVersionSnapshot"})
public void testSetDefaultSnapshot() throws InterruptedException {
    Channel managementChannel = TestUtils.getManagementChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    String requestURL = "/models/noopversioned/1.2.1/set-default";

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, requestURL);
    managementChannel.writeAndFlush(req);
    TestUtils.getLatch().await();

    validateSnapshot("snapshot8.cfg");
    waitForSnapshot();
}
 
Example 4
Source File: SingleMatcherTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void static_factory_with_path_and_methods_varargs_sets_values_as_expected() {
    // given
    String path = "/" + UUID.randomUUID().toString();
    HttpMethod[] methodVarargs = new HttpMethod[]{HttpMethod.GET, HttpMethod.PUT};

    // when
    SingleMatcher matcher = SingleMatcher.match(path, methodVarargs);

    // then
    assertThat(matcher.matchingPathTemplates(), is(Arrays.asList(path)));
    assertThat(matcher.matchingMethods(), notNullValue());
    assertThat(matcher.matchingMethods().size(), is(methodVarargs.length));
    for (HttpMethod expectedMethod : methodVarargs) {
        assertThat(matcher.matchingMethods().contains(expectedMethod), is(true));
    }
    assertThat(matcher.isMatchAllMethods(), is(false));
}
 
Example 5
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 6
Source File: ThriftUnmarshaller.java    From xio with Apache License 2.0 6 votes vote down vote up
private static HttpMethod build(Http1Method method) {
  if (method != null) {
    switch (method) {
      case CONNECT:
        return HttpMethod.CONNECT;
      case DELETE:
        return HttpMethod.DELETE;
      case GET:
        return HttpMethod.GET;
      case HEAD:
        return HttpMethod.HEAD;
      case OPTIONS:
        return HttpMethod.OPTIONS;
      case PATCH:
        return HttpMethod.PATCH;
      case POST:
        return HttpMethod.POST;
      case PUT:
        return HttpMethod.PUT;
      case TRACE:
        return HttpMethod.TRACE;
    }
  }
  return null;
}
 
Example 7
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link NettyRequest#addContent(HttpContent)} and
 * {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} with different digest algorithms (including a test
 * with no digest algorithm).
 * @throws Exception
 */
@Test
public void contentAddAndReadTest() throws Exception {
  String[] digestAlgorithms = {"", "MD5", "SHA-1", "SHA-256"};
  HttpMethod[] methods = {HttpMethod.POST, HttpMethod.PUT};
  for (HttpMethod method : methods) {
    for (String digestAlgorithm : digestAlgorithms) {
      contentAddAndReadTest(digestAlgorithm, true, method);
      contentAddAndReadTest(digestAlgorithm, false, method);
    }
  }
}
 
Example 8
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testScaleModelNotFound() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/models/fake");
    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: fake");
}
 
Example 9
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 10
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testSyncScaleModel(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.PUT,
                    "/models/noop_v0.1?synchronous=true&min_worker=1");
    channel.writeAndFlush(req);
    latch.await();

    StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
    Assert.assertEquals(resp.getStatus(), "Workers scaled");
}
 
Example 11
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testScaleModel(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.PUT, "/models/noop_v0.1?min_worker=2");
    channel.writeAndFlush(req);
    latch.await();

    StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
    Assert.assertEquals(resp.getStatus(), "Processing worker updates...");
}
 
Example 12
Source File: HttpClient.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
private static void setContent(IHttpRequest request, HttpMethod httpMethod, HttpEntityEnclosingRequestBase httpRequest) {
    if (httpMethod != HttpMethod.POST && httpMethod != HttpMethod.PUT) return;
    httpRequest.setEntity(request.getContent());
    if (request.getContentType() != null && request.getContent() != null) {
        httpRequest.setHeader("ContentType", request.getContentType());
    }
}
 
Example 13
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link NettyRequest#addContent(HttpContent)} and
 * {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} with different digest algorithms (including a test
 * with no digest algorithm) and checks that back pressure is applied correctly.
 * @throws Exception
 */
@Test
public void backPressureTest() throws Exception {
  String[] digestAlgorithms = {"", "MD5", "SHA-1", "SHA-256"};

  HttpMethod[] methods = {HttpMethod.POST, HttpMethod.PUT};
  for (HttpMethod method : methods) {
    for (String digestAlgorithm : digestAlgorithms) {
      backPressureTest(digestAlgorithm, true, method);
      backPressureTest(digestAlgorithm, false, method);
    }
  }
}
 
Example 14
Source File: SnapshotTest.java    From serve with Apache License 2.0 5 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testNoSnapshotOnInvalidModelVersionScale"})
public void testNoSnapshotOnInvalidModelVersionSetDefault() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);
    String requestURL = "/models/noopversioned/3.0/set-default";

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, requestURL);
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    validateSnapshot("snapshot9.cfg");
}
 
Example 15
Source File: TestUtils.java    From serve with Apache License 2.0 5 votes vote down vote up
public static void setDefault(Channel channel, String modelName, String defaultVersion) {
    String requestURL = "/models/" + modelName + "/" + defaultVersion + "/set-default";

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, requestURL);
    channel.writeAndFlush(req);
}
 
Example 16
Source File: HttpRequestUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isWriteFromBrowserWithoutOrigin(HttpRequest request) {
  HttpMethod method = request.method();

  return StringUtil.isEmpty(getOrigin(request)) && isRegularBrowser(request) && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE);
}
 
Example 17
Source File: InboundHttp2ToHttpAdapterTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test
public void clientRequestStreamDependencyInHttpMessageFlow() throws Exception {
    boostrapEnv(1, 2, 1);
    final String text = "hello world big time data!";
    final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
    final String text2 = "hello world big time data...number 2!!";
    final ByteBuf content2 = Unpooled.copiedBuffer(text2.getBytes());
    final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            "/some/path/resource", content, true);
    final FullHttpMessage request2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            "/some/path/resource2", content2, true);
    try {
        HttpHeaders httpHeaders = request.headers();
        httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
        httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
        httpHeaders.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 16);
        HttpHeaders httpHeaders2 = request2.headers();
        httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
        httpHeaders2.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3);
        httpHeaders2.setShort(HttpConversionUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), (short) 123);
        httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length());
        final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("PUT")).path(
                new AsciiString("/some/path/resource"));
        final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(new AsciiString("PUT")).path(
                new AsciiString("/some/path/resource2"));
        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientHandler.encoder().writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
                clientHandler.encoder().writeHeaders(ctxClient(), 5, http2Headers2, 3, (short) 123, true, 0,
                        false, newPromiseClient());
                clientChannel.flush(); // Headers are queued in the flow controller and so flush them.
                clientHandler.encoder().writeData(ctxClient(), 3, content.retainedDuplicate(), 0, true,
                                                  newPromiseClient());
                clientHandler.encoder().writeData(ctxClient(), 5, content2.retainedDuplicate(), 0, true,
                                                  newPromiseClient());
                clientChannel.flush();
            }
        });
        awaitRequests();
        ArgumentCaptor<FullHttpMessage> httpObjectCaptor = ArgumentCaptor.forClass(FullHttpMessage.class);
        verify(serverListener, times(2)).messageReceived(httpObjectCaptor.capture());
        capturedRequests = httpObjectCaptor.getAllValues();
        assertEquals(request, capturedRequests.get(0));
        assertEquals(request2, capturedRequests.get(1));
    } finally {
        request.release();
        request2.release();
    }
}
 
Example 18
Source File: Route.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static Route put(String uri) {
    return new Route(HttpMethod.PUT, uri);
}
 
Example 19
Source File: HttpToHttp2OutboundAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
private void writeRequest(HttpToHttp2OutboundAdapter adapter, ChannelPromise promise) {
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/", Unpooled.wrappedBuffer(new byte[16]));
    request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http");
    adapter.write(ctx, request, promise);
}
 
Example 20
Source File: EtcdKeyPutRequest.java    From etcd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs an EtcdKeysRequest
 *
 * @param clientImpl   the client to handle this request
 * @param key          key to change
 * @param retryHandler Handles retries on fails
 */
public EtcdKeyPutRequest(EtcdClientImpl clientImpl, String key, RetryPolicy retryHandler) {
  super(clientImpl, HttpMethod.PUT, retryHandler, key);
}