com.linecorp.armeria.common.util.Exceptions Java Examples

The following examples show how to use com.linecorp.armeria.common.util.Exceptions. 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: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_FileService_create_exception(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAZ);
    assertThat(out.length()).isGreaterThan(0);

    final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
    final THttpService service = THttpService.of(
            (FileService.AsyncIface) (path, resultHandler) ->
                    resultHandler.onError(exception), defaultSerializationFormat);

    invoke(service);

    try {
        client.recv_create();
        fail(TApplicationException.class.getSimpleName() + " not raised.");
    } catch (TApplicationException e) {
        assertThat(e.getType()).isEqualTo(TApplicationException.INTERNAL_ERROR);
        assertThat(e.getMessage()).contains(exception.toString());
    }
}
 
Example #2
Source File: ManagedArmeriaServer.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    logger.trace("Getting Armeria Server Builder");
    final ServerBuilder sb = ((ArmeriaServerFactory) serverFactory).getServerBuilder();
    logger.trace("Calling Server Configurator");
    serverConfigurator.configure(sb);
    server = sb.build();
    if (logger.isDebugEnabled()) {
        logger.debug("Built server {}", server);
    }
    logger.info("Starting Armeria Server");
    try {
        server.start().join();
    } catch (Throwable cause) {
        Exceptions.throwUnsafely(Exceptions.peel(cause));
    }
    logger.info("Started Armeria Server");
}
 
Example #3
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxOutboundSize_tooBig() throws Exception {
    // set at least one field to ensure the size is non-zero.
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue(
                            request.getSerializedSize() - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.CANCELLED);
    assertThat(Exceptions.traceText(t)).contains("message too large");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED);
    });
}
 
Example #4
Source File: GoogleCredentialsDecoratingClient.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) {
  // if (ctx.additionalRequestHeaders().contains(header) || req.headers().contains(header)) {
  //  return delegate().execute(ctx, req);
  // }
  return HttpResponse.from(
      (type == TokenType.ACCESS_TOKEN
              ? accessTokenProvider.getAccessToken()
              : accessTokenProvider.getGoogleIdToken())
          .thenApplyAsync(
              (token) -> {
                ctx.addAdditionalRequestHeader(header, "Bearer " + token);
                try {
                  return delegate().execute(ctx, req);
                } catch (Exception e) {
                  return Exceptions.throwUnsafely(e);
                }
              },
              ctx.contextAwareEventLoop()));
}
 
Example #5
Source File: CentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
protected CompletionStage<Void> doStart(@Nullable Void unused) throws Exception {
    return execute("startup", () -> {
        try {
            CentralDogma.this.doStart();
            if (pluginsForAllReplicas != null) {
                final ProjectManager pm = CentralDogma.this.pm;
                final CommandExecutor executor = CentralDogma.this.executor;
                final MeterRegistry meterRegistry = CentralDogma.this.meterRegistry;
                if (pm != null && executor != null && meterRegistry != null) {
                    pluginsForAllReplicas.start(cfg, pm, executor, meterRegistry, purgeWorker).join();
                }
            }
        } catch (Exception e) {
            Exceptions.throwUnsafely(e);
        }
    });
}
 
Example #6
Source File: AbstractHttpFile.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
private HttpResponse read(Executor fileReadExecutor, ByteBufAllocator alloc,
                          @Nullable HttpFileAttributes attrs) {
    final ResponseHeaders headers = readHeaders(attrs);
    if (headers == null) {
        return null;
    }

    final long length = attrs.length();
    if (length == 0) {
        // No need to stream an empty file.
        return HttpResponse.of(headers);
    }

    try {
        return doRead(headers, length, fileReadExecutor, alloc);
    } catch (IOException e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example #7
Source File: DeferredHttpFile.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpService asService() {
    final HttpFile delegate = this.delegate;
    if (delegate != null) {
        return delegate.asService();
    }

    return (ctx, req) -> HttpResponse.from(stage.thenApply(file -> {
        setDelegate(file);
        try {
            return file.asService().serve(ctx, req);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }));
}
 
Example #8
Source File: AuthService.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    return HttpResponse.from(AuthorizerUtil.authorize(authorizer, ctx, req).handleAsync((result, cause) -> {
        try {
            final HttpService delegate = (HttpService) unwrap();
            if (cause == null) {
                if (result != null) {
                    return result ? successHandler.authSucceeded(delegate, ctx, req)
                                  : failureHandler.authFailed(delegate, ctx, req, null);
                }
                cause = AuthorizerUtil.newNullResultException(authorizer);
            }

            return failureHandler.authFailed(delegate, ctx, req, cause);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }, ctx.contextAwareEventLoop()));
}
 
Example #9
Source File: DefaultExceptionHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) {
    if (cause instanceof IllegalArgumentException) {
        if (needsToWarn()) {
            logger.warn("{} Failed processing a request:", ctx, cause);
        }
        return HttpResponse.of(HttpStatus.BAD_REQUEST);
    }

    if (cause instanceof HttpStatusException) {
        return HttpResponse.of(((HttpStatusException) cause).httpStatus());
    }

    if (cause instanceof HttpResponseException) {
        return ((HttpResponseException) cause).httpResponse();
    }

    if (needsToWarn() && !Exceptions.isExpected(cause)) {
        logger.warn("{} Unhandled exception from an annotated service:", ctx, cause);
    }

    return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example #10
Source File: KeepAliveHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        logger.debug("{} PING write successful", channel);
        final EventLoop el = channel.eventLoop();
        shutdownFuture = el.schedule(shutdownRunnable, pingIdleTimeNanos, TimeUnit.NANOSECONDS);
        pingState = PingState.PENDING_PING_ACK;
        resetStopwatch();
    } else {
        // Mostly because the channel is already closed. So ignore and change state to IDLE.
        // If the channel is closed, we change state to SHUTDOWN on destroy.
        if (!future.isCancelled() && Exceptions.isExpected(future.cause())) {
            logger.debug("{} PING write failed", channel, future.cause());
        }
        if (pingState != PingState.SHUTDOWN) {
            pingState = PingState.IDLE;
        }
    }
}
 
Example #11
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testSync_FileService_create_exception(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAZ);
    assertThat(out.length()).isGreaterThan(0);

    final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
    final THttpService service = THttpService.of((FileService.Iface) path -> {
        throw exception;
    }, defaultSerializationFormat);

    invoke(service);

    try {
        client.recv_create();
        fail(TApplicationException.class.getSimpleName() + " not raised.");
    } catch (TApplicationException e) {
        assertThat(e.getType()).isEqualTo(TApplicationException.INTERNAL_ERROR);
        assertThat(e.getMessage()).contains(exception.toString());
    }
}
 
Example #12
Source File: RpcResponse.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RpcResponse} that is completed successfully or exceptionally based on the
 * completion of the specified {@link CompletionStage}.
 */
static RpcResponse from(CompletionStage<?> stage) {
    requireNonNull(stage, "stage");
    final CompletableRpcResponse res = new CompletableRpcResponse();
    stage.handle((value, cause) -> {
        if (cause != null) {
            res.completeExceptionally(cause);
        } else if (value instanceof RpcResponse) {
            ((RpcResponse) value).handle((rpcResponseResult, rpcResponseCause) -> {
                if (rpcResponseCause != null) {
                    res.completeExceptionally(Exceptions.peel(rpcResponseCause));
                } else {
                    res.complete(rpcResponseResult);
                }
                return null;
            });
        } else {
            res.complete(value);
        }
        return null;
    });
    return res;
}
 
Example #13
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testIdentity_FileService_create_exception(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAZ);
    assertThat(out.length()).isGreaterThan(0);

    final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
    final THttpService syncService = THttpService.of((FileService.Iface) path -> {
        throw exception;
    }, defaultSerializationFormat);

    final THttpService asyncService = THttpService.of(
            (FileService.AsyncIface) (path, resultHandler) ->
                    resultHandler.onError(exception), defaultSerializationFormat);

    invokeTwice(syncService, asyncService);

    assertThat(promise.get()).isEqualTo(promise2.get());
}
 
Example #14
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxInboundSize_tooBig() throws Exception {
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final int size = blockingStub.streamingOutputCall(request).next().getSerializedSize();
    requestLogQueue.take();

    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    assertThat(Exceptions.traceText(t)).contains("exceeds maximum");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    });
}
 
Example #15
Source File: ArmeriaGrpcServerInteropTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.https(new InetSocketAddress("127.0.0.1", 0));
    sb.tls(ssc.certificateFile(), ssc.privateKeyFile());
    sb.tlsCustomizer(ssl -> {
        try {
            ssl.trustManager(TestUtils.loadCert("ca.pem"));
        } catch (IOException e) {
            Exceptions.throwUnsafely(e);
        }
    });
    sb.maxRequestLength(16 * 1024 * 1024);
    sb.serviceUnder("/", grpcService.decorate((delegate, ctx, req) -> {
        ctxCapture.set(ctx);
        return delegate.serve(ctx, req);
    }));
}
 
Example #16
Source File: HttpRequestSubscriber.java    From armeria with Apache License 2.0 6 votes vote down vote up
private void failAndReset(Throwable cause) {
    if (cause instanceof ProxyConnectException) {
        // ProxyConnectException is handled by HttpSessionHandler.exceptionCaught().
        return;
    }

    fail(cause);

    final Http2Error error;
    if (Exceptions.isStreamCancelling(cause)) {
        error = Http2Error.CANCEL;
    } else {
        error = Http2Error.INTERNAL_ERROR;
    }

    if (error.code() != Http2Error.CANCEL.code()) {
        Exceptions.logIfUnexpected(logger, ch,
                                   HttpSession.get(ch).protocol(),
                                   "a request publisher raised an exception", cause);
    }

    if (ch.isActive()) {
        encoder.writeReset(id, streamId(), error);
        ch.flush();
    }
}
 
Example #17
Source File: RequiresPermissionDecorator.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private HttpResponse serveInternalRepo(ServiceRequestContext ctx, HttpRequest req,
                                       MetadataService mds, User user,
                                       String projectName) throws Exception {
    if (user.isAdmin()) {
        return unwrap().serve(ctx, req);
    }
    // We do not manage permission for the internal repository. Actually we do not have a metadata of that.
    // So we need to check whether the current user is an 'administrator' or not when the request is
    // accessing to the internal repository.
    return HttpResponse.from(mds.findRole(projectName, user).handle((role, cause) -> {
        if (cause != null) {
            return handleException(ctx, cause);
        }
        if (!user.isAdmin()) {
            return HttpApiUtil.throwResponse(
                    ctx, HttpStatus.FORBIDDEN,
                    "Repository '%s/%s' can be accessed only by an administrator.",
                    projectName, Project.REPO_DOGMA);
        }
        try {
            return unwrap().serve(ctx, req);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }));
}
 
Example #18
Source File: AbstractEndpointSelectorTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void timeout() {
    final DynamicEndpointGroup group = new DynamicEndpointGroup();
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final CompletableFuture<Endpoint> future =
            newSelector(group).select(ctx, ctx.eventLoop(), 1000)
                              .handle((res, cause) -> {
                                  // Must be invoked from the event loop thread.
                                  assertThat(ctx.eventLoop().inEventLoop()).isTrue();

                                  if (cause != null) {
                                      Exceptions.throwUnsafely(cause);
                                  }

                                  return res;
                              });
    assertThat(future).isNotDone();

    final Stopwatch stopwatch = Stopwatch.createStarted();
    assertThat(future.join()).isNull();
    assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS)).isGreaterThan(900);
}
 
Example #19
Source File: HttpServerStreamingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpResponse doPost(ServiceRequestContext ctx, HttpRequest req) {
    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
    final HttpResponse res = HttpResponse.from(responseFuture);
    req.subscribe(new StreamConsumer(ctx.eventLoop(), slow) {
        @Override
        public void onError(Throwable cause) {
            responseFuture.complete(
                    HttpResponse.of(
                            HttpStatus.INTERNAL_SERVER_ERROR,
                            MediaType.PLAIN_TEXT_UTF_8,
                            Exceptions.traceText(cause)));
        }

        @Override
        public void onComplete() {
            responseFuture.complete(
                    HttpResponse.of(
                            HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "%d", numReceivedBytes()));
        }
    });
    return res;
}
 
Example #20
Source File: ClassPathHttpFile.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<HttpFileAttributes> readAttributes(Executor fileReadExecutor) {
    requireNonNull(fileReadExecutor, "fileReadExecutor");

    if (attrsFuture != null) {
        return attrsFuture;
    }

    return attrsFuture = CompletableFuture.supplyAsync(() -> {
        try {
            final URLConnection conn = url.openConnection();
            final long length = conn.getContentLengthLong();
            final long lastModifiedMillis = conn.getLastModified();
            return new HttpFileAttributes(length, lastModifiedMillis);
        } catch (IOException e) {
            return Exceptions.throwUnsafely(e);
        }
    }, fileReadExecutor);
}
 
Example #21
Source File: FileService.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    return HttpResponse.from(
            first.findFile(ctx, req)
                 .readAttributes(ctx.blockingTaskExecutor())
                 .thenApply(firstAttrs -> {
                     try {
                         if (firstAttrs != null) {
                             return first.serve(ctx, req);
                         }

                         return second.serve(ctx, req);
                     } catch (Exception e) {
                         return Exceptions.throwUnsafely(e);
                     }
                 }));
}
 
Example #22
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void httpsRequestWithInvalidCertificate() throws Exception {
    final WebClient client = WebClient.builder(
            SessionProtocol.HTTPS, server.httpEndpoint()).build();
    final Throwable throwable = catchThrowable(() -> client.get("/hello/world").aggregate().get());
    assertThat(Exceptions.peel(throwable))
            .isInstanceOf(UnprocessedRequestException.class)
            .hasCauseInstanceOf(SSLException.class);
}
 
Example #23
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void httpsRequestToPlainTextEndpoint() throws Exception {
    final WebClient client = WebClient.builder(SessionProtocol.HTTPS, server.httpEndpoint())
                                      .factory(ClientFactory.insecure()).build();
    final Throwable throwable = catchThrowable(() -> client.get("/hello/world").aggregate().get());
    assertThat(Exceptions.peel(throwable))
            .isInstanceOf(UnprocessedRequestException.class)
            .hasCauseInstanceOf(SSLException.class);
}
 
Example #24
Source File: JsonTextSequences.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static HttpData toHttpData(ObjectMapper mapper, @Nullable Object value) {
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(RECORD_SEPARATOR);
        mapper.writeValue(out, value);
        out.write(LINE_FEED);
        return HttpData.wrap(out.toByteArray());
    } catch (Exception e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example #25
Source File: CachingHttpFile.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpService asService() {
    return (ctx, req) -> {
        try {
            return getFile(ctx.blockingTaskExecutor()).asService().serve(ctx, req);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    };
}
 
Example #26
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (!Exceptions.isExpected(cause)) {
        logger.warn("{} Unexpected exception while detecting the session protocol.", ctx, cause);
    }
    ctx.close();
}
 
Example #27
Source File: Server.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Waits until the result of {@link CompletableFuture} which is completed after the {@link #close()} or
 * {@link #closeAsync()} operation is completed.
 */
public void blockUntilShutdown() throws InterruptedException {
    try {
        whenClosed().get();
    } catch (ExecutionException e) {
        throw new CompletionException(e.toString(), Exceptions.peel(e));
    }
}
 
Example #28
Source File: AccessLogComponent.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String handleThrowable(@Nullable Throwable cause) {
    if (cause == null) {
        return null;
    }
    cause = Exceptions.peel(cause);
    final String message = cause.getMessage();
    return message != null ? cause.getClass().getSimpleName() + ": " + message
                           : cause.getClass().getSimpleName();
}
 
Example #29
Source File: JacksonResponseConverterFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
private HttpData toJsonHttpData(@Nullable Object value) {
    try {
        return HttpData.wrap(mapper.writeValueAsBytes(value));
    } catch (Exception e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example #30
Source File: HttpServerHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    Exceptions.logIfUnexpected(logger, ctx.channel(), protocol, cause);
    if (ctx.channel().isActive()) {
        ctx.close();
    }
}