View Javadoc
1   /**
2    * This file Copyright (c) 2012-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.rest;
35  
36  import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
37  
38  import javax.ws.rs.BadRequestException;
39  import javax.ws.rs.NotAcceptableException;
40  import javax.ws.rs.NotAllowedException;
41  import javax.ws.rs.NotAuthorizedException;
42  import javax.ws.rs.NotFoundException;
43  import javax.ws.rs.WebApplicationException;
44  import javax.ws.rs.container.ResourceInfo;
45  import javax.ws.rs.core.Context;
46  import javax.ws.rs.core.MediaType;
47  import javax.ws.rs.core.Response;
48  import javax.ws.rs.core.Response.StatusType;
49  import javax.ws.rs.ext.ExceptionMapper;
50  import javax.ws.rs.ext.Provider;
51  
52  import org.apache.commons.lang3.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * Maps exceptions encountered to response status codes.
58   */
59  @Provider
60  public class RestExceptionMapper implements ExceptionMapper<Throwable> {
61      private static final Logger log = LoggerFactory.getLogger(RestExceptionMapper.class);
62  
63      @Context
64      private ResourceInfo resourceInfo;
65  
66      @Override
67      public Response toResponse(Throwable exception) {
68          StatusType status = INTERNAL_SERVER_ERROR;
69          String errorCode = "unknown";
70          String errorMessage = exception.getMessage();
71  
72          if (exception instanceof WebApplicationException) {
73              if (exception instanceof NotAuthorizedException) {
74                  errorCode = "notAuthorized";
75              } else if (exception instanceof BadRequestException) {
76                  errorCode = "badRequest";
77              } else if (exception instanceof NotAllowedException) {
78                  errorCode = "methodNotAllowed";
79              } else if (exception instanceof NotAcceptableException) {
80                  errorCode = "notAcceptable";
81              } else if (exception instanceof NotFoundException) {
82                  errorCode = "notFound";
83              } else {
84                  try {
85                      Class<?> restEasyReaderEx = Class.forName("org.jboss.resteasy.spi.ReaderException");
86                      Class<?> restEasyWriterEx = Class.forName("org.jboss.resteasy.spi.WriterException");
87                      if (restEasyReaderEx.isAssignableFrom(exception.getClass())) {
88                          errorCode = "readerError";
89                      } else if (restEasyWriterEx.isAssignableFrom(exception.getClass())) {
90                          errorCode = "writerError";
91                      }
92                  } catch (ClassNotFoundException e) {
93                      // do nothing, cannot be a RESTEasy-specific exception then
94                  }
95              }
96  
97              // Trim sensitive information of JAX-RS implementation.
98              if (errorMessage.startsWith("RESTEASY")) {
99                  errorMessage = StringUtils.substringAfter(errorMessage, ": ");
100             }
101 
102             Response response = ((WebApplicationException) exception).getResponse();
103             status = response.getStatusInfo();
104 
105             /**
106              * If requested media type is not supported, JSON is returned as fallback.
107              * For example, curl -i -X GET '.../.rest/delivery/website/v1' -u username:password -H "Accept: application/something".
108              *
109              * If no resource method is matched, JSON is returned as fallback.
110              * For example, a request like ".../.rest/delivery/something" (without "v1" part) doesn't match any resource.
111              */
112             if (exception instanceof NotAcceptableException
113                     || resourceInfo.getResourceMethod() == null) {
114                 return Response.status(status)
115                         .type(MediaType.APPLICATION_JSON)
116                         .entity(new RestError(errorCode, errorMessage))
117                         .build();
118             }
119         }
120 
121         log.error("Exception thrown executing REST endpoint, returning {}", status.getStatusCode(), exception);
122 
123         return Response.status(status)
124                 .entity(new RestError(errorCode, errorMessage))
125                 .build();
126     }
127 }