View Javadoc

1   package org.lsst.ccs.command;
2   
3   import java.util.ArrayList;
4   import java.util.Iterator;
5   import java.util.LinkedHashSet;
6   
7   /**
8    * A command dictionary to which other command dictionaries can be added and
9    * removed.
10   *
11   * @author tonyj
12   */
13  /*
14  * note by Bernard AMADE: why was this class turned public though it was package friendly?
15  * if you implement a method f() that returns a Dictionary
16  * this method is built using a CommandSetBuilder
17  * now if you have another method g() with the same feature
18  * if you want to create a composite which uses the result of f() and g()
19  * you have to reuse 2 CommandSetBuilder from the ground up .
20  * or  have methods m() and n() that return an intermediary CommandSet
21  * and build first a CompositeCommandSet!
22  * so not worth the hassle!
23   */
24  public class CompositeCommandDictionary implements Dictionary {
25  
26      private LinkedHashSet<Dictionary> dicts = new LinkedHashSet<>();
27  
28      public void add(Dictionary commandDictionary) {
29          dicts.add(commandDictionary);
30      }
31  
32      public void remove(Dictionary commandDictionary) {
33          dicts.remove(commandDictionary);
34      }
35  
36      @Override
37      public boolean containsCommand(BasicCommand tc) {
38          return containsCommand(tc.getCommand(), tc.getArgumentCount());
39      }
40  
41      @Override
42      public DictionaryCommand findCommand(BasicCommand tc) {
43          return findCommand(tc.getCommand(), tc.getArgumentCount());
44      }
45  
46      @Override
47      public boolean containsCommand(String command, int argumentCount) {
48          for (Dictionary dict : dicts) {
49              if (dict.containsCommand(command, argumentCount)) {
50                  return true;
51              }
52          }
53          return false;
54      }
55  
56      @Override
57      public DictionaryCommand findCommand(String command, int argumentCount) {
58          for (Dictionary dict : dicts) {
59              if (dict.containsCommand(command, argumentCount)) {
60                  return dict.findCommand(command, argumentCount);
61              }
62          }
63          return null;
64      }
65  
66      @Override
67      public Iterator<DictionaryCommand> iterator() {
68          // Brute force implementation, could do better
69          ArrayList<DictionaryCommand> allCommands = new ArrayList<>();
70          for (Dictionary dict : dicts) {
71              for (DictionaryCommand def : dict) {
72                  allCommands.add(def);
73              }
74          }
75          return allCommands.iterator();
76      }
77  
78      @Override
79      public int size() {
80          int result = 0;
81          for (Dictionary dict : dicts) {
82              result += dict.size();
83          }
84          return result;
85      }
86  }