Java源码示例:com.linecorp.armeria.common.MediaType

示例1
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
    }
}
 
示例2
@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);
}
 
示例3
@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);
}
 
示例4
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;
}
 
示例5
@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);
    }
}
 
示例6
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;
}
 
示例7
/**
 * 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!");
}
 
示例8
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));
}
 
示例9
/**
 * 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>"));
}
 
示例10
@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);
}
 
示例11
@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()));
}
 
示例12
@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");
            }
        }
    });
}
 
示例13
@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();
    }
}
 
示例14
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();
                      });
}
 
示例15
@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();
}
 
示例16
/**
 * 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));
        }
    }
}
 
示例17
@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);
  }
}
 
示例18
@Test
public void jsonArrayToListOfInteger() 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<Integer>>() {}.getType());

    assertThat(result).isEqualTo(ImmutableList.of(1, 2, 3));
}
 
示例19
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final Response response = requireNonNull(message, "message").getMessage();
    final String username = Optional.ofNullable(findLoginNameFromSubjects(response))
                                    .orElseGet(() -> findLoginNameFromAttributes(response));
    if (Strings.isNullOrEmpty(username)) {
        return loginFailed(ctx, req, message,
                           new IllegalStateException("Cannot get a username from the response"));
    }

    final String sessionId = sessionIdGenerator.get();
    final Session session =
            new Session(sessionId, loginNameNormalizer.apply(username), sessionValidDuration);

    final String redirectionScript;
    if (!Strings.isNullOrEmpty(relayState)) {
        redirectionScript = "window.location.href='/#" + relayState + '\'';
    } else {
        redirectionScript = "window.location.href='/'";
    }
    return HttpResponse.from(loginSessionPropagator.apply(session).thenApply(
            unused -> HttpResponse.of(HttpStatus.OK, MediaType.HTML_UTF_8, getHtmlWithOnload(
                    "localStorage.setItem('sessionId','" + sessionId + "')",
                    redirectionScript))));
}
 
示例20
@Override
protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    // Create a response for streaming. If you don't need to stream, use HttpResponse.of(...) instead.
    final HttpResponseWriter res = HttpResponse.streaming();
    res.write(ResponseHeaders.of(HttpStatus.OK,
                                 HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8));
    res.whenConsumed().thenRun(() -> streamData(ctx.eventLoop(), res, 0));
    return res;
}
 
示例21
@Nullable
private SerializationFormat findSerializationFormat(@Nullable MediaType contentType) {
    if (contentType == null) {
        return null;
    }

    for (SerializationFormat format : supportedSerializationFormats) {
        if (format.isAccepted(contentType)) {
            return format;
        }
    }

    return null;
}
 
示例22
HttpEncodedResponse(HttpResponse delegate,
                    HttpEncodingType encodingType,
                    Predicate<MediaType> encodableContentTypePredicate,
                    long minBytesToForceChunkedAndEncoding) {
    super(delegate);
    this.encodingType = encodingType;
    this.encodableContentTypePredicate = encodableContentTypePredicate;
    this.minBytesToForceChunkedAndEncoding = minBytesToForceChunkedAndEncoding;
}
 
示例23
/**
 * Registers the specified {@link InstanceInfo} to the Eureka registry.
 */
public HttpResponse register(InstanceInfo info) {
    requireNonNull(info, "info");
    final String path = APPS + info.getAppName();
    final RequestHeaders headers = RequestHeaders.builder(HttpMethod.POST, path)
                                                 .contentType(MediaType.JSON)
                                                 .build();
    try {
        return webClient.execute(headers, mapper.writeValueAsBytes(info));
    } catch (JsonProcessingException e) {
        return HttpResponse.ofFailure(e);
    }
}
 
示例24
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers,
                                    @Nullable Object resObj,
                                    HttpHeaders trailingHeaders) throws Exception {
    try {
        final HttpRequest request = RequestContext.current().request();
        if (resObj == null || HttpMethod.DELETE == request.method() ||
            (resObj instanceof Iterable && Iterables.size((Iterable<?>) resObj) == 0)) {
            return HttpResponse.of(HttpStatus.NO_CONTENT);
        }

        final ResponseHeaders resHeaders;
        if (headers.contentType() == null) {
            final ResponseHeadersBuilder builder = headers.toBuilder();
            builder.contentType(MediaType.JSON_UTF_8);
            resHeaders = builder.build();
        } else {
            resHeaders = headers;
        }

        final HttpData httpData = HttpData.wrap(Jackson.writeValueAsBytes(resObj));
        return HttpResponse.of(resHeaders, httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
        logger.debug("Failed to convert a response:", e);
        return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
 
示例25
@Test
void shuttingDown() throws Exception {
    final AggregatedHttpResponse res = handler.authFailed(delegate, ctx, req, new ShuttingDownException())
                                              .aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8()).isEqualTo(
            '{' +
            "  \"exception\": \"com.linecorp.centraldogma.common.ShuttingDownException\"," +
            "  \"message\":\"\"" +
            '}');
}
 
示例26
@Post("/exceptionHandlerOrder")
@ExceptionHandler(MethodLevelExceptionHandler.class)
public HttpResponse exceptionHandlerOrder(@RequestObject String name) {
    assertThat(name).isEqualTo("foo");
    final AggregatedHttpResponse response = AggregatedHttpResponse.of(
            HttpStatus.NOT_IMPLEMENTED, MediaType.PLAIN_TEXT_UTF_8, "hello " + name);
    throw HttpResponseException.of(response);
}
 
示例27
@Override
public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) {
    if (cause instanceof IllegalArgumentException) {
        return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, MediaType.PLAIN_TEXT_UTF_8,
                               "Cause:" + IllegalArgumentException.class.getSimpleName());
    }
    return ExceptionHandlerFunction.fallthrough();
}
 
示例28
@Test
public void jsonArrayToTreeNode() throws Exception {
    when(req.contentType()).thenReturn(MediaType.JSON);
    when(req.content(StandardCharsets.UTF_8)).thenReturn(JSON_ARRAY);

    final Object result = function.convertRequest(ctx, req, TreeNode.class, null);

    assertThat(result).isEqualTo(new ObjectMapper().readTree(JSON_ARRAY));
}
 
示例29
@Test
void testConsumeType() {
    final Route route = Route.builder()
                             .path(PATH)
                             .methods(HttpMethod.POST)
                             .consumes(JSON_UTF_8)
                             .build();

    assertThat(route.apply(consumeType(HttpMethod.POST, JSON_UTF_8)).isPresent()).isTrue();
    assertThat(route.apply(consumeType(HttpMethod.POST, MediaType.create("application", "json")))
                    .isPresent()).isFalse();
}
 
示例30
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/", (ctx, req) -> {
        final ResponseHeaders headers = ResponseHeaders.builder(HttpStatus.NO_CONTENT).contentType(
                MediaType.PLAIN_TEXT_UTF_8).build();
        final HttpResponseWriter streaming = HttpResponse.streaming();
        streaming.write(headers);
        streaming.write(HttpData.ofUtf8("foo"));
        streaming.close();
        return streaming;
    });
}