1 package org.onap.aai.config;
3 import java.util.LinkedHashMap;
5 import java.util.Optional;
6 import java.util.regex.Matcher;
7 import java.util.regex.Pattern;
9 import org.springframework.context.ApplicationContextInitializer;
10 import org.springframework.context.ConfigurableApplicationContext;
11 import org.springframework.core.env.CompositePropertySource;
12 import org.springframework.core.env.ConfigurableEnvironment;
13 import org.springframework.core.env.EnumerablePropertySource;
14 import org.springframework.core.env.MapPropertySource;
15 import org.springframework.core.env.PropertySource;
16 import org.springframework.stereotype.Component;
18 public class PropertyPasswordConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext> {
20 private static final Pattern decodePasswordPattern = Pattern.compile("password\\((.*?)\\)");
22 private PasswordDecoder passwordDecoder = new JettyPasswordDecoder();
25 public void initialize(ConfigurableApplicationContext applicationContext) {
26 ConfigurableEnvironment environment = applicationContext.getEnvironment();
27 for (PropertySource<?> propertySource : environment.getPropertySources()) {
28 Map<String, Object> propertyOverrides = new LinkedHashMap<>();
29 decodePasswords(propertySource, propertyOverrides);
30 if (!propertyOverrides.isEmpty()) {
31 PropertySource<?> decodedProperties = new MapPropertySource("decoded "+ propertySource.getName(), propertyOverrides);
32 environment.getPropertySources().addBefore(propertySource.getName(), decodedProperties);
37 private void decodePasswords(PropertySource<?> source, Map<String, Object> propertyOverrides) {
38 if (source instanceof EnumerablePropertySource) {
39 EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) source;
40 for (String key : enumerablePropertySource.getPropertyNames()) {
41 Object rawValue = source.getProperty(key);
42 if (rawValue instanceof String) {
43 String decodedValue = decodePasswordsInString((String) rawValue);
44 propertyOverrides.put(key, decodedValue);
50 private String decodePasswordsInString(String input) {
51 if (input == null) return null;
52 StringBuffer output = new StringBuffer();
53 Matcher matcher = decodePasswordPattern.matcher(input);
54 while (matcher.find()) {
55 String replacement = passwordDecoder.decode(matcher.group(1));
56 matcher.appendReplacement(output, replacement);
58 matcher.appendTail(output);
59 return output.toString();