Java Code Examples for org.eclipse.microprofile.config.ConfigProvider

The following examples show how to use org.eclipse.microprofile.config.ConfigProvider. These examples are extracted from open source projects. 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 Project: quarkus   Source File: QuarkusConfig.java    License: Apache License 2.0 6 votes vote down vote up
public static Integer getBoxedInt(String configKey, String defaultValue, boolean allowNull) {
    Optional<String> res = ConfigProvider.getConfig().getOptionalValue(configKey, String.class);
    String val = res.orElse(defaultValue);
    Integer result;
    if (val == null || val.isEmpty()) {
        if (!allowNull) {
            throw requiredConfigMissing(configKey);
        }
        return null;
    } else {
        result = asInteger(val, configKey);
    }
    //this is deliberate, we need to make sure the returned value
    //has a unique identity, so if it is passed into the bytecode recorder
    //we know that it is a configured value
    result = new Integer(result);
    reverseMap.put(result, configKey);
    return result;
}
 
Example 2
private static <A extends Annotation> Boolean getConfigStatus(Class<A> annotationType, Method method) {
    Config config = ConfigProvider.getConfig();
    final String undifined = "undifined";
    String onMethod = config.getOptionalValue(method.getDeclaringClass().getName() +
            "/" + method.getName() + "/" + annotationType.getSimpleName() + "/enabled", String.class).orElse(undifined);
    String onClass = config.getOptionalValue(method.getDeclaringClass().getName() +
            "/" + annotationType.getSimpleName() + "/enabled", String.class).orElse(undifined);
    String onGlobal = config.getOptionalValue(annotationType.getSimpleName() + "/enabled", String.class).orElse(undifined);
    Boolean returnConfig = !annotationType.equals(Fallback.class)
            ? config.getOptionalValue("MP_Fault_Tolerance_NonFallback_Enabled", Boolean.class).orElse(true)
            : true;

    if (!undifined.equals(onMethod)) {
        returnConfig = new Boolean(onMethod);
    } else if (!undifined.equals(onClass)) {
        returnConfig = new Boolean(onClass);
    } else if (!undifined.equals(onGlobal)) {
        returnConfig = new Boolean(onGlobal);
    }
    return returnConfig;
}
 
Example 3
Source Project: quarkus   Source File: ConfigGenerationBuildStep.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Warns if build time config properties have been changed at runtime.
 */
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
public void checkForBuildTimeConfigChange(
        ConfigChangeRecorder recorder, ConfigurationBuildItem configItem, LoggingSetupBuildItem loggingSetupBuildItem) {
    BuildTimeConfigurationReader.ReadResult readResult = configItem.getReadResult();
    Config config = ConfigProvider.getConfig();

    Map<String, String> values = new HashMap<>();
    for (RootDefinition root : readResult.getAllRoots()) {
        if (root.getConfigPhase() == ConfigPhase.BUILD_AND_RUN_TIME_FIXED ||
                root.getConfigPhase() == ConfigPhase.BUILD_TIME) {

            Iterable<ClassDefinition.ClassMember> members = root.getMembers();
            handleMembers(config, values, members, "quarkus." + root.getRootName() + ".");
        }
    }
    values.remove("quarkus.profile");
    recorder.handleConfigChange(values);
}
 
Example 4
Source Project: quarkus   Source File: TestHTTPResourceManager.java    License: Apache License 2.0 6 votes vote down vote up
public static String getUri() {
    try {
        Config config = ConfigProvider.getConfig();
        String value = config.getValue("test.url", String.class);
        if (value.equals(TestHTTPConfigSourceProvider.TEST_URL_VALUE)) {
            //massive hack for dev mode tests, dev mode has not started yet
            //so we don't have any way to load this correctly from config
            return "http://" + config.getOptionalValue("quarkus.http.host", String.class).orElse("localhost") + ":"
                    + config.getOptionalValue("quarkus.http.port", String.class).orElse("8080");
        }
        return value;
    } catch (IllegalStateException e) {
        //massive hack for dev mode tests, dev mode has not started yet
        //so we don't have any way to load this correctly from config
        return "http://localhost:8080";
    }
}
 
Example 5
@PostConstruct
@Inject
public void init() {
    DefaultCamelReactiveStreamsServiceFactory factory = new DefaultCamelReactiveStreamsServiceFactory();
    ReactiveStreamsEngineConfiguration configuration = new ReactiveStreamsEngineConfiguration();

    Config config = ConfigProvider.getConfig();
    config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-max-size",
            Integer.class).ifPresent(configuration::setThreadPoolMaxSize);
    config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-min-size",
            Integer.class).ifPresent(configuration::setThreadPoolMinSize);
    config.getOptionalValue("camel.component.reactive-streams.internal-engine-configuration.thread-pool-name",
            String.class).ifPresent(configuration::setThreadPoolName);

    this.reactive = factory.newInstance(camel, configuration);
}
 
Example 6
@After
public void cleanup() {
    if (provider != null) {
        provider.terminate(null);
    }

    if (container != null) {
        container.shutdown();
    }

    MapBasedConfig.clear();
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());

    System.clearProperty("mp-config");
    System.clearProperty("client-options-name");
    System.clearProperty("amqp-client-options-name");
}
 
Example 7
Source Project: quarkus   Source File: RunningQuarkusApplicationImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<String> getConfigKeys() {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        Class<?> configProviderClass = classLoader.loadClass(ConfigProvider.class.getName());
        Method getConfig = configProviderClass.getMethod("getConfig", ClassLoader.class);
        Thread.currentThread().setContextClassLoader(classLoader);
        Object config = getConfig.invoke(null, classLoader);
        return (Iterable<String>) getConfig.getReturnType().getMethod("getPropertyNames")
                .invoke(config);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
 
Example 8
private void generate(List<ConnectorAttribute> attributes, String packageName,
        String className, String simpleName, String connector) throws IOException {
    JavaFileObject file = environment.getFiler().createSourceFile(className);
    file.delete();
    try (PrintWriter out = new PrintWriter(file.openWriter())) {
        writePackageDeclaration(packageName, out);

        writeImportStatements(out);
        out.println("import " + ConfigProvider.class.getName() + ";");
        out.println("import " + ConnectorFactory.class.getName() + ";");

        writeClassDeclaration(simpleName, connector, out);
        writeConstructorAndConfigAccessor(simpleName, out);
        attributes.forEach(ca -> generateGetterForAttribute(ca, connector, out));
        writeValidateMethod(attributes, out);

        out.println("}"); // End of class.
    }
}
 
Example 9
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
public OpenApiDocument loadDocument(OpenAPI staticModel, OpenAPI annotationModel) {
    Config config = ConfigProvider.getConfig();
    OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);

    OpenAPI readerModel = OpenApiProcessor.modelFromReader(openApiConfig,
            Thread.currentThread().getContextClassLoader());

    OpenApiDocument document = createDocument(openApiConfig);
    if (annotationModel != null) {
        document.modelFromAnnotations(annotationModel);
    }
    document.modelFromReader(readerModel);
    document.modelFromStaticFile(staticModel);
    document.filter(filter(openApiConfig));
    document.initialize();
    return document;
}
 
Example 10
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 11
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private OpenAPI generateAnnotationModel(IndexView indexView, Capabilities capabilities) {
    Config config = ConfigProvider.getConfig();
    OpenApiConfig openApiConfig = new OpenApiConfigImpl(config);

    String defaultPath = config.getValue("quarkus.http.root-path", String.class);

    List<AnnotationScannerExtension> extensions = new ArrayList<>();
    // Add RestEasy if jaxrs
    if (capabilities.isCapabilityPresent(Capabilities.RESTEASY)) {
        extensions.add(new RESTEasyExtension(indexView));
    }
    // Add path if not null
    if (defaultPath != null) {
        extensions.add(new CustomPathExtension(defaultPath));
    }
    return new OpenApiAnnotationScanner(openApiConfig, indexView, extensions).scan();
}
 
Example 12
Source Project: quarkus   Source File: KafkaRuntimeConfigProducer.java    License: Apache License 2.0 6 votes vote down vote up
@Produces
@DefaultBean
@ApplicationScoped
@Named("default-kafka-broker")
public Map<String, Object> createKafkaRuntimeConfig() {
    Map<String, Object> properties = new HashMap<>();
    final Config config = ConfigProvider.getConfig();

    StreamSupport
            .stream(config.getPropertyNames().spliterator(), false)
            .map(String::toLowerCase)
            .filter(name -> name.startsWith(configPrefix))
            .distinct()
            .sorted()
            .forEach(name -> {
                final String key = name.substring(configPrefix.length() + 1).toLowerCase().replaceAll("[^a-z0-9.]", ".");
                final String value = config.getOptionalValue(name, String.class).orElse("");
                properties.put(key, value);
            });

    return properties;
}
 
Example 13
Source Project: quarkus   Source File: ConfigRecorder.java    License: Apache License 2.0 6 votes vote down vote up
public void validateConfigProperties(Map<String, Set<String>> properties) {
    Config config = ConfigProvider.getConfig();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = ConfigRecorder.class.getClassLoader();
    }
    for (Entry<String, Set<String>> entry : properties.entrySet()) {
        Set<String> propertyTypes = entry.getValue();
        for (String propertyType : propertyTypes) {
            Class<?> propertyClass = load(propertyType, cl);
            // For parameterized types and arrays, we only check if the property config exists without trying to convert it
            if (propertyClass.isArray() || propertyClass.getTypeParameters().length > 0) {
                propertyClass = String.class;
            }
            try {
                if (!config.getOptionalValue(entry.getKey(), propertyClass).isPresent()) {
                    throw new DeploymentException(
                            "No config value of type " + entry.getValue() + " exists for: " + entry.getKey());
                }
            } catch (IllegalArgumentException e) {
                throw new DeploymentException(e);
            }
        }
    }
}
 
Example 14
Source Project: quarkus   Source File: ApplicationYamlTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void doBefore() {
    SmallRyeConfigBuilder builder = new SmallRyeConfigBuilder();
    builder.addDefaultSources().addDiscoveredConverters().addDiscoveredSources();
    QuarkusConfigFactory.setConfig(config = builder.build());
    Config conf = ConfigProvider.getConfig();
    if (conf != config) {
        ConfigProviderResolver cpr = ConfigProviderResolver.instance();
        cpr.releaseConfig(conf);
        ConfigProvider.getConfig();
    }
    System.out.println(System.getProperty("user.dir"));
}
 
Example 15
Source Project: quarkus   Source File: SmallRyeGraphQLProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Record(ExecutionTime.STATIC_INIT)
@BuildStep
void buildEndpoints(
        BuildProducer<RouteBuildItem> routeProducer,
        BuildProducer<NotFoundPageDisplayableEndpointBuildItem> notFoundPageDisplayableEndpointProducer,
        LaunchModeBuildItem launchMode,
        SmallRyeGraphQLRecorder recorder,
        ShutdownContextBuildItem shutdownContext,
        BeanContainerBuildItem beanContainerBuildItem // don't remove this - makes sure beanContainer is initialized
) {

    /*
     * <em>Ugly Hack</em>
     * In dev mode, we pass a classloader to use in the CDI Loader.
     * This hack is required because using the TCCL would get an outdated version - the initial one.
     * This is because the worker thread on which the handler is called captures the TCCL at creation time
     * and does not allow updating it.
     *
     * In non dev mode, the TCCL is used.
     */
    if (launchMode.getLaunchMode() == LaunchMode.DEVELOPMENT) {
        recorder.setupClDevMode(shutdownContext);
    }
    // add graphql endpoint for not found display in dev or test mode
    if (launchMode.getLaunchMode().isDevOrTest()) {
        notFoundPageDisplayableEndpointProducer
                .produce(new NotFoundPageDisplayableEndpointBuildItem(quarkusConfig.rootPath));
        notFoundPageDisplayableEndpointProducer
                .produce(new NotFoundPageDisplayableEndpointBuildItem(quarkusConfig.rootPath + SCHEMA_PATH));
    }

    Boolean allowGet = ConfigProvider.getConfig().getOptionalValue(ConfigKey.ALLOW_GET, boolean.class).orElse(false);

    Handler<RoutingContext> executionHandler = recorder.executionHandler(allowGet);
    routeProducer.produce(new RouteBuildItem(quarkusConfig.rootPath, executionHandler, HandlerType.BLOCKING));

    Handler<RoutingContext> schemaHandler = recorder.schemaHandler();
    routeProducer.produce(
            new RouteBuildItem(quarkusConfig.rootPath + SCHEMA_PATH, schemaHandler, HandlerType.BLOCKING));
}
 
Example 16
@Path("/lookup")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getLookupConfigValue() {
    Config config = ConfigProvider.getConfig();
    String value = config.getValue("lookup.value", String.class);
    return String.format("Config value via API lookup: '%s'", value);
}
 
Example 17
default String lookupUserAgent() {
    Config config = ConfigProvider.getConfig();
    String userAgent = config.getValue("WorldClockApi.userAgent", String.class);
    if(userAgent == null) {
        userAgent = "MicroProfile Rest Client 1.2";
    }
    return userAgent;
}
 
Example 18
Source Project: smallrye-jwt   Source File: JwtSignatureImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean signingKeyConfigured() {
    try {
        ConfigProvider.getConfig().getValue("smallrye.jwt.sign.key-location", String.class);
        return true;
    } catch (NoSuchElementException ex) {
        return false;
    }
}
 
Example 19
Source Project: smallrye-jwt   Source File: JwtSignTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JwtBuildConfigSource getConfigSource() {
    for (ConfigSource cs : ConfigProvider.getConfig().getConfigSources()) {
        if (cs instanceof JwtBuildConfigSource) {
            return (JwtBuildConfigSource) cs;
        }
    }
    return null;
}
 
Example 20
Source Project: smallrye-jwt   Source File: JwtSignEncryptTest.java    License: Apache License 2.0 5 votes vote down vote up
private static JwtBuildConfigSource getConfigSource() {
    for (ConfigSource cs : ConfigProvider.getConfig().getConfigSources()) {
        if (cs instanceof JwtBuildConfigSource) {
            return (JwtBuildConfigSource) cs;
        }
    }
    return null;
}
 
Example 21
void changeInterceptorPriority(@Observes ProcessAnnotatedType<FaultToleranceInterceptor> event) {
    ConfigProvider.getConfig()
            .getOptionalValue("mp.fault.tolerance.interceptor.priority", Integer.class)
            .ifPresent(configuredInterceptorPriority -> {
                event.configureAnnotatedType()
                        .remove(ann -> ann instanceof Priority)
                        .add(new PriorityLiteral(configuredInterceptorPriority));
            });
}
 
Example 22
Source Project: quarkus   Source File: SmallRyeOpenApiProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@BuildStep
OpenApiFilteredIndexViewBuildItem smallryeOpenApiIndex(CombinedIndexBuildItem combinedIndexBuildItem,
        BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) {
    CompositeIndex compositeIndex = CompositeIndex.create(combinedIndexBuildItem.getIndex(),
            beanArchiveIndexBuildItem.getIndex());
    return new OpenApiFilteredIndexViewBuildItem(
            new FilteredIndexView(
                    compositeIndex,
                    new OpenApiConfigImpl(ConfigProvider.getConfig())));
}
 
Example 23
Source Project: quarkus   Source File: SmallRyeFaultToleranceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem transformInterceptorPriority(BeanArchiveIndexBuildItem index) {
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
        @Override
        public boolean appliesTo(Kind kind) {
            return kind == Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext ctx) {
            if (ctx.isClass()) {
                if (!ctx.getTarget().asClass().name().toString()
                        .equals("io.smallrye.faulttolerance.FaultToleranceInterceptor")) {
                    return;
                }
                final Config config = ConfigProvider.getConfig();

                OptionalInt priority = config.getValue("mp.fault.tolerance.interceptor.priority", OptionalInt.class);
                if (priority.isPresent()) {
                    ctx.transform()
                            .remove(ann -> ann.name().toString().equals(Priority.class.getName()))
                            .add(Priority.class, AnnotationValue.createIntegerValue("value", priority.getAsInt()))
                            .done();
                }
            }
        }
    });
}
 
Example 24
Source Project: smallrye-reactive-messaging   Source File: AmqpLinkTest.java    License: Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.shutdown();
    }

    MapBasedConfig.clear();
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example 25
Source Project: quarkus   Source File: QuarkusConfig.java    License: Apache License 2.0 5 votes vote down vote up
public static String getString(String configKey, String defaultValue, boolean allowNull) {
    String opt = ConfigProvider.getConfig().getOptionalValue(configKey, String.class).orElse(defaultValue);
    if (opt == null) {
        if (!allowNull) {
            throw requiredConfigMissing(configKey);
        }
        return null;
    }
    //this is deliberate, we need to make sure the returned value
    //has a unique identity, so if it is passed into the bytecode recorder
    //we know that it is a configured value
    String retVal = new String(opt);
    reverseMap.put(retVal, configKey);
    return retVal;
}
 
Example 26
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example 27
Source Project: smallrye-reactive-messaging   Source File: AmqpTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    executionHolder = new ExecutionHolder(Vertx.vertx());
    host = artemis.getContainerIpAddress();
    port = artemis.getMappedPort(5672);
    System.setProperty("amqp-host", host);
    System.setProperty("amqp-port", Integer.toString(port));
    System.setProperty("amqp-user", username);
    System.setProperty("amqp-pwd", password);
    usage = new AmqpUsage(executionHolder.vertx(), host, port);
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
    MapBasedConfig.clear();
}
 
Example 28
Source Project: smallrye-reactive-messaging   Source File: AmqpTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
    System.clearProperty("amqp-host");
    System.clearProperty("amqp-port");

    usage.close();
    executionHolder.terminate(null);
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
    MapBasedConfig.clear();
}
 
Example 29
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example 30
Source Project: quarkus   Source File: QuarkusConfig.java    License: Apache License 2.0 5 votes vote down vote up
public static int getInt(String configKey, String defaultValue) {
    Optional<String> res = ConfigProvider.getConfig().getOptionalValue(configKey, String.class);
    String val = res.orElse(defaultValue);
    if (val == null || val.isEmpty()) {
        return 0;
    }
    return asInteger(val, configKey);
}