Java Code Examples for java.util.Properties#forEach()

The following examples show how to use java.util.Properties#forEach() . 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: SystemConfigLoader.java    From joyqueue with Apache License 2.0 8 votes vote down vote up
public static void load() {
    Properties sysEvn = new Properties();

    try {
        URL sysEnvFileUrl = SystemConfigLoader.class.getClassLoader().getResource(SYSTEM_EVN_FILE);
        if(null != sysEnvFileUrl) {
            logger.info("Found system properties file: {}.", sysEnvFileUrl);
            sysEvn.load(sysEnvFileUrl.openStream());
        } else {
            logger.info("No system properties file in classpath, using default properties.");
            sysEvn = DEFAULT_PROPERTIES;
        }
    } catch (IOException e) {
        logger.warn("load system config exception, using default.", e);
        sysEvn = DEFAULT_PROPERTIES;
    }

    sysEvn.forEach((k, v) -> {
        logger.info("Set system property: {} -> {}.", k, v);
        System.setProperty(k.toString(), v.toString());
    });

}
 
Example 2
Source File: PublicApiHandler.java    From syndesis with Apache License 2.0 7 votes vote down vote up
private static Map<String, Map<String, String>> getParams(InputStream paramFile) throws IOException {
    Properties properties = new Properties();
    properties.load(paramFile);

    Map<String, Map<String, String>> result = new HashMap<>();
    properties.forEach((key1, value) -> {

        final String key = key1.toString();
        final String val = value.toString();

        // key is of the form <connection-name>.<property-name>
        final int index = key.indexOf('.');
        if (index == -1) {
            LOG.warn(String.format("Ignoring invalid substitution key: %s", key));
        } else {
            final String conn = key.substring(0, index);
            final String prop = key.substring(index + 1);

            final Map<String, String> valueMap = result.computeIfAbsent(conn, k -> new HashMap<>());
            valueMap.put(prop, val);
        }
    });

    return result;
}
 
Example 3
Source File: LiKafkaClientsUtils.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static Map<String, String> propertiesToStringMap(Properties props, List<String> errors) {
  if (props == null) {
    return null;
  }
  if (props.isEmpty()) {
    return Collections.emptyMap();
  }
  Map<String, String> translated = new HashMap<>(props.size());
  props.forEach((k, v) -> {
    //Properties does not allow for null keys or values
    String sk = k.toString();
    String sv = v.toString();
    String other = translated.put(sk, sv);
    if (other != null && errors != null) {
      errors.add("value " + sk + "=" + sv + " clobbers over value " + other + " after string conversion");
    }
  });
  return translated;
}
 
Example 4
Source File: ModuleOverridesTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void testOverridesDistributions() throws Exception {
  List<String> includeFields = Arrays.asList("distribution");
  List<String> includeModules = null;
  List<String> excludeFields = null;
  List<String> excludeModules = null;
  ModuleOverrides mo =
      new ModuleOverrides(includeFields, includeModules, excludeFields, excludeModules);
  List<String> overrides = mo.generateOverrides();
  assertNotNull(overrides);
  assertTrue(overrides.size() > 0);
  String fullFileContent = String.join(System.lineSeparator(), overrides);
  Properties props = new Properties();
  props.load(IOUtils.toInputStream(fullFileContent, StandardCharsets.UTF_8));

  props.forEach((k, v) -> {
    String key = k.toString();
    String value = v.toString();
    assertStringEndsWith(key, "['distribution']");
    assertCorrectFormat(key, value);
  });
}
 
Example 5
Source File: ModuleOverridesTest.java    From synthea with Apache License 2.0 6 votes vote down vote up
@Test
public void testOverridesExcludeModule() throws Exception {
  List<String> includeFields = Arrays.asList("distribution");
  List<String> includeModules = null;
  List<String> excludeFields = null;
  List<String> excludeModules = Arrays.asList("med_rec*");
  ModuleOverrides mo =
      new ModuleOverrides(includeFields, includeModules, excludeFields, excludeModules);
  List<String> overrides = mo.generateOverrides();
  assertNotNull(overrides);
  assertTrue(overrides.size() > 0);
  String fullFileContent = String.join(System.lineSeparator(), overrides);
  Properties props = new Properties();
  props.load(IOUtils.toInputStream(fullFileContent, StandardCharsets.UTF_8));

  props.forEach((k, v) -> {
    String key = k.toString();
    String value = v.toString();
    assertStringDoesNotContain(key, "med_rec.json");
    assertStringEndsWith(key, "['distribution']");
    assertCorrectFormat(key, value);
  });
}
 
Example 6
Source File: PlatformAuthServerApplication.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    SpringApplicationBuilder b = new SpringApplicationBuilder(PlatformAuthServerApplication.class);
    String loadDefaultProperties = System.getenv(ENV_KEY_LOAD_DEFAULT_PROPERTIES);

    if (loadDefaultProperties != null) {
        Properties loadedProperties = loadDefaultProperties();
        b.properties(loadedProperties);
        if (log.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("loaded default properties:\n");
            
            loadedProperties.forEach( (k , v) -> {
                sb.append("key=").append(k).append(",value=").append(v).append("\n");
            });
            
            log.info(sb.toString());
        }
    }
    ConfigurableApplicationContext ctx = b.run(args);

    log.info("{} started for : {} ", PlatformAuthServerApplication.class.getSimpleName(),
            ctx.getEnvironment().getActiveProfiles());
}
 
Example 7
Source File: PropertyFileMerger.java    From commerce-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public Map<String, String> mergeProperties() {
    Map<String, String> finalProperties = new HashMap<>();
    for (Path propertyFile : propertyFiles) {
        if (!Files.exists(propertyFile)) {
            continue;
        }
        try (BufferedReader reader = Files.newBufferedReader(propertyFile)) {
            Properties properties = new Properties();
            properties.load(reader);
            properties.forEach((key, value) -> finalProperties.put(String.valueOf(key), String.valueOf(value)));
        } catch (IOException e) {
            //ignore
        }
    }
    return Collections.unmodifiableMap(finalProperties);
}
 
Example 8
Source File: ConfigurationResolver.java    From vividus with Apache License 2.0 5 votes vote down vote up
Properties loadFromResourceTreeRecursively(String... resourcePathParts) throws IOException
{
    String resourcePath = String.join(DELIMITER, resourcePathParts);
    List<Resource> propertyResources = collectResourcesRecursively(resourcePatternResolver, resourcePath);
    LOGGER.info("Loading properties from /{}", resourcePath);
    Properties loadedProperties = loadProperties(propertyResources.toArray(new Resource[0]));
    loadedProperties.forEach((key, value) -> LOGGER.debug("{}=={}", key, value));
    return loadedProperties;
}
 
Example 9
Source File: AbstractDockerComposeMojo.java    From docker-compose-maven-plugin with MIT License 5 votes vote down vote up
private void setEnvironment(ProcessBuilder processBuilder) throws MojoExecutionException {
    Map<String, String> environment = processBuilder.environment();

    if (apiVersion != null) {
        getLog().info("COMPOSE_API_VERSION: " + apiVersion);
        environment.put("COMPOSE_API_VERSION", apiVersion);
    }

    if (envVars != null && !envVars.isEmpty()) {
        envVars.forEach(environment::put);
    }

    if (envFile != null) {
        final Properties properties = new Properties();

        try {
            properties.load(new FileInputStream(envFile));
            properties.forEach((k, v) -> environment.put(k.toString(), v.toString()));
        } catch (final IOException e) {
            throw new MojoExecutionException(e.getMessage());
        }
    }

    if (null != envVars) {
        envVars.forEach((name, value) -> {
            getLog().info(String.format("%s: %s", name, value));
            environment.put(name, value);
        });
    }
}
 
Example 10
Source File: DefaultMPConfigSource.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
DefaultMPConfigSource(ClassLoader loader) throws IOException {
    mpcURL = loader.getResource("META-INF/microprofile-config.properties");
    Properties tmp = new Properties();
    if(mpcURL != null) {
        tmp.load(mpcURL.openStream());
    }
    tmp.forEach((key, value) -> properties.put((String) key, (String) value));
}
 
Example 11
Source File: GradleInfoReader.java    From dekorate with Apache License 2.0 5 votes vote down vote up
/**
 * Parse gradle.properties into {@link Map}.
 * @return A map containing all configuration found it the properties file.
 */
protected static Map<String, String> readGradleProperties(Path gradlePropertiesPath) {
  Map<String, String> result = new HashMap<>();
  Properties properties = new Properties();
  try (FileInputStream fis = new FileInputStream(gradlePropertiesPath.toFile())) {
    properties.load(fis);
    properties.forEach( (k,v) -> result.put(String.valueOf(k), String.valueOf(v)));
    return result;
  } catch (IOException e) {
    return Collections.emptyMap();
  }
}
 
Example 12
Source File: ConfigInitializer.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Set map items.
 *
 * @param configKey  config key must not be null
 * @param map        map to set must not be null
 * @param properties properties must not be null
 * @param keyType    key type of the map
 * @param valueType  value type of the map
 */
private static void setForMapType(String configKey, Map<Object, Object> map, Properties properties,
                                  final Type keyType, final Type valueType) {

    Objects.requireNonNull(configKey);
    Objects.requireNonNull(map);
    Objects.requireNonNull(properties);

    String prefix = configKey + "[";
    String suffix = "]";

    properties.forEach((propertyKey, propertyValue) -> {
        String propertyStringKey = propertyKey.toString();
        if (propertyStringKey.startsWith(prefix) && propertyStringKey.endsWith(suffix)) {
            String itemKey = propertyStringKey.substring(
                prefix.length(), propertyStringKey.length() - suffix.length());
            Object keyObj;
            Object valueObj;

            keyObj = convertToTypicalType(keyType, itemKey);
            valueObj = convertToTypicalType(valueType, propertyValue.toString());

            if (keyObj == null) {
                keyObj = itemKey;
            }

            if (valueObj == null) {
                valueObj = propertyValue;
            }

            map.put(keyObj, valueObj);
        }
    });
}
 
Example 13
Source File: PropertiesUtils.java    From indexr with Apache License 2.0 5 votes vote down vote up
public static Properties subSet(Properties properties, String prefix) {
    if (!prefix.endsWith(".")) {
        prefix = prefix + ".";
    }
    Properties p = new Properties();
    final String finalPrefix = prefix;

    properties.forEach((k, v) -> {
        String key = k.toString();
        if (key.startsWith(finalPrefix)) {
            p.put(key.substring(finalPrefix.length()), v);
        }
    });
    return p;
}
 
Example 14
Source File: LiveTestCase.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setPersistenceOnlyProps(Properties props) {
    props.forEach((k, v) -> liveProperties.setProperty(k.toString(), v.toString()));
}
 
Example 15
Source File: ResourceFileEncoding.java    From demo-java-x with MIT License 4 votes vote down vote up
private static void printWithProperties(InputStream propertyFile) throws IOException {
	System.out.println("\nWith `Properties`...");
	Properties properties = new Properties();
	properties.load(propertyFile);
	properties.forEach((key, value) -> System.out.println(key + " = " + value));
}
 
Example 16
Source File: ProjectProperties.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
private void addFromProperties(Properties properties) {
	properties.forEach((key, value) -> {
		this.properties.putIfAbsent(key.toString(), value.toString());
	});
}
 
Example 17
Source File: RabbitMQConsumer.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public RabbitMQConsumer(RabbitMQConnectionFactory rabbitMQConnectionFactory, Properties properties,
                        RabbitMQInjectHandler injectHandler) {
    this.rabbitMQConnectionFactory = rabbitMQConnectionFactory;
    this.injectHandler = injectHandler;
    properties.forEach((key, value) -> rabbitMQProperties.put(key.toString(), value.toString()));
}
 
Example 18
Source File: CliServerRouter.java    From rawhttp with Apache License 2.0 4 votes vote down vote up
private static Map<String, String> convertToMap(Properties mediaTypes) {
    Map<String, String> mimeMapping = new HashMap<>(mimeByFileExtension);
    mediaTypes.forEach((ext, mime) -> mimeMapping.put(ext.toString(), mime.toString()));
    return mimeMapping;
}
 
Example 19
Source File: ContentNegotiationManagerFactoryBean.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Add a mapping from a key, extracted from a path extension or a query
 * parameter, to a MediaType. This is required in order for the parameter
 * strategy to work. Any extensions explicitly registered here are also
 * whitelisted for the purpose of Reflected File Download attack detection
 * (see Spring Framework reference documentation for more details on RFD
 * attack protection).
 * <p>The path extension strategy will also try to use
 * {@link ServletContext#getMimeType} and
 * {@link org.springframework.http.MediaTypeFactory} to resolve path extensions.
 * @param mediaTypes media type mappings
 * @see #addMediaType(String, MediaType)
 * @see #addMediaTypes(Map)
 */
public void setMediaTypes(Properties mediaTypes) {
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		mediaTypes.forEach((key, value) -> {
			String extension = ((String) key).toLowerCase(Locale.ENGLISH);
			MediaType mediaType = MediaType.valueOf((String) value);
			this.mediaTypes.put(extension, mediaType);
		});
	}
}
 
Example 20
Source File: LuceneSpinSail.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Add only absent parameters from argument.
 *
 * @see Properties#putIfAbsent(java.lang.Object, java.lang.Object)
 * @param parameters
 */
public void addAbsentParameters(Properties parameters) {
	parameters.forEach((Object k, Object v) -> {
		LuceneSpinSail.this.parameters.putIfAbsent(k, v);
	});
}