com.linecorp.armeria.common.HttpHeaders Java Examples

The following examples show how to use com.linecorp.armeria.common.HttpHeaders. 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: Armeria085ServerInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst, final Method method, final Object[] allArguments,
                         final Class<?>[] argumentsTypes, final MethodInterceptResult result) {

    DefaultHttpRequest httpRequest = (DefaultHttpRequest) allArguments[1];
    HttpHeaders headers = httpRequest.headers();

    ContextCarrier carrier = new ContextCarrier();
    for (CarrierItem item = carrier.items(); item.hasNext(); ) {
        item = item.next();
        item.setHeadValue(headers.get(AsciiString.of(item.getHeadKey())));
    }

    AbstractSpan entrySpan = ContextManager.createEntrySpan(httpRequest.path(), carrier);
    entrySpan.setComponent(ComponentsDefine.ARMERIA);
    entrySpan.setLayer(SpanLayer.HTTP);
    entrySpan.setPeer(httpRequest.authority());
    Tags.URL.set(entrySpan, httpRequest.path());
    Tags.HTTP.METHOD.set(entrySpan, httpRequest.method().name());
}
 
Example #2
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 #3
Source File: ServerHttp1ObjectEncoder.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void convertHeaders(HttpHeaders inHeaders, io.netty.handler.codec.http.HttpHeaders outHeaders,
                            boolean isTrailersEmpty) {
    ArmeriaHttpUtil.toNettyHttp1ServerHeader(inHeaders, outHeaders);

    if (!isTrailersEmpty && outHeaders.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        // We don't apply chunked encoding when the content-length header is set, which would
        // prevent the trailers from being sent so we go ahead and remove content-length to
        // force chunked encoding.
        outHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
    }

    if (enableServerHeader && !outHeaders.contains(HttpHeaderNames.SERVER)) {
        outHeaders.add(HttpHeaderNames.SERVER, ArmeriaHttpUtil.SERVER_HEADER);
    }

    if (enableDateHeader && !outHeaders.contains(HttpHeaderNames.DATE)) {
        outHeaders.add(HttpHeaderNames.DATE, HttpTimestampSupplier.currentTime());
    }
}
 
Example #4
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 #5
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Function<? super HttpClient, ContentPreviewingClient> decodingContentPreviewDecorator() {
    final BiPredicate<? super RequestContext, ? super HttpHeaders> previewerPredicate =
            (requestContext, headers) -> "gzip".equals(headers.get(HttpHeaderNames.CONTENT_ENCODING));
    final BiFunction<HttpHeaders, ByteBuf, String> producer = (headers, data) -> {
        final byte[] bytes = new byte[data.readableBytes()];
        data.getBytes(0, bytes);
        final byte[] decoded;
        try (GZIPInputStream unzipper = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
            decoded = ByteStreams.toByteArray(unzipper);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
        return new String(decoded, StandardCharsets.UTF_8);
    };

    final ContentPreviewerFactory factory =
            ContentPreviewerFactory.builder()
                                   .maxLength(100)
                                   .binary(producer, previewerPredicate)
                                   .build();

    return ContentPreviewingClient.newDecorator(factory);
}
 
Example #6
Source File: ContentPreviewingServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private Function<? super HttpService, ContentPreviewingService> decodingContentPreviewDecorator() {
    final BiPredicate<? super RequestContext, ? super HttpHeaders> previewerPredicate =
            (requestContext, headers) -> "gzip".equals(headers.get(HttpHeaderNames.CONTENT_ENCODING));

    final BiFunction<HttpHeaders, ByteBuf, String> producer = (headers, data) -> {
        final byte[] bytes = new byte[data.readableBytes()];
        data.getBytes(0, bytes);
        final byte[] decoded;
        try (GZIPInputStream unzipper = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
            decoded = ByteStreams.toByteArray(unzipper);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
        return new String(decoded, StandardCharsets.UTF_8);
    };

    final ContentPreviewerFactory factory =
            ContentPreviewerFactory.builder()
                                   .maxLength(100)
                                   .binary(producer, previewerPredicate)
                                   .build();
    return ContentPreviewingService.newDecorator(factory);
}
 
Example #7
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void excludeBlacklistHeadersWhileHttp2ToHttp1() {
    final HttpHeaders in = HttpHeaders.builder()
                                      .add(HttpHeaderNames.TRAILER, "foo")
                                      .add(HttpHeaderNames.HOST, "bar")
                                      .add(HttpHeaderNames.PATH, "dummy")
                                      .add(HttpHeaderNames.METHOD, "dummy")
                                      .add(HttpHeaderNames.SCHEME, "dummy")
                                      .add(HttpHeaderNames.STATUS, "dummy")
                                      .add(HttpHeaderNames.TRANSFER_ENCODING, "dummy")
                                      .add(ExtensionHeaderNames.STREAM_ID.text(), "dummy")
                                      .add(ExtensionHeaderNames.SCHEME.text(), "dummy")
                                      .add(ExtensionHeaderNames.PATH.text(), "dummy")
                                      .build();

    final io.netty.handler.codec.http.HttpHeaders out =
            new DefaultHttpHeaders();

    toNettyHttp1ServerHeader(in, out);
    assertThat(out).isEqualTo(new DefaultHttpHeaders()
                                      .add(io.netty.handler.codec.http.HttpHeaderNames.TRAILER, "foo")
                                      .add(io.netty.handler.codec.http.HttpHeaderNames.HOST, "bar"));
}
 
Example #8
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void toNettyHttp1Server(
        HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders,
        boolean isTrailer) {
    for (Entry<AsciiString, String> entry : inputHeaders) {
        final AsciiString name = entry.getKey();
        final String value = entry.getValue();
        if (HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) {
            continue;
        }

        if (isTrailer && isTrailerBlacklisted(name)) {
            continue;
        }
        outputHeaders.add(name, value);
    }
}
 
Example #9
Source File: HttpHeaderUtilTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void proxiedAddresses_X_Forwarded_For() {
    final ProxiedAddresses proxiedAddresses = ProxiedAddresses.of(
            new InetSocketAddress("10.1.0.1", 80),
            new InetSocketAddress("10.1.0.2", 443));
    assertThat(HttpHeaderUtil.determineProxiedAddresses(
            HttpHeaders.of(HttpHeaderNames.X_FORWARDED_FOR, "10.1.0.1:80,10.1.0.2:443"),
            ClientAddressSource.DEFAULT_SOURCES, null, remoteAddr, ACCEPT_ANY))
            .isEqualTo(proxiedAddresses);

    assertThat(HttpHeaderUtil.determineProxiedAddresses(
            HttpHeaders.of(HttpHeaderNames.FORWARDED, "for=10.0.0.1,for=10.0.0.2",
                           HttpHeaderNames.X_FORWARDED_FOR, "10.1.0.1:80,10.1.0.2:443"),
            ImmutableList.of(ofHeader(HttpHeaderNames.X_FORWARDED_FOR)),
            null, remoteAddr, ACCEPT_ANY))
            .isEqualTo(proxiedAddresses);
}
 
Example #10
Source File: Armeria084ServerInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(final EnhancedInstance objInst, final Method method, final Object[] allArguments,
    final Class<?>[] argumentsTypes, final MethodInterceptResult result) throws Throwable {

    DefaultHttpRequest httpRequest = (DefaultHttpRequest) allArguments[1];
    HttpHeaders headers = httpRequest.headers();

    ContextCarrier carrier = new ContextCarrier();
    for (CarrierItem item = carrier.items(); item.hasNext(); ) {
        item = item.next();
        item.setHeadValue(headers.get(AsciiString.of(item.getHeadKey())));
    }

    AbstractSpan entrySpan = ContextManager.createEntrySpan(httpRequest.path(), carrier);
    entrySpan.setComponent(ComponentsDefine.ARMERIA);
    entrySpan.setLayer(SpanLayer.HTTP);
    entrySpan.setPeer(httpRequest.authority());
    Tags.URL.set(entrySpan, httpRequest.path());
    Tags.HTTP.METHOD.set(entrySpan, httpRequest.method().name());
}
 
Example #11
Source File: ThriftHttpHeaderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void httpResponseHeaderContainsFoo() throws TException {
    final Iface client =
            Clients.builder(server.httpUri(BINARY) + "/hello")
                   .decorator((delegate, ctx, req) -> {
                       final HttpResponse res = delegate.execute(ctx, req);
                       return new FilteredHttpResponse(res) {
                           @Override
                           protected HttpObject filter(HttpObject obj) {
                               if (obj instanceof HttpHeaders) {
                                   final HttpHeaders headers = (HttpHeaders) obj;
                                   assertThat(headers.get("foo")).isEqualTo("bar");
                               }
                               return obj;
                           }
                       };
                   })
                   .build(Iface.class);
    try (SafeCloseable ignored = Clients.withHttpHeader(AUTHORIZATION, SECRET)) {
        assertThat(client.hello("trustin")).isEqualTo("Hello, trustin!");
    }
}
 
Example #12
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testMessageLogsForOneWay(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final OnewayHelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                                   .options(clientOptions)
                                                   .build(Handlers.ONEWAYHELLO.iface());
    recordMessageLogs = true;
    client.hello("trustin");

    final RequestLog log = requestLogs.take();

    assertThat(log.requestHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.requestContent()).isInstanceOf(RpcRequest.class);
    assertThat(log.rawRequestContent()).isInstanceOf(ThriftCall.class);

    final RpcRequest request = (RpcRequest) log.requestContent();
    assertThat(request.serviceType()).isEqualTo(OnewayHelloService.Iface.class);
    assertThat(request.method()).isEqualTo("hello");
    assertThat(request.params()).containsExactly("trustin");

    final ThriftCall rawRequest = (ThriftCall) log.rawRequestContent();
    assertThat(rawRequest.header().type).isEqualTo(TMessageType.ONEWAY);
    assertThat(rawRequest.header().name).isEqualTo("hello");
    assertThat(rawRequest.args()).isInstanceOf(OnewayHelloService.hello_args.class);
    assertThat(((OnewayHelloService.hello_args) rawRequest.args()).getName()).isEqualTo("trustin");

    assertThat(log.responseHeaders()).isInstanceOf(HttpHeaders.class);
    assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
    assertThat(log.rawResponseContent()).isNull();

    final RpcResponse response = (RpcResponse) log.responseContent();
    assertThat(response.get()).isNull();
}
 
Example #13
Source File: AbstractThriftOverHttpTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptHeaderWithQValues() throws Exception {
    // Server should choose TBINARY because it has higher q-value (0.5) than that of TTEXT (0.2)
    try (TTransport transport = newTransport(
            "http", "/hello",
            HttpHeaders.of(HttpHeaderNames.ACCEPT,
                           "application/x-thrift; protocol=TTEXT; q=0.2, " +
                           "application/x-thrift; protocol=TBINARY; q=0.5"))) {
        final HelloService.Client client =
                new HelloService.Client.Factory().getClient(
                        ThriftProtocolFactories.BINARY.getProtocol(transport));

        assertThat(client.hello("Trustin")).isEqualTo("Hello, Trustin!");
    }
}
 
Example #14
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public HttpResponse convertResponse(ServiceRequestContext ctx,
                                    ResponseHeaders headers,
                                    @Nullable Object result,
                                    HttpHeaders trailers) throws Exception {
    final CompletableFuture<?> f;
    if (result instanceof Publisher) {
        f = collectFrom((Publisher<Object>) result);
    } else if (result instanceof Stream) {
        f = collectFrom((Stream<Object>) result, ctx.blockingTaskExecutor());
    } else {
        return ResponseConverterFunction.fallthrough();
    }

    assert f != null;
    return HttpResponse.from(f.handle((aggregated, cause) -> {
        if (cause != null) {
            return handleExceptionWithContext(exceptionHandler, ctx, ctx.request(), cause);
        }
        try {
            return responseConverter.convertResponse(ctx, headers, aggregated, trailers);
        } catch (Exception e) {
            return handleExceptionWithContext(exceptionHandler, ctx, ctx.request(), e);
        }
    }));
}
 
Example #15
Source File: Http1ObjectEncoder.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture doWriteTrailers(int id, int streamId, HttpHeaders headers) {
    if (!isWritable(id)) {
        return newClosedSessionFuture();
    }

    return write(id, convertTrailers(headers), true);
}
 
Example #16
Source File: AbstractClientOptionsBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified {@link ClientOptionValue}.
 */
public <T> AbstractClientOptionsBuilder option(ClientOptionValue<T> optionValue) {
    requireNonNull(optionValue, "optionValue");
    final ClientOption<?> opt = optionValue.option();
    if (opt == ClientOption.DECORATION) {
        decoration.add((ClientDecoration) optionValue.value());
    } else if (opt == ClientOption.HTTP_HEADERS) {
        final HttpHeaders h = (HttpHeaders) optionValue.value();
        setHttpHeaders(h);
    } else {
        options.put(opt, optionValue);
    }
    return this;
}
 
Example #17
Source File: ContentPreviewerFactoryBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the specified {@link BiPredicate} to produce the preview using the specified
 * {@link BiFunction} when the predicate returns {@code true}.
 */
public ContentPreviewerFactoryBuilder binary(
        BiFunction<? super HttpHeaders, ? super ByteBuf, String> producer,
        BiPredicate<? super RequestContext, ? super HttpHeaders> predicate) {
    requireNonNull(predicate, "predicate");
    requireNonNull(producer, "producer");
    previewSpecsBuilder.add(new PreviewSpec(predicate, PreviewMode.BINARY, producer));
    return this;
}
 
Example #18
Source File: ServiceSpecification.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
public ServiceSpecification(Iterable<ServiceInfo> services,
                            Iterable<EnumInfo> enums,
                            Iterable<StructInfo> structs,
                            Iterable<ExceptionInfo> exceptions,
                            Iterable<HttpHeaders> exampleHttpHeaders) {

    this.services = Streams.stream(requireNonNull(services, "services"))
                           .collect(toImmutableSortedSet(comparing(ServiceInfo::name)));
    this.enums = collectNamedTypeInfo(enums, "enums");
    this.structs = collectNamedTypeInfo(structs, "structs");
    this.exceptions = collectNamedTypeInfo(exceptions, "exceptions");
    this.exampleHttpHeaders = ImmutableList.copyOf(requireNonNull(exampleHttpHeaders,
                                                                  "exampleHttpHeaders"));
}
 
Example #19
Source File: ClientOptionsBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testAddHttpHeaders() {
    final ClientOptionsBuilder b = ClientOptions.builder();
    b.addHttpHeaders(HttpHeaders.of(HttpHeaderNames.AUTHORIZATION, "Basic QWxhZGRpbjpPcGVuU2VzYW1l"));

    assertThat(b.build().httpHeaders().get(HttpHeaderNames.AUTHORIZATION))
            .isEqualTo("Basic QWxhZGRpbjpPcGVuU2VzYW1l");
}
 
Example #20
Source File: ClassPathHttpFile.java    From armeria with Apache License 2.0 5 votes vote down vote up
ClassPathHttpFile(URL url,
                  boolean contentTypeAutoDetectionEnabled,
                  Clock clock,
                  boolean dateEnabled,
                  boolean lastModifiedEnabled,
                  @Nullable BiFunction<String, HttpFileAttributes, String> entityTagFunction,
                  HttpHeaders headers) {
    super(contentTypeAutoDetectionEnabled ? MimeTypeUtil.guessFromPath(url.toString()) : null,
          clock, dateEnabled, lastModifiedEnabled, entityTagFunction, headers);
    this.url = requireNonNull(url, "url");
}
 
Example #21
Source File: AnnotatedServiceHandlersOrderTest.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 && "hello foo".equals(result)) {
        assertThat(responseCounter.getAndIncrement()).isOne();
    }
    return ResponseConverterFunction.fallthrough();
}
 
Example #22
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void endOfStreamSet() {
    final Http2Headers in = new DefaultHttp2Headers();
    in.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
    final HttpHeaders out = toArmeria(in, true, true);
    assertThat(out.isEndOfStream()).isTrue();

    final HttpHeaders out2 = toArmeria(in, true, false);
    assertThat(out2.isEndOfStream()).isFalse();
}
 
Example #23
Source File: StringResponseConverterFunction.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 {
    final MediaType mediaType = headers.contentType();
    if (mediaType != null) {
        // @Produces("text/plain") or @ProducesText is specified.
        if (mediaType.is(MediaType.ANY_TEXT_TYPE)) {
            // Use 'utf-8' charset by default.
            final Charset charset = mediaType.charset(ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET);

            // To avoid sending an unfinished text to the client, always aggregate the published strings.
            if (result instanceof Publisher) {
                return aggregateFrom((Publisher<?>) result, headers, trailers, o -> toHttpData(o, charset));
            }
            if (result instanceof Stream) {
                return aggregateFrom((Stream<?>) result, headers, trailers,
                                     o -> toHttpData(o, charset), ctx.blockingTaskExecutor());
            }
            return HttpResponse.of(headers, toHttpData(result, charset), trailers);
        }
    } else if (result instanceof CharSequence) {
        return HttpResponse.of(headers.toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8).build(),
                               HttpData.ofUtf8(((CharSequence) result).toString()),
                               trailers);
    }

    return ResponseConverterFunction.fallthrough();
}
 
Example #24
Source File: MessageConverterService.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 Response) {
        final Response response = (Response) result;
        final HttpData body = HttpData.ofUtf8(response.result() + ':' + response.from());
        return HttpResponse.of(headers, body, trailers);
    }
    return ResponseConverterFunction.fallthrough();
}
 
Example #25
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void stripTEHeadersAccountsForOWS() {
    final io.netty.handler.codec.http.HttpHeaders in = new DefaultHttpHeaders();
    in.add(HttpHeaderNames.TE, " " + HttpHeaderValues.TRAILERS + ' ');
    final HttpHeadersBuilder out = HttpHeaders.builder();
    toArmeria(in, out);
    assertThat(out.get(HttpHeaderNames.TE)).isEqualTo(HttpHeaderValues.TRAILERS.toString());
}
 
Example #26
Source File: GrpcServiceRegistrationBean.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds example HTTP headers for the specified method.
 *
 * @deprecated Use {@link DocServiceBuilder#exampleHttpHeaders(String, String, Iterable)} via
 *             {@link DocServiceConfigurator}.
 */
@Deprecated
public GrpcServiceRegistrationBean addExampleHeaders(
        String serviceName, String methodName, @NotNull Iterable<? extends HttpHeaders> exampleHeaders) {
    exampleHeaders.forEach(h -> addExampleHeaders(serviceName, methodName, h));
    return this;
}
 
Example #27
Source File: TestConverters.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 Number) {
        return httpResponse(HttpData.ofUtf8("Number[%s]", result));
    }
    return ResponseConverterFunction.fallthrough();
}
 
Example #28
Source File: ContentPreviewerFactoryBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static BiPredicate<? super RequestContext, ? super HttpHeaders> previewerPredicate(
        MediaTypeSet mediaTypeSet) {
    requireNonNull(mediaTypeSet, "mediaTypesSet");
    return (ctx, headers) -> {
        final MediaType contentType = headers.contentType();
        if (contentType == null) {
            return false;
        }
        return mediaTypeSet.match(contentType) != null;
    };
}
 
Example #29
Source File: DefaultRequestLog.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public String toStringRequestOnly(
        BiFunction<? super RequestContext, ? super RequestHeaders, ?> headersSanitizer,
        BiFunction<? super RequestContext, Object, ?> contentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> trailersSanitizer) {

    return DefaultRequestLog.this.toStringRequestOnly(
            headersSanitizer, contentSanitizer, trailersSanitizer);
}
 
Example #30
Source File: TestConverters.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 Integer) {
        return httpResponse(HttpData.ofUtf8("Integer: %d", result));
    }
    return ResponseConverterFunction.fallthrough();
}