1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.chain.impl;
17
18
19 import java.util.HashMap;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.Map;
23 import org.apache.commons.chain.Catalog;
24 import org.apache.commons.chain.Command;
25
26
27 /***
28 * <p>Simple in-memory implementation of {@link Catalog}. This class can
29 * also be used as the basis for more advanced implementations.</p>
30 *
31 * <p>This implementation is thread-safe.</p>
32 *
33 * @author Craig R. McClanahan
34 * @author Matthew J. Sgarlata
35 * @version $Revision: 411876 $ $Date: 2006-06-05 19:02:19 +0100 (Mon, 05 Jun 2006) $
36 */
37
38 public class CatalogBase implements Catalog {
39
40
41
42
43
44 /***
45 * <p>The map of named {@link Command}s, keyed by name.
46 */
47 protected Map commands = Collections.synchronizedMap(new HashMap());
48
49
50
51
52 /***
53 * Create an empty catalog.
54 */
55 public CatalogBase() { }
56
57 /***
58 * <p>Create a catalog whose commands are those specified in the given <code>Map</code>.
59 * All Map keys should be <code>String</code> and all values should be <code>Command</code>.</p>
60 *
61 * @param commands Map of Commands.
62 *
63 * @since Chain 1.1
64 */
65 public CatalogBase( Map commands ) {
66 this.commands = Collections.synchronizedMap(commands);
67 }
68
69
70
71
72 /***
73 * <p>Add a new name and associated {@link Command}
74 * to the set of named commands known to this {@link Catalog},
75 * replacing any previous command for that name.
76 *
77 * @param name Name of the new command
78 * @param command {@link Command} to be returned
79 * for later lookups on this name
80 */
81 public void addCommand(String name, Command command) {
82
83 commands.put(name, command);
84
85 }
86
87 /***
88 * <p>Return the {@link Command} associated with the
89 * specified name, if any; otherwise, return <code>null</code>.</p>
90 *
91 * @param name Name for which a {@link Command}
92 * should be retrieved
93 * @return The Command associated with the specified name.
94 */
95 public Command getCommand(String name) {
96
97 return ((Command) commands.get(name));
98
99 }
100
101
102 /***
103 * <p>Return an <code>Iterator</code> over the set of named commands
104 * known to this {@link Catalog}. If there are no known commands,
105 * an empty Iterator is returned.</p>
106 * @return An iterator of the names in this Catalog.
107 */
108 public Iterator getNames() {
109
110 return (commands.keySet().iterator());
111
112 }
113
114 /***
115 * Converts this Catalog to a String. Useful for debugging purposes.
116 * @return a representation of this catalog as a String
117 */
118 public String toString() {
119
120 Iterator names = getNames();
121 StringBuffer str =
122 new StringBuffer("[" + this.getClass().getName() + ": ");
123
124 while (names.hasNext()) {
125 str.append(names.next());
126 if (names.hasNext()) {
127 str.append(", ");
128 }
129 }
130 str.append("]");
131
132 return str.toString();
133
134 }
135 }