Search in sources :

Example 1 with DeploymentException

use of jakarta.enterprise.inject.spi.DeploymentException in project helidon by oracle.

the class ConfigBeanDescriptor method create.

static ConfigBeanDescriptor create(AnnotatedType<?> annotatedType, ConfigProperties configProperties) {
    Class<?> type = annotatedType.getJavaClass();
    if (type.isInterface()) {
        throw new DeploymentException("Only concrete classes can be annotated with ConfigProperties, got " + type.getName());
    }
    Supplier<Object> instanceCreator;
    try {
        Constructor<?> defaultConstructor = type.getConstructor();
        instanceCreator = () -> {
            try {
                return defaultConstructor.newInstance();
            } catch (Exception e) {
                throw new ConfigException("Failed to instantiate ConfigProperties type " + type.getName(), e);
            }
        };
    } catch (NoSuchMethodException e) {
        throw new DeploymentException("Failed to find default constructor on config properties class " + type.getName());
    }
    List<FieldSetter> fieldSetters = new LinkedList<>();
    for (Field field : type.getDeclaredFields()) {
        String configKey;
        String defaultValue;
        ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
        if (configProperty == null) {
            configKey = field.getName();
            defaultValue = null;
        } else {
            configKey = configProperty.name();
            defaultValue = configProperty.defaultValue();
            if (ConfigProperty.UNCONFIGURED_VALUE.equals(defaultValue) || defaultValue.isEmpty()) {
                defaultValue = null;
            }
        }
        fieldSetters.add(new FieldSetter(field, configKey, defaultValue));
    }
    String prefix = findPrefix(configProperties.prefix(), null);
    ConfigBeanDescriptor descriptor = new ConfigBeanDescriptor(type, prefix, instanceCreator, fieldSetters);
    descriptor.validate(ConfigProvider.getConfig(), prefix);
    return descriptor;
}
Also used : ConfigException(io.helidon.config.ConfigException) ConfigException(io.helidon.config.ConfigException) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) LinkedList(java.util.LinkedList) Field(java.lang.reflect.Field) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException)

Example 2 with DeploymentException

use of jakarta.enterprise.inject.spi.DeploymentException in project helidon by oracle.

the class MessageUtils method isMessageType.

/**
 * Check if expected type is {@link org.eclipse.microprofile.reactive.messaging.Message}.
 *
 * @param method {@link java.lang.reflect.Method} to check
 * @return true is expected type of method is {@link org.eclipse.microprofile.reactive.messaging.Message}
 */
static boolean isMessageType(Method method) {
    Type returnType = method.getGenericReturnType();
    ParameterizedType parameterizedType = (ParameterizedType) returnType;
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    if (SubscriberBuilder.class.equals(method.getReturnType())) {
        if (actualTypeArguments.length != 2) {
            throw new DeploymentException("Invalid method return type " + method);
        }
        return isMessageType(actualTypeArguments[0]);
    } else if (Subscriber.class.equals(method.getReturnType())) {
        if (actualTypeArguments.length != 1) {
            throw new DeploymentException("Invalid method return type " + method);
        }
        return isMessageType(actualTypeArguments[0]);
    } else if (Processor.class.equals(method.getReturnType())) {
        return isMessageType(actualTypeArguments[0]);
    } else if (ProcessorBuilder.class.equals(method.getReturnType())) {
        return isMessageType(actualTypeArguments[0]);
    } else if (PublisherBuilder.class.equals(method.getReturnType())) {
        return isMessageType(actualTypeArguments[0]);
    } else if (Publisher.class.equals(method.getReturnType())) {
        return isMessageType(actualTypeArguments[0]);
    }
    throw new InvalidParameterException("Unsupported method for unwrapping " + method);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) InvalidParameterException(java.security.InvalidParameterException) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Subscriber(org.reactivestreams.Subscriber) ProcessorBuilder(org.eclipse.microprofile.reactive.streams.operators.ProcessorBuilder) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) Publisher(org.reactivestreams.Publisher)

Example 3 with DeploymentException

use of jakarta.enterprise.inject.spi.DeploymentException in project helidon by oracle.

the class MessagingCdiExtension method deploymentValidation.

private void deploymentValidation(@Observes AfterDeploymentValidation event) {
    Errors.Collector errors = channelRouter.getErrors();
    boolean hasFatal = errors.hasFatal();
    Errors errorMessages = errors.collect();
    if (hasFatal) {
        throw new DeploymentException(errorMessages.toString());
    } else {
        errorMessages.log(LOGGER);
    }
}
Also used : Errors(io.helidon.common.Errors) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException)

Example 4 with DeploymentException

use of jakarta.enterprise.inject.spi.DeploymentException in project helidon by oracle.

the class SchedulingCdiExtension method invoke.

void invoke(@Observes @Priority(PLATFORM_AFTER + 4000) @Initialized(ApplicationScoped.class) Object event, BeanManager beanManager) {
    ScheduledThreadPoolSupplier scheduledThreadPoolSupplier = ScheduledThreadPoolSupplier.builder().threadNamePrefix(schedulingConfig.get("thread-name-prefix").asString().orElse("scheduled-")).config(schedulingConfig).build();
    for (AnnotatedMethod<?> am : methods) {
        Class<?> aClass = am.getDeclaringType().getJavaClass();
        Bean<?> bean = beans.get(am);
        Object beanInstance = lookup(bean, beanManager);
        ScheduledExecutorService executorService = scheduledThreadPoolSupplier.get();
        executors.add(executorService);
        Method method = am.getJavaMember();
        if (!method.trySetAccessible()) {
            throw new DeploymentException(String.format("Scheduled method %s#%s is not accessible!", method.getDeclaringClass().getName(), method.getName()));
        }
        if (am.isAnnotationPresent(FixedRate.class) && am.isAnnotationPresent(Scheduled.class)) {
            throw new DeploymentException(String.format("Scheduled method %s#%s can have only one scheduling annotation.", method.getDeclaringClass().getName(), method.getName()));
        }
        Config methodConfig = config.get(aClass.getName() + "." + method.getName() + ".schedule");
        if (am.isAnnotationPresent(FixedRate.class)) {
            FixedRate annotation = am.getAnnotation(FixedRate.class);
            long initialDelay = methodConfig.get("initial-delay").asLong().orElseGet(annotation::initialDelay);
            long delay = methodConfig.get("delay").asLong().orElseGet(annotation::value);
            TimeUnit timeUnit = methodConfig.get("time-unit").asString().map(TimeUnit::valueOf).orElseGet(annotation::timeUnit);
            Task task = Scheduling.fixedRateBuilder().executor(executorService).initialDelay(initialDelay).delay(delay).timeUnit(timeUnit).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        } else if (am.isAnnotationPresent(Scheduled.class)) {
            Scheduled annotation = am.getAnnotation(Scheduled.class);
            String cron = methodConfig.get("cron").asString().orElseGet(() -> resolvePlaceholders(annotation.value(), config));
            boolean concurrent = methodConfig.get("concurrent").asBoolean().orElseGet(annotation::concurrentExecution);
            Task task = Scheduling.cronBuilder().executor(executorService).concurrentExecution(concurrent).expression(cron).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        }
    }
}
Also used : Observes(jakarta.enterprise.event.Observes) Task(io.helidon.scheduling.Task) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) Invocation(io.helidon.scheduling.Invocation) ProcessManagedBean(jakarta.enterprise.inject.spi.ProcessManagedBean) Level(java.util.logging.Level) Bean(jakarta.enterprise.inject.spi.Bean) RuntimeStart(io.helidon.microprofile.cdi.RuntimeStart) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Matcher(java.util.regex.Matcher) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) Map(java.util.Map) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) PLATFORM_AFTER(jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Priority(jakarta.annotation.Priority) LinkedList(java.util.LinkedList) Method(java.lang.reflect.Method) Initialized(jakarta.enterprise.context.Initialized) ExecutorService(java.util.concurrent.ExecutorService) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Scheduling(io.helidon.scheduling.Scheduling) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) CreationalContext(jakarta.enterprise.context.spi.CreationalContext) Logger(java.util.logging.Logger) BeforeDestroyed(jakarta.enterprise.context.BeforeDestroyed) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) WithAnnotations(jakarta.enterprise.inject.spi.WithAnnotations) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Task(io.helidon.scheduling.Task) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Method(java.lang.reflect.Method) TimeUnit(java.util.concurrent.TimeUnit) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException)

Example 5 with DeploymentException

use of jakarta.enterprise.inject.spi.DeploymentException in project helidon by oracle.

the class ServerCdiExtension method startServer.

private void startServer(@Observes @Priority(PLATFORM_AFTER + 100) @Initialized(ApplicationScoped.class) Object event, BeanManager beanManager) {
    // make sure all configuration is in place
    if (null == jaxRsExecutorService) {
        Config serverConfig = config.get("server");
        // support for Loom is built into the thread pool supplier
        jaxRsExecutorService = ServerThreadPoolSupplier.builder().name("server").config(serverConfig.get("executor-service")).build();
    }
    // redirect to the first page when root is accessed (if configured)
    registerDefaultRedirect();
    // register static content if configured
    registerStaticContent();
    // reactive services
    registerWebServerServices(beanManager);
    // JAX-RS applications (and resources)
    registerJaxRsApplications(beanManager);
    // start the webserver
    serverBuilder.routing(routingBuilder.build());
    namedRoutings.forEach(serverBuilder::addNamedRouting);
    webserver = serverBuilder.build();
    try {
        webserver.start().toCompletableFuture().get();
        started = true;
    } catch (Exception e) {
        throw new DeploymentException("Failed to start webserver", e);
    }
    this.port = webserver.port();
    long initializationElapsedTime = ManagementFactory.getRuntimeMXBean().getUptime();
    String protocol = "http" + (webserver.hasTls() ? "s" : "");
    String host = "0.0.0.0".equals(listenHost) ? "localhost" : listenHost;
    String note = "0.0.0.0".equals(listenHost) ? " (and all other host addresses)" : "";
    LOGGER.info(() -> "Server started on " + protocol + "://" + host + ":" + port + note + " in " + initializationElapsedTime + " milliseconds (since JVM startup).");
    // this is not needed at runtime, collect garbage
    serverBuilder = null;
    routingBuilder = null;
    namedRoutings = null;
    STARTUP_LOGGER.finest("Server created");
}
Also used : Config(io.helidon.config.Config) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

DeploymentException (jakarta.enterprise.inject.spi.DeploymentException)11 Config (io.helidon.config.Config)3 Type (java.lang.reflect.Type)3 Reflected (io.helidon.common.Reflected)2 ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)2 Inject (jakarta.inject.Inject)2 Method (java.lang.reflect.Method)2 ParameterizedType (java.lang.reflect.ParameterizedType)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 TimeUnit (java.util.concurrent.TimeUnit)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 Collectors (java.util.stream.Collectors)2 Errors (io.helidon.common.Errors)1 ScheduledThreadPoolSupplier (io.helidon.common.configurable.ScheduledThreadPoolSupplier)1 HelidonServiceLoader (io.helidon.common.serviceloader.HelidonServiceLoader)1