• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *******************************************************************************
3  * Copyright (C) 2002-2012, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7 package org.unicode.cldr.util;
8 
9 import java.util.Collections;
10 import java.util.Iterator;
11 import java.util.Map;
12 import java.util.TreeMap;
13 
14 public class VariableReplacer {
15     // simple implementation for now
16     private Map m = new TreeMap(Collections.reverseOrder());
17 
18     // TODO - fix to do streams also, clean up implementation
19 
add(String variable, String value)20     public VariableReplacer add(String variable, String value) {
21         m.put(variable, value);
22         return this;
23     }
24 
replace(String source)25     public String replace(String source) {
26         String oldSource;
27         do {
28             oldSource = source;
29             for (Iterator it = m.keySet().iterator(); it.hasNext();) {
30                 String variable = (String) it.next();
31                 String value = (String) m.get(variable);
32                 source = replaceAll(source, variable, value);
33             }
34         } while (!source.equals(oldSource));
35         return source;
36     }
37 
replaceAll(String source, String key, String value)38     public String replaceAll(String source, String key, String value) {
39         while (true) {
40             int pos = source.indexOf(key);
41             if (pos < 0) return source;
42             source = source.substring(0, pos) + value + source.substring(pos + key.length());
43         }
44     }
45 }
46