com.linecorp.armeria.common.HttpMethod Java Examples

The following examples show how to use com.linecorp.armeria.common.HttpMethod. 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: HttpClientWithRequestLogTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void exceptionRaisedInDecorator() {
    final WebClient client =
            WebClient.builder(LOCAL_HOST)
                     .decorator((delegate, ctx, req1) -> {
                         throw new AnticipatedException();
                     })
                     .decorator(new ExceptionHoldingDecorator())
                     .build();

    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    assertThatThrownBy(() -> client.execute(req).aggregate().get())
            .hasCauseExactlyInstanceOf(AnticipatedException.class);

    // If the RequestLog has requestCause and responseCause, the RequestLog is complete.
    // The RequestLog should be complete so that ReleasableHolder#release() is called in UserClient
    // to decrease the active request count of EventLoop.
    await().untilAsserted(() -> assertThat(
            requestCauseHolder.get()).isExactlyInstanceOf(AnticipatedException.class));
    await().untilAsserted(() -> assertThat(
            responseCauseHolder.get()).isExactlyInstanceOf(AnticipatedException.class));
    await().untilAsserted(() -> assertThat(req.isComplete()).isTrue());
}
 
Example #2
Source File: LoggingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void sanitizeRequestHeaders() throws Exception {
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "test.com"));

    final ClientRequestContext ctx = ClientRequestContext.of(req);

    // use default logger
    final LoggingClient defaultLoggerClient =
            LoggingClient.builder()
                         .requestLogLevel(LogLevel.INFO)
                         .successfulResponseLogLevel(LogLevel.INFO)
                         .requestHeadersSanitizer(RegexBasedSanitizer.of(
                                 Pattern.compile("trustin"),
                                 Pattern.compile("com")))
                         .build(delegate);

    // Pre sanitize step
    assertThat(ctx.logBuilder().toString()).contains("trustin");
    assertThat(ctx.logBuilder().toString()).contains("test.com");
    defaultLoggerClient.execute(ctx, req);
    // After the sanitize
    assertThat(ctx.logBuilder().toString()).doesNotContain("trustin");
    assertThat(ctx.logBuilder().toString()).doesNotContain("com");
}
 
Example #3
Source File: Http1EmptyRequestTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(value = HttpMethod.class, mode = Mode.EXCLUDE, names = "UNKNOWN")
void emptyRequest(HttpMethod method) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();

        final WebClient client = WebClient.of("h1c://127.0.0.1:" + port);
        client.execute(HttpRequest.of(method, "/")).aggregate();

        try (Socket s = ss.accept()) {
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(s.getInputStream(), StandardCharsets.US_ASCII));
            assertThat(in.readLine()).isEqualTo(method.name() + " / HTTP/1.1");
            assertThat(in.readLine()).startsWith("host: 127.0.0.1:");
            assertThat(in.readLine()).startsWith("user-agent: armeria/");
            if (hasContent(method)) {
                assertThat(in.readLine()).isEqualTo("content-length: 0");
            }
            assertThat(in.readLine()).isEmpty();
        }
    }
}
 
Example #4
Source File: RestfulJsonResponseConverter.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers,
                                    @Nullable Object resObj,
                                    HttpHeaders trailingHeaders) throws Exception {
    try {
        final HttpRequest request = RequestContext.current().request();
        final HttpData httpData =
                resObj != null &&
                resObj.getClass() == Object.class ? EMPTY_RESULT
                                                  : HttpData.wrap(Jackson.writeValueAsBytes(resObj));

        final ResponseHeadersBuilder builder = headers.toBuilder();
        if (HttpMethod.POST == request.method()) {
            builder.status(HttpStatus.CREATED);
        }
        if (builder.contentType() == null) {
            builder.contentType(MediaType.JSON_UTF_8);
        }
        return HttpResponse.of(builder.build(), httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
        return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
 
Example #5
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testStreamRequestLongerThanTimeout(WebClient client) throws Exception {
    // Disable timeouts and length limits so that test does not fail due to slow transfer.
    clientWriteTimeoutMillis = 0;
    clientResponseTimeoutMillis = 0;
    clientMaxResponseLength = 0;
    serverRequestTimeoutMillis = 0;

    final HttpRequestWriter request = HttpRequest.streaming(HttpMethod.POST, "/echo");
    final HttpResponse response = client.execute(request);
    request.write(HttpData.ofUtf8("a"));
    Thread.sleep(2000);
    request.write(HttpData.ofUtf8("b"));
    Thread.sleep(2000);
    request.write(HttpData.ofUtf8("c"));
    Thread.sleep(2000);
    request.write(HttpData.ofUtf8("d"));
    Thread.sleep(2000);
    request.write(HttpData.ofUtf8("e"));
    request.close();
    assertThat(response.aggregate().get().contentUtf8()).isEqualTo("abcde");
}
 
Example #6
Source File: ProjectServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void unremoveProject() {
    final WebClient client = dogma.httpClient();
    createProject(client, "bar");

    final String projectPath = PROJECTS_PREFIX + "/bar";
    client.delete(projectPath).aggregate().join();

    final RequestHeaders headers = RequestHeaders.of(HttpMethod.PATCH, projectPath,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH);

    final String unremovePatch = "[{\"op\":\"replace\",\"path\":\"/status\",\"value\":\"active\"}]";
    final AggregatedHttpResponse aRes = client.execute(headers, unremovePatch).aggregate().join();
    assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.OK);
    final String expectedJson =
            '{' +
            "   \"name\": \"bar\"," +
            "   \"creator\": {" +
            "       \"name\": \"System\"," +
            "       \"email\": \"[email protected]\"" +
            "   }," +
            "   \"url\": \"/api/v1/projects/bar\"," +
            "   \"createdAt\": \"${json-unit.ignore}\"" +
            '}';
    assertThatJson(aRes.contentUtf8()).isEqualTo(expectedJson);
}
 
Example #7
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public <T> CompletableFuture<Entry<T>> getFile(String projectName, String repositoryName, Revision revision,
                                               Query<T> query) {
    try {
        validateProjectAndRepositoryName(projectName, repositoryName);
        requireNonNull(revision, "revision");
        requireNonNull(query, "query");

        // TODO(trustin) No need to normalize a revision once server response contains it.
        return maybeNormalizeRevision(projectName, repositoryName, revision).thenCompose(normRev -> {
            final StringBuilder path = pathBuilder(projectName, repositoryName);
            path.append("/contents").append(query.path());
            path.append("?revision=").append(normRev.text());
            appendJsonPaths(path, query.type(), query.expressions());

            return client.execute(headers(HttpMethod.GET, path.toString()))
                         .aggregate()
                         .thenApply(res -> getFile(normRev, res, query));
        });
    } catch (Exception e) {
        return exceptionallyCompletedFuture(e);
    }
}
 
Example #8
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ServiceRequestContext newServiceContext(
        String path, @Nullable String query) throws Exception {

    final InetSocketAddress remoteAddress = new InetSocketAddress(
            InetAddress.getByAddress("client.com", new byte[] { 1, 2, 3, 4 }), 5678);
    final InetSocketAddress localAddress = new InetSocketAddress(
            InetAddress.getByAddress("server.com", new byte[] { 5, 6, 7, 8 }), 8080);

    final String pathAndQuery = path + (query != null ? '?' + query : "");
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.GET, pathAndQuery,
                                                             HttpHeaderNames.AUTHORITY, "server.com:8080",
                                                             HttpHeaderNames.USER_AGENT, "some-client"));

    final ServiceRequestContext ctx =
            ServiceRequestContext.builder(req)
                                 .sslSession(newSslSession())
                                 .remoteAddress(remoteAddress)
                                 .localAddress(localAddress)
                                 .proxiedAddresses(
                                         ProxiedAddresses.of(new InetSocketAddress("9.10.11.12", 0)))
                                 .build();

    ctx.setAttr(MY_ATTR, new CustomObject("some-name", "some-value"));
    return ctx;
}
 
Example #9
Source File: AnnotatedServiceAnnotationAliasTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void metaOfMetaAnnotation_ProducesJson() {
    final AggregatedHttpResponse msg =
            WebClient.of(rule.httpUri())
                     .execute(RequestHeaders.of(HttpMethod.POST, "/hello",
                                                HttpHeaderNames.CONTENT_TYPE,
                                                MediaType.PLAIN_TEXT_UTF_8,
                                                HttpHeaderNames.ACCEPT,
                                                "application/json; charset=utf-8"),
                              HttpData.ofUtf8("Armeria"))
                     .aggregate().join();
    assertThat(msg.status()).isEqualTo(HttpStatus.CREATED);
    assertThat(msg.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThat(msg.headers().get(HttpHeaderNames.of("x-foo"))).isEqualTo("foo");
    assertThat(msg.headers().get(HttpHeaderNames.of("x-bar"))).isEqualTo("bar");
    assertThat(msg.contentUtf8())
            .isEqualTo("Hello, Armeria (decorated-1) (decorated-2) (decorated-3)!");
    assertThat(msg.trailers().get(HttpHeaderNames.of("x-baz"))).isEqualTo("baz");
    assertThat(msg.trailers().get(HttpHeaderNames.of("x-qux"))).isEqualTo("qux");
}
 
Example #10
Source File: DefaultClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void canBringAttributeInServiceRequestContext() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext serviceContext = ServiceRequestContext.of(req);
    final AttributeKey<String> fooKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "foo");
    serviceContext.setAttr(fooKey, "foo");
    try (SafeCloseable ignored = serviceContext.push()) {
        final ClientRequestContext clientContext = ClientRequestContext.of(req);
        assertThat(clientContext.attr(fooKey)).isEqualTo("foo");
        assertThat(clientContext.attrs().hasNext()).isTrue();

        final ClientRequestContext derivedContext = clientContext.newDerivedContext(
                clientContext.id(), clientContext.request(),
                clientContext.rpcRequest());
        assertThat(derivedContext.attr(fooKey)).isNotNull();
        // Attributes in serviceContext is not copied to clientContext when derived.

        final AttributeKey<String> barKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class,
                                                                 "bar");
        clientContext.setAttr(barKey, "bar");
        assertThat(serviceContext.attr(barKey)).isNull();
    }
}
 
Example #11
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static AggregatedHttpResponse addFooJson(WebClient client) {
    final String body =
            '{' +
            "   \"path\" : \"/foo.json\"," +
            "   \"type\" : \"UPSERT_JSON\"," +
            "   \"content\" : {\"a\": \"bar\"}," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Add foo.json\"," +
            "       \"detail\": \"Add because we need it.\"," +
            "       \"markup\": \"PLAINTEXT\"" +
            "   }" +
            '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    return client.execute(headers, body).aggregate().join();
}
 
Example #12
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static AggregatedHttpResponse editFooJson(WebClient client) {
    final String body =
            '{' +
            "   \"path\" : \"/foo.json\"," +
            "   \"type\" : \"APPLY_JSON_PATCH\"," +
            "   \"content\" : [{" +
            "       \"op\" : \"safeReplace\"," +
            "       \"path\": \"/a\"," +
            "       \"oldValue\": \"bar\"," +
            "       \"value\": \"baz\"" +
            "   }]," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Edit foo.json\"," +
            "       \"detail\": \"Edit because we need it.\"," +
            "       \"markup\": \"PLAINTEXT\"" +
            "   }" +
            '}';

    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    return client.execute(headers, body).aggregate().join();
}
 
Example #13
Source File: FramedGrpcServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void missingMethod() throws Exception {
    final HttpRequest req = HttpRequest.of(
            RequestHeaders.of(HttpMethod.POST, "/grpc.testing.TestService/FooCall",
                              HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto"));
    final RoutingResult routingResult = RoutingResult.builder()
                                                     .path("/grpc.testing.TestService/FooCall")
                                                     .build();
    final ServiceRequestContext ctx = ServiceRequestContext.builder(req)
                                                           .routingResult(routingResult)
                                                           .build();
    final HttpResponse response = grpcService.doPost(ctx, PooledHttpRequest.of(req));
    assertThat(response.aggregate().get()).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.builder(HttpStatus.OK)
                           .endOfStream(true)
                           .add(HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto")
                           .addInt("grpc-status", 12)
                           .add("grpc-message", "Method not found: grpc.testing.TestService/FooCall")
                           .addInt(HttpHeaderNames.CONTENT_LENGTH, 0)
                           .build(),
            HttpData.empty()));
}
 
Example #14
Source File: AnnotatedServiceFactory.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Map<HttpMethod, List<String>> getHttpMethodAnnotatedPatternMap(
        Set<Annotation> methodAnnotations) {
    final Map<HttpMethod, List<String>> httpMethodPatternMap = new EnumMap<>(HttpMethod.class);
    methodAnnotations.stream()
                     .filter(annotation -> HTTP_METHOD_MAP.containsKey(annotation.annotationType()))
                     .forEach(annotation -> {
                         final HttpMethod httpMethod = HTTP_METHOD_MAP.get(annotation.annotationType());
                         final String value = (String) invokeValueMethod(annotation);
                         final List<String> patterns = httpMethodPatternMap
                                 .computeIfAbsent(httpMethod, ignored -> new ArrayList<>());
                         if (DefaultValues.isSpecified(value)) {
                             patterns.add(value);
                         }
                     });
    return httpMethodPatternMap;
}
 
Example #15
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ClientRequestContext newClientContext(
        String path, @Nullable String query) throws Exception {

    final InetSocketAddress remoteAddress = new InetSocketAddress(
            InetAddress.getByAddress("server.com", new byte[] { 1, 2, 3, 4 }), 8080);
    final InetSocketAddress localAddress = new InetSocketAddress(
            InetAddress.getByAddress("client.com", new byte[] { 5, 6, 7, 8 }), 5678);

    final String pathAndQuery = path + (query != null ? '?' + query : "");
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.GET, pathAndQuery,
                                                             HttpHeaderNames.AUTHORITY, "server.com:8080",
                                                             HttpHeaderNames.USER_AGENT, "some-client"));

    final ClientRequestContext ctx =
            ClientRequestContext.builder(req)
                                .remoteAddress(remoteAddress)
                                .localAddress(localAddress)
                                .endpoint(Endpoint.of("server.com", 8080))
                                .sslSession(newSslSession())
                                .build();

    ctx.setAttr(MY_ATTR, new CustomObject("some-name", "some-value"));
    return ctx;
}
 
Example #16
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void unframed_serviceError() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());
    final SimpleRequest request =
            SimpleRequest.newBuilder()
                         .setResponseStatus(
                                 EchoStatus.newBuilder()
                                           .setCode(Status.DEADLINE_EXCEEDED.getCode().value()))
                         .build();
    final AggregatedHttpResponse response = client.execute(
            RequestHeaders.of(HttpMethod.POST,
                              UnitTestServiceGrpc.getStaticUnaryCallMethod().getFullMethodName(),
                              HttpHeaderNames.CONTENT_TYPE, "application/protobuf"),
            request.toByteArray()).aggregate().get();
    assertThat(response.status()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall");
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.UNKNOWN);
    });
}
 
Example #17
Source File: DefaultServiceRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void extendRequestTimeoutFromZero() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext ctx = ServiceRequestContext.of(req);

    ctx.eventLoop().execute(() -> {
        // This request now has an infinite timeout
        ctx.clearRequestTimeout();

        ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000);
        assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);

        ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, -1000);
        assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);
        finished.set(true);
    });

    await().untilTrue(finished);
}
 
Example #18
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handle(
    String hostName,
    String url,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  return handleMethod(
      HttpMethod.GET,
      hostName,
      url,
      HttpData.empty(),
      userAgent,
      experienceIdHeaderValue,
      clazz,
      fieldNamingPolicy,
      errorTimeout,
      maxRetries,
      exceptionsAllowedToRetry);
}
 
Example #19
Source File: ArmeriaReactiveWebServerFactory.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ServerBuilder configureService(ServerBuilder sb, HttpHandler httpHandler,
                                              DataBufferFactoryWrapper<?> factoryWrapper,
                                              @Nullable String serverHeader) {
    final ArmeriaHttpHandlerAdapter handler =
            new ArmeriaHttpHandlerAdapter(httpHandler, factoryWrapper);
    return sb.service(Route.ofCatchAll(), (ctx, req) -> {
        final CompletableFuture<HttpResponse> future = new CompletableFuture<>();
        final HttpResponse response = HttpResponse.from(future);
        final Disposable disposable = handler.handle(ctx, req, future, serverHeader).subscribe();
        response.whenComplete().handle((unused, cause) -> {
            if (cause != null) {
                if (ctx.method() != HttpMethod.HEAD) {
                    logger.debug("{} Response stream has been cancelled.", ctx, cause);
                }
                disposable.dispose();
            }
            return null;
        });
        return response;
    });
}
 
Example #20
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testUpgradeRequestExecutesLogicOnlyOnce() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder()
                                                     .useHttp2Preface(false)
                                                     .build();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .decorator(DecodingClient.newDecorator())
                                      .build();

    final AggregatedHttpResponse response = client.execute(
            AggregatedHttpRequest.of(HttpMethod.GET, "/only-once/request")).aggregate().get();

    assertThat(response.status()).isEqualTo(HttpStatus.OK);

    clientFactory.close();
}
 
Example #21
Source File: MatchesHeaderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void doesNotContain() {
    assertThat(client.execute(HttpRequest.of(RequestHeaders.of(
            HttpMethod.GET, "/doesNotContain", "your-header", "your-value")))
                     .aggregate().join().contentUtf8()).isEqualTo("!my-header");
    assertThat(client.execute(HttpRequest.of(RequestHeaders.of(
            HttpMethod.GET, "/doesNotContain", "my-header", "my-value")))
                     .aggregate().join().contentUtf8()).isEqualTo("fallback");
}
 
Example #22
Source File: ServerRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void url() {
    final HttpRequest req = HttpRequest.of(
            RequestHeaders.of(HttpMethod.GET, "/foo?name=hoge",
                              HttpHeaderNames.SCHEME, "http",
                              HttpHeaderNames.AUTHORITY, "example.com"));

    final HttpServerRequest braveReq = ServiceRequestContextAdapter.asHttpServerRequest(
            ServiceRequestContext.of(req));

    assertThat(braveReq.url()).isEqualTo("http://example.com/foo?name=hoge");
}
 
Example #23
Source File: RouteBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly-created {@link Route} based on the properties of this builder.
 */
public Route build() {
    checkState(pathMapping != null, "Must set a path before calling this.");
    if ((!consumes.isEmpty() || !produces.isEmpty()) && methods.isEmpty()) {
        throw new IllegalStateException("Must set methods if consumes or produces is not empty." +
                                        " consumes: " + consumes + ", produces: " + produces);
    }
    final Set<HttpMethod> pathMethods = methods.isEmpty() ? HttpMethod.knownMethods() : methods;
    return new DefaultRoute(pathMapping, pathMethods, consumes, produces,
                            paramPredicates, headerPredicates);
}
 
Example #24
Source File: HttpServerCorsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorsExposeHeaders() throws Exception {
    final WebClient client = client();
    final AggregatedHttpResponse response = request(client, HttpMethod.POST, "/cors", "http://example.com",
                                                    "POST");
    assertEquals(HttpStatus.OK, response.status());
    assertEquals("http://example.com", response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN));
    assertEquals("allow_request_header",
                 response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS));
    assertEquals("expose_header_1,expose_header_2",
                 response.headers().get(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS));
}
 
Example #25
Source File: AdministrativeServiceTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void updateStatus_setUnwritableAndNonReplicating() {
    final WebClient client = dogma.httpClient();
    final AggregatedHttpResponse res = client.execute(
            RequestHeaders.of(HttpMethod.PATCH, API_V1_PATH_PREFIX + "status",
                              HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_PATCH),
            "[{ \"op\": \"replace\", \"path\": \"/writable\", \"value\": false }," +
            " { \"op\": \"replace\", \"path\": \"/replicating\", \"value\": false }]").aggregate().join();

    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).isEqualTo(
            "{ \"writable\": false, \"replicating\": false }");
}
 
Example #26
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void longPollingDisabled() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());
    final CompletableFuture<AggregatedHttpResponse> f = client.execute(
            RequestHeaders.of(HttpMethod.GET, "/hc_long_polling_disabled",
                              HttpHeaderNames.PREFER, "wait=60",
                              HttpHeaderNames.IF_NONE_MATCH, "\"healthy\"")).aggregate();
    assertThat(f.get(10, TimeUnit.SECONDS)).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                               "armeria-lphc", "0, 0"),
            HttpData.ofUtf8("{\"healthy\":true}")));
}
 
Example #27
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testInjectionService() {
    AggregatedHttpResponse res;

    res = client.get("/injection/param/armeria/1?gender=male").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).isArray()
                                     .ofLength(3)
                                     .thatContains("armeria")
                                     .thatContains(1)
                                     .thatContains("MALE");

    final RequestHeaders headers = RequestHeaders.builder(HttpMethod.GET, "/injection/header")
                                                 .add(HttpHeaderNames.of("x-armeria-text"), "armeria")
                                                 .add(HttpHeaderNames.of("x-armeria-sequence"), "1")
                                                 .add(HttpHeaderNames.of("x-armeria-sequence"), "2")
                                                 .add(HttpHeaderNames.COOKIE, "a=1")
                                                 .add(HttpHeaderNames.COOKIE, "b=1").build();

    res = client.execute(headers).aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).isArray()
                                     .ofLength(3)
                                     .thatContains("armeria")
                                     .thatContains(Arrays.asList(1, 2))
                                     .thatContains(Arrays.asList("a", "b"));
}
 
Example #28
Source File: AnnotatedServiceHandlersOrderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void responseConverterOrder() throws Exception {
    final AggregatedHttpRequest aReq = AggregatedHttpRequest.of(
            HttpMethod.POST, "/1/responseConverterOrder", MediaType.PLAIN_TEXT_UTF_8, "foo");
    final AggregatedHttpResponse aRes = executeRequest(aReq);

    assertThat(aRes.status()).isEqualTo(HttpStatus.OK);
    // Converted from the ServiceLevelResponseConverter.
    assertThat(aRes.contentUtf8()).isEqualTo("hello foo");

    // method level(+1) -> class level(+1) -> service level(+1) -> server level(+1)
    assertThat(responseCounter.get()).isEqualTo(4);
}
 
Example #29
Source File: MethodInfo.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
public MethodInfo(String name,
                  TypeSignature returnTypeSignature,
                  Iterable<FieldInfo> parameters,
                  Iterable<TypeSignature> exceptionTypeSignatures,
                  Iterable<EndpointInfo> endpoints) {
    this(name, returnTypeSignature, parameters, exceptionTypeSignatures, endpoints, HttpMethod.POST, null);
}
 
Example #30
Source File: MeterIdPrefixFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ServiceRequestContext newContext(HttpMethod method, String path,
                                                @Nullable Object requestContent) {
    final ServiceRequestContext ctx = ServiceRequestContext.of(HttpRequest.of(method, path));
    ctx.logBuilder().requestContent(requestContent, null);
    ctx.logBuilder().endRequest();
    return ctx;
}