1 package org.kuali.common.util.base.string;
2
3 import static org.kuali.common.util.base.Precondition.checkNotNull;
4
5 import java.util.Map;
6
7 import com.google.common.collect.BiMap;
8 import com.google.common.collect.HashBiMap;
9 import com.google.common.collect.ImmutableBiMap;
10
11 public final class Replacer {
12
13 private final ImmutableBiMap<String, String> tokens;
14
15 public String replace(final String string) {
16 String s = string;
17 for (Map.Entry<String, String> pair : tokens.entrySet()) {
18 s = s.replace(pair.getKey(), pair.getValue());
19 }
20 return s;
21 }
22
23 public String restore(final String string) {
24 String s = string;
25 for (Map.Entry<String, String> pair : tokens.entrySet()) {
26 s = s.replace(pair.getValue(), pair.getKey());
27 }
28 return s;
29 }
30
31 private Replacer(Builder builder) {
32 this.tokens = ImmutableBiMap.copyOf(builder.tokens);
33 }
34
35 public static Replacer create(String oldToken, String newToken) {
36 return builder().add(oldToken, newToken).build();
37 }
38
39 public static Builder builder() {
40 return new Builder();
41 }
42
43 public static class Builder implements org.apache.commons.lang3.builder.Builder<Replacer> {
44
45 private BiMap<String, String> tokens = HashBiMap.create();
46
47 public Builder add(String oldToken, String newToken) {
48 this.tokens.put(oldToken, newToken);
49 return this;
50 }
51
52 public Builder tokens(BiMap<String, String> tokens) {
53 this.tokens = tokens;
54 return this;
55 }
56
57 @Override
58 public Replacer build() {
59 Replacer instance = new Replacer(this);
60 validate(instance);
61 return instance;
62 }
63
64 private static void validate(Replacer instance) {
65 checkNotNull(instance.tokens, "tokens");
66 }
67
68 public BiMap<String, String> getTokens() {
69 return tokens;
70 }
71
72 public void setTokens(BiMap<String, String> tokens) {
73 this.tokens = tokens;
74 }
75 }
76
77 public BiMap<String, String> getTokens() {
78 return tokens;
79 }
80
81 }