0d928cbb0c197723f67a55e7e06e9d9f01ecbad0
[so.git] / mso-api-handlers / mso-api-handler-common / src / main / java / org / onap / so / apihandlerinfra / exceptions / ApiExceptionMapper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra.exceptions;
24
25 import java.io.StringWriter;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import javax.ws.rs.core.Context;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.ext.ExceptionMapper;
35 import javax.ws.rs.ext.Provider;
36 import javax.xml.bind.JAXBContext;
37 import javax.xml.bind.JAXBException;
38 import javax.xml.bind.Marshaller;
39 import org.onap.so.logger.LoggingAnchor;
40 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
41 import org.onap.so.logger.ErrorCode;
42 import org.onap.so.logger.MessageEnum;
43 import org.onap.so.serviceinstancebeans.RequestError;
44 import org.onap.so.serviceinstancebeans.ServiceException;
45 import com.fasterxml.jackson.annotation.JsonInclude;
46 import com.fasterxml.jackson.core.JsonProcessingException;
47 import com.fasterxml.jackson.databind.ObjectMapper;
48 import com.fasterxml.jackson.databind.SerializationFeature;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @Provider
53 public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
54
55     private static Logger logger = LoggerFactory.getLogger(ApiExceptionMapper.class);
56
57
58     private final JAXBContext context;
59     private final Marshaller marshaller;
60
61     @Context
62     private HttpHeaders headers;
63
64     public ApiExceptionMapper() {
65         try {
66             context = JAXBContext.newInstance(RequestError.class);
67             marshaller = context.createMarshaller();
68         } catch (JAXBException e) {
69             logger.debug("could not create JAXB marshaller");
70             throw new IllegalStateException(e);
71         }
72     }
73
74     @Override
75     public Response toResponse(ApiException exception) {
76
77         return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build();
78     }
79
80     protected String buildErrorString(ApiException exception) {
81         String errorText = exception.getMessage();
82         String messageId = exception.getMessageID();
83         List<String> variables = exception.getVariables();
84         ErrorLoggerInfo errorLoggerInfo = exception.getErrorLoggerInfo();
85
86
87
88         if (errorText.length() > 1999) {
89             errorText = errorText.substring(0, 1999);
90         }
91
92
93
94         List<MediaType> typeList = Optional.ofNullable(headers.getAcceptableMediaTypes()).orElse(new ArrayList<>());
95         List<String> typeListString = typeList.stream().map(item -> item.toString()).collect(Collectors.toList());
96         MediaType type;
97         if (typeListString.stream().anyMatch(item -> item.contains(MediaType.APPLICATION_XML))) {
98             type = MediaType.APPLICATION_XML_TYPE;
99         } else if (typeListString.stream().anyMatch(item -> typeListString.contains(MediaType.APPLICATION_JSON))) {
100             type = MediaType.APPLICATION_JSON_TYPE;
101         } else {
102             type = MediaType.APPLICATION_JSON_TYPE;
103         }
104
105         return buildServiceErrorResponse(errorText, messageId, variables, type);
106
107     }
108
109     protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables,
110             MediaType type) {
111         RequestError re = new RequestError();
112         ServiceException se = new ServiceException();
113         se.setMessageId(messageId);
114         se.setText(errorText);
115         if (variables != null) {
116             for (String variable : variables) {
117                 se.getVariables().add(variable);
118             }
119         }
120         re.setServiceException(se);
121         String requestErrorStr;
122
123         ObjectMapper mapper = createObjectMapper();
124
125         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
126         mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
127         try {
128             if (MediaType.APPLICATION_JSON_TYPE.equals(type)) {
129                 requestErrorStr = mapper.writeValueAsString(re);
130             } else {
131                 StringWriter sw = new StringWriter();
132                 this.getMarshaller().marshal(re, sw);
133                 requestErrorStr = sw.toString();
134             }
135         } catch (JsonProcessingException | JAXBException e) {
136             String errorMsg =
137                     "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage();
138             logger.error(LoggingAnchor.FOUR, MessageEnum.GENERAL_EXCEPTION.toString(), "BuildServiceErrorResponse",
139                     ErrorCode.DataError.getValue(), errorMsg, e);
140             return errorMsg;
141         }
142
143         return requestErrorStr;
144     }
145
146     protected void writeErrorLog(Exception e, String errorText, ErrorLoggerInfo errorLogInfo) {
147         if (e != null)
148             logger.error("Exception occurred", e);
149         if (errorLogInfo != null)
150             logger.error(errorLogInfo.getLoggerMessageType().toString(), errorLogInfo.getErrorSource(),
151                     errorLogInfo.getTargetEntity(), errorLogInfo.getTargetServiceName(), errorLogInfo.getErrorCode(),
152                     errorText);
153
154     }
155
156     public ObjectMapper createObjectMapper() {
157         return new ObjectMapper();
158     }
159
160     public Marshaller getMarshaller() {
161         return marshaller;
162     }
163
164 }