com.linecorp.armeria.common.MediaType Java Examples

The following examples show how to use com.linecorp.armeria.common.MediaType. 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: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void makeUnframedRequest(String name) throws Exception {
    final WebClient client =
            Clients.builder(server.httpUri())
                   .factory(clientFactory)
                   .addHttpHeader(HttpHeaderNames.CONTENT_TYPE, MediaType.PROTOBUF.toString())
                   .build(WebClient.class);

    final SimpleRequest request =
            SimpleRequest.newBuilder()
                         .setPayload(Payload.newBuilder()
                                            .setBody(ByteString.copyFromUtf8(name)))
                         .build();
    try {
        client.post("/armeria.grpc.testing.TestService/UnaryCall2", request.toByteArray());
    } catch (Throwable t) {
        // Ignore, we will count these up
    }
}
 
Example #2
Source File: ArmeriaHttpHandlerAdapter.java    From armeria with Apache License 2.0 6 votes vote down vote up
Mono<Void> handle(ServiceRequestContext ctx, HttpRequest req, CompletableFuture<HttpResponse> future,
                  @Nullable String serverHeader) {
    final ArmeriaServerHttpRequest convertedRequest;
    try {
        convertedRequest = new ArmeriaServerHttpRequest(ctx, req, factoryWrapper);
    } catch (Exception e) {
        final String path = req.path();
        logger.warn("{} Invalid request path: {}", ctx, path, e);
        future.complete(HttpResponse.of(HttpStatus.BAD_REQUEST,
                                        MediaType.PLAIN_TEXT_UTF_8,
                                        HttpStatus.BAD_REQUEST + "\nInvalid request path: " + path));
        return Mono.empty();
    }

    final ArmeriaServerHttpResponse convertedResponse =
            new ArmeriaServerHttpResponse(ctx, future, factoryWrapper, serverHeader);
    return httpHandler.handle(convertedRequest, convertedResponse)
                      .doOnSuccess(unused -> {
                          convertedResponse.setComplete().subscribe();
                      })
                      .doOnError(cause -> {
                          logger.debug("{} Failed to handle a request", ctx, cause);
                          convertedResponse.setComplete(cause).subscribe();
                      });
}
 
Example #3
Source File: SamlService.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link SamlParameters} instance with the specified {@link AggregatedHttpRequest}.
 */
SamlParameters(AggregatedHttpRequest req) {
    requireNonNull(req, "req");
    final MediaType contentType = req.contentType();

    if (contentType != null && contentType.belongsTo(MediaType.FORM_DATA)) {
        final String query = req.content(contentType.charset(StandardCharsets.UTF_8));
        params = QueryParams.fromQueryString(query);
    } else {
        final String path = req.path();
        final int queryStartIdx = path.indexOf('?');
        if (queryStartIdx < 0) {
            params = QueryParams.of();
        } else {
            params = QueryParams.fromQueryString(path.substring(queryStartIdx + 1));
        }
    }
}
 
Example #4
Source File: AnnotatedServiceHandlersOrderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void requestConverterOrder() throws Exception {
    final String body = "{\"foo\":\"bar\"}";
    final AggregatedHttpRequest aReq = AggregatedHttpRequest.of(
            HttpMethod.POST, "/1/requestConverterOrder", MediaType.JSON, body);

    final AggregatedHttpResponse aRes = executeRequest(aReq);

    assertThat(aRes.status()).isEqualTo(HttpStatus.OK);
    // Converted from the default converter which is JacksonRequestConverterFunction.
    assertThat(aRes.contentUtf8()).isEqualTo(body);

    // parameter level(+1) -> method level(+1) -> class level(+1) -> service level(+1) -> server level(+1)
    // -> default
    assertThat(requestCounter.get()).isEqualTo(5);
}
 
Example #5
Source File: SamlAuthTest.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseBuiltinWebPageOnlyForLogout() {
    AggregatedHttpResponse resp;

    // Receive HTML which submits SAMLRequest to IdP.
    resp = dogma.httpClient().get(AuthProvider.LOGIN_PATH).aggregate().join();
    assertThat(resp.status()).isEqualTo(HttpStatus.OK);
    assertThat(resp.headers().contentType()).isEqualTo(MediaType.HTML_UTF_8);
    assertThat(resp.contentUtf8()).contains("<input type=\"hidden\" name=\"SAMLRequest\"");

    // Redirect to built-in web logout page.
    resp = dogma.httpClient().get(AuthProvider.LOGOUT_PATH).aggregate().join();
    assertThat(resp.status()).isEqualTo(HttpStatus.MOVED_PERMANENTLY);
    assertThat(resp.headers().get(HttpHeaderNames.LOCATION))
            .isEqualTo(AuthProvider.BUILTIN_WEB_LOGOUT_PATH);
}
 
Example #6
Source File: THttpService.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
private SerializationFormat determineSerializationFormat(HttpRequest req) {
    final HttpHeaders headers = req.headers();
    final MediaType contentType = headers.contentType();

    final SerializationFormat serializationFormat;
    if (contentType != null) {
        serializationFormat = findSerializationFormat(contentType);
        if (serializationFormat == null) {
            // Browser clients often send a non-Thrift content type.
            // Choose the default serialization format for some vague media types.
            if (!("text".equals(contentType.type()) &&
                  "plain".equals(contentType.subtype())) &&
                !("application".equals(contentType.type()) &&
                  "octet-stream".equals(contentType.subtype()))) {
                return null;
            }
        } else {
            return serializationFormat;
        }
    }

    return defaultSerializationFormat();
}
 
Example #7
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private RequestHeadersBuilder headersBuilder(HttpMethod method, String path) {
    final RequestHeadersBuilder builder = RequestHeaders.builder();
    builder.method(method)
           .path(path)
           .set(HttpHeaderNames.AUTHORIZATION, authorization)
           .setObject(HttpHeaderNames.ACCEPT, MediaType.JSON);

    switch (method) {
        case POST:
        case PUT:
            builder.contentType(MediaType.JSON_UTF_8);
            break;
        case PATCH:
            builder.contentType(JSON_PATCH_UTF8);
            break;
    }

    return builder;
}
 
Example #8
Source File: StringResponseConverterFunctionTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void aggregatedText() throws Exception {
    final ResponseHeaders expectedHeadersWithoutContentLength =
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
    final ResponseHeaders expectedHeadersWithContentLength =
            expectedHeadersWithoutContentLength.withMutations(h -> {
                h.addInt(HttpHeaderNames.CONTENT_LENGTH, 11);
            });

    final List<String> contents = ImmutableList.of("foo", ",", "bar", ",", "baz");
    for (final Object result : ImmutableList.of(Flux.fromIterable(contents),    // publisher
                                                contents.stream(),              // stream
                                                contents)) {                    // iterable
        StepVerifier.create(from(result))
                    .expectNext(result instanceof Iterable ? expectedHeadersWithContentLength
                                                           : expectedHeadersWithoutContentLength)
                    .expectNext(HttpData.wrap("foo,bar,baz".getBytes()))
                    .expectComplete()
                    .verify();
    }
}
 
Example #9
Source File: CreateApiResponseConverter.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 ResponseHeadersBuilder builder = headers.toBuilder();
        if (builder.contentType() == null) {
            builder.contentType(MediaType.JSON_UTF_8);
        }

        final JsonNode jsonNode = Jackson.valueToTree(resObj);
        if (builder.get(HttpHeaderNames.LOCATION) == null) {
            final String url = jsonNode.get("url").asText();

            // Remove the url field and send it with the LOCATION header.
            ((ObjectNode) jsonNode).remove("url");
            builder.add(HttpHeaderNames.LOCATION, url);
        }

        return HttpResponse.of(builder.build(), HttpData.wrap(Jackson.writeValueAsBytes(jsonNode)),
                               trailingHeaders);
    } catch (JsonProcessingException e) {
        logger.debug("Failed to convert a response:", e);
        return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
 
Example #10
Source File: TestConverters.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HttpResponse httpResponse(HttpData data) {
    final HttpResponseWriter res = HttpResponse.streaming();
    final long current = System.currentTimeMillis();
    final ResponseHeadersBuilder headers = ResponseHeaders.builder(HttpStatus.OK);
    headers.setInt(HttpHeaderNames.CONTENT_LENGTH, data.length());
    headers.setTimeMillis(HttpHeaderNames.DATE, current);

    final MediaType contentType = ServiceRequestContext.current().negotiatedResponseMediaType();
    if (contentType != null) {
        headers.contentType(contentType);
    }

    res.write(headers.build());
    res.write(data);
    res.close();
    return res;
}
 
Example #11
Source File: RetryingClientWithLoggingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/hello", new AbstractHttpService() {
        final AtomicInteger reqCount = new AtomicInteger();

        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) {
            ctx.mutateAdditionalResponseTrailers(
                    mutator -> mutator.add(HttpHeaderNames.of("foo"), "bar"));
            if (reqCount.getAndIncrement() < 1) {
                return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
            } else {
                return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "hello");
            }
        }
    });
}
 
Example #12
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Unlike {@link #decodedContentPreview()}, the content preview of this test is encoded data because
 * the previewing decorator is inserted before {@link DecodingClient}.
 */
@Test
void contentPreviewIsDecodedInPreviewer() {
    final WebClient client = WebClient.builder(server.httpUri())
                                      .decorator(decodingContentPreviewDecorator())
                                      .decorator(DecodingClient.newDecorator())
                                      .build();
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, "/",
                                                     HttpHeaderNames.CONTENT_TYPE,
                                                     MediaType.PLAIN_TEXT_UTF_8);

    final ClientRequestContext context;
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        final AggregatedHttpResponse res = client.execute(headers, "Armeria").aggregate().join();
        assertThat(res.contentUtf8()).isEqualTo("Hello Armeria!");
        assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip");
        context = captor.get();
    }

    final RequestLog requestLog = context.log().whenComplete().join();
    assertThat(requestLog.requestContentPreview()).isEqualTo("Armeria");
    assertThat(requestLog.responseContentPreview()).isEqualTo("Hello Armeria!");
}
 
Example #13
Source File: AnnotatedServiceResponseConverterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void shouldBeConvertedByDefaultResponseConverter(WebClient client) throws Exception {
    AggregatedHttpResponse res;

    res = aggregated(client.get("/string"));
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.contentUtf8()).isEqualTo(STRING);
    assertThat(res.contentAscii()).isNotEqualTo(STRING);

    res = aggregated(client.get("/byteArray"));
    assertThat(res.contentType()).isEqualTo(MediaType.OCTET_STREAM);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/httpData"));
    assertThat(res.contentType()).isEqualTo(MediaType.OCTET_STREAM);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/jsonNode"));
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThat(res.content().array()).isEqualTo(mapper.writeValueAsBytes(JSONNODE));
}
 
Example #14
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void waitUntilHealthy() throws Exception {
    // Make the server unhealthy.
    checker.setHealthy(false);

    final CompletableFuture<AggregatedHttpResponse> f = sendLongPollingGet("unhealthy");

    // Should not wake up until the server becomes unhealthy.
    assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS))
            .isInstanceOf(TimeoutException.class);

    // Make the server healthy so the response comes in.
    checker.setHealthy(true);
    assertThat(f.get()).isEqualTo(AggregatedHttpResponse.of(
            ImmutableList.of(ResponseHeaders.builder(HttpStatus.PROCESSING)
                                            .set("armeria-lphc", "60, 5")
                                            .build()),
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8,
                               "armeria-lphc", "60, 5"),
            HttpData.ofUtf8("{\"healthy\":true}"),
            HttpHeaders.of()));
}
 
Example #15
Source File: ObservableResponseConverterFunctionTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void observable() {
    final WebClient client = WebClient.of(server.httpUri() + "/observable");

    AggregatedHttpResponse res;

    res = client.get("/string").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.contentUtf8()).isEqualTo("a");

    res = client.get("/json/1").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8())
            .isArray().ofLength(1).thatContains("a");

    res = client.get("/json/3").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8())
            .isArray().ofLength(3).thatContains("a").thatContains("b").thatContains("c");

    res = client.get("/error").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example #16
Source File: MyAuthHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when the SAML authentication process is finished and a user is authenticated. You can get
 * information about the authenticated user from the {@link Response}, especially his or her login name.
 * In this example, an email address is used as a login name. The login name is transferred to a web
 * browser via {@code Set-Cookie} header.
 */
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final NameID nameId = getNameId(message.getMessage(), SamlNameIdFormat.EMAIL);
    final String username = nameId != null ? nameId.getValue() : null;
    if (username == null) {
        return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                               "<html><body>Username is not found.</body></html>");
    }

    logger.info("{} user '{}' has been logged in.", ctx, username);

    final Cookie cookie = Cookie.builder("username", username)
                                .httpOnly(true)
                                .domain("localhost")
                                .maxAge(60)
                                .path("/")
                                .build();
    return HttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.HTML_UTF_8,
                               HttpHeaderNames.SET_COOKIE, cookie.toSetCookieHeader(false)),
            HttpData.ofUtf8("<html><body onLoad=\"window.location.href='/welcome'\"></body></html>"));
}
 
Example #17
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private AggregatedHttpResponse sendViaHttpRedirectBindingProtocol(
        String path, String paramName, SAMLObject samlObject) throws Exception {

    final QueryParamsBuilder params = QueryParams.builder();
    params.add(paramName, toDeflatedBase64(samlObject));
    params.add(SIGNATURE_ALGORITHM, signatureAlgorithm);
    final String input = params.toQueryString();
    final String output = generateSignature(idpCredential, signatureAlgorithm, input);
    params.add(SIGNATURE, output);

    final HttpRequest req = HttpRequest.of(HttpMethod.POST, path, MediaType.FORM_DATA,
                                           params.toQueryString());
    return client.execute(req).aggregate().join();
}
 
Example #18
Source File: ElasticsearchDomainEndpointTest.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Test public void publicUrl() {
  MOCK_RESPONSE.set(AggregatedHttpResponse.of(
      HttpStatus.OK,
      MediaType.JSON_UTF_8,
      "{\n"
          + "  \"DomainStatus\": {\n"
          + "    \"Endpoint\": \"search-zipkin53-mhdyquzbwwzwvln6phfzr3lldi.ap-southeast-1.es.amazonaws.com\",\n"
          + "    \"Endpoints\": null\n"
          + "  }\n"
          + "}"));

  assertThat(client.get()).extracting("hostname")
      .isEqualTo(
          "search-zipkin53-mhdyquzbwwzwvln6phfzr3lldi.ap-southeast-1.es.amazonaws.com");
}
 
Example #19
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx,
                                    ResponseHeaders headers,
                                    @Nullable Object result,
                                    HttpHeaders trailers) throws Exception {
    if (result instanceof String) {
        return HttpResponse.of(HttpStatus.OK,
                               MediaType.ANY_TEXT_TYPE,
                               result.toString(),
                               trailers);
    }
    return ResponseConverterFunction.fallthrough();
}
 
Example #20
Source File: PostgresFortunesService.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Get("/fortunes")
public CompletableFuture<HttpResponse> fortunes(ServiceRequestContext ctx) {
  return getFortunes(ctx).thenApply(fortunes -> {
    fortunes.add(
        new Fortune(0, "Additional fortune added at request time."));
    fortunes.sort(Comparator.comparing(Fortune::getMessage));

    return HttpResponse.of(
            HttpStatus.OK, MediaType.HTML_UTF_8, buildMustacheTemplate(fortunes));
  });
}
 
Example #21
Source File: AnnotatedServiceResponseConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void produceTypeAnnotationBasedDefaultResponseConverter() throws Exception {
    final WebClient client = WebClient.of(rule.httpUri() + "/produce");

    AggregatedHttpResponse res;

    res = aggregated(client.get("/string"));
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.content().array()).isEqualTo("100".getBytes());

    res = aggregated(client.get("/byteArray"));
    assertThat(res.contentType()).isEqualTo(MediaType.OCTET_STREAM);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/httpData"));
    assertThat(res.contentType()).isEqualTo(MediaType.OCTET_STREAM);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/byteArrayGif"));
    assertThat(res.contentType()).isEqualTo(MediaType.GIF);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/httpDataPng"));
    assertThat(res.contentType()).isEqualTo(MediaType.PNG);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/byteArrayTxt"));
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/httpDataTxt"));
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.content().array()).isEqualTo(BYTEARRAY);

    res = aggregated(client.get("/jsonNode"));
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThat(res.content().array()).isEqualTo(mapper.writeValueAsBytes(JSONNODE));
}
 
Example #22
Source File: StringRequestConverterFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void jsonTextToCharSequence() throws Exception {
    when(req.contentType()).thenReturn(MediaType.JSON);
    when(req.content(ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET)).thenReturn(JSON_TEXT);

    final Object result = function.convertRequest(ctx, req, CharSequence.class, null);
    assertThat(result).isInstanceOf(CharSequence.class);
}
 
Example #23
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void editFileWithTextPatch() throws IOException {
    final WebClient client = dogma.httpClient();
    addBarTxt(client);
    final String patch =
            '{' +
            "   \"path\": \"/a/bar.txt\"," +
            "   \"type\": \"APPLY_TEXT_PATCH\"," +
            "   \"content\" : \"--- /a/bar.txt\\n" +
            "+++ /a/bar.txt\\n" +
            "@@ -1,1 +1,1 @@\\n" +
            "-text in the file.\\n" +
            "+text in some file.\\n\"," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Edit bar.txt\"," +
            "       \"detail\": \"Edit because we need it.\"," +
            "       \"markup\": \"PLAINTEXT\"" +
            "   }" +
            '}';

    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    final AggregatedHttpResponse res1 = client.execute(headers, patch).aggregate().join();
    final String expectedJson =
            '{' +
            "   \"revision\": 3," +
            "   \"pushedAt\": \"${json-unit.ignore}\"" +
            '}';
    final String actualJson = res1.contentUtf8();
    assertThatJson(actualJson).isEqualTo(expectedJson);

    final AggregatedHttpResponse res2 = client.get(CONTENTS_PREFIX + "/a/bar.txt").aggregate().join();
    assertThat(Jackson.readTree(res2.contentUtf8()).get("content").textValue())
            .isEqualTo("text in some file.\n");
}
 
Example #24
Source File: FramedGrpcServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void badContentType() throws Exception {
    final HttpRequest req = HttpRequest.of(
            RequestHeaders.of(HttpMethod.POST, "/grpc.testing.TestService.UnaryCall",
                              HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8));
    final ServiceRequestContext ctx = ServiceRequestContext.of(req);
    final HttpResponse response = grpcService.doPost(ctx, PooledHttpRequest.of(req));
    assertThat(response.aggregate().get()).isEqualTo(AggregatedHttpResponse.of(
            ResponseHeaders.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8,
                               HttpHeaderNames.CONTENT_LENGTH, 39),
            HttpData.ofUtf8("Missing or invalid Content-Type header.")));
}
 
Example #25
Source File: AbstractBindingBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void multiRouteBuilder() {
    final List<Route> routes = new AbstractBindingBuilder() {}
            .path("/foo")
            .pathPrefix("/bar")
            .get("/baz")
            .post("/qux")
            .methods(HttpMethod.GET, HttpMethod.POST)
            .consumes(MediaType.JSON_UTF_8, MediaType.HTML_UTF_8)
            .produces(MediaType.JAVASCRIPT_UTF_8)
            .buildRouteList();

    assertThat(routes.size()).isEqualTo(4);
    assertThat(routes).contains(
            Route.builder()
                 .path("/foo")
                 .methods(HttpMethod.GET, HttpMethod.POST)
                 .consumes(MediaType.JSON_UTF_8, MediaType.HTML_UTF_8)
                 .produces(MediaType.JAVASCRIPT_UTF_8)
                 .build(),
            Route.builder()
                 .pathPrefix("/bar")
                 .methods(HttpMethod.GET, HttpMethod.POST)
                 .consumes(MediaType.JSON_UTF_8, MediaType.HTML_UTF_8)
                 .produces(MediaType.JAVASCRIPT_UTF_8)
                 .build(),
            Route.builder()
                 .path("/baz")
                 .methods(HttpMethod.GET)
                 .consumes(MediaType.JSON_UTF_8, MediaType.HTML_UTF_8)
                 .produces(MediaType.JAVASCRIPT_UTF_8)
                 .build(),
            Route.builder()
                 .path("/qux")
                 .methods(HttpMethod.POST)
                 .consumes(MediaType.JSON_UTF_8, MediaType.HTML_UTF_8)
                 .produces(MediaType.JAVASCRIPT_UTF_8)
                 .build()
    );
}
 
Example #26
Source File: JacksonRequestConverterFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void jsonArrayToListOfLong() throws Exception {
    when(req.contentType()).thenReturn(MediaType.JSON);
    when(req.content(StandardCharsets.UTF_8)).thenReturn(JSON_ARRAY);

    final Object result = function.convertRequest(
            ctx, req, List.class,
            (ParameterizedType) new TypeReference<List<Long>>() {}.getType());

    assertThat(result).isEqualTo(ImmutableList.of(1L, 2L, 3L));
}
 
Example #27
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 5 votes vote down vote up
@Get("/dependencies")
public AggregatedHttpResponse getDependencies(
    @Param("endTs") long endTs,
    @Param("lookback") long lookback
) {
  try {
    if (!storage.dependencyQueryEnabled) return AggregatedHttpResponse.of(HttpStatus.NOT_FOUND);
    ReadOnlyWindowStore<Long, DependencyLink> store =
        storage.getDependencyStorageStream()
            .store(DEPENDENCIES_STORE_NAME, QueryableStoreTypes.windowStore());
    List<DependencyLink> links = new ArrayList<>();
    Instant from = Instant.ofEpochMilli(endTs - lookback);
    Instant to = Instant.ofEpochMilli(endTs);
    try (KeyValueIterator<Windowed<Long>, DependencyLink> iterator = store.fetchAll(from, to)) {
      iterator.forEachRemaining(keyValue -> links.add(keyValue.value));
    }
    List<DependencyLink> mergedLinks = DependencyLinker.merge(links);
    LOG.debug("Dependencies found from={}-to={}: {}", from, to, mergedLinks.size());
    return AggregatedHttpResponse.of(
        HttpStatus.OK,
        MediaType.JSON,
        DependencyLinkBytesEncoder.JSON_V1.encodeList(mergedLinks));
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    return AggregatedHttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE);
  }
}
 
Example #28
Source File: JacksonRequestConverterFunctionTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test(expected = FallthroughException.class)
public void jsonTextToString() throws Exception {
    when(req.contentType()).thenReturn(MediaType.JSON);
    when(req.content(StandardCharsets.UTF_8)).thenReturn(JSON_TEXT);

    function.convertRequest(ctx, req, String.class, null);
}
 
Example #29
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private AggregatedHttpResponse sendViaHttpPostBindingProtocol(
        String path, String paramName, SignableSAMLObject signableObj) throws Exception {
    final String encoded = toSignedBase64(signableObj, idpCredential, signatureAlgorithm);
    final HttpRequest req = HttpRequest.of(HttpMethod.POST, path, MediaType.FORM_DATA,
                                           QueryParams.of(paramName, encoded).toQueryString());
    return client.execute(req).aggregate().join();
}
 
Example #30
Source File: DefaultHealthCheckUpdateHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static JsonNode toJsonNode(AggregatedHttpRequest req) {
    final MediaType contentType = req.contentType();
    if (contentType != null && !contentType.is(MediaType.JSON)) {
        throw HttpStatusException.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    final Charset charset = contentType == null ? StandardCharsets.UTF_8
                                                : contentType.charset(StandardCharsets.UTF_8);
    try {
        return StandardCharsets.UTF_8.equals(charset) ? mapper.readTree(req.content().array())
                                                      : mapper.readTree(req.content(charset));
    } catch (IOException e) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }
}