01: /*
02: * Copyright 2007 Roy van der Kuil (roy@vanderkuil.nl) and Stefan Rotman (stefan@rotman.net)
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package nl.improved.sqlclient.commands;
17:
18: import java.util.Collection;
19: import java.util.Map;
20: import java.util.HashMap;
21: import java.util.Iterator;
22:
23: /**
24: * Class for handling the available commands.
25: */
26: public class CommandManager {
27:
28: /**
29: * A map of command patterns to command instance.
30: */
31: private Map<String, Command> commands = new HashMap<String, Command>();
32:
33: /**
34: * Register a command for a specified regular expression.
35: * @param pattern a regular expression the command should match for executing the command
36: * @param cmd the command that is returned when a string matches the pattern
37: */
38: public void register(String pattern, Command cmd) {
39: commands.put(pattern, cmd);
40: }
41:
42: /**
43: * Return the command that is registered with a pattern matching the command string.
44: * NOTE: the commandString is matched to the pattern in uppercase
45: * @param commandString a string to find a matching command for so it can be executed
46: * @return the command that is registered with a pattern matching the command string.
47: */
48: public Command findCommand(String commandString) {
49: String cmdUp = commandString.toUpperCase();
50: Iterator<String> patterns = commands.keySet().iterator();
51: while (patterns.hasNext()) {
52: String pattern = patterns.next();
53: if (cmdUp.matches(pattern)) {
54: return commands.get(pattern);
55: }
56: }
57: return null;
58: }
59:
60: /**
61: * Return a collection of all available/registred commands.
62: * @return a collection of all available/registred commands.
63: */
64: public Collection<Command> getCommands() {
65: return commands.values();
66: }
67: }
|