Java Code Examples for org.springframework.boot.context.properties.bind.Binder

The following examples show how to use org.springframework.boot.context.properties.bind.Binder. 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
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)  {
	final BindResult<SpringDocConfigProperties> result = Binder.get(environment)
			.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
	if (result.isBound()) {
		SpringDocConfigProperties springDocGroupConfig = result.get();
		List<GroupedOpenApi> groupedOpenApis = springDocGroupConfig.getGroupConfigs().stream()
				.map(elt -> {
					GroupedOpenApi.Builder builder = GroupedOpenApi.builder();
					if (!CollectionUtils.isEmpty(elt.getPackagesToScan()))
						builder.packagesToScan(elt.getPackagesToScan().toArray(new String[0]));
					if (!CollectionUtils.isEmpty(elt.getPathsToMatch()))
						builder.pathsToMatch(elt.getPathsToMatch().toArray(new String[0]));
					return builder.group(elt.getGroup()).build();
				})
				.collect(Collectors.toList());
		groupedOpenApis.forEach(elt -> beanFactory.registerSingleton(elt.getGroup(), elt));
	}
	initBeanFactoryPostProcessor(beanFactory);
}
 
Example 2
Source Project: jeecg-boot-with-activiti   Source File: OSSCondition.java    License: MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	String sourceClass = "";
	if (metadata instanceof ClassMetadata) {
		sourceClass = ((ClassMetadata) metadata).getClassName();
	}
	ConditionMessage.Builder message = ConditionMessage.forCondition("OSS", sourceClass);
	Environment environment = context.getEnvironment();
	try {
		BindResult<OSSType> specified = Binder.get(environment).bind("oss.type", OSSType.class);
		if (!specified.isBound()) {
			return ConditionOutcome.match(message.because("automatic OSS type"));
		}
		OSSType required = OSSConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
		if (specified.get() == required) {
			return ConditionOutcome.match(message.because(specified.get() + " OSS type"));
		}
	}
	catch (BindException ex) {
	}
	return ConditionOutcome.noMatch(message.because("unknown OSS type"));
}
 
Example 3
Source Project: spring-cloud-formula   Source File: SpacedLogbackSystem.java    License: Apache License 2.0 6 votes vote down vote up
protected LoggingProperties parseProperties(ConfigurableEnvironment environment) {
    LoggingProperties properties = Binder.get(environment)
            .bind(LoggingProperties.PREFIX, LoggingProperties.class)
            .orElseGet(LoggingProperties::new);

    if (isSet(environment, "trace")) {
        logger.info("debug mode, set default threshold to trace");
        properties.getDefaultSpec().setThreshold("trace");
    } else if (isSet(environment, "debug")) {
        logger.info("debug mode, set default threshold to debug");
        properties.getDefaultSpec().setThreshold("debug");
    } else {
        properties.getDefaultSpec().setThreshold("info");
    }

    return properties;
}
 
Example 4
Source Project: joyrpc   Source File: RpcDefinitionPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 构造方法
 */
public RpcDefinitionPostProcessor(final ApplicationContext applicationContext,
                                  final ConfigurableEnvironment environment,
                                  final ResourceLoader resourceLoader) {
    this.applicationContext = applicationContext;
    this.environment = environment;
    this.resourceLoader = resourceLoader;
    this.counter = Counter.getOrCreate(applicationContext);
    this.rpcProperties = Binder.get(environment).bind(RPC_PREFIX, RpcProperties.class).orElseGet(RpcProperties::new);
    //值引用前缀
    this.refPrefix = environment.getProperty(REF_PREFIX_KEY, REF_PREFIX);
    //添加消费者
    if (rpcProperties.getConsumers() != null) {
        rpcProperties.getConsumers().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, consumers));
    }
    //添加消费组
    if (rpcProperties.getGroups() != null) {
        rpcProperties.getGroups().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, groups));
    }
    //添加服务提供者
    if (rpcProperties.getProviders() != null) {
        rpcProperties.getProviders().forEach(c -> addConfig(c, PROVIDER_PREFIX, providerNameCounters, providers));
    }
}
 
Example 5
@Test
public void loadYaml() throws Exception {
	YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
	List<PropertySource<?>> yaml = yamlLoader.load("application",
			new ClassPathResource("test-application.yml", getClass()));
	Binder binder = new Binder(ConfigurationPropertySources.from(yaml));
	ApplicationProperties properties = binder.bind("releasenotes", ApplicationProperties.class).get();
	Github github = properties.getGithub();
	assertThat(github.getUsername()).isEqualTo("testuser");
	assertThat(github.getPassword()).isEqualTo("testpass");
	assertThat(github.getOrganization()).isEqualTo("testorg");
	assertThat(github.getRepository()).isEqualTo("testrepo");
	List<Section> sections = properties.getSections();
	assertThat(sections.get(0).getTitle()).isEqualTo("New Features");
	assertThat(sections.get(0).getEmoji()).isEqualTo(":star:");
	assertThat(sections.get(0).getLabels()).containsExactly("enhancement");
}
 
Example 6
public static void main(String[] args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(BinderBootstrap.class)
            .web(WebApplicationType.NONE) // 非 Web 应用
            .properties("user.city.postCode=0731")
            .run(args);
    ConfigurableEnvironment environment = context.getEnvironment();
    // 从 Environment 中获取 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
    // 构造 Binder 对象,并使用 ConfigurationPropertySource 集合作为配置源
    Binder binder = new Binder(sources);
    // 构造 ConfigurationPropertyName(Spring Boot 2.0 API)
    ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code");
    // 构造 Bindable 对象,包装 postCode
    Bindable<String> postCodeBindable = Bindable.of(String.class);
    BindResult<String> result = binder.bind(propertyName, postCodeBindable);
    String postCode = result.get();
    System.out.println("postCode = " + postCode);
    // 关闭上下文
    context.close();
}
 
Example 7
public static void main(String[] args) throws IOException {
    // application.properties 文件资源 classpath 路径
    String location = "application.properties";
    // 编码化的 Resource 对象(解决乱码问题)
    EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8");
    // 加载 application.properties 文件,转化为 Properties 对象
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    // 创建 Properties 类型的 PropertySource
    PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
    // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
    // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力)
    Binder binder = new Binder(propertySources, null, conversionService());
    // 执行绑定,返回绑定结果
    BindResult<User> bindResult = binder.bind("user", User.class);
    // 获取绑定对象
    User user = bindResult.get();
    // 输出结果
    System.out.println(user);

}
 
Example 8
Source Project: brpc-java   Source File: BrpcProperties.java    License: Apache License 2.0 6 votes vote down vote up
public BrpcConfig getServiceConfig(Class<?> serviceInterface) {
    BrpcConfig brpcConfig = new BrpcConfig(global);
    if (brpcConfig.getClient() == null) {
        brpcConfig.setClient(new RpcClientConfig());
    }
    if (brpcConfig.getServer() == null) {
        brpcConfig.setServer(new RpcServerConfig());
    }
    if (brpcConfig.getNaming() == null) {
        brpcConfig.setNaming(new RpcNamingConfig());
    }
    String prefix = "brpc.custom." + normalizeName(serviceInterface.getName()) + ".";
    Binder binder = Binder.get(environment);
    binder.bind(prefix + "client", Bindable.ofInstance(brpcConfig.getClient()));
    binder.bind(prefix + "server", Bindable.ofInstance(brpcConfig.getServer()));
    binder.bind(prefix + "naming", Bindable.ofInstance(brpcConfig.getNaming()));
    rewriteMap(brpcConfig.getNaming().getExtra());
    return brpcConfig;
}
 
Example 9
@Bean
public ApplicationRunner runner(DemoApplicationProperties myApplicationProperties, Environment environment) {
	return args -> {

		List<Address> addresses = Binder.get(environment)
				.bind("demo.addresses", Bindable.listOf(Address.class))
				.orElseThrow(IllegalStateException::new);

		System.out.printf("Demo Addresses : %s\n", addresses);

		// DEMO_ENV_1 Environment Variable
		System.out.printf("Demo Env 1 : %s\n", environment.getProperty("demo.env[1]"));

		System.out.printf("Demo First Name : %s\n", myApplicationProperties.getFirstName());
		System.out.printf("Demo Last Name : %s\n", myApplicationProperties.getLastName());
		System.out.printf("Demo Username : %s\n", myApplicationProperties.getUsername());
		System.out.printf("Demo Working Time (Hours) : %s\n", myApplicationProperties.getWorkingTime().toHours());
		System.out.printf("Demo Number : %d\n", myApplicationProperties.getNumber());
		System.out.printf("Demo Telephone Number : %s\n", myApplicationProperties.getTelephoneNumber());
		System.out.printf("Demo Email 1 : %s\n", myApplicationProperties.getEmailAddresses().get(0));
		System.out.printf("Demo Email 2 : %s\n", myApplicationProperties.getEmailAddresses().get(1));
	};
}
 
Example 10
Source Project: liiklus   Source File: PropertiesUtil.java    License: MIT License 6 votes vote down vote up
public static <T> T bind(ConfigurableEnvironment environment, @NonNull T properties) {
    var configurationProperties = AnnotationUtils.findAnnotation(properties.getClass(), ConfigurationProperties.class);

    if (configurationProperties == null) {
        throw new IllegalArgumentException(properties.getClass() + " Must be annotated with @ConfigurationProperties");
    }

    var property = configurationProperties.prefix();

    var validationBindHandler = new ValidationBindHandler(
            new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator())
    );

    var bindable = Bindable.ofInstance(properties);
    return Binder.get(environment).bind(property, bindable, validationBindHandler).orElseGet(bindable.getValue());
}
 
Example 11
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
                 boolean ignoreInvalidFields, Object configurationBean) {

    Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));

    // Converts ConfigurationPropertySources
    Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);

    // Wrap Bindable from DubboConfig instance
    Bindable bindable = Bindable.ofInstance(configurationBean);

    Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));

    // Get BindHandler
    BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);

    // Bind
    binder.bind("", bindable, bindHandler);
}
 
Example 12
@Override
protected void doBind(Object bean, String beanName, String dataId, String groupId,
		String configType, NacosConfigurationProperties properties, String content,
		ConfigService configService) {
	String name = "nacos-bootstrap-" + beanName;
	NacosPropertySource propertySource = new NacosPropertySource(name, dataId,
			groupId, content, configType);
	environment.getPropertySources().addLast(propertySource);
	Binder binder = Binder.get(environment);
	ResolvableType type = getBeanType(bean, beanName);
	Bindable<?> target = Bindable.of(type).withExistingValue(bean);
	binder.bind(properties.prefix(), target);
	publishBoundEvent(bean, beanName, dataId, groupId, properties, content,
			configService);
	publishMetadataEvent(bean, beanName, dataId, groupId, properties);
	environment.getPropertySources().remove(name);
}
 
Example 13
InitializrProperties toProperties(String url) {
	return CACHE.computeIfAbsent(url, s -> {
		String retrievedFile = this.rawGithubRetriever.raw(s);
		if (StringUtils.isEmpty(retrievedFile)) {
			return null;
		}
		YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
		yamlProcessor.setResources(new InputStreamResource(new ByteArrayInputStream(
				retrievedFile.getBytes(StandardCharsets.UTF_8))));
		Properties properties = yamlProcessor.getObject();
		return new Binder(
				new MapConfigurationPropertySource(properties.entrySet().stream()
						.collect(Collectors.toMap(e -> e.getKey().toString(),
								e -> e.getValue().toString()))))
										.bind("initializr",
												InitializrProperties.class)
										.get();
	});
}
 
Example 14
Source Project: loc-framework   Source File: PrefixPropertyCondition.java    License: MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
    AnnotatedTypeMetadata metadata) {
  String prefix = (String) attribute(metadata, "prefix");
  Class<?> value = (Class<?>) attribute(metadata, "value");
  ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
  try {
    new Binder(ConfigurationPropertySources.from(environment.getPropertySources()))
        .bind(prefix, Bindable.of(value))
        .orElseThrow(
            () -> new FatalBeanException("Could not bind DataSourceSettings properties"));
    return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix));
  } catch (Exception e) {
    //ignore
  }
  return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix));
}
 
Example 15
/**
 * Binds the YAML formatted value of a deployment property to a {@link KubernetesDeployerProperties} instance.
 *
 * @param kubernetesDeployerProperties the map of Kubernetes deployer properties
 * @param propertyKey the property key to obtain the value to bind for
 * @param yamlLabel the label representing the field to bind to
 * @return a {@link KubernetesDeployerProperties} with the bound property data
 */
private static KubernetesDeployerProperties bindProperties(Map<String, String> kubernetesDeployerProperties,
		String propertyKey, String yamlLabel) {
	String deploymentPropertyValue = kubernetesDeployerProperties.getOrDefault(propertyKey, "");

	KubernetesDeployerProperties deployerProperties = new KubernetesDeployerProperties();

	if (!StringUtils.isEmpty(deploymentPropertyValue)) {
		try {
			YamlPropertiesFactoryBean properties = new YamlPropertiesFactoryBean();
			String tmpYaml = "{ " + yamlLabel + ": " + deploymentPropertyValue + " }";
			properties.setResources(new ByteArrayResource(tmpYaml.getBytes()));
			Properties yaml = properties.getObject();
			MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml);
			deployerProperties = new Binder(source)
					.bind("", Bindable.of(KubernetesDeployerProperties.class)).get();
		} catch (Exception e) {
			throw new IllegalArgumentException(
					String.format("Invalid binding property '%s'", deploymentPropertyValue), e);
		}
	}

	return deployerProperties;
}
 
Example 16
Source Project: spring-cloud-gateway   Source File: ConfigurationService.java    License: Apache License 2.0 6 votes vote down vote up
static <T> T bindOrCreate(Bindable<T> bindable,
		Map<String, Object> properties, String configurationPropertyName,
		Validator validator, ConversionService conversionService) {
	// see ConfigurationPropertiesBinder from spring boot for this definition.
	BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler();

	if (validator != null) { // TODO: list of validators?
		handler = new ValidationBindHandler(handler, validator);
	}

	List<ConfigurationPropertySource> propertySources = Collections
			.singletonList(new MapConfigurationPropertySource(properties));

	return new Binder(propertySources, null, conversionService)
			.bindOrCreate(configurationPropertyName, bindable, handler);
}
 
Example 17
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
Example 18
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
Example 19
@SuppressWarnings("unchecked")
private void bindToDefault(String binding) {
	T extendedBindingPropertiesTarget = (T) BeanUtils
			.instantiateClass(this.getExtendedPropertiesEntryClass());
	Binder binder = new Binder(
			ConfigurationPropertySources
					.get(this.applicationContext.getEnvironment()),
			new PropertySourcesPlaceholdersResolver(
					this.applicationContext.getEnvironment()),
			IntegrationUtils.getConversionService(
					this.applicationContext.getBeanFactory()),
			null);
	binder.bind(this.getDefaultsPrefix(),
			Bindable.ofInstance(extendedBindingPropertiesTarget));
	this.bindings.put(binding, extendedBindingPropertiesTarget);
}
 
Example 20
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	Map<String, String> subProperties = Binder.get(context.getEnvironment())
			.bind(ZOOKEEPER_DEPENDENCIES_PROP, STRING_STRING_MAP)
			.orElseGet(Collections::emptyMap);
	if (!subProperties.isEmpty()) {
		return ConditionOutcome.match("Dependencies are defined in configuration");
	}
	Boolean dependenciesEnabled = context.getEnvironment().getProperty(
			"spring.cloud.zookeeper.dependency.enabled", Boolean.class, false);
	if (dependenciesEnabled) {
		return ConditionOutcome.match(
				"Dependencies are not defined in configuration, but switch is turned on");
	}
	return ConditionOutcome
			.noMatch("No dependencies have been passed for the service");
}
 
Example 21
private void reinitializeLoggingSystem(ConfigurableEnvironment environment,
		String oldLogConfig, LogFile oldLogFile) {
	Map<String, Object> props = Binder.get(environment)
			.bind("logging", Bindable.mapOf(String.class, Object.class))
			.orElseGet(Collections::emptyMap);
	if (!props.isEmpty()) {
		String logConfig = environment.resolvePlaceholders("${logging.config:}");
		LogFile logFile = LogFile.get(environment);
		LoggingSystem system = LoggingSystem
				.get(LoggingSystem.class.getClassLoader());
		try {
			ResourceUtils.getURL(logConfig).openStream().close();
			// Three step initialization that accounts for the clean up of the logging
			// context before initialization. Spring Boot doesn't initialize a logging
			// system that hasn't had this sequence applied (since 1.4.1).
			system.cleanUp();
			system.beforeInitialize();
			system.initialize(new LoggingInitializationContext(environment),
					logConfig, logFile);
		}
		catch (Exception ex) {
			PropertySourceBootstrapConfiguration.logger
					.warn("Error opening logging config file " + logConfig, ex);
		}
	}
}
 
Example 22
Source Project: kork   Source File: Front50PluginsConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * We are a bit inconsistent with how we configure service URLs, so we proceed in this order:
 *
 * <p>1) {@code spinnaker.extensibility.repositories.front50.url} 2) {@code front50.base-url} 3)
 * {@code services.front50.base-url}
 *
 * @param environment The Spring environment
 * @param front50RepositoryProps Front50 update repository configuration
 * @return The configured Front50 URL
 */
private static URL getFront50Url(
    Environment environment, PluginRepositoryProperties front50RepositoryProps) {
  try {
    return front50RepositoryProps.getUrl();
  } catch (Exception e) {
    log.warn(
        "Front50 update repository URL is either not specified or malformed, falling back "
            + "to default configuration",
        e);
    return Binder.get(environment)
        .bind("front50.base-url", Bindable.of(URL.class))
        .orElseGet(
            () ->
                Binder.get(environment)
                    .bind("services.front50.base-url", Bindable.of(URL.class))
                    .get());
  }
}
 
Example 23
@Test
public void bind() {
	String vcap = "{\"application_users\":[]," + "\"application_id\":\"9958288f-9842-4ddc-93dd-1ea3c90634cd\","
			+ "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\","
			+ "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\","
			+ "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," + "\"started_at\":\"2013-05-29 02:37:59 +0000\","
			+ "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034,"
			+ "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384},"
			+ "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\","
			+ "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"],"
			+ "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}";

	MockEnvironment env = new MockEnvironment();
	env.setProperty("VCAP_APPLICATION", vcap);
	new CloudFoundryVcapEnvironmentPostProcessor().postProcessEnvironment(env, null);

	CloudFoundryApplicationProperties cfProperties = Binder.get(env)
			.bind("vcap.application", Bindable.of(CloudFoundryApplicationProperties.class)).get();
	assertThat(cfProperties.getApplicationId()).isEqualTo("9958288f-9842-4ddc-93dd-1ea3c90634cd");
	assertThat(cfProperties.getInstanceIndex()).isEqualTo("0");
}
 
Example 24
Source Project: Milkomeda   Source File: SourcesLogApplicationListener.java    License: MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    if (environment.getClass() == StandardEnvironment.class) {
        return;
    }

    // StandardServletEnvironment or StandardReactiveEnvironment
    // 绑定类型
    boolean logEnable = Binder.get(environment).bind("milkomeda.show-log", Boolean.class).orElseGet(() -> false);
    log.info("milkomeda log is {}", logEnable ? "enable" : "disable");
    log.info("Load sources: {}", environment.getPropertySources());
}
 
Example 25
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
    Binder binder = Binder.get(context.getEnvironment());
    Map<String, Object> sslProperties = binder.bind("camel.ssl.config", Bindable.mapOf(String.class, Object.class)).orElse(Collections.emptyMap());
    ConditionMessage.Builder message = ConditionMessage.forCondition("camel.ssl.config");
    if (sslProperties.size() > 0) {
        return ConditionOutcome.match(message.because("enabled"));
    }

    return ConditionOutcome.noMatch(message.because("not enabled"));
}
 
Example 26
Source Project: synopsys-detect   Source File: DetectCustomFieldParser.java    License: Apache License 2.0 5 votes vote down vote up
public CustomFieldDocument parseCustomFieldDocument(final Map<String, String> currentProperties) throws DetectUserFriendlyException {
    try {
        final ConfigurationPropertySource source = new MapConfigurationPropertySource(currentProperties);
        final Binder objectBinder = new Binder(source);
        final BindResult<CustomFieldDocument> fieldDocumentBinding = objectBinder.bind("detect.custom.fields", CustomFieldDocument.class);
        final CustomFieldDocument fieldDocument = fieldDocumentBinding.orElse(new CustomFieldDocument());
        fieldDocument.getProject().forEach(this::filterEmptyQuotes);
        fieldDocument.getVersion().forEach(this::filterEmptyQuotes);
        return fieldDocument;
    } catch (final Exception e) {
        throw new DetectUserFriendlyException("Unable to parse custom fields.", e, ExitCodeType.FAILURE_CONFIGURATION);
    }
}
 
Example 27
Source Project: fastdep   Source File: FastDepRedisRegister.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * init environment
 *
 * @param environment environment
 */
@Override
public void setEnvironment(Environment environment) {
    this.env = environment;
    // bing binder
    binder = Binder.get(this.env);
}
 
Example 28
Source Project: fastdep   Source File: FastDepDataSourceRegister.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * init environment
 *
 * @param environment environment
 */
@Override
public void setEnvironment(Environment environment) {
    this.env = environment;
    // bing binder
    binder = Binder.get(this.env);
}
 
Example 29
@Override
public void postProcessBeforeDestruction(Object bean, String name) throws BeansException {
    if (environment == null) {
        return;
    }

    Object target = bean;
    if (AopUtils.isAopProxy(bean)) {
        target = ProxyUtils.getTargetObject(target);
    }

    if (AnnotationUtils.findAnnotation(target.getClass(), ConfigurationProperties.class) == null) {
        return;
    }

    try {
        target.getClass().getConstructor();
    } catch (NoSuchMethodException e) {
        logger.debug("can not found default constructor, skip it");
        return;
    }

    try {
        ConfigurationProperties annotation = AnnotationUtils.findAnnotation(
                target.getClass(), ConfigurationProperties.class);
        String prefix = annotation.prefix();
        Object result = Binder.get(environment).bind(prefix, (Class) target.getClass()).orElseCreate(target.getClass());
        BeanUtils.copyProperties(result, target);
    } catch (Throwable t) {
        logger.warn("error while process destruction bean with name: {}", name, t);
    }
}
 
Example 30
@ConditionalOnProperty(prefix = "", value = "", havingValue = "", matchIfMissing = true)
@ConditionalOnMissingBean
@Bean
public LauncherInfoProperties launcherInfoProperties(Environment environment) {
    Properties map = new Properties();
    Binder.get(environment)
            .bind("formula.launcher", Bindable.mapOf(String.class, String.class))
            .orElseGet(Collections::emptyMap).forEach(map::put);

    if (properties.getLauncher().mode == InfoPropertiesInfoContributor.Mode.SIMPLE) {

    }

    return new LauncherInfoProperties(map);
}