1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package gov.nist.secauto.metaschema.cli.processor.command;
7   
8   import gov.nist.secauto.metaschema.cli.processor.ExitCode;
9   import gov.nist.secauto.metaschema.cli.processor.ExitStatus;
10  
11  import edu.umd.cs.findbugs.annotations.NonNull;
12  
13  /**
14   * For use in commands to short-circut command execution.
15   */
16  public class CommandExecutionException
17      extends Exception {
18    private final ExitCode exitCode;
19  
20    /**
21     * the serial version UID.
22     */
23    private static final long serialVersionUID = 1L;
24  
25    /**
26     * Constructs a new exception with the provided {@code code}, and no message or
27     * cause.
28     *
29     * @param code
30     *          the exit code associated with this error
31     */
32    public CommandExecutionException(@NonNull ExitCode code) {
33      this.exitCode = code;
34    }
35  
36    /**
37     * Constructs a new exception with the provided {@code code}, {@code message},
38     * and no cause.
39     *
40     * @param code
41     *          the exit code associated with this error
42     * @param message
43     *          the exception message
44     */
45    public CommandExecutionException(@NonNull ExitCode code, String message) {
46      super(message);
47      this.exitCode = code;
48    }
49  
50    /**
51     * Constructs a new exception with no message and the provided {@code code} and
52     * {@code cause}.
53     *
54     * @param code
55     *          the exit code associated with this error
56     * @param cause
57     *          the original exception cause
58     */
59    public CommandExecutionException(@NonNull ExitCode code, Throwable cause) {
60      super(cause);
61      this.exitCode = code;
62    }
63  
64    /**
65     * Constructs a new exception with the provided {@code code}, {@code message},
66     * and {@code cause}.
67     *
68     * @param code
69     *          the exit code associated with this error
70     * @param message
71     *          the exception message
72     * @param cause
73     *          the original exception cause
74     */
75    public CommandExecutionException(@NonNull ExitCode code, String message, Throwable cause) {
76      super(message, cause);
77      this.exitCode = code;
78    }
79  
80    /**
81     * Generate an {@link ExitStatus} based on this exception.
82     *
83     * @return the exit status
84     */
85    @NonNull
86    public ExitStatus toExitStatus() {
87      String message = getLocalizedMessage();
88  
89      ExitStatus retval = message == null
90          ? exitCode.exit()
91          : exitCode.exitMessage(message);
92  
93      Throwable cause = getCause();
94      if (cause != null) {
95        retval.withThrowable(cause);
96      }
97      return retval;
98    }
99  }