Java Code Examples for com.linecorp.armeria.common.RequestHeaders#builder()

The following examples show how to use com.linecorp.armeria.common.RequestHeaders#builder() . 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: 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 2
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}.
 */
public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers,
                                                     boolean endOfStream, String scheme,
                                                     ServerConfig cfg) {
    final RequestHeadersBuilder builder = RequestHeaders.builder();
    toArmeria(builder, headers, endOfStream);
    // A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3
    if (!builder.contains(HttpHeaderNames.SCHEME)) {
        builder.add(HttpHeaderNames.SCHEME, scheme);
    }
    if (!builder.contains(HttpHeaderNames.AUTHORITY)) {
        final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
        final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
        builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port);
    }
    return builder.build();
}
 
Example 3
Source File: EurekaEndpointGroup.java    From armeria with Apache License 2.0 6 votes vote down vote up
EurekaEndpointGroup(EndpointSelectionStrategy selectionStrategy,
                    WebClient webClient, long registryFetchIntervalSeconds, @Nullable String appName,
                    @Nullable String instanceId, @Nullable String vipAddress,
                    @Nullable String secureVipAddress, @Nullable List<String> regions) {
    super(selectionStrategy);
    this.webClient = PooledWebClient.of(webClient);
    this.registryFetchIntervalSeconds = registryFetchIntervalSeconds;

    final RequestHeadersBuilder headersBuilder = RequestHeaders.builder();
    headersBuilder.method(HttpMethod.GET);
    headersBuilder.add(HttpHeaderNames.ACCEPT, MediaTypeNames.JSON_UTF_8);
    responseConverter = responseConverter(headersBuilder, appName, instanceId,
                                          vipAddress, secureVipAddress, regions);
    requestHeaders = headersBuilder.build();

    webClient.options().factory().whenClosed().thenRun(this::closeAsync);
    fetchRegistry();
}
 
Example 4
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 5 votes vote down vote up
private <T, R extends ApiResponse<T>> PendingResult<T> handleMethod(
    HttpMethod method,
    String hostName,
    String url,
    HttpData payload,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry) {
  var client =
      httpClients.computeIfAbsent(
          hostName,
          host -> WebClient.builder(host).factory(clientFactory).options(clientOptions).build());

  var gson = gsonForPolicy(fieldNamingPolicy);

  var headers = RequestHeaders.builder(method, url);
  if (experienceIdHeaderValue != null) {
    headers.add("X-Goog-Maps-Experience-ID", experienceIdHeaderValue);
  }
  var request = HttpRequest.of(headers.build(), payload);

  return new ArmeriaPendingResult<>(client, request, clazz, gson);
}
 
Example 5
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers.
 */
public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) {
    final HttpHeadersBuilder builder;
    if (request) {
        builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder()
                                                           : HttpHeaders.builder();
    } else {
        builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder()
                                                           : HttpHeaders.builder();
    }

    toArmeria(builder, headers, endOfStream);
    return builder.build();
}
 
Example 6
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
 * The following headers are only used if they can not be found in the {@code HOST} header or the
 * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
 * <ul>
 * <li>{@link ExtensionHeaderNames#SCHEME}</li>
 * </ul>
 * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
 */
public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in,
                                       ServerConfig cfg) throws URISyntaxException {
    final URI requestTargetUri = toUri(in);

    final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
    final RequestHeadersBuilder out = RequestHeaders.builder();
    out.sizeHint(inHeaders.size());
    out.add(HttpHeaderNames.METHOD, in.method().name());
    out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri));

    addHttp2Scheme(inHeaders, requestTargetUri, out);

    // Add the HTTP headers which have not been consumed above
    toArmeria(inHeaders, out);
    if (!out.contains(HttpHeaderNames.HOST)) {
        // The client violates the spec that the request headers must contain a Host header.
        // But we just add Host header to allow the request.
        // https://tools.ietf.org/html/rfc7230#section-5.4
        if (isOriginForm(requestTargetUri) || isAsteriskForm(requestTargetUri)) {
            // requestTargetUri does not contain authority information.
            final String defaultHostname = cfg.defaultVirtualHost().defaultHostname();
            final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
            out.add(HttpHeaderNames.HOST, defaultHostname + ':' + port);
        } else {
            out.add(HttpHeaderNames.HOST, stripUserInfo(requestTargetUri.getAuthority()));
        }
    }
    return out.build();
}
 
Example 7
Source File: ArmeriaCallFactory.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static HttpResponse doCall(ArmeriaCallFactory callFactory, Request request) {
    final HttpUrl httpUrl = request.url();
    final WebClient webClient = callFactory.getWebClient(httpUrl);
    final String absolutePathRef;
    if (httpUrl.encodedQuery() == null) {
        absolutePathRef = httpUrl.encodedPath();
    } else {
        absolutePathRef = httpUrl.encodedPath() + '?' + httpUrl.encodedQuery();
    }

    final RequestHeadersBuilder headers = RequestHeaders.builder(HttpMethod.valueOf(request.method()),
                                                                 absolutePathRef);
    final Headers requestHeaders = request.headers();
    final int numHeaders = requestHeaders.size();
    for (int i = 0; i < numHeaders; i++) {
        headers.add(HttpHeaderNames.of(requestHeaders.name(i)),
                    requestHeaders.value(i));
    }

    final RequestBody body = request.body();
    final Invocation invocation = request.tag(Invocation.class);
    if (body == null) {
        // Without a body.
        try (SafeCloseable ignored = withContextCustomizer(
                ctx -> InvocationUtil.setInvocation(ctx, invocation))) {
            return webClient.execute(headers.build());
        }
    }

    // With a body.
    final MediaType contentType = body.contentType();
    if (contentType != null) {
        headers.set(HttpHeaderNames.CONTENT_TYPE, contentType.toString());
    }

    try (Buffer contentBuffer = new Buffer()) {
        body.writeTo(contentBuffer);

        try (SafeCloseable ignored = withContextCustomizer(
                ctx -> InvocationUtil.setInvocation(ctx, invocation))) {
            return webClient.execute(headers.build(), contentBuffer.readByteArray());
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(
                "Failed to convert RequestBody to HttpData. " + request.method(), e);
    }
}