001/*
002 * SPDX-FileCopyrightText: none
003 * SPDX-License-Identifier: CC0-1.0
004 */
005
006package gov.nist.secauto.metaschema.cli.processor;
007
008import org.apache.logging.log4j.LogBuilder;
009import org.apache.logging.log4j.LogManager;
010import org.apache.logging.log4j.Logger;
011
012import edu.umd.cs.findbugs.annotations.NonNull;
013import edu.umd.cs.findbugs.annotations.Nullable;
014import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
015
016public abstract class AbstractExitStatus implements ExitStatus {
017  private static final Logger LOGGER = LogManager.getLogger(AbstractExitStatus.class);
018
019  @NonNull
020  private final ExitCode exitCode;
021
022  private Throwable throwable;
023
024  /**
025   * Construct a new exit status based on the provided {@code exitCode}.
026   *
027   * @param exitCode
028   *          the exit code
029   */
030  public AbstractExitStatus(@NonNull ExitCode exitCode) {
031    this.exitCode = exitCode;
032  }
033
034  @Override
035  public ExitCode getExitCode() {
036    return exitCode;
037  }
038
039  /**
040   * Get the associated throwable.
041   *
042   * @return the throwable or {@code null}
043   */
044  @Override
045  public Throwable getThrowable() {
046    return throwable;
047  }
048
049  @Override
050  @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "intended as a exposed property")
051  public ExitStatus withThrowable(@NonNull Throwable throwable) {
052    this.throwable = throwable;
053    return this;
054  }
055
056  /**
057   * Get the associated message.
058   *
059   * @return the message or {@code null}
060   */
061  @Nullable
062  protected abstract String getMessage();
063
064  @Override
065  public void generateMessage(boolean showStackTrace) {
066    LogBuilder logBuilder = null;
067    if (getExitCode().getStatusCode() <= 0) {
068      if (LOGGER.isInfoEnabled()) {
069        logBuilder = LOGGER.atInfo();
070      }
071    } else if (LOGGER.isErrorEnabled()) {
072      logBuilder = LOGGER.atError();
073    }
074
075    if (logBuilder != null) {
076      if (showStackTrace && throwable != null) {
077        Throwable throwable = getThrowable();
078        logBuilder.withThrowable(throwable);
079      }
080
081      String message = getMessage();
082      if (message == null && throwable != null) {
083        message = throwable.getLocalizedMessage();
084      }
085
086      if (message != null && !message.isEmpty()) {
087        logBuilder.log(message);
088      } else if (showStackTrace && throwable != null) {
089        // log the throwable
090        logBuilder.log();
091      }
092    }
093  }
094
095}