• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 
17 package dagger.example.atm;
18 
19 import dagger.example.atm.Command.Result;
20 import dagger.example.atm.Command.Status;
21 import java.util.Arrays;
22 import java.util.List;
23 import java.util.Map;
24 import javax.inject.Inject;
25 
26 /** Routes individual text commands to the appropriate {@link Command}(s). */
27 final class CommandRouter {
28   private final Map<String, Command> commands;
29   private final Outputter outputter;
30 
31   @Inject
CommandRouter(Map<String, Command> commands, Outputter outputter)32   CommandRouter(Map<String, Command> commands, Outputter outputter) {
33     this.commands = commands;
34     this.outputter = outputter;
35   }
36 
37   /**
38    * Calls {@link Command#handleInput(String) command.handleInput(input)} on this router's
39    * {@linkplain #commands commands}.
40    */
route(String input)41   Result route(String input) {
42     List<String> splitInput = split(input);
43     if (splitInput.isEmpty()) {
44       return invalidCommand(input);
45     }
46 
47     String commandKey = splitInput.get(0);
48     Command command = commands.get(commandKey);
49     if (command == null) {
50       return invalidCommand(input);
51     }
52 
53     List<String> args = splitInput.subList(1, splitInput.size());
54     Result result = command.handleInput(args);
55     return result.status().equals(Status.INVALID) ? invalidCommand(input) : result;
56   }
57 
invalidCommand(String input)58   private Result invalidCommand(String input) {
59     outputter.output(String.format("couldn't understand \"%s\". please try again.", input));
60     return Result.invalid();
61   }
62 
split(String input)63   private static List<String> split(String input) {
64     return Arrays.asList(input.trim().split("\\s+"));
65   }
66 }
67