blob: 50c27ae2a5ec06d6de3eae3b874ac5880c5e9dbc [file] [log] [blame]
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.onos.rest.exceptions;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20
21import javax.ws.rs.core.Response;
22import javax.ws.rs.ext.ExceptionMapper;
23
24/**
25 * Base exception mapper implementation.
26 */
27public abstract class AbstractMapper<E extends Throwable> implements ExceptionMapper<E> {
28
29 /**
30 * Returns the response status to be given when the exception occurs.
31 *
32 * @return response status
33 */
34 protected abstract Response.Status responseStatus();
35
36 @Override
37 public Response toResponse(E exception) {
38 return response(responseStatus(), exception).build();
39 }
40
41 /**
42 * Produces a response builder primed with the supplied status code
43 * and JSON entity with the status code and exception message.
44 *
45 * @param status response status
46 * @param exception exception to encode
47 * @return response builder
48 */
49 protected Response.ResponseBuilder response(Response.Status status,
50 Throwable exception) {
51 ObjectMapper mapper = new ObjectMapper();
52 ObjectNode result = mapper.createObjectNode()
53 .put("code", status.getStatusCode())
54 .put("message", exception.getMessage());
55 return Response.status(status).entity(result.toString());
56 }
57}