Java Code Examples for com.linecorp.armeria.common.util.Exceptions#throwUnsafely()

The following examples show how to use com.linecorp.armeria.common.util.Exceptions#throwUnsafely() . 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: 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 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: SamlServiceProviderBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Credential apply(String keyName) {
    final CriteriaSet cs = new CriteriaSet();
    cs.add(new EntityIdCriterion(keyName));
    try {
        return resolver.resolveSingle(cs);
    } catch (Throwable cause) {
        return Exceptions.throwUnsafely(cause);
    }
}
 
Example 4
Source File: FlagsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    if (!name.startsWith("com.linecorp.armeria.common")) {
        return super.loadClass(name);
    }

    // Reload every class in common package.
    try {
        // Classes do not have an inner class.
        final String replaced = name.replace('.', File.separatorChar) + ".class";
        final URL url = getClass().getClassLoader().getResource(replaced);
        final URLConnection connection = url.openConnection();
        final InputStream input = connection.getInputStream();
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int data = input.read();

        while (data != -1) {
            buffer.write(data);
            data = input.read();
        }

        input.close();
        final byte[] classData = buffer.toByteArray();

        return defineClass(name, classData, 0, classData.length);
    } catch (IOException e) {
        Exceptions.throwUnsafely(e);
    }
    return null;
}
 
Example 5
Source File: LoggingTestUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
public static void throwIfCaptured(AtomicReference<Throwable> capturedCause) {
    final Throwable cause = capturedCause.get();
    if (cause != null) {
        capturedCause.set(null);
        Exceptions.throwUnsafely(cause);
    }
}
 
Example 6
Source File: AnnotatedValueResolver.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a bean resolver which retrieves a value using request converters. If the target element
 * is an annotated bean, a bean factory of the specified {@link BeanFactoryId} will be used for creating an
 * instance.
 */
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object>
resolver(List<RequestObjectResolver> objectResolvers, BeanFactoryId beanFactoryId) {
    return (resolver, ctx) -> {
        boolean found = false;
        Object value = null;
        for (final RequestObjectResolver objectResolver : objectResolvers) {
            try {
                value = objectResolver.convert(ctx, resolver.elementType(),
                                               resolver.parameterizedElementType(), beanFactoryId);
                found = true;
                break;
            } catch (FallthroughException ignore) {
                // Do nothing.
            } catch (Throwable cause) {
                Exceptions.throwUnsafely(cause);
            }
        }

        if (!found) {
            throw new IllegalArgumentException(
                    "No suitable request converter found for a @" +
                    RequestObject.class.getSimpleName() + " '" +
                    resolver.elementType().getSimpleName() + '\'');
        }

        if (value == null && resolver.shouldExist()) {
            throw new IllegalArgumentException(
                    "A request converter converted the request into null, but the injection target " +
                    "is neither an Optional nor annotated with @Nullable");
        }

        return value;
    };
}
 
Example 7
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 8
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 9
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 10
Source File: SamlEndpoint.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link SamlEndpoint} of the specified {@code uri} and the HTTP POST binding protocol.
 */
public static SamlEndpoint ofHttpPost(String uri) {
    requireNonNull(uri, "uri");
    try {
        return ofHttpPost(new URI(uri));
    } catch (URISyntaxException e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example 11
Source File: SamlEndpoint.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link SamlEndpoint} of the specified {@code uri} and the HTTP Redirect binding protocol.
 */
public static SamlEndpoint ofHttpRedirect(String uri) {
    requireNonNull(uri, "uri");
    try {
        return ofHttpRedirect(new URI(uri));
    } catch (URISyntaxException e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example 12
Source File: RepositorySupport.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
Revision normalize(Repository repository) {
    requireNonNull(repository, "repository");
    try {
        return repository.normalizeNow(Revision.HEAD);
    } catch (Throwable cause) {
        return Exceptions.throwUnsafely(cause);
    }
}
 
Example 13
Source File: ZooKeeperExtension.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableZooKeeper connection() {
    // Try up to three times to reduce flakiness.
    Throwable lastCause = null;
    for (int i = 0; i < 3; i++) {
        try {
            return ZooKeeperAssert.super.connection();
        } catch (Throwable t) {
            lastCause = t;
        }
    }

    return Exceptions.throwUnsafely(lastCause);
}
 
Example 14
Source File: StackdriverSpanConsumer.java    From zipkin-gcp with Apache License 2.0 5 votes vote down vote up
@Override
protected Void doExecute() {
  try {
    sendRequest().join();
    return null;
  } catch (CompletionException e) {
    propagateIfFatal(e);
    Exceptions.throwUnsafely(e.getCause());
    return null;  // Unreachable
  }
}
 
Example 15
Source File: MetadataApiService.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static String urlDecode(String input) {
    try {
        // TODO(hyangtack) Remove this after https://github.com/line/armeria/issues/756 is resolved.
        return URLDecoder.decode(input, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        return Exceptions.throwUnsafely(e);
    }
}
 
Example 16
Source File: ContentServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static Object handleWatchFailure(Throwable thrown) {
    if (Throwables.getRootCause(thrown) instanceof CancellationException) {
        // timeout happens
        return HttpResponse.of(HttpStatus.NOT_MODIFIED);
    }
    return Exceptions.throwUnsafely(thrown);
}
 
Example 17
Source File: RequiresRoleDecorator.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
static HttpResponse handleException(ServiceRequestContext ctx, Throwable cause) {
    cause = Exceptions.peel(cause);
    if (cause instanceof RepositoryNotFoundException ||
        cause instanceof ProjectNotFoundException) {
        return HttpApiUtil.newResponse(ctx, HttpStatus.NOT_FOUND, cause);
    } else {
        return Exceptions.throwUnsafely(cause);
    }
}
 
Example 18
Source File: RepositorySupport.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static <T> T convertWithJackson(Entry<?> entry, Class<T> clazz) {
    requireNonNull(entry, "entry");
    requireNonNull(clazz, "clazz");
    try {
        return Jackson.treeToValue(((Entry<JsonNode>) entry).content(), clazz);
    } catch (Throwable cause) {
        return Exceptions.throwUnsafely(cause);
    }
}
 
Example 19
Source File: CentralDogma.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private Server startServer(ProjectManager pm, CommandExecutor executor,
                           PrometheusMeterRegistry meterRegistry, @Nullable SessionManager sessionManager) {
    final ServerBuilder sb = Server.builder();
    sb.verboseResponses(true);
    cfg.ports().forEach(sb::port);

    if (cfg.ports().stream().anyMatch(ServerPort::hasTls)) {
        try {
            final TlsConfig tlsConfig = cfg.tls();
            if (tlsConfig != null) {
                sb.tls(tlsConfig.keyCertChainFile(), tlsConfig.keyFile(), tlsConfig.keyPassword());
            } else {
                logger.warn(
                        "Missing TLS configuration. Generating a self-signed certificate for TLS support.");
                sb.tlsSelfSigned();
            }
        } catch (Exception e) {
            Exceptions.throwUnsafely(e);
        }
    }

    sb.clientAddressSources(cfg.clientAddressSourceList());
    sb.clientAddressTrustedProxyFilter(cfg.trustedProxyAddressPredicate());

    cfg.numWorkers().ifPresent(
            numWorkers -> sb.workerGroup(EventLoopGroups.newEventLoopGroup(numWorkers), true));
    cfg.maxNumConnections().ifPresent(sb::maxNumConnections);
    cfg.idleTimeoutMillis().ifPresent(sb::idleTimeoutMillis);
    cfg.requestTimeoutMillis().ifPresent(sb::requestTimeoutMillis);
    cfg.maxFrameLength().ifPresent(sb::maxRequestLength);
    cfg.gracefulShutdownTimeout().ifPresent(
            t -> sb.gracefulShutdownTimeoutMillis(t.quietPeriodMillis(), t.timeoutMillis()));

    final MetadataService mds = new MetadataService(pm, executor);
    final WatchService watchService = new WatchService(meterRegistry);
    final AuthProvider authProvider = createAuthProvider(executor, sessionManager, mds);

    configureThriftService(sb, pm, executor, watchService, mds);

    sb.service("/title", webAppTitleFile(cfg.webAppTitle(), SystemInfo.hostname()).asService());

    sb.service(HEALTH_CHECK_PATH, HealthCheckService.of());

    // TODO(hyangtack): This service is temporarily added to support redirection from '/docs' to '/docs/'.
    //                  It would be removed if this kind of redirection is handled by Armeria.
    sb.service("/docs", new AbstractHttpService() {
        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req)
                throws Exception {
            return HttpResponse.of(
                    ResponseHeaders.of(HttpStatus.TEMPORARY_REDIRECT, HttpHeaderNames.LOCATION, "/docs/"));
        }
    });
    sb.serviceUnder("/docs/",
                    DocService.builder()
                              .exampleHttpHeaders(CentralDogmaService.class,
                                                  HttpHeaders.of(HttpHeaderNames.AUTHORIZATION,
                                                                 "Bearer " + CsrfToken.ANONYMOUS))
                              .build());

    configureHttpApi(sb, pm, executor, watchService, mds, authProvider, sessionManager);

    configureMetrics(sb, meterRegistry);

    // Configure access log format.
    final String accessLogFormat = cfg.accessLogFormat();
    if (isNullOrEmpty(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.disabled(), true);
    } else if ("common".equals(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.common(), true);
    } else if ("combined".equals(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.combined(), true);
    } else {
        sb.accessLogFormat(accessLogFormat);
    }

    final Server s = sb.build();
    s.start().join();
    return s;
}
 
Example 20
Source File: HttpApiUtil.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Throws the specified {@link Throwable} if it is not {@code null}.
 */
static void throwUnsafelyIfNonNull(@Nullable Throwable cause) {
    if (cause != null) {
        Exceptions.throwUnsafely(cause);
    }
}