下面列出了java.util.Properties#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
@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);
});
}
@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);
});
}
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());
}
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);
}
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());
});
}
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;
}
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;
}
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;
}
/**
* 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);
}
});
}
/**
* 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();
}
}
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));
}
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);
});
}
}
public RabbitMQConsumer(RabbitMQConnectionFactory rabbitMQConnectionFactory, Properties properties,
RabbitMQInjectHandler injectHandler) {
this.rabbitMQConnectionFactory = rabbitMQConnectionFactory;
this.injectHandler = injectHandler;
properties.forEach((key, value) -> rabbitMQProperties.put(key.toString(), value.toString()));
}
private void addFromProperties(Properties properties) {
properties.forEach((key, value) -> {
this.properties.putIfAbsent(key.toString(), value.toString());
});
}
public void setPersistenceOnlyProps(Properties props) {
props.forEach((k, v) -> liveProperties.setProperty(k.toString(), v.toString()));
}
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));
}
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;
}
/**
* 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);
});
}
}
/**
* 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);
});
}