com.linecorp.armeria.server.ServiceRequestContext Java Examples

The following examples show how to use com.linecorp.armeria.server.ServiceRequestContext. 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: MainGraph.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Produces
static ListenableFuture<List<Long>> fetchFromFakeDb(ServiceRequestContext context,
                                                    ListeningScheduledExecutorService blockingExecutor) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());
    // This logic mimics using a blocking method, which would usually be something like a MySQL database
    // query using JDBC.
    // Always run blocking logic on the blocking task executor. By using
    // ServiceRequestContext.blockingTaskExecutor (indirectly via the ListeningScheduledExecutorService
    // wrapper we defined in MainModule), you also ensure the context is mounted inside the logic (e.g.,
    // your DB call will be traced!).
    return blockingExecutor.submit(() -> {
        // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
        checkState(ServiceRequestContext.current() == context);
        checkState(!context.eventLoop().inEventLoop());

        Uninterruptibles.sleepUninterruptibly(Duration.ofMillis(50));
        return ImmutableList.of(23L, -23L);
    });
}
 
Example #2
Source File: ClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushWithOldClientCtxWhoseRootIsSameServiceCtx__ctx2IsCreatedUnderCtx1() {
    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable ignored = sctx.push()) {
        assertCurrentCtx(sctx);
        final ClientRequestContext cctx1 = clientRequestContext();
        try (SafeCloseable ignored1 = cctx1.push()) {
            assertCurrentCtx(cctx1);
            final ClientRequestContext cctx2 = clientRequestContext();
            assertThat(cctx1.root()).isSameAs(cctx2.root());

            try (SafeCloseable ignored2 = cctx2.push()) {
                assertCurrentCtx(cctx2);
            }
            assertCurrentCtx(cctx1);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);
}
 
Example #3
Source File: HelloServiceImpl.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a {@link HelloReply} using {@code blockingTaskExecutor}.
 *
 * @see <a href="https://line.github.io/armeria/server-grpc.html#blocking-service-implementation">Blocking
 *      service implementation</a>
 */
@Override
public void blockingHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
    // Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default.
    // Therefore, this method will run in the event loop, which means that you can suffer the performance
    // degradation if you call a blocking API in this method. In this case, you have the following options:
    //
    // 1. Call a blocking API in the blockingTaskExecutor provided by Armeria.
    // 2. Set GrpcServiceBuilder.useBlockingTaskExecutor(true) when building your GrpcService.
    // 3. Call a blocking API in the separate thread pool you manage.
    //
    // In this example, we chose the option 1:
    ServiceRequestContext.current().blockingTaskExecutor().submit(() -> {
        try {
            // Simulate a blocking API call.
            Thread.sleep(3000);
        } catch (Exception ignored) {
            // Do nothing.
        }
        responseObserver.onNext(buildReply(toMessage(request.getName())));
        responseObserver.onCompleted();
    });
}
 
Example #4
Source File: StringRequestConverterFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@link AggregatedHttpRequest} to a {@link String}.
 */
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType == String.class ||
        expectedResultType == CharSequence.class) {
        final Charset charset;
        final MediaType contentType = request.contentType();
        if (contentType != null) {
            charset = contentType.charset(ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET);
        } else {
            charset = ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET;
        }
        return request.content(charset);
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #5
Source File: ClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushWithOldClientCtxWhoseRootIsSameServiceCtx_derivedCtx() {
    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable ignored = sctx.push()) {
        assertCurrentCtx(sctx);
        final ClientRequestContext cctx1 = clientRequestContext();
        final ClientRequestContext derived = cctx1.newDerivedContext(cctx1.id(), cctx1.request(),
                                                                     cctx1.rpcRequest());
        try (SafeCloseable ignored1 = derived.push()) {
            assertCurrentCtx(derived);
            final ClientRequestContext cctx2 = clientRequestContext();
            assertThat(derived.root()).isSameAs(cctx2.root());

            try (SafeCloseable ignored2 = cctx2.push()) {
                assertCurrentCtx(cctx2);
            }
            assertCurrentCtx(derived);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);
}
 
Example #6
Source File: FileService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private HttpFile cache(
        ServiceRequestContext ctx, PathAndEncoding pathAndEncoding, HttpFile uncachedFile) {

    assert cache != null;

    final Executor executor = ctx.blockingTaskExecutor();
    final ByteBufAllocator alloc = ctx.alloc();

    return HttpFile.from(uncachedFile.aggregateWithPooledObjects(executor, alloc).thenApply(aggregated -> {
        cache.put(pathAndEncoding, aggregated);
        return (HttpFile) aggregated;
    }).exceptionally(cause -> {
        logger.warn("{} Failed to cache a file: {}", ctx, uncachedFile, Exceptions.peel(cause));
        return uncachedFile;
    }));
}
 
Example #7
Source File: WebOperationService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> getArguments(ServiceRequestContext ctx, AggregatedHttpRequest req) {
    final Map<String, Object> arguments = new LinkedHashMap<>(ctx.pathParams());
    if (!req.content().isEmpty()) {
        final Map<String, Object> bodyParams;
        try {
            bodyParams = OBJECT_MAPPER.readValue(req.content().array(), JSON_MAP);
        } catch (IOException e) {
            throw new IllegalArgumentException("Invalid JSON in request.");
        }
        arguments.putAll(bodyParams);
    }

    final QueryParams params = QueryParams.fromQueryString(ctx.query());
    for (String name : params.names()) {
        final List<String> values = params.getAll(name);
        arguments.put(name, values.size() != 1 ? values : values.get(0));
    }

    return ImmutableMap.copyOf(arguments);
}
 
Example #8
Source File: ArmeriaServerCall.java    From armeria with Apache License 2.0 6 votes vote down vote up
static HttpHeaders statusToTrailers(
        ServiceRequestContext ctx, Status status, Metadata metadata, boolean headersSent) {
    final HttpHeadersBuilder trailers = GrpcTrailersUtil.statusToTrailers(
            status.getCode().value(), status.getDescription(), headersSent);

    MetadataUtil.fillHeaders(metadata, trailers);

    if (ctx.config().verboseResponses() && status.getCause() != null) {
        final ThrowableProto proto = GrpcStatus.serializeThrowable(status.getCause());
        trailers.add(GrpcHeaderNames.ARMERIA_GRPC_THROWABLEPROTO_BIN,
                     Base64.getEncoder().encodeToString(proto.toByteArray()));
    }

    final HttpHeaders additionalTrailers = ctx.additionalResponseTrailers();
    ctx.mutateAdditionalResponseTrailers(HttpHeadersBuilder::clear);
    trailers.add(additionalTrailers);
    return trailers.build();
}
 
Example #9
Source File: HelloServiceImpl.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a {@link HelloReply} using {@code blockingTaskExecutor}.
 *
 * @see <a href="https://armeria.dev/docs/server-grpc#blocking-service-implementation">Blocking
 *      service implementation</a>
 */
@Override
public void blockingHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
    // Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default.
    // Therefore, this method will run in the event loop, which means that you can suffer the performance
    // degradation if you call a blocking API in this method. In this case, you have the following options:
    //
    // 1. Call a blocking API in the blockingTaskExecutor provided by Armeria.
    // 2. Set GrpcServiceBuilder.useBlockingTaskExecutor(true) when building your GrpcService.
    // 3. Call a blocking API in the separate thread pool you manage.
    //
    // In this example, we chose the option 1:
    ServiceRequestContext.current().blockingTaskExecutor().submit(() -> {
        try {
            // Simulate a blocking API call.
            Thread.sleep(3000);
        } catch (Exception ignored) {
            // Do nothing.
        }
        responseObserver.onNext(buildReply(toMessage(request.getName())));
        responseObserver.onCompleted();
    });
}
 
Example #10
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 #11
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 #12
Source File: HelloServiceImpl.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a {@link HelloReply} using {@code blockingTaskExecutor}.
 *
 * @see <a href="https://armeria.dev/docs/server-grpc#blocking-service-implementation">Blocking
 *      service implementation</a>
 */
@Override
public Mono<HelloReply> blockingHello(Mono<HelloRequest> request) {
    // Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default.
    // Therefore, this method will run in the event loop, which means that you can suffer the performance
    // degradation if you call a blocking API in this method. In this case, you have the following options:
    //
    // 1. Call a blocking API in the blockingTaskExecutor provided by Armeria.
    // 2. Set GrpcServiceBuilder.useBlockingTaskExecutor(true) when building your GrpcService.
    // 3. Call a blocking API in the separate thread pool you manage.
    //
    // In this example, we chose the option 1:
    return request
            .publishOn(Schedulers.fromExecutor(ServiceRequestContext.current()
                                                                    .blockingTaskExecutor()))
            .map(it -> {
                try {
                    // Simulate a blocking API call.
                    Thread.sleep(3000);
                } catch (Exception ignored) {
                    // Do nothing.
                }
                return buildReply(toMessage(it.getName()));
            });
}
 
Example #13
Source File: TokenService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * PATCH /tokens/{appId}
 *
 * <p>Activates or deactivates the token of the specified {@code appId}.
 */
@Patch("/tokens/{appId}")
@Consumes("application/json-patch+json")
public CompletableFuture<Token> updateToken(ServiceRequestContext ctx,
                                            @Param String appId,
                                            JsonNode node, Author author, User loginUser) {
    if (node.equals(activation)) {
        return getTokenOrRespondForbidden(ctx, appId, loginUser).thenCompose(
                token -> mds.activateToken(author, appId)
                            .thenApply(unused -> token.withoutSecret()));
    }
    if (node.equals(deactivation)) {
        return getTokenOrRespondForbidden(ctx, appId, loginUser).thenCompose(
                token -> mds.deactivateToken(author, appId)
                            .thenApply(unused -> token.withoutSecret()));
    }
    throw new IllegalArgumentException("Unsupported JSON patch: " + node +
                                       " (expected: " + activation + " or " + deactivation + ')');
}
 
Example #14
Source File: TestServiceImpl.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    final HttpResponse res = unwrap().serve(ctx, req);
    return new FilteredHttpResponse(res) {
        private boolean headersReceived;

        @Override
        protected HttpObject filter(HttpObject obj) {
            if (obj instanceof HttpHeaders) {
                if (!headersReceived) {
                    headersReceived = true;
                } else {
                    final HttpHeaders trailers = (HttpHeaders) obj;
                    final String extraHeader = req.headers().get(EXTRA_HEADER_NAME);
                    if (extraHeader != null) {
                        return trailers.toBuilder().set(EXTRA_HEADER_NAME, extraHeader).build();
                    }
                }
            }
            return obj;
        }
    };
}
 
Example #15
Source File: AbstractCompositeService.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public O serve(ServiceRequestContext ctx, I req) throws Exception {
    final RoutingContext routingCtx = ctx.routingContext();
    final Routed<T> result = findService(routingCtx.overridePath(ctx.mappedPath()));
    if (!result.isPresent()) {
        throw HttpStatusException.of(HttpStatus.NOT_FOUND);
    }

    if (result.route().pathType() == RoutePathType.PREFIX) {
        assert ctx.config().route().pathType() == RoutePathType.PREFIX;
        final ServiceRequestContext newCtx = new CompositeServiceRequestContext(
                ctx, result.routingResult().path());
        try (SafeCloseable ignored = newCtx.replace()) {
            return result.value().serve(newCtx, req);
        }
    } else {
        return result.value().serve(ctx, req);
    }
}
 
Example #16
Source File: RequestContextCurrentTraceContextTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    when(eventLoop.inEventLoop()).thenReturn(true);
    ctx = ServiceRequestContext.builder(HttpRequest.of(HttpMethod.GET, "/"))
                               .eventLoop(eventLoop)
                               .build();
}
 
Example #17
Source File: DefaultRequestLogTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void logNameWithRequestContent() {
    final ServiceRequestContext ctx = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final DefaultRequestLog log = (DefaultRequestLog) ctx.log();

    assertThat(log.isAvailable(RequestLogProperty.NAME)).isFalse();
    log.requestContent(RpcRequest.of(DefaultRequestLogTest.class, "test"), null);
    log.endRequest();
    assertThat(log.name()).isSameAs("test");
}
 
Example #18
Source File: FailFastUtil.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("MethodParameterNamingConvention")
static void failFastIfTimedOut(GitRepository repo, Logger logger, @Nullable ServiceRequestContext ctx,
                               String methodName, Object arg1, Object arg2, Object arg3) {
    if (ctx != null && ctx.isTimedOut()) {
        logger.info("{} Rejecting a request timed out already: repo={}/{}, method={}, args=[{}, {}, {}]",
                    ctx, repo.parent().name(), repo.name(), methodName, arg1, arg2, arg3);
        throw REQUEST_ALREADY_TIMED_OUT;
    }
}
 
Example #19
Source File: TokenlessClientLoggerTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static ServiceRequestContext newContext(String hostname, String ip) {
    final ServiceRequestContext ctx = mock(ServiceRequestContext.class);
    try {
        when(ctx.remoteAddress()).thenReturn(new InetSocketAddress(
                InetAddress.getByAddress(hostname, NetUtil.createByteArrayFromIpAddressString(ip)),
                ThreadLocalRandom.current().nextInt(32768, 65536)));
    } catch (UnknownHostException e) {
        throw new Error(e);
    }
    return ctx;
}
 
Example #20
Source File: PooledResponseBufferBenchmark.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpResponse serve(PooledHttpService delegate, ServiceRequestContext ctx,
                             PooledHttpRequest req) throws Exception {
    final PooledHttpResponse res = delegate.serve(ctx, req);
    final HttpResponseWriter decorated = HttpResponse.streaming();
    res.subscribeWithPooledObjects(new Subscriber<HttpObject>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(HttpObject httpObject) {
            decorated.write(httpObject);
        }

        @Override
        public void onError(Throwable t) {
            decorated.close(t);
        }

        @Override
        public void onComplete() {
            decorated.close();
        }
    });
    return decorated;
}
 
Example #21
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
ExceptionFilteredHttpResponse(ServiceRequestContext ctx, HttpRequest req,
                              HttpResponse delegate, ExceptionHandlerFunction exceptionHandler) {
    super(delegate);
    this.ctx = ctx;
    this.req = req;
    this.exceptionHandler = exceptionHandler;
}
 
Example #22
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Commit>> history(
        Revision from, Revision to, String pathPattern, int maxCommits) {

    final ServiceRequestContext ctx = context();
    return CompletableFuture.supplyAsync(() -> {
        failFastIfTimedOut(this, logger, ctx, "history", from, to, pathPattern, maxCommits);
        return blockingHistory(from, to, pathPattern, maxCommits);
    }, repositoryWorker);
}
 
Example #23
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 #24
Source File: ObservableResponseConverterFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
private HttpResponse onSuccess(ServiceRequestContext ctx,
                               ResponseHeaders headers,
                               @Nullable Object result,
                               HttpHeaders trailers) {
    try {
        return responseConverter.convertResponse(ctx, headers, result, trailers);
    } catch (Exception e) {
        return onError(ctx, e);
    }
}
 
Example #25
Source File: THttpService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    if (req.method() != HttpMethod.POST) {
        return HttpResponse.of(HttpStatus.METHOD_NOT_ALLOWED);
    }

    final SerializationFormat serializationFormat = determineSerializationFormat(req);
    if (serializationFormat == null) {
        return HttpResponse.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               MediaType.PLAIN_TEXT_UTF_8, PROTOCOL_NOT_SUPPORTED);
    }

    if (!validateAcceptHeaders(req, serializationFormat)) {
        return HttpResponse.of(HttpStatus.NOT_ACCEPTABLE,
                               MediaType.PLAIN_TEXT_UTF_8, ACCEPT_THRIFT_PROTOCOL_MUST_MATCH_CONTENT_TYPE);
    }

    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
    final HttpResponse res = HttpResponse.from(responseFuture);
    ctx.logBuilder().serializationFormat(serializationFormat);
    ctx.logBuilder().defer(RequestLogProperty.REQUEST_CONTENT);
    PooledHttpRequest.of(req).aggregateWithPooledObjects(
            ctx.eventLoop(), ctx.alloc()).handle((aReq, cause) -> {
        if (cause != null) {
            final HttpResponse errorRes;
            if (ctx.config().verboseResponses()) {
                errorRes = HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR,
                                           MediaType.PLAIN_TEXT_UTF_8,
                                           Exceptions.traceText(cause));
            } else {
                errorRes = HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
            }
            responseFuture.complete(errorRes);
            return null;
        }
        decodeAndInvoke(ctx, aReq, serializationFormat, responseFuture);
        return null;
    }).exceptionally(CompletionActions::log);
    return res;
}
 
Example #26
Source File: JettyService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) {
    final ArmeriaConnector connector = this.connector;
    assert connector != null;

    final HttpResponseWriter res = HttpResponse.streaming();

    req.aggregate().handle((aReq, cause) -> {
        if (cause != null) {
            logger.warn("{} Failed to aggregate a request:", ctx, cause);
            if (res.tryWrite(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR))) {
                res.close();
            }
            return null;
        }

        boolean success = false;
        try {
            final ArmeriaHttpTransport transport = new ArmeriaHttpTransport(req.method());
            final HttpChannel httpChannel = new HttpChannel(
                    connector,
                    connector.getHttpConfiguration(),
                    new ArmeriaEndPoint(hostname, connector.getScheduler(),
                                        ctx.localAddress(), ctx.remoteAddress()),
                    transport);

            fillRequest(ctx, aReq, httpChannel.getRequest());

            ctx.blockingTaskExecutor().execute(() -> invoke(ctx, res, transport, httpChannel));
            success = true;
            return null;
        } finally {
            if (!success) {
                res.close();
            }
        }
    }).exceptionally(CompletionActions::log);

    return res;
}
 
Example #27
Source File: ApplicationTokenAuthorizer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, HttpRequest data) {
    final OAuth2Token token = AuthTokenExtractors.oAuth2().apply(data.headers());
    if (token == null || !Tokens.isValidSecret(token.accessToken())) {
        return completedFuture(false);
    }

    final CompletableFuture<Boolean> res = new CompletableFuture<>();
    tokenLookupFunc.apply(token.accessToken())
                   .thenAccept(appToken -> {
                       if (appToken != null && appToken.isActive()) {
                           final StringBuilder login = new StringBuilder(appToken.appId());
                           final SocketAddress ra = ctx.remoteAddress();
                           if (ra instanceof InetSocketAddress) {
                               login.append('@').append(((InetSocketAddress) ra).getHostString());
                           }

                           AuthUtil.setCurrentUser(
                                   ctx, new UserWithToken(login.toString(), appToken));
                           res.complete(true);
                       } else {
                           res.complete(false);
                       }
                   })
                   // Should be authorized by the next authorizer.
                   .exceptionally(voidFunction(cause -> {
                       cause = Exceptions.peel(cause);
                       if (!(cause instanceof IllegalArgumentException)) {
                           logger.warn("Application token authorization failed: {}",
                                       token.accessToken(), cause);
                       }
                       res.complete(false);
                   }));

    return res;
}
 
Example #28
Source File: ServerRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void serializationFormat() {
    final ServiceRequestContext ctx1 = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().serializationFormat(SerializationFormat.UNKNOWN);
    ctx1.logBuilder().endRequest();
    ctx1.logBuilder().endResponse();

    assertThat(ServiceRequestContextAdapter.serializationFormat(ctx1.log().ensureComplete()))
            .isEqualTo("unknown");

    final ServiceRequestContext ctx2 = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().endRequest();
    ctx2.logBuilder().endResponse();
    assertThat(ServiceRequestContextAdapter.serializationFormat(ctx2.log().ensureComplete())).isNull();
}
 
Example #29
Source File: PostgresDbService.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Get("/updates/{count}")
@ProducesJson
public CompletableFuture<World[]> update(
        @Param("count") String count,
        ServiceRequestContext ctx) {
  return doUpdate(count, ctx);
}
 
Example #30
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static ResponseHeadersBuilder addNegotiatedResponseMediaType(ServiceRequestContext ctx,
                                                                     HttpHeaders headers) {

    final MediaType negotiatedResponseMediaType = ctx.negotiatedResponseMediaType();
    if (negotiatedResponseMediaType == null || headers.contentType() != null) {
        // Do not overwrite 'content-type'.
        return ResponseHeaders.builder()
                              .add(headers);
    }

    return ResponseHeaders.builder()
                          .add(headers)
                          .contentType(negotiatedResponseMediaType);
}