io.micronaut.context.exceptions.ConfigurationException Java Examples

The following examples show how to use io.micronaut.context.exceptions.ConfigurationException. 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: KafkaConsumerFactory.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link KafkaConsumer} for the given configuration.
 *
 * @param consumerConfiguration The consumer configuration
 * @param <K> The key type
 * @param <V> The value type
 * @return The consumer
 */
@Prototype
public <K, V> KafkaConsumer<K, V> createConsumer(
        @Parameter AbstractKafkaConsumerConfiguration<K, V> consumerConfiguration) {

    Optional<Deserializer<K>> keyDeserializer = consumerConfiguration.getKeyDeserializer();
    Optional<Deserializer<V>> valueDeserializer = consumerConfiguration.getValueDeserializer();
    Properties config = consumerConfiguration.getConfig();

    if (keyDeserializer.isPresent() && valueDeserializer.isPresent()) {
        return new KafkaConsumer<>(
                config,
                keyDeserializer.get(),
                valueDeserializer.get()
        );
    } else if (keyDeserializer.isPresent() || valueDeserializer.isPresent()) {
        throw new ConfigurationException("Both the [keyDeserializer] and [valueDeserializer] must be set when setting either");
    } else {
        return new KafkaConsumer<>(
                config
        );
    }

}
 
Example #2
Source File: KafkaProducerFactory.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link KafkaProducer} for the given configuration.
 *
 * @param producerConfiguration The producer configuration
 * @param <K> The key type
 * @param <V> The value type
 * @return The consumer
 */
@Prototype
public <K, V> KafkaProducer<K, V> createProducer(@Parameter AbstractKafkaProducerConfiguration<K, V> producerConfiguration) {
    Optional<Serializer<K>> keySerializer = producerConfiguration.getKeySerializer();
    Optional<Serializer<V>> valueSerializer = producerConfiguration.getValueSerializer();

    Properties config = producerConfiguration.getConfig();
    if (keySerializer.isPresent() && valueSerializer.isPresent()) {
        Serializer<K> ks = keySerializer.get();
        Serializer<V> vs = valueSerializer.get();
        return new KafkaProducer<>(
                config,
                ks,
                vs
        );
    } else if (keySerializer.isPresent() || valueSerializer.isPresent()) {
        throw new ConfigurationException("Both the [keySerializer] and [valueSerializer] must be set when setting either");
    } else {
        return new KafkaProducer<>(
                config
        );
    }
}
 
Example #3
Source File: CalculatedSettings.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the URL based on the configured value. If the URL is
 * not configured, search for an embedded database driver on the
 * classpath and retrieve a default URL for it.
 *
 * @return The calculated URL
 */
public String getUrl() {
    final String url = basicJdbcConfiguration.getConfiguredUrl();
    if (calculatedUrl == null || StringUtils.hasText(url)) {
        calculatedUrl = url;
        if (!StringUtils.hasText(calculatedUrl) && embeddedDatabaseConnection.isPresent()) {
            calculatedUrl = embeddedDatabaseConnection.get().getUrl(basicJdbcConfiguration.getName());
        }
        if (!StringUtils.hasText(calculatedUrl)) {
            throw new ConfigurationException(String.format("Error configuring data source '%s'. No URL specified", basicJdbcConfiguration.getName()));
        }
    }

    return calculatedUrl;
}
 
Example #4
Source File: GraphiQLController.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
private String loadTemplate(final String templateFile) {
    Optional<InputStream> template = resourceResolver.getResourceAsStream(templateFile);
    if (template.isPresent()) {
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(template.get(), StandardCharsets.UTF_8))) {
            return IOUtils.readText(in);
        } catch (IOException e) {
            throw new ConfigurationException("Cannot read GraphiQL template: " + templateFile, e);
        }
    } else {
        throw new ConfigurationException("Cannot find GraphiQL template: " + templateFile);
    }
}
 
Example #5
Source File: DataIntroductionAdvice.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
private @NonNull
DataInterceptor<Object, Object> findInterceptor(
        @Nullable String dataSourceName,
        @NonNull Class<?> operationsType,
        @NonNull Class<?> interceptorType) {
    DataInterceptor interceptor;
    if (!RepositoryOperations.class.isAssignableFrom(operationsType)) {
        throw new IllegalArgumentException("Repository type must be an instance of RepositoryOperations!");
    }

    RepositoryOperations datastore;
    try {
        if (dataSourceName != null) {
            Qualifier qualifier = Qualifiers.byName(dataSourceName);
            datastore = (RepositoryOperations) beanLocator.getBean(operationsType, qualifier);
        } else {
            datastore = (RepositoryOperations) beanLocator.getBean(operationsType);
        }
    } catch (NoSuchBeanException e) {
        throw new ConfigurationException("No backing RepositoryOperations configured for repository. Check your configuration and try again", e);
    }
    BeanIntrospection<Object> introspection = BeanIntrospector.SHARED.findIntrospections(ref -> interceptorType.isAssignableFrom(ref.getBeanType())).stream().findFirst().orElseThrow(() ->
            new DataAccessException("No Data interceptor found for type: " + interceptorType)
    );
    if (introspection.getConstructorArguments().length == 0) {
        interceptor = (DataInterceptor) introspection.instantiate();
    } else {
        interceptor = (DataInterceptor) introspection.instantiate(datastore);
    }
    return interceptor;
}
 
Example #6
Source File: DatasourceConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
@Override
public void setDataSourceProperties(Map<String, ?> dsProperties) {
    if (dsProperties != null) {
        Properties properties = new Properties();
        properties.putAll(dsProperties);
        try {
            this.delegate.setConnectionProperties(properties);
        } catch (SQLException e) {
            throw new ConfigurationException("Unable to set datasource properties: " + e.getMessage(), e);
        }
    }
}
 
Example #7
Source File: DatasourceConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
@Override
public void setPassword(String password) {
    try {
        this.delegate.setPassword(password);
    } catch (SQLException e) {
        throw new ConfigurationException("Unable to set datasource password: " + e.getMessage(), e);
    }

}
 
Example #8
Source File: DatasourceConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * @param username the username
 */
public void setUsername(String username) {
    this.username = username;
    try {
        this.delegate.setUser(username);
    } catch (SQLException e) {
        throw new ConfigurationException("Unable to set datasource username: " + e.getMessage(), e);
    }
}
 
Example #9
Source File: DatasourceConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
@Override
public void setUrl(String url) {
    try {
        this.delegate.setURL(url);
    } catch (SQLException e) {
        throw new ConfigurationException("Unable to set datasource URL: " + e.getMessage(), e);
    }
}
 
Example #10
Source File: DatasourceConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
@Override
public void setDriverClassName(String driverClassName) {
    try {
        this.delegate.setConnectionFactoryClassName(driverClassName);
    } catch (SQLException e) {
        throw new ConfigurationException("Unable to set driver class name: " + e.getMessage(), e);
    }
}
 
Example #11
Source File: GoogleCredentialsFactory.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to return the default {@link GoogleCredentials} and provide it as a bean.
 *
 * It will determine which credential in the following way:
 * <ol>
 *     <li>If <pre>gcp.credentials.location</pre> is specified, use its location</li>
 *     <li>Otherwise, if <pre>gcp.credentials.encodedKey</pre> is specified, decode it and use its content</li>
 *     <li>None of the 2 properties were specified, use Application Default credential resolution. See
 *     <a href="https://github.com/googleapis/google-cloud-java#authentication">Google Cloud Java authentication</a>.
 *     This will resolve credential in the following order:
 *       <ol>
 *           <li>The credentials file pointed to by the <pre>GOOGLE_APPLICATION_CREDENTIALS</pre> environment variable</li>
 *           <li>Credentials provided by the Google Cloud SDK <pre>gcloud auth application-default login</pre> command</li>
 *           <li>Google App Engine built-in credentials when running inside of Google App Engine</li>
 *           <li>Google Cloud Shell built-in credentials when running inside of Google Cloud Shell</li>
 *           <li>Google Compute Engine built-in credentials when running inside of Google Compute Engine or Kubernetes Engine</li>
 *       </ol>
 *     </li>
 * </ol>
 *
 * @return The {@link GoogleCredentials}
 * @throws IOException An exception if an error occurs
 */
@Requires(missingBeans = GoogleCredentials.class)
@Requires(classes = com.google.auth.oauth2.GoogleCredentials.class)
@Primary
@Singleton
protected GoogleCredentials defaultGoogleCredentials() throws IOException {
    final List<String> scopes = configuration.getScopes().stream()
            .map(URI::toString).collect(Collectors.toList());

    GoogleCredentials credentials;
    if (configuration.getLocation().isPresent() && configuration.getEncodedKey().isPresent()) {
        throw new ConfigurationException("Please specify only one of gcp.credentials.location or gcp.credentials.encodedKey");
    } else if (configuration.getLocation().isPresent()) {
        LOG.info("Google Credentials from gcp.credentials.location = " + configuration.getLocation());
        FileInputStream fis = new FileInputStream(configuration.getLocation().get());
        credentials = GoogleCredentials.fromStream(fis);
        fis.close();
    } else if (configuration.getEncodedKey().isPresent()) {
        LOG.info("Google Credentials from gcp.credentials.encodedKey");
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(configuration.getEncodedKey().get());
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        credentials = GoogleCredentials.fromStream(is);
        is.close();
    } else {
        LOG.info("Google Credentials from Application Default Credentials");
        credentials = GoogleCredentials.getApplicationDefault();
    }

    return credentials.createScoped(scopes);
}
 
Example #12
Source File: CalculatedSettings.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the driver class name based on the configured value. If not
 * configured, determine the driver class name based on the URL. If the
 * URL is not configured, look for an embedded database driver on the
 * classpath.
 *
 * @return The calculated driver class name
 */
public String getDriverClassName() {
    final String driverClassName = basicJdbcConfiguration.getConfiguredDriverClassName();
    if (calculatedDriverClassName == null || StringUtils.hasText(driverClassName)) {
        if (StringUtils.hasText(driverClassName)) {
            if (!driverClassIsPresent(driverClassName)) {
                throw new ConfigurationException(String.format("Error configuring data source '%s'. The driver class '%s' was not found on the classpath", basicJdbcConfiguration.getName(), driverClassName));
            }
            calculatedDriverClassName = driverClassName;
        } else {
            final String url = basicJdbcConfiguration.getUrl();
            if (StringUtils.hasText(url)) {
                JdbcDatabaseManager.findDatabase(url).ifPresent(db ->
                    calculatedDriverClassName = db.getDriverClassName());
            }

            if (!StringUtils.hasText(calculatedDriverClassName) && embeddedDatabaseConnection.isPresent()) {
                calculatedDriverClassName = this.embeddedDatabaseConnection.get().getDriverClassName();
            }

            if (!StringUtils.hasText(calculatedDriverClassName)) {
                throw new ConfigurationException(String.format("Error configuring data source '%s'. No driver class name specified", basicJdbcConfiguration.getName()));
            }
        }
    }

    return calculatedDriverClassName;
}
 
Example #13
Source File: AbstractMicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws ConfigurationException if the handler is not of type RequestHandler or RequestStreamHandler
 */
protected void validateHandler() throws ConfigurationException {
    if (handler == null) {
        throw new ConfigurationException("no handler instantiated. Override either createHandler() or createRequestStreamHandler() or annotate your Handler class with @Introspected");
    }
    if (!(handler instanceof RequestHandler || handler instanceof RequestStreamHandler)) {
        throw new ConfigurationException("handler must be of type com.amazonaws.services.lambda.runtime.RequestHandler or com.amazonaws.services.lambda.runtime.RequestStreamHandler");
    }
}
 
Example #14
Source File: MicronautLambdaRuntime.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestHandler<AwsProxyRequest, AwsProxyResponse> createRequestHandler(String... args) {
    try {
        return new MicronautLambdaHandler(createApplicationContextBuilderWithArgs(args));
    } catch (ContainerInitializationException e) {
        throw new ConfigurationException("Exception thrown instantiating MicronautLambdaRuntimeHandler");
    }
}
 
Example #15
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends GetParametersByPathResult> onGetParametersByPathResult(Throwable throwable) {
    if (throwable instanceof SdkClientException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example #16
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends GetParametersResult> onGetParametersError(Throwable throwable) {
    if (throwable instanceof SdkClientException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example #17
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends PropertySource> onPropertySourceError(Throwable throwable) {
    if (throwable instanceof ConfigurationException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example #18
Source File: GoogleCloudConfiguration.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Whether a project id is configured.
 * @return True if one is
 */
public boolean hasProjectId() {
    try {
        getProjectId();
        return true;
    } catch (ConfigurationException e) {
        return false;
    }
}
 
Example #19
Source File: GoogleCloudConfiguration.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Google project ID for the project.
 *
 * @return The project id
 * @throws ConfigurationException if no project ID is found
 */
public @Nonnull String getProjectId() {
    if (projectId == null) {
        projectId = ServiceOptions.getDefaultProjectId();
        if (projectId == null) {
            throw new ConfigurationException(NO_PROJECT_ID_MESSAGE);
        }
    }
    return projectId;
}