View Javadoc
1   package xuml.tools.model.compiler;
2   
3   import java.util.TreeSet;
4   
5   import com.google.common.collect.BiMap;
6   import com.google.common.collect.HashBiMap;
7   
8   public class TypeRegister {
9   
10      /**
11       * Full type name -> abbr (if possible)
12       */
13      private final BiMap<String, String> types = HashBiMap.create();
14  
15      public String addType(java.lang.Class<?> clsWithoutGenerics) {
16          return addType(new Type(clsWithoutGenerics.getName()));
17      }
18  
19      public String addType(Type type) {
20          StringBuilder result = new StringBuilder(addType(type.getBase()));
21          StringBuilder typeParams = new StringBuilder();
22          for (Type t : type.getGenerics()) {
23              String typeParameter = addType(t);
24              if (typeParams.length() > 0)
25                  typeParams.append(",");
26              typeParams.append(typeParameter);
27          }
28          if (typeParams.length() > 0) {
29              result.append("<");
30              result.append(typeParams);
31              result.append(">");
32          }
33          if (type.isArray())
34              result.append("[]");
35          return result.toString();
36      }
37  
38      String addType(String type) {
39          String abbr = types.get(type);
40          if (abbr != null)
41              return abbr;
42          else {
43              int i = type.lastIndexOf(".");
44              if (i >= 0) {
45                  String last = type.substring(i + 1);
46                  if (types.inverse().get(last) != null)
47                      return type;
48                  else {
49                      types.put(type, last);
50                      return last;
51                  }
52              } else
53                  return type;
54          }
55      }
56  
57      public String getImports(String relativeToClass) {
58          TreeSet<String> set = new TreeSet<String>(types.keySet());
59          StringBuilder s = new StringBuilder();
60          for (String t : set) {
61              boolean isImmediateChildOfRelativeClass = t.startsWith(relativeToClass)
62                      && t.length() > relativeToClass.length()
63                      && t.indexOf('.', relativeToClass.length() + 1) == -1;
64              if (!isImmediateChildOfRelativeClass)
65                  s.append("import " + t + ";\n");
66          }
67          return s.toString();
68      }
69  
70      public void addTypes(java.lang.Class<?>... classes) {
71          for (Class<?> cls : classes) {
72              addType(cls);
73          }
74      }
75  }