View Javadoc
1   /**
2    * Copyright 2010-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.common.util.base.string;
17  
18  import static org.kuali.common.util.base.Precondition.checkNotNull;
19  
20  import java.util.Map;
21  
22  import com.google.common.collect.BiMap;
23  import com.google.common.collect.HashBiMap;
24  import com.google.common.collect.ImmutableBiMap;
25  
26  public final class Replacer {
27  
28  	private final ImmutableBiMap<String, String> tokens;
29  
30  	public String replace(final String string) {
31  		String s = string;
32  		for (Map.Entry<String, String> pair : tokens.entrySet()) {
33  			s = s.replace(pair.getKey(), pair.getValue());
34  		}
35  		return s;
36  	}
37  
38  	public String restore(final String string) {
39  		String s = string;
40  		for (Map.Entry<String, String> pair : tokens.entrySet()) {
41  			s = s.replace(pair.getValue(), pair.getKey());
42  		}
43  		return s;
44  	}
45  
46  	private Replacer(Builder builder) {
47  		this.tokens = ImmutableBiMap.copyOf(builder.tokens);
48  	}
49  
50  	public static Replacer create(String oldToken, String newToken) {
51  		return builder().add(oldToken, newToken).build();
52  	}
53  
54  	public static Builder builder() {
55  		return new Builder();
56  	}
57  
58  	public static class Builder implements org.apache.commons.lang3.builder.Builder<Replacer> {
59  
60  		private BiMap<String, String> tokens = HashBiMap.create();
61  
62  		public Builder add(String oldToken, String newToken) {
63  			this.tokens.put(oldToken, newToken);
64  			return this;
65  		}
66  
67  		public Builder tokens(BiMap<String, String> tokens) {
68  			this.tokens = tokens;
69  			return this;
70  		}
71  
72  		@Override
73  		public Replacer build() {
74  			Replacer instance = new Replacer(this);
75  			validate(instance);
76  			return instance;
77  		}
78  
79  		private static void validate(Replacer instance) {
80  			checkNotNull(instance.tokens, "tokens");
81  		}
82  
83  		public BiMap<String, String> getTokens() {
84  			return tokens;
85  		}
86  
87  		public void setTokens(BiMap<String, String> tokens) {
88  			this.tokens = tokens;
89  		}
90  	}
91  
92  	public BiMap<String, String> getTokens() {
93  		return tokens;
94  	}
95  
96  }