1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package gov.nist.secauto.metaschema.cli.processor;
7   
8   import org.apache.logging.log4j.LogBuilder;
9   import org.apache.logging.log4j.LogManager;
10  import org.apache.logging.log4j.Logger;
11  
12  import edu.umd.cs.findbugs.annotations.NonNull;
13  import edu.umd.cs.findbugs.annotations.Nullable;
14  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15  
16  public abstract class AbstractExitStatus implements ExitStatus {
17    private static final Logger LOGGER = LogManager.getLogger(AbstractExitStatus.class);
18  
19    @NonNull
20    private final ExitCode exitCode;
21  
22    private Throwable throwable;
23  
24    /**
25     * Construct a new exit status based on the provided {@code exitCode}.
26     *
27     * @param exitCode
28     *          the exit code
29     */
30    public AbstractExitStatus(@NonNull ExitCode exitCode) {
31      this.exitCode = exitCode;
32    }
33  
34    @Override
35    public ExitCode getExitCode() {
36      return exitCode;
37    }
38  
39    /**
40     * Get the associated throwable.
41     *
42     * @return the throwable or {@code null}
43     */
44    @Override
45    public Throwable getThrowable() {
46      return throwable;
47    }
48  
49    @Override
50    @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "intended as a exposed property")
51    public ExitStatus withThrowable(@NonNull Throwable throwable) {
52      this.throwable = throwable;
53      return this;
54    }
55  
56    /**
57     * Get the associated message.
58     *
59     * @return the message or {@code null}
60     */
61    @Nullable
62    protected abstract String getMessage();
63  
64    @Override
65    public void generateMessage(boolean showStackTrace) {
66      LogBuilder logBuilder = null;
67      if (getExitCode().getStatusCode() <= 0) {
68        if (LOGGER.isInfoEnabled()) {
69          logBuilder = LOGGER.atInfo();
70        }
71      } else if (LOGGER.isErrorEnabled()) {
72        logBuilder = LOGGER.atError();
73      }
74  
75      if (logBuilder != null) {
76        if (showStackTrace && throwable != null) {
77          Throwable throwable = getThrowable();
78          logBuilder.withThrowable(throwable);
79        }
80  
81        String message = getMessage();
82        if (message == null && throwable != null) {
83          message = throwable.getLocalizedMessage();
84        }
85  
86        if (message != null && !message.isEmpty()) {
87          logBuilder.log(message);
88        } else if (showStackTrace && throwable != null) {
89          // log the throwable
90          logBuilder.log();
91        }
92      }
93    }
94  
95  }