private void addDefaultProperty(ConfigurableEnvironment environment, String name, String value) { MutablePropertySources sources = environment.getPropertySources(); Map<String, Object> map = null; if (sources.contains("defaultProperties")) { PropertySource<?> source = sources.get("defaultProperties"); if (source instanceof MapPropertySource) { map = ((MapPropertySource) source).getSource(); } } else { map = new LinkedHashMap<>(); sources.addLast(new MapPropertySource("defaultProperties", map)); } if (map != null) { map.put(name, value); } }
@SuppressWarnings("unchecked") private void translateZuulRoutes(ConfigurableEnvironment environment) { //TODO should be fixed to multiple propertySource usage MapPropertySource zuulSource = findZuulPropertySource(environment); if (zuulSource == null) { return; } Map<String, String> customServiceVersions = new HashMap<>(); for (String name : zuulSource.getPropertyNames()) { extractServiceVersion(zuulSource, name, customServiceVersions); } Map<String, Object> properties = new HashMap<>(); properties.put(CUSTOM_SERVICE_VERSIONS_PROP, customServiceVersions); MapPropertySource target = new MapPropertySource(ZUUL_PROPERTY_SOURCE_NAME, properties); environment.getPropertySources().addFirst(target); }
@Before public void setUp() throws IOException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(TarantoolConfiguration.class); DockerPort dockerPort = docker.containers() .container("tarantool") .port(3301); ImmutableMap<String, Object> env = ImmutableMap.of("tarantoolPort", dockerPort.getExternalPort()); applicationContext.getEnvironment().getPropertySources() .addFirst(new MapPropertySource("rule", env)); applicationContext.refresh(); TarantoolClientOps bean = (TarantoolClientOps) applicationContext.getBean("tarantoolSyncOps"); String eval = IOUtils.toString(RepositoryIntegrationTests.class.getResource("/init.lua")); bean.eval(eval); // userRepository = applicationContext.getBean(UserRepository.class); userRepository.deleteAll(); logEntryRepository = applicationContext.getBean(LogEntryRepository.class); logEntryRepository.deleteAll(); addressRepository = applicationContext.getBean(AddressRepository.class); addressRepository.deleteAll(); }
@Before public void setUp() throws IOException { this.applicationContext = new AnnotationConfigApplicationContext(); this.applicationContext.register(TarantoolConfiguration.class); DockerPort dockerPort = docker.containers().container("tarantool").port(3301); ImmutableMap<String, Object> env = ImmutableMap.of("tarantoolPort", dockerPort.getExternalPort()); this.applicationContext.getEnvironment().getPropertySources() .addFirst(new MapPropertySource("rule", env)); this.applicationContext.refresh(); TarantoolClientOps bean = (TarantoolClientOps) applicationContext.getBean("tarantoolSyncOps"); String eval = IOUtils.toString(RepositoryIntegrationTests.class.getResource("/init.lua")); bean.eval(eval); userOperations = ((TarantoolOperations<Long, User>) applicationContext.getBean("userTarantoolOperations")); // userOperations.deleteAll(SPACE_ID); // stringUserTarantoolOperations = ((TarantoolOperations<String, User>) applicationContext.getBean("stringUserTarantoolOperations")); // stringUserTarantoolOperations.deleteAll(SPACE_STRING_ID); }
@Override public PropertySource<?> locate(Environment environment) { if (!this.enabled) { return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap()); } Map<String, Object> config; try { GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment(); Assert.notNull(googleConfigEnvironment, "Configuration not in expected format."); config = googleConfigEnvironment.getConfig(); } catch (Exception e) { String message = String.format("Error loading configuration for %s/%s_%s", this.projectId, this.name, this.profile); throw new RuntimeException(message, e); } return new MapPropertySource(PROPERTY_SOURCE_NAME, config); }
public static Map<String,String> getAllProperties(AbstractEnvironment env, String prefix){ int prefixLength = prefix.length(); Map<String, Object> map = new TreeMap<>(); for(Iterator it = (env).getPropertySources().iterator(); it.hasNext(); ) { org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next(); if (propertySource instanceof MapPropertySource) { map.putAll(((MapPropertySource) propertySource).getSource()); } } Map<String,String> result = new TreeMap<>(); for(String name: map.keySet()){ if(name.startsWith(prefix)){ result.put(name.substring(prefixLength + 1, name.length()), env.getProperty(name)); } } return result; }
/** * Constructor. * * @param catalogName connector name. Also the catalog name. * @param infoConverter hive info converter * @param connectorContext connector config */ HiveConnectorFactory( final String catalogName, final HiveConnectorInfoConverter infoConverter, final ConnectorContext connectorContext ) { super(catalogName, infoConverter, connectorContext); final boolean useLocalMetastore = Boolean.parseBoolean( connectorContext.getConfiguration() .getOrDefault(HiveConfigConstants.USE_EMBEDDED_METASTORE, "false") ); final boolean useFastHiveService = useLocalMetastore && Boolean.parseBoolean( connectorContext.getConfiguration() .getOrDefault(HiveConfigConstants.USE_FASTHIVE_SERVICE, "false") ); final Map<String, Object> properties = new HashMap<>(); properties.put("useHiveFastService", useFastHiveService); properties.put("useEmbeddedClient", useLocalMetastore); super.addEnvProperties(new MapPropertySource("HIVE_CONNECTOR", properties)); super.registerClazz(HiveConnectorFastServiceConfig.class, HiveConnectorClientConfig.class, HiveConnectorConfig.class); super.refresh(); }
@Test public void shouldConfigureSsl() { Map<String, Object> map = new HashMap<String, Object>(); map.put("vault.ssl.key-store", "classpath:certificate.json"); map.put("vault.ssl.trust-store", "classpath:certificate.json"); MapPropertySource propertySource = new MapPropertySource("shouldConfigureSsl", map); configurableEnvironment.getPropertySources().addFirst(propertySource); SslConfiguration sslConfiguration = configuration.sslConfiguration(); assertThat(sslConfiguration.getKeyStore()).isInstanceOf(ClassPathResource.class); assertThat(sslConfiguration.getKeyStorePassword()) .isEqualTo("key store password"); assertThat(sslConfiguration.getTrustStore()) .isInstanceOf(ClassPathResource.class); assertThat(sslConfiguration.getTrustStorePassword()).isEqualTo( "trust store password"); configurableEnvironment.getPropertySources().remove(propertySource.getName()); }
/** * Add, remove or re-order any {@link PropertySource}s in this application's * environment. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( name + "-" + args.hashCode(), args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String url = cleanRemoteUrl(environment.getProperty(NON_OPTION_ARGS)); Assert.state(StringUtils.hasLength(url), "No remote URL specified"); Assert.state(url.indexOf(",") == -1, "Multiple URLs specified"); try { new URI(url); } catch (URISyntaxException ex) { throw new IllegalStateException("Malformed URL '" + url + "'"); } Map<String, Object> source = Collections.singletonMap("remoteUrl", (Object) url); PropertySource<?> propertySource = new MapPropertySource("remoteUrl", source); environment.getPropertySources().addLast(propertySource); }
@Before public void init() { this.propertySources.addFirst(new PropertySource<String>("static", "foo") { @Override public Object getProperty(String name) { if (name.equals(getSource())) { return "bar"; } return null; } }); this.propertySources.addFirst(new MapPropertySource("map", Collections.<String, Object>singletonMap("name", "${foo}"))); }
@Test public void testOrderPreserved() { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put("one", 1); map.put("two", 2); map.put("three", 3); map.put("four", 4); map.put("five", 5); this.propertySources.addFirst(new MapPropertySource("ordered", map)); PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); PropertyValue[] values = propertyValues.getPropertyValues(); assertThat(values).hasSize(6); Collection<String> names = new ArrayList<String>(); for (PropertyValue value : values) { names.add(value.getName()); } assertThat(names).containsExactly("one", "two", "three", "four", "five", "name"); }
@Override public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { SpringApplication application = new SpringApplication(); application.setMainApplicationClass(config.getTestClass()); application.setWebEnvironment(false); application.setSources( new LinkedHashSet<Object>(Arrays.asList(config.getClasses()))); ConfigurableEnvironment environment = new StandardEnvironment(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("spring.jmx.enabled", "false"); properties.putAll(TestPropertySourceUtils .convertInlinedPropertiesToMap(config.getPropertySourceProperties())); environment.getPropertySources().addAfter( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("integrationTest", properties)); application.setEnvironment(environment); return application.run(); }
@Scheduled(initialDelayString = "${spring.cloud.kubernetes.reload.period:15000}", fixedDelayString = "${spring.cloud.kubernetes.reload.period:15000}") public void executeCycle() { boolean changedConfigMap = false; if (properties.isMonitoringConfigMaps()) { MapPropertySource currentConfigMapSource = findPropertySource(ConfigMapPropertySource.class); if (currentConfigMapSource != null) { MapPropertySource newConfigMapSource = configMapPropertySourceLocator.locate(environment); changedConfigMap = changed(currentConfigMapSource, newConfigMapSource); } } boolean changedSecrets = false; if (properties.isMonitoringSecrets()) { MapPropertySource currentSecretSource = findPropertySource(SecretsPropertySource.class); if (currentSecretSource != null) { MapPropertySource newSecretSource = secretsPropertySourceLocator.locate(environment); changedSecrets = changed(currentSecretSource, newSecretSource); } } if (changedConfigMap || changedSecrets) { reloadProperties(); } }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); if ("true".equals(environment .resolvePlaceholders("${spring.sleuth.stream.enabled:}"))) { return ConditionOutcome .noMatch("Found spring.sleuth.stream.enabled=true"); } if (environment instanceof ConfigurableEnvironment) { ConfigurableEnvironment configurable = (ConfigurableEnvironment) environment; configurable.getPropertySources() .addLast( new MapPropertySource("spring.sleuth.stream", Collections.<String, Object>singletonMap( "spring.sleuth.stream.enabled", "false"))); } return ConditionOutcome.match("Not found: spring.sleuth.stream.enabled"); }
@Bean public RedisClusterConfiguration getClusterConfiguration() { Map<String, Object> source = Maps.newHashMap(); source.put("spring.redis.cluster.nodes", redisProperties.getClusterNodes()); source.put("spring.redis.cluster.max-redirects", redisProperties.getMaxRedirects()); return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source)); }
public static StringValueResolver createStringValueResolver(Map<String, Object> map) { StandardEnvironment standardEnvironment = new StandardEnvironment(); standardEnvironment.getPropertySources().addFirst( new MapPropertySource(UUID.randomUUID().toString(), map)); return standardEnvironment::resolvePlaceholders; }
/** * Configure endpoint via property source override. * * @param serviceInfo * @return */ @Override protected PropertySource<?> toPropertySource(VaultServiceInfo serviceInfo) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("spring.cloud.vault.host", serviceInfo.getHost()); properties.put("spring.cloud.vault.port", serviceInfo.getPort()); properties.put("spring.cloud.vault.scheme", serviceInfo.getScheme()); return new MapPropertySource("spring-cloud-vault-connector", properties); }
/** * redisCluster配置 * @return */ @Bean public RedisClusterConfiguration redisClusterConfiguration() { Map<String, Object> source = new HashMap<String, Object>(); source.put("spring.redis.cluster.nodes", redisProperties.getNodes()); source.put("spring.redis.cluster.timeout", redisProperties.getCommandTimeout()); return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source)); }
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Map<String, Object> propertiesToAdd = new HashMap<>(); propertiesToAdd.put("spring.cloud.stream.bindings.input.destination", "metrics"); propertiesToAdd.put("spring.jackson.default-property-inclusion", "non_null"); environment.getPropertySources().addLast(new MapPropertySource("collectorDefaultProperties", propertiesToAdd)); }
private MapPropertySource findZuulPropertySource(ConfigurableEnvironment environment) { for (PropertySource<?> propertySource : environment.getPropertySources()) { if (propertySource instanceof MapPropertySource) { for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) { if (key.toLowerCase().startsWith(ZUUL_SERVICE_VERSIONS_ROOT)) { return (MapPropertySource) propertySource; } } } } return null; }
private void extractServiceVersion(MapPropertySource zuulSource, String name, Map<String,String> targetMap) { if (!name.toLowerCase().startsWith(ZUUL_SERVICE_VERSIONS_ROOT)) { return; } if (!name.toLowerCase().contains(ZUUL_SERVICE_ID_PROP)) { return; } String baseName = name.replaceAll("." + ZUUL_SERVICE_ID_PROP, ""); if (!zuulSource.containsProperty(baseName + "." + ZUUL_SERVICE_VERSIONS_PROP)) return; String versions = (String) zuulSource.getProperty(baseName + "." + ZUUL_SERVICE_VERSIONS_PROP); String serviceId = (String) zuulSource.getProperty(baseName + "." + ZUUL_SERVICE_ID_PROP); targetMap.put(serviceId, versions); }
private void translateClientVersionProperty(ConfigurableEnvironment environment) { if(!environment.containsProperty(CUSTOM_VERSION_PROP)) { return; } String versions = environment.getProperty(CUSTOM_VERSION_PROP); Map<String, Object> properties = new HashMap<>(); properties.put(DEFAULT_VERSION_PROP, versions); MapPropertySource target = new MapPropertySource(CLIENT_PROPERTY_SOURCE_NAME, properties); environment.getPropertySources().addFirst(target); }
@PostConstruct public void postConstruct() { Map<String, Object> properties = ImmutableMap .<String, Object> builder() .put("copier-options.file-attribute", "replication, blocksize, user, group, permission, checksumtype, xattr") .put("copier-options.preserve-raw-xattrs", true) .build(); env.getPropertySources().addLast(new MapPropertySource("distCpProperties", properties)); }
@Test public void isSensitiveOverride() throws Exception { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections.<String, Object>singletonMap(this.property + ".sensitive", String.valueOf(!this.sensitive))); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive); }
@Test public void isSensitiveOverrideWithGlobal() throws Exception { this.context = new AnnotationConfigApplicationContext(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("endpoint.sensitive", this.sensitive); properties.put(this.property + ".sensitive", String.valueOf(!this.sensitive)); PropertySource<?> propertySource = new MapPropertySource("test", properties); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive); }
@Test public void isEnabledFallbackToEnvironment() throws Exception { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections .<String, Object>singletonMap(this.property + ".enabled", false)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isEnabled()).isFalse(); }
@Test @SuppressWarnings("rawtypes") public void isExplicitlyEnabled() throws Exception { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections .<String, Object>singletonMap(this.property + ".enabled", false)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); ((AbstractEndpoint) getEndpointBean()).setEnabled(true); assertThat(getEndpointBean().isEnabled()).isTrue(); }
@Test public void isAllEndpointsDisabled() throws Exception { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections.<String, Object>singletonMap("endpoints.enabled", false)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isEnabled()).isFalse(); }
@Test public void isOptIn() throws Exception { this.context = new AnnotationConfigApplicationContext(); Map<String, Object> source = new HashMap<String, Object>(); source.put("endpoints.enabled", false); source.put(this.property + ".enabled", true); PropertySource<?> propertySource = new MapPropertySource("test", source); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isEnabled()).isTrue(); }
private void testGlobalEndpointsSensitive(boolean sensitive) { this.context = new AnnotationConfigApplicationContext(); PropertySource<?> propertySource = new MapPropertySource("test", Collections .<String, Object>singletonMap("endpoints.sensitive", sensitive)); this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); assertThat(getEndpointBean().isSensitive()).isEqualTo(sensitive); }
@Test public void testFooCreatePropertyTrue() { context.getEnvironment().getPropertySources().addLast( new MapPropertySource("test", Collections.singletonMap("foo.create", "true")) ); context.register(FooConfiguration.class); context.refresh(); assertNotNull(context.getBean(Foo.class)); }