1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.spf4j.test.log;
17
18 import com.google.common.base.Ascii;
19 import com.google.common.base.MoreObjects;
20 import com.google.common.collect.Maps;
21 import com.google.common.io.Resources;
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.Reader;
25 import java.io.UncheckedIOException;
26 import java.net.URL;
27 import java.nio.charset.StandardCharsets;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.util.Map;
31 import java.util.Properties;
32 import java.util.Set;
33 import javax.annotation.Nullable;
34 import javax.annotation.ParametersAreNonnullByDefault;
35 import org.spf4j.log.Level;
36
37
38
39
40
41 @ParametersAreNonnullByDefault
42 public final class PrintLogConfigsIO {
43
44 private PrintLogConfigsIO() {
45 }
46
47 public static Map<String, PrintConfig> loadConfig(final Path path) throws IOException {
48 try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
49 return loadConfig(br);
50 }
51 }
52
53 @Nullable
54 public static Map<String, PrintConfig> loadConfigFromResource(final String resourceName) {
55 ClassLoader loader = MoreObjects.firstNonNull(
56 Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());
57 URL url = loader.getResource(resourceName);
58 if (url == null) {
59 return null;
60 }
61 try (BufferedReader cfgR = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream()) {
62 return loadConfig(cfgR);
63 } catch (IOException ex) {
64 throw new UncheckedIOException(ex);
65 }
66 }
67
68 public static Map<String, PrintConfig> loadConfig(final Reader reader) throws IOException {
69 Properties props = new Properties();
70 props.load(reader);
71 Map<String, PrintConfig> cfgs = Maps.newHashMapWithExpectedSize(props.size());
72 Set<Map.Entry<String, String>> entrySet = (Set) props.entrySet();
73 for (Map.Entry<String, String> entry : entrySet) {
74 String category = entry.getKey().trim();
75 String[] cfg = entry.getValue().trim().split(",");
76 int len = cfg.length;
77 if (len == 0) {
78 throw new IllegalArgumentException("Invalid config entry: " + entry);
79 }
80 final boolean greedy;
81 String lval = cfg[len - 1];
82 if (Ascii.equalsIgnoreCase("true", lval)) {
83 greedy = true;
84 len--;
85 } else if (Ascii.equalsIgnoreCase("false", lval)) {
86 greedy = false;
87 len--;
88 } else {
89 greedy = false;
90 }
91 if (len != 1) {
92 throw new IllegalArgumentException("Invalid config entry: " + entry);
93 }
94 final Level minLevel = Level.valueOf(cfg[0]);
95 cfgs.put(category, new PrintConfig(category, minLevel, greedy));
96 }
97 return cfgs;
98 }
99
100 }