View Javadoc
1   package org.bremersee.exception;
2   
3   import org.springframework.http.HttpStatus;
4   import org.springframework.security.core.AuthenticationException;
5   import org.springframework.util.StringUtils;
6   
7   /**
8    * The access token retriever authentication exception.
9    *
10   * @author Christian Bremer
11   */
12  public class AccessTokenRetrieverAuthenticationException extends AuthenticationException
13      implements HttpStatusAware {
14  
15    private final HttpStatus httpStatus;
16  
17    /**
18     * Instantiates a new access token retriever authentication exception.
19     *
20     * @param httpStatus the http status
21     * @param body the body
22     */
23    public AccessTokenRetrieverAuthenticationException(
24        final HttpStatus httpStatus, final String body) {
25      super(buildMessage(httpStatus, body));
26      this.httpStatus = httpStatus;
27    }
28  
29    @Override
30    public int status() {
31      return httpStatus != null ? httpStatus.value() : HttpStatus.UNAUTHORIZED.value();
32    }
33  
34    private static String buildMessage(final HttpStatus httpStatus, final String body) {
35      if ((httpStatus == null || !StringUtils.hasText(httpStatus.getReasonPhrase()))
36          && !StringUtils.hasText(body)) {
37        return RestApiExceptionUtils.NO_MESSAGE_VALUE;
38      }
39      if (httpStatus == null) {
40        return body;
41      }
42      final StringBuilder sb = new StringBuilder();
43      sb.append("Server returned status code ").append(httpStatus.value());
44      if (StringUtils.hasText(httpStatus.getReasonPhrase())) {
45        sb.append(" (").append(httpStatus.getReasonPhrase()).append(")");
46      }
47      if (StringUtils.hasText(body)) {
48        sb.append(": ").append(body);
49      }
50      return sb.toString();
51    }
52  }
53