Skip to content

Commit

Permalink
add properties filter
Browse files Browse the repository at this point in the history
  • Loading branch information
tvd12 committed Apr 21, 2021
1 parent e354d0e commit b2f7b7b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/main/java/com/tvd12/properties/file/util/PropertiesUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.function.Predicate;

/**
*
Expand Down Expand Up @@ -236,4 +237,32 @@ public static Object defaultValueOf(Class<?> type) {
return null;
}

/**
* Filter properties by key prefix
*
* @param properties the properties to filter
* @param keyPrefix the key prefix
* @return the filtered properties
*/
public static Properties filterPropertiesByKeyPrefix(
Properties properties, String keyPrefix) {
return filterProperties(properties, it -> it.startsWith(keyPrefix));
}

/**
* Filter properties by predicate
*
* @param properties the properties to filter
* @param filter the filter
* @return the filtered properties
*/
public static Properties filterProperties(
Properties properties, Predicate<String> filter) {
Properties answer = new Properties();
for(Object key : properties.keySet()) {
if(filter.test(key.toString()))
answer.put(key, properties.get(key));
}
return answer;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,17 @@ public void getFirstPropertyKeysWithFirstDotIndex0() {
assertEquals(actual, expected);
}

@Test
public void filterPropertiesByPrefixTest() {
Properties properties = new Properties();
properties.put("datasource", "database");
properties.put("datasource.username", "hello");
properties.put("cache.username", "hello");
properties.put("cache.pass", "pass");
Properties expected = new Properties();
expected.put("datasource", "database");
expected.put("datasource.username", "hello");
assertEquals(PropertiesUtil.filterPropertiesByKeyPrefix(properties, "datasource"), expected);
}

}

0 comments on commit b2f7b7b

Please sign in to comment.