Java Code Examples for org.eclipse.microprofile.config.Config#getOptionalValue()

The following examples show how to use org.eclipse.microprofile.config.Config#getOptionalValue() . 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: HotDeploymentProcessor.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@BuildStep
List<HotDeploymentWatchedFileBuildItem> routes() {
    final Config config = ConfigProvider.getConfig();
    final Optional<String> value = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_ROUTES, String.class);

    List<HotDeploymentWatchedFileBuildItem> items = new ArrayList<>();

    if (value.isPresent()) {
        for (String source : value.get().split(",", -1)) {
            String path = StringHelper.after(source, ":");
            if (path == null) {
                path = source;
            }

            Path p = Paths.get(path);
            if (Files.exists(p)) {
                LOGGER.info("Register source for hot deployment: {}", p.toAbsolutePath());
                items.add(new HotDeploymentWatchedFileBuildItem(p.toAbsolutePath().toString()));
            }
        }
    }

    return items;
}
 
Example 2
Source File: GenericConfig.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * Note that:
 *
 * <pre>
 * If no annotation matches the specified parameter, the property will be ignored.
 * </pre>
 *
 * @param key
 * @param expectedType
 * @return the configured value
 */
private <U> U lookup(String key, Class<U> expectedType) {
    Config config = getConfig();
    Optional<U> value;
    if (ElementType.METHOD.equals(annotationSource)) {
        // <classname>/<methodname>/<annotation>/<parameter>
        value = config.getOptionalValue(getConfigKeyForMethod() + key, expectedType);
    } else {
        // <classname>/<annotation>/<parameter>
        value = config.getOptionalValue(getConfigKeyForClass() + key, expectedType);
    }
    if (!value.isPresent()) {
        // <annotation>/<parameter>
        value = config.getOptionalValue(annotationType.getSimpleName() + "/" + key, expectedType);
    }
    // annotation values
    return value.orElseGet(() -> getConfigFromAnnotation(key));
}
 
Example 3
Source File: ConnectorConfig.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
protected ConnectorConfig(String prefix, Config overall, String channel) {
    this.prefix = Objects.requireNonNull(prefix, msg.prefixMustNotBeSet());
    this.overall = Objects.requireNonNull(overall, msg.configMustNotBeSet());
    this.name = Objects.requireNonNull(channel, msg.channelMustNotBeSet());

    Optional<String> value = overall.getOptionalValue(channelKey(CONNECTOR_ATTRIBUTE), String.class);
    this.connector = value
            .orElseGet(() -> overall.getOptionalValue(channelKey("type"), String.class) // Legacy
                    .orElseThrow(() -> ex.illegalArgumentChannelConnectorConfiguration(name)));

    // Detect invalid channel-name attribute
    for (String key : overall.getPropertyNames()) {
        if ((channelKey(CHANNEL_NAME_ATTRIBUTE)).equalsIgnoreCase(key)) {
            throw ex.illegalArgumentInvalidChannelConfiguration(name);
        }
    }
}
 
Example 4
Source File: QuarkusSmallRyeTracingDynamicFeature.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public QuarkusSmallRyeTracingDynamicFeature() {
    Config config = ConfigProvider.getConfig();
    Optional<String> skipPattern = config.getOptionalValue("mp.opentracing.server.skip-pattern", String.class);
    Optional<String> operationNameProvider = config.getOptionalValue("mp.opentracing.server.operation-name-provider",
            String.class);

    ServerTracingDynamicFeature.Builder builder = new ServerTracingDynamicFeature.Builder(
            CDI.current().select(Tracer.class).get())
                    .withOperationNameProvider(OperationNameProvider.ClassNameOperationName.newBuilder())
                    .withTraceSerialization(false);
    if (skipPattern.isPresent()) {
        builder.withSkipPattern(skipPattern.get());
    }
    if (operationNameProvider.isPresent()) {
        if ("http-path".equalsIgnoreCase(operationNameProvider.get())) {
            builder.withOperationNameProvider(OperationNameProvider.WildcardOperationName.newBuilder());
        } else if (!"class-method".equalsIgnoreCase(operationNameProvider.get())) {
            logger.warn("Provided operation name does not match http-path or class-method. Using default class-method.");
        }
    }
    this.delegate = builder.build();
}
 
Example 5
Source File: ConfigGenerationBuildStep.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void handleMembers(Config config, Map<String, String> values, Iterable<ClassDefinition.ClassMember> members,
        String prefix) {
    for (ClassDefinition.ClassMember member : members) {
        if (member instanceof ClassDefinition.ItemMember) {
            ClassDefinition.ItemMember itemMember = (ClassDefinition.ItemMember) member;
            String propertyName = prefix + member.getPropertyName();
            Optional<String> val = config.getOptionalValue(propertyName, String.class);
            if (val.isPresent()) {
                values.put(propertyName, val.get());
            } else {
                values.put(propertyName, itemMember.getDefaultValue());
            }
        } else if (member instanceof ClassDefinition.GroupMember) {
            handleMembers(config, values, ((ClassDefinition.GroupMember) member).getGroupDefinition().getMembers(),
                    prefix + member.getDescriptor().getName() + ".");
        }
    }
}
 
Example 6
Source File: Configuration.java    From microprofile-sandbox with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to get a configuration from MicoProfile Config.
 * 
 * @param configItem The Configuration Item to retrieve.
 * 
 * @return The configuration value (or its default).
 */
public static Level get(Configuration.Item configItem) {
  Level returnLevel = configItem.getDefault();
  Optional<String> configValue = null;
  try {
    Config config = ConfigProvider.getConfig();
    configValue = config.getOptionalValue(configItem.getKey(), String.class);
  } catch (Throwable t) {
    // Do nothing as MP Config is an optional component.
  }

  if (configValue != null && configValue.isPresent()) {
    try {
      returnLevel = Level.parse(configValue.get());
    } catch (IllegalArgumentException iae) {
      // Unable to find level with configured name
    }
  }
  
  return returnLevel;
}
 
Example 7
Source File: MetricID.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a MetricID with the given metric name and {@link Tag}s.
 * If global tags are available then they will be appended to this MetricID
 *
 * @param name the name of the metric
 * @param tags the tags associated with this metric
 */
public MetricID(String name, Tag... tags) {
    this.name = name;
    try {
        Config config = ConfigProvider.getConfig();
        Optional<String> globalTags = config.getOptionalValue(GLOBAL_TAGS_VARIABLE, String.class);
        globalTags.ifPresent(this::parseGlobalTags);

        // for application servers with multiple applications deployed, distinguish metrics from different applications by adding the "_app" tag
        Optional<String> applicationName = config.getOptionalValue(APPLICATION_NAME_VARIABLE, String.class);
        applicationName.ifPresent(appName -> {
            if (!appName.isEmpty()) {
                addTag(new Tag(APPLICATION_NAME_TAG, appName));
            }
        });
    }
    catch(NoClassDefFoundError | IllegalStateException | ExceptionInInitializerError e) {
        // MP Config is probably not available, so just go on
    }

    addTags(tags);
}
 
Example 8
Source File: ConfigInjectionBean.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Override
public T create(CreationalContext<T> context) {
    InjectionPoint ip = (InjectionPoint) bm.getInjectableReference(new InjectionPointMetadataInjectionPoint(), context);
    Annotated annotated = ip.getAnnotated();
    ConfigProperty configProperty = annotated.getAnnotation(ConfigProperty.class);
    String key = ConfigProducerUtil.getConfigKey(ip, configProperty);
    String defaultValue = configProperty.defaultValue();

    if (annotated.getBaseType() instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) annotated.getBaseType();
        Type rawType = paramType.getRawType();

        // handle Provider<T> and Instance<T>
        if (rawType instanceof Class
                && (((Class<?>) rawType).isAssignableFrom(Provider.class)
                        || ((Class<?>) rawType).isAssignableFrom(Instance.class))
                && paramType.getActualTypeArguments().length == 1) {
            Class<?> paramTypeClass = (Class<?>) paramType.getActualTypeArguments()[0];
            return (T) getConfig().getValue(key, paramTypeClass);
        }
    } else {
        Class annotatedTypeClass = (Class) annotated.getBaseType();
        if (defaultValue == null || defaultValue.length() == 0) {
            return (T) getConfig().getValue(key, annotatedTypeClass);
        } else {
            Config config = getConfig();
            Optional<T> optionalValue = config.getOptionalValue(key, annotatedTypeClass);
            if (optionalValue.isPresent()) {
                return optionalValue.get();
            } else {
                return (T) ((SmallRyeConfig) config).convert(defaultValue, annotatedTypeClass);
            }
        }
    }

    throw InjectionMessages.msg.unhandledConfigProperty();
}
 
Example 9
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
public OpenMetricsExporter() {
    try {
        Config config = ConfigProvider.getConfig();
        Optional<Boolean> tmp = config.getOptionalValue(MICROPROFILE_METRICS_OMIT_HELP_LINE, Boolean.class);
        usePrefixForScope = config.getOptionalValue(SMALLRYE_METRICS_USE_PREFIX_FOR_SCOPE, Boolean.class).orElse(true);
        writeHelpLine = !tmp.isPresent() || !tmp.get();
    } catch (IllegalStateException | ExceptionInInitializerError | NoClassDefFoundError t) {
        // MP Config implementation is probably not available. Resort to default configuration.
        usePrefixForScope = true;
        writeHelpLine = true;
    }

}
 
Example 10
Source File: ConfigBeanCreator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Object create(CreationalContext<Object> creationalContext, Map<String, Object> params) {
    String requiredType = params.get("requiredType").toString();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = ConfigBeanCreator.class.getClassLoader();
    }
    Class<?> clazz;
    try {
        clazz = Class.forName(requiredType, true, cl);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Cannot load required type: " + requiredType);
    }

    InjectionPoint injectionPoint = InjectionPointProvider.get();
    if (injectionPoint == null) {
        throw new IllegalStateException("No current injection point found");
    }

    ConfigProperty configProperty = getConfigProperty(injectionPoint);
    if (configProperty == null) {
        throw new IllegalStateException("@ConfigProperty not found");
    }

    String key = configProperty.name();
    String defaultValue = configProperty.defaultValue();

    if (defaultValue.isEmpty() || ConfigProperty.UNCONFIGURED_VALUE.equals(defaultValue)) {
        return getConfig().getValue(key, clazz);
    } else {
        Config config = getConfig();
        Optional<?> value = config.getOptionalValue(key, clazz);
        if (value.isPresent()) {
            return value.get();
        } else {
            return ((SmallRyeConfig) config).convert(defaultValue, clazz);
        }
    }
}
 
Example 11
Source File: SmallRyeJwtProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * If the configuration specified a deployment local key resource, register it in native mode
 *
 * @return NativeImageResourceBuildItem
 */
@BuildStep
NativeImageResourceBuildItem registerNativeImageResources() {
    final Config config = ConfigProvider.getConfig();
    Optional<String> publicKeyLocationOpt = config.getOptionalValue("mp.jwt.verify.publickey.location", String.class);
    if (publicKeyLocationOpt.isPresent()) {
        final String publicKeyLocation = publicKeyLocationOpt.get();
        if (publicKeyLocation.indexOf(':') < 0 || publicKeyLocation.startsWith("classpath:")) {
            log.infof("Adding %s to native image", publicKeyLocation);
            return new NativeImageResourceBuildItem(publicKeyLocation);
        }
    }
    return null;
}
 
Example 12
Source File: KafkaStreamsPropertiesUtil.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void includeKafkaStreamsProperty(Config config, Properties kafkaStreamsProperties, String prefix,
        String property) {
    Optional<String> value = config.getOptionalValue(property, String.class);
    if (value.isPresent()) {
        kafkaStreamsProperties.setProperty(property.substring(prefix.length()), value.get());
    }
}
 
Example 13
Source File: ConfigChangeRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void handleConfigChange(Map<String, String> buildTimeConfig) {
    Config configProvider = ConfigProvider.getConfig();
    for (Map.Entry<String, String> entry : buildTimeConfig.entrySet()) {
        Optional<String> val = configProvider.getOptionalValue(entry.getKey(), String.class);
        if (val.isPresent()) {
            if (!val.get().equals(entry.getValue())) {
                log.warn("Build time property cannot be changed at runtime. " + entry.getKey() + " was "
                        + entry.getValue() + " at build time and is now " + val.get());
            }
        }
    }
}
 
Example 14
Source File: RestClientBase.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private <T> Optional<T> getOptionalProperty(String propertyFormat, Class<T> type) {
    final Config config = ConfigProvider.getConfig();
    Optional<T> interfaceNameValue = config.getOptionalValue(String.format(propertyFormat, proxyType.getName()), type);
    return interfaceNameValue.isPresent() ? interfaceNameValue
            : config.getOptionalValue(String.format(propertyFormat, propertyPrefix), type);
}