View Javadoc

1   package org.starobjects.tested.fitnesse.internal;
2   
3   import java.util.Collections;
4   import java.util.HashMap;
5   import java.util.Iterator;
6   import java.util.Map;
7   import java.util.Set;
8   import java.util.TreeMap;
9   import java.util.Map.Entry;
10  
11  import org.nakedobjects.metamodel.adapter.NakedObject;
12  
13  public class AliasesRegistry implements
14          Iterable<Map.Entry<String, NakedObject>> {
15  
16      private final Map<String, NakedObject> adaptersByAlias = new HashMap<String, NakedObject>();
17      private final Map<NakedObject, String> aliasesByAdapter = new HashMap<NakedObject, String>();
18      /**
19       * @see #nextAlias()
20       * @see #aliasPrefixedAs(String, NakedObject)
21       */
22      private final Map<String, int[]> aliasCountsByPrefix = new TreeMap<String, int[]>();
23  
24      public void put(final String alias, final NakedObject adapter) {
25          adaptersByAlias.put(alias, adapter);
26          aliasesByAdapter.put(adapter, alias);
27      }
28  
29      public NakedObject getAliased(final String alias) {
30          return adaptersByAlias.get(alias);
31      }
32  
33      public String getAlias(final NakedObject adapter) {
34          return aliasesByAdapter.get(adapter);
35      }
36  
37      public String aliasPrefixedAs(final String prefix, final NakedObject adapter) {
38          int[] aliasCountForPrefix = aliasCountsByPrefix.get(prefix);
39          if (aliasCountForPrefix == null) {
40              aliasCountForPrefix = new int[1];
41              aliasCountsByPrefix.put(prefix, aliasCountForPrefix);
42          }
43          final String nextAliasForPrefix = nextAlias(prefix, aliasCountForPrefix);
44          adaptersByAlias.put(nextAliasForPrefix, adapter);
45          return nextAliasForPrefix;
46      }
47  
48      private String nextAlias(final String prefix, final int[] heldAsCount) {
49          return prefix + "#" + (++heldAsCount[0]);
50      }
51  
52      public void aliasAs(final String aliasAs, final NakedObject adapter) {
53          adaptersByAlias.put(aliasAs, adapter);
54      }
55  
56      public Iterator<Entry<String, NakedObject>> iterator() {
57          final Set<Entry<String, NakedObject>> entrySet = adaptersByAlias
58                  .entrySet();
59          return Collections.unmodifiableSet(entrySet).iterator();
60      }
61  
62  }