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

The following examples show how to use org.eclipse.microprofile.config.Config#getValue() . 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: 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 2
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 3
Source File: DummyConnector.java    From microprofile-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    configs.add(config);
    String[] values = config.getValue("items", String.class).split(",");

    // Check mandatory attributes
    assertThat(config.getValue(CHANNEL_NAME_ATTRIBUTE, String.class)).isNotBlank();
    assertThat(config.getValue(CONNECTOR_ATTRIBUTE, String.class)).isEqualTo("Dummy");

    // Would throw a NoSuchElementException if not set.
    config.getValue("attribute", String.class);
    config.getValue("common-A", String.class);
    config.getValue("common-B", String.class);

    return ReactiveStreams.fromIterable(Arrays.asList(values)).map(Message::of);
}
 
Example 4
Source File: ConverterTest.java    From microprofile-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testDuckConversionWithMultipleConverters() {
    // defines 2 config with the converters defined in different orders.
    // Order must not matter, the UpperCaseDuckConverter must always be used as it has the highest priority
    Config config1 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new UpperCaseDuckConverter(), new DuckConverter())
        .build();
    Config config2 = ConfigProviderResolver.instance().getBuilder().addDefaultSources()
        .withConverters(new DuckConverter(), new UpperCaseDuckConverter())
        .build();

    Duck duck = config1.getValue("tck.config.test.javaconfig.converter.duckname", Duck.class);
    Assert.assertNotNull(duck);
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");

    duck = config2.getValue("tck.config.test.javaconfig.converter.duckname", Duck.class);
    Assert.assertNotNull(duck);
    // the UpperCaseDuckConverter has highest priority
    Assert.assertEquals(duck.getName(), "HANNELORE",
        "The converter with the highest priority (UpperCaseDuckConverter) must be used.");
}
 
Example 5
Source File: TestConnector.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Override
public SubscriberBuilder<? extends Message<String>, Void> getSubscriberBuilder(Config config) {
    String channel = config.getValue(CHANNEL_NAME_ATTRIBUTE, String.class);
    LinkedBlockingQueue<Message<String>> queue = new LinkedBlockingQueue<>();
    outgoingQueues.put(channel, queue);
    return ReactiveStreams.<Message<String>>builder().forEach(queue::add);
}
 
Example 6
Source File: SimpleScheduler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
SimpleTrigger createTrigger(String invokerClass, CronParser parser, Scheduled scheduled, int nameSequence, Config config) {
    String id = scheduled.identity().trim();
    if (id.isEmpty()) {
        id = nameSequence + "_" + invokerClass;
    }
    ZonedDateTime start = ZonedDateTime.now().truncatedTo(ChronoUnit.SECONDS);
    Long millisToAdd = null;
    if (scheduled.delay() > 0) {
        millisToAdd = scheduled.delayUnit().toMillis(scheduled.delay());
    } else if (!scheduled.delayed().isEmpty()) {
        millisToAdd = Math.abs(parseDuration(scheduled, scheduled.delayed(), "delayed").toMillis());
    }
    if (millisToAdd != null) {
        start = start.toInstant().plusMillis(millisToAdd).atZone(start.getZone());
    }

    String cron = scheduled.cron().trim();
    if (!cron.isEmpty()) {
        if (SchedulerContext.isConfigValue(cron)) {
            cron = config.getValue(SchedulerContext.getConfigProperty(cron), String.class);
        }
        Cron cronExpr;
        try {
            cronExpr = parser.parse(cron);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Cannot parse cron expression: " + cron, e);
        }
        return new CronTrigger(id, start, cronExpr);
    } else if (!scheduled.every().isEmpty()) {
        return new IntervalTrigger(id, start, Math.abs(parseDuration(scheduled, scheduled.every(), "every").toMillis()));
    } else {
        throw new IllegalArgumentException("Invalid schedule configuration: " + scheduled);
    }
}
 
Example 7
Source File: SmallRyeFaultToleranceProcessor.java    From quarkus with 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 8
Source File: VaultITCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void configPropertyIndirection() {
    assertEquals(DB_PASSWORD, someSecretThroughIndirection);

    Config config = ConfigProviderResolver.instance().getConfig();
    String value = config.getValue(MY_PASSWORD, String.class);
    assertEquals(DB_PASSWORD, value);
}
 
Example 9
Source File: CustomConverterTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCharacterConverter() {
    Config config = buildConfig(
            "my.char", "a");
    char c = config.getValue("my.char", Character.class);
    assertEquals('a', c);
}
 
Example 10
Source File: CustomConverterTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomInetAddressConverter() {
    Config config = buildConfig(
            "my.address", "10.0.0.1");
    InetAddress inetaddress = config.getValue("my.address", InetAddress.class);
    assertNotNull(inetaddress);
    assertArrayEquals(new byte[] { 10, 0, 0, 1 }, inetaddress.getAddress());
}
 
Example 11
Source File: ImplicitConverterTestCase.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testImplicitLocalDateConverter() {
    Config config = buildConfig(
            "my.date", "2019-04-01");
    LocalDate date = config.getValue("my.date", LocalDate.class);
    assertNotNull(date);
    assertEquals(2019, date.getYear());
    assertEquals(4, date.getMonthValue());
    assertEquals(1, date.getDayOfMonth());
}
 
Example 12
Source File: ServiceInfo.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
public static Integer getServicePort(Config config) {
    Integer servicePort = config.getValue("payara.instance.http.port", Integer.class);
    if (servicePort == null) {
        servicePort = config.getValue("http.port", Integer.class);
    }
    if (servicePort == null) {
        servicePort = 80;
    }
    return servicePort;
}
 
Example 13
Source File: ConfigTestController.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
@Path("/lookup")
@GET
public String getLookupConfigValue() {
    Config config = ConfigProvider.getConfig();
    String value = config.getValue("value", String.class);
    return "Config value from ConfigProvider " + value;
}
 
Example 14
Source File: ServiceInfo.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
public static String getServiceAddress(Config config) {
    String serviceAddress = config.getValue("payara.instance.http.address", String.class);
    if (serviceAddress == null) {
        serviceAddress = config.getValue("http.address", String.class);
    }
    if (serviceAddress == null || serviceAddress.equals("0.0.0.0")) {
        serviceAddress = "localhost";
    }
    return serviceAddress;
}
 
Example 15
Source File: WorldClockApiWithHeaders.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 5 votes vote down vote up
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 16
Source File: AutoDiscoveredConfigSourceTest.java    From microprofile-config with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testAutoDiscoveredConverterNotAddedAutomatically() {
    Config config = ConfigProviderResolver.instance().getBuilder().addDefaultSources().addDiscoveredSources().build();
    Pizza dVaule = config.getValue("tck.config.test.customDbConfig.key3", Pizza.class);
    Assert.fail("The auto discovered converter should not be added automatically.");
}
 
Example 17
Source File: ExternalRoutingService.java    From pragmatic-microservices-lab with MIT License 4 votes vote down vote up
@Override
public List<Itinerary> fetchRoutesForSpecification(
        RouteSpecification routeSpecification) {
    Config config = ConfigProvider.getConfig();
    URL url;
    try {
        url = config.getValue("discovery.service.pathfinder.url", URL.class);
    } catch (RuntimeException e) {
        LOGGER.log(Level.WARNING, "No pathfinder service discovered, returning empty list of itineraries", e);
        return new ArrayList<>();
    }
    WebTarget graphTraversalResource = null;
    try {
        URL target = new URL(url, "rest/graph-traversal/shortest-path");
        Logger.getLogger(ExternalRoutingService.class.getName())
                .log(Level.INFO, "URL of a healthy pathfinder service: {0}", target);
        graphTraversalResource = jaxrsClient.target(target.toURI());
    } catch (URISyntaxException | MalformedURLException ex) {
        throw new RuntimeException("Pathfinder URL is malformed: " + url, ex);
    }

    // The RouteSpecification is picked apart and adapted to the external API.
    String origin = routeSpecification.getOrigin().getUnLocode().getIdString();
    String destination = routeSpecification.getDestination().getUnLocode()
            .getIdString();

    List<TransitPath> transitPaths = graphTraversalResource
            .queryParam("origin", origin)
            .queryParam("destination", destination)
            .request(MediaType.APPLICATION_JSON)
            .get(new GenericType<List<TransitPath>>() {
            });

    // The returned result is then translated back into our domain model.
    List<Itinerary> itineraries = new ArrayList<>();

    for (TransitPath transitPath : transitPaths) {
        Itinerary itinerary = toItinerary(transitPath);
        // Use the specification to safe-guard against invalid itineraries
        if (routeSpecification.isSatisfiedBy(itinerary)) {
            itineraries.add(itinerary);
        } else {
            LOGGER.log(Level.FINE,
                    "Received itinerary that did not satisfy the route specification");
        }
    }

    return itineraries;
}
 
Example 18
Source File: AmqpEventService.java    From trellis with Apache License 2.0 4 votes vote down vote up
private AmqpEventService(final EventSerializationService serializer, final Channel channel, final Config config) {
    this(serializer, channel, config.getValue(CONFIG_AMQP_EXCHANGE_NAME, String.class),
            config.getValue(CONFIG_AMQP_ROUTING_KEY, String.class),
        config.getOptionalValue(CONFIG_AMQP_MANDATORY, Boolean.class).orElse(Boolean.TRUE),
        config.getOptionalValue(CONFIG_AMQP_IMMEDIATE, Boolean.class).orElse(Boolean.FALSE));
}
 
Example 19
Source File: FileBinaryService.java    From trellis with Apache License 2.0 4 votes vote down vote up
private FileBinaryService(final IdentifierService idService, final Config config) {
    this(idService, config.getValue(CONFIG_FILE_BINARY_PATH, String.class),
            config.getOptionalValue(CONFIG_FILE_BINARY_HIERARCHY, Integer.class).orElse(DEFAULT_HIERARCHY),
            config.getOptionalValue(CONFIG_FILE_BINARY_LENGTH, Integer.class).orElse(DEFAULT_LENGTH));
}
 
Example 20
Source File: DumbConnector.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    String values = config.getValue("values", String.class);
    return ReactiveStreams.of(values, values.toUpperCase())
            .map(Message::of);
}