xref: /aosp_15_r20/external/dagger2/java/dagger/example/atm/Command.java (revision f585d8a307d0621d6060bd7e80091fdcbf94fe27)
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 java.util.List;
20 import java.util.Optional;
21 
22 /** A text-based command handler. */
23 interface Command {
24   /**
25    * Processes and optionally acts upon the given {@code input}.
26    *
27    * @return a {@link Result} indicating how the input was handled
28    */
handleInput(List<String> input)29   Result handleInput(List<String> input);
30 
31   /**
32    * A command result, which has a {@link Status} and optionally a new {@link CommandRouter} that
33    * will handle subsequent commands.
34    */
35   final class Result {
36     private final Status status;
37     private final Optional<CommandRouter> nestedCommandRouter;
38 
Result(Status status, Optional<CommandRouter> nestedCommandRouter)39     private Result(Status status, Optional<CommandRouter> nestedCommandRouter) {
40       this.status = status;
41       this.nestedCommandRouter = nestedCommandRouter;
42     }
43 
invalid()44     static Result invalid() {
45       return new Result(Status.INVALID, Optional.empty());
46     }
47 
handled()48     static Result handled() {
49       return new Result(Status.HANDLED, Optional.empty());
50     }
51 
inputCompleted()52     static Result inputCompleted() {
53       return new Result(Status.INPUT_COMPLETED, Optional.empty());
54     }
55 
enterNestedCommandSet(CommandRouter nestedCommandRouter)56     static Result enterNestedCommandSet(CommandRouter nestedCommandRouter) {
57       return new Result(Status.HANDLED, Optional.of(nestedCommandRouter));
58     }
59 
status()60     Status status() {
61       return status;
62     }
63 
nestedCommandRouter()64     Optional<CommandRouter> nestedCommandRouter() {
65       return nestedCommandRouter;
66     }
67   }
68 
69   enum Status {
70     /** The command or its arguments were invalid. */
71     INVALID,
72 
73     /** The command handled the input and no other commands should attempt to handle it. */
74     HANDLED,
75 
76      // TODO(ronshapiro): maybe call this TERMINATED? If so, maybe this should be called
77     // ContinueStatus?
78     /** The command handled the input and no further inputs should be submitted. */
79     INPUT_COMPLETED,
80     ;
81   }
82 }
83