01: package org.kohsuke.javanet.approval;
02:
03: import java.io.BufferedReader;
04: import java.io.IOException;
05: import java.io.InputStream;
06: import java.io.InputStreamReader;
07: import java.io.PrintWriter;
08: import java.io.Reader;
09: import java.io.StringWriter;
10: import java.io.StringReader;
11: import java.util.Map;
12: import java.util.List;
13: import java.util.HashMap;
14: import java.util.ArrayList;
15:
16: /**
17: * @author Kohsuke Kawaguchi
18: */
19: public class Util {
20: public static String replace(InputStream in,
21: Map<String, String> props) throws IOException {
22: return replace(new InputStreamReader(in, "UTF-8"), props);
23: }
24:
25: public static String replace(String text, Map<String, String> props)
26: throws IOException {
27: return replace(new StringReader(text), props);
28: }
29:
30: /**
31: * Replace keywords in the input.
32: */
33: public static String replace(Reader in, Map<String, String> props)
34: throws IOException {
35: BufferedReader r = new BufferedReader(in);
36: StringWriter sw = new StringWriter();
37: PrintWriter w = new PrintWriter(sw);
38:
39: String line;
40:
41: while ((line = r.readLine()) != null) {
42: for (Map.Entry<String, String> e : props.entrySet()) {
43: String value = e.getValue();
44: if (value == null)
45: value = "null";
46: line = line.replace("${" + e.getKey() + "}", value);
47: }
48: w.println(line);
49: }
50: r.close();
51: w.close();
52: return sw.toString();
53: }
54:
55: /**
56: * Creates a reverse map.
57: */
58: public static <T, V> Map<T, List<V>> reverseMap(Map<V, T> map) {
59: Map<T, List<V>> r = new HashMap<T, List<V>>();
60: for (Map.Entry<V, T> e : map.entrySet()) {
61: if (e.getValue() == null)
62: continue; // avoid null keys
63: List<V> vs = r.get(e.getValue());
64: if (vs == null)
65: r.put(e.getValue(), vs = new ArrayList<V>());
66: vs.add(e.getKey());
67: }
68: return r;
69: }
70:
71: /**
72: * Creates an unique reverse map.
73: */
74: public static <T, V> Map<T, V> reverseUniqueMap(Map<V, T> map) {
75: Map<T, V> r = new HashMap<T, V>();
76: for (Map.Entry<V, T> e : map.entrySet()) {
77: if (e.getValue() == null)
78: continue; // avoid null keys
79: r.put(e.getValue(), e.getKey());
80: }
81: return r;
82: }
83: }
|