org.eclipse.microprofile.config.ConfigProvider Java Examples

The following examples show how to use org.eclipse.microprofile.config.ConfigProvider. 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: 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 #2
Source File: SmallRyeOpenApiProcessor.java    From quarkus with 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 #3
Source File: CamelConnector.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: TestHTTPResourceManager.java    From quarkus with 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
Source File: ConfigGenerationBuildStep.java    From quarkus with 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 #6
Source File: FaultToleranceOperation.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: AmqpSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: RunningQuarkusApplicationImpl.java    From quarkus with 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 #9
Source File: QuarkusConfig.java    From quarkus with 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 #10
Source File: SmallRyeOpenApiProcessor.java    From quarkus with 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 #11
Source File: KafkaRuntimeConfigProducer.java    From quarkus with 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 #12
Source File: ConfigRecorder.java    From quarkus with 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 #13
Source File: CommonConfigurationClassWriter.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: ClientResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual/complex")
@Produces("application/json")
public List<ComponentType> complexManual() throws Exception {
    ProgrammaticRestInterface iface = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    System.out.println(iface.complex());
    return iface.complex();
}
 
Example #15
Source File: ClientResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual/headers")
@Produces("application/json")
public Map<String, String> getAllHeaders(String headerValue) throws Exception {
    ProgrammaticRestInterface client = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    return client.getAllHeaders();
}
 
Example #16
Source File: KubernetesConfigUtil.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static List<String> getUserSpecifiedDeploymentTargets() {
    Config config = ConfigProvider.getConfig();
    String configValue = config.getOptionalValue(DEPLOYMENT_TARGET, String.class)
            .orElse(config.getOptionalValue(OLD_DEPLOYMENT_TARGET, String.class).orElse(""));
    if (configValue.isEmpty()) {
        return Collections.emptyList();
    }
    return Arrays.stream(configValue
            .split(","))
            .map(String::trim)
            .map(String::toLowerCase)
            .collect(Collectors.toList());
}
 
Example #17
Source File: QuarkusConfig.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static boolean getBoolean(String configKey, String defaultValue) {
    Optional<String> res = ConfigProvider.getConfig().getOptionalValue(configKey, String.class);
    String val = res.orElse(defaultValue);
    if (val == null || val.isEmpty()) {
        return false;
    }
    return asBoolean(val, configKey);
}
 
Example #18
Source File: QuarkusConfig.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static Set<String> getNames(String prefix) {
    Set<String> props = new HashSet<>();
    for (String i : ConfigProvider.getConfig().getPropertyNames()) {
        if (i.startsWith(prefix)) {
            int index = i.indexOf('.', prefix.length() + 1);
            if (index == -1) {
                props.add(i.substring(prefix.length() + 1));
            } else {
                props.add(i.substring(prefix.length() + 1, index));
            }
        }
    }
    return props;
}
 
Example #19
Source File: ChannelNameConflictTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #20
Source File: ReactiveMongoOperations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static String getDefaultDatabaseName() {
    if (defaultDatabaseName == null) {
        synchronized (MongoOperations.class) {
            if (defaultDatabaseName == null) {
                defaultDatabaseName = ConfigProvider.getConfig()
                        .getValue(MONGODB_DATABASE, String.class);
            }
        }
    }
    return defaultDatabaseName;
}
 
Example #21
Source File: ClientResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual")
public String manual() throws Exception {
    ProgrammaticRestInterface iface = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    return iface.get();
}
 
Example #22
Source File: JmsTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void initializeWeld() {
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
    if (withConnectionFactory()) {
        initWeldWithConnectionFactory();
    } else {
        initWithoutConnectionFactory();
    }
}
 
Example #23
Source File: KafkaFailureHandlerTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #24
Source File: KafkaSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #25
Source File: MissingBackPressureTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void stop() {
    if (container != null) {
        container.shutdown();
    }
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #26
Source File: NoKafkaTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
    if (container != null) {
        container.shutdown();
    }
    KafkaTestBase.stopKafkaBroker();
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #27
Source File: KafkaSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #28
Source File: DefaultConfigTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #29
Source File: MetadataPropagationTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    if (container != null) {
        container.close();
    }
    // Release the config objects
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
}
 
Example #30
Source File: SmallRyeGraphQLProcessor.java    From quarkus with 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));
}