Skip to content

Commit

Permalink
Finished woith pattern predicatse utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-v committed Feb 17, 2020
1 parent 0c1a244 commit 6c42f78
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ public static void main(String[] args) {
.build());

StringConfigProperty orderedProp1 = configRegistry.stringProperty("orderedProp1");
String foo = configRegistry.stringValue("foo", null);
String bar = configRegistry.stringValue("bar", null);
String sysFoo = configRegistry.stringValue("sys.foo", null);
String foo = configRegistry.stringProperty("foo").valueOrThrow();
String bar = configRegistry.stringProperty("bar").valueOrThrow();
String sysFoo = configRegistry.stringProperty("sys.foo").valueOrThrow();

System.out.println(
"### Matched by first predicate: orderedProp1=" + orderedProp1.value().get());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package io.scalecube.config.examples;

import io.scalecube.config.ConfigRegistry;
import io.scalecube.config.ConfigRegistrySettings;
import io.scalecube.config.StringConfigProperty;
import io.scalecube.config.source.ClassPathConfigSource;
import io.scalecube.config.source.SystemPropertiesConfigSource;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@SuppressWarnings("OptionalGetWithoutIsPresent")
public class PredicateShortcutsConfigExample {

/**
* Main method for example of predicate ordering.
*
* @param args program arguments
*/
public static void main(String[] args) {
// Emulate scenario where sys.foo was also given from system properties
// System.setProperty("sys.foo", "sys foo from java system properties");

String mask = ".*config\\.props";

ConfigRegistry configRegistry =
ConfigRegistry.create(
ConfigRegistrySettings.builder()
.addLastSource("sysProps", new SystemPropertiesConfigSource())
.addLastSource(
"customSysProps",
new SystemPropertiesConfigSource(
ClassPathConfigSource.createWithPattern(
mask, Stream.of("customSys").collect(Collectors.toList()))))
.addLastSource(
"classpath",
ClassPathConfigSource.createWithPattern(
mask, Stream.of("order1", "order2").collect(Collectors.toList())))
.build());

StringConfigProperty orderedProp1 = configRegistry.stringProperty("orderedProp1");
String foo = configRegistry.stringProperty("foo").valueOrThrow();
String bar = configRegistry.stringProperty("bar").valueOrThrow();
String sysFoo = configRegistry.stringProperty("sys.foo").valueOrThrow();

System.out.println(
"### Matched by first predicate: orderedProp1=" + orderedProp1.value().get());
System.out.println("### Regardeless of predicates: foo=" + foo + ", bar=" + bar);
System.out.println(
"### Custom system property: sysFoo="
+ sysFoo
+ ", System.getProperty(sysFoo)="
+ System.getProperty("sys.foo"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public final class ClassPathConfigSource extends FilteredPathConfigSource {
Expand Down Expand Up @@ -65,19 +64,7 @@ public ClassPathConfigSource(List<Predicate<Path>> predicates) {
public static ClassPathConfigSource createWithPattern(String mask, List<String> prefixes) {
Objects.requireNonNull(mask, "ClassPathConfigSource: mask is required");
Objects.requireNonNull(prefixes, "ClassPathConfigSource: prefixes is required");

Pattern pattern = Pattern.compile(mask);

Predicate<Path> patternPredicate =
path -> pattern.matcher(path.getFileName().toString()).matches();

List<Predicate<Path>> predicates =
prefixes.stream()
.map(p -> (Predicate<Path>) path -> path.getFileName().startsWith(p))
.map(patternPredicate::and)
.collect(Collectors.toList());

return new ClassPathConfigSource(predicates);
return new ClassPathConfigSource(preparePatternPredicates(mask, prefixes));
}

@Override
Expand Down Expand Up @@ -106,7 +93,6 @@ public Map<String, ConfigProperty> loadConfig() {
});

Map<String, ConfigProperty> result = new TreeMap<>();

filterAndCollectInOrder(
predicates.iterator(),
loadConfigMap(pathCollection),
Expand All @@ -119,11 +105,10 @@ public Map<String, ConfigProperty> loadConfig() {
LoadedConfigProperty.withNameAndValue(entry)
.origin(path.toString())
.build())));

return loadedConfig = result;
}

static Collection<URI> getClassPathEntries(ClassLoader classloader) {
private static Collection<URI> getClassPathEntries(ClassLoader classloader) {
Collection<URI> entries = new LinkedHashSet<>();
ClassLoader parent = classloader.getParent();
if (parent != null) {
Expand Down Expand Up @@ -174,7 +159,7 @@ private static Collection<URL> parseJavaClassPath() {
return new LinkedHashSet<>(urls);
}

private void scanDirectory(
private static void scanDirectory(
File directory, String prefix, Set<File> ancestors, Collection<Path> collector)
throws IOException {
File canonical = directory.getCanonicalFile();
Expand All @@ -198,7 +183,7 @@ private void scanDirectory(
}
}

private void scanJar(File file, Collection<Path> collector) throws IOException {
private static void scanJar(File file, Collection<Path> collector) throws IOException {
JarFile jarFile;
try {
jarFile = new JarFile(file);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public final class FileDirectoryConfigSource extends FilteredPathConfigSource {
Expand Down Expand Up @@ -56,20 +55,8 @@ public static FileDirectoryConfigSource createWithPattern(
String directory, String mask, List<String> prefixes) {
Objects.requireNonNull(directory, "FileDirectoryConfigSource: directory is required");
Objects.requireNonNull(mask, "FileDirectoryConfigSource: mask is required");
Objects.requireNonNull(mask, "FileDirectoryConfigSource: prefixes is required");

Pattern pattern = Pattern.compile(mask);

Predicate<Path> patternPredicate =
path -> pattern.matcher(path.getFileName().toString()).matches();

List<Predicate<Path>> predicates =
prefixes.stream()
.map(p -> (Predicate<Path>) path -> path.getFileName().startsWith(p))
.map(patternPredicate::and)
.collect(Collectors.toList());

return new FileDirectoryConfigSource(directory, predicates);
Objects.requireNonNull(prefixes, "FileDirectoryConfigSource: prefixes is required");
return new FileDirectoryConfigSource(directory, preparePatternPredicates(mask, prefixes));
}

@Override
Expand All @@ -88,7 +75,6 @@ public Map<String, ConfigProperty> loadConfig() {
List<Path> pathCollection = Arrays.stream(files).map(File::toPath).collect(Collectors.toList());

Map<String, ConfigProperty> result = new TreeMap<>();

filterAndCollectInOrder(
predicates.iterator(),
loadConfigMap(pathCollection),
Expand All @@ -101,7 +87,6 @@ public Map<String, ConfigProperty> loadConfig() {
LoadedConfigProperty.withNameAndValue(entry)
.origin(path.toString())
.build())));

return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@
import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Stream;

public abstract class FilteredPathConfigSource implements ConfigSource {
private static final Logger LOGGER = LoggerFactory.getLogger(FilteredPathConfigSource.class);

protected final List<Predicate<Path>> predicates;

protected FilteredPathConfigSource(List<Predicate<Path>> predicates) {
Expand All @@ -31,10 +29,22 @@ protected FilteredPathConfigSource(List<Predicate<Path>> predicates) {
protected final Map<Path, Map<String, String>> loadConfigMap(Collection<Path> pathCollection) {
return pathCollection.stream()
.filter(path -> predicates.stream().anyMatch(predicate -> predicate.test(path)))
.collect(Collectors.toMap(path -> path, this::loadProperties));
.collect(Collectors.toMap(path -> path, FilteredPathConfigSource::loadProperties));
}

static List<Predicate<Path>> preparePatternPredicates(String mask, List<String> prefixes) {
Pattern pattern = Pattern.compile(mask);
Predicate<Path> patternPredicate = path -> pattern.matcher(path.toString()).matches();

Stream<Predicate<Path>> stream =
prefixes.stream()
.map(p -> (Predicate<Path>) path -> path.getFileName().toString().startsWith(p))
.map(p -> p.and(patternPredicate));

return Stream.concat(stream, Stream.of(patternPredicate)).collect(Collectors.toList());
}

protected final void filterAndCollectInOrder(
static void filterAndCollectInOrder(
Iterator<Predicate<Path>> predicateIterator,
Map<Path, Map<String, String>> configMap,
BiConsumer<Path, Map<String, String>> configCollector) {
Expand All @@ -56,18 +66,17 @@ protected final void filterAndCollectInOrder(
filterAndCollectInOrder(predicateIterator, configMap, configCollector);
}

private Map<String, String> loadProperties(Path input) {
private static Map<String, String> loadProperties(Path input) {
try (InputStream is = input.toUri().toURL().openStream()) {
Properties properties = new Properties();
properties.load(is);
return fromProperties(properties);
} catch (Exception e) {
LOGGER.error("Exception at loading props from '{}', cause: {}", input, e);
throw ThrowableUtil.propagate(e);
}
}

private Map<String, String> fromProperties(Properties properties) {
private static Map<String, String> fromProperties(Properties properties) {
Map<String, String> map = new HashMap<>();
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
Expand Down

0 comments on commit 6c42f78

Please sign in to comment.