View Javadoc

1   /*
2    * Copyright 2015 Data Archiving and Networked Services (an institute of
3    * Koninklijke Nederlandse Akademie van Wetenschappen), King's College London,
4    * Georg-August-Universitaet Goettingen Stiftung Oeffentlichen Rechts
5    *
6    * Licensed under the EUPL, Version 1.1 or – as soon they will be approved by
7    * the European Commission - subsequent versions of the EUPL (the "Licence");
8    * You may not use this work except in compliance with the Licence.
9    * You may obtain a copy of the Licence at:
10   *
11   * https://joinup.ec.europa.eu/software/page/eupl
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the Licence is distributed on an "AS IS" basis,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the Licence for the specific language governing
17   * permissions and limitations under the Licence.
18   */
19  
20  package eu.ehri.extension.errors;
21  
22  import com.fasterxml.jackson.core.JsonProcessingException;
23  import com.fasterxml.jackson.databind.ObjectMapper;
24  import com.google.common.base.Charsets;
25  import com.google.common.collect.ImmutableList;
26  import com.google.common.collect.ImmutableMap;
27  
28  import javax.ws.rs.WebApplicationException;
29  import javax.ws.rs.core.Response;
30  import java.util.Map;
31  
32  public class InvalidJsonError extends WebApplicationException {
33      private static final ObjectMapper mapper = new ObjectMapper();
34  
35      public InvalidJsonError(JsonProcessingException cause) {
36          super(Response.status(Response.Status.BAD_REQUEST)
37                  .entity(errorToJson(cause).getBytes(Charsets.UTF_8)).build());
38      }
39  
40      private static String errorToJson(JsonProcessingException cause) {
41          try {
42              Map<String, Object> error = ImmutableMap.of(
43                      "message", cause.getOriginalMessage(),
44                      "location", ImmutableList.of(ImmutableMap.of(
45                              "line", cause.getLocation().getLineNr(),
46                              "column", cause.getLocation().getColumnNr()
47                      )),
48                      "type", "JsonError"
49              );
50              return mapper.writeValueAsString(
51                      ImmutableMap.of("errors", ImmutableList.of(error))
52              );
53          } catch (JsonProcessingException err) {
54              throw new RuntimeException(err);
55          }
56      }
57  }