Merge "add junit coverage for SvnfmService"
[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.apihandlerinfra.logging.ErrorLoggerInfo;
40 import org.onap.so.serviceinstancebeans.RequestError;
41 import org.onap.so.serviceinstancebeans.ServiceException;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import com.fasterxml.jackson.annotation.JsonInclude;
45 import com.fasterxml.jackson.core.JsonProcessingException;
46 import com.fasterxml.jackson.databind.ObjectMapper;
47 import com.fasterxml.jackson.databind.SerializationFeature;
48
49 @Provider
50 public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
51
52     private static Logger logger = LoggerFactory.getLogger(ApiExceptionMapper.class);
53
54
55     private final JAXBContext context;
56     private final Marshaller marshaller;
57
58     @Context
59     private HttpHeaders headers;
60
61     public ApiExceptionMapper() {
62         try {
63             context = JAXBContext.newInstance(RequestError.class);
64             marshaller = context.createMarshaller();
65         } catch (JAXBException e) {
66             logger.debug("could not create JAXB marshaller");
67             throw new IllegalStateException(e);
68         }
69     }
70
71     @Override
72     public Response toResponse(ApiException exception) {
73         logger.error("Error During API Call", exception);
74         return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build();
75     }
76
77     protected String buildErrorString(ApiException exception) {
78         String errorText = exception.getMessage();
79         String messageId = exception.getMessageID();
80         List<String> variables = exception.getVariables();
81         ErrorLoggerInfo errorLoggerInfo = exception.getErrorLoggerInfo();
82
83
84
85         if (errorText.length() > 1999) {
86             errorText = errorText.substring(0, 1999);
87         }
88
89
90
91         List<MediaType> typeList = Optional.ofNullable(headers.getAcceptableMediaTypes()).orElse(new ArrayList<>());
92         List<String> typeListString = typeList.stream().map(item -> item.toString()).collect(Collectors.toList());
93         MediaType type;
94         if (typeListString.stream().anyMatch(item -> item.contains(MediaType.APPLICATION_XML))) {
95             type = MediaType.APPLICATION_XML_TYPE;
96         } else if (typeListString.stream().anyMatch(item -> typeListString.contains(MediaType.APPLICATION_JSON))) {
97             type = MediaType.APPLICATION_JSON_TYPE;
98         } else {
99             type = MediaType.APPLICATION_JSON_TYPE;
100         }
101
102         return buildServiceErrorResponse(errorText, messageId, variables, type);
103
104     }
105
106     protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables,
107             MediaType type) {
108         RequestError re = new RequestError();
109         ServiceException se = new ServiceException();
110         se.setMessageId(messageId);
111         se.setText(errorText);
112         if (variables != null) {
113             for (String variable : variables) {
114                 se.getVariables().add(variable);
115             }
116         }
117         re.setServiceException(se);
118         String requestErrorStr;
119
120         ObjectMapper mapper = createObjectMapper();
121
122         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
123         mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
124         try {
125             if (MediaType.APPLICATION_JSON_TYPE.equals(type)) {
126                 requestErrorStr = mapper.writeValueAsString(re);
127             } else {
128                 StringWriter sw = new StringWriter();
129                 this.getMarshaller().marshal(re, sw);
130                 requestErrorStr = sw.toString();
131             }
132         } catch (JsonProcessingException | JAXBException e) {
133             String errorMsg =
134                     "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage();
135             logger.error("BuildServiceErrorResponse", e);
136             return errorMsg;
137         }
138
139         return requestErrorStr;
140     }
141
142     protected void writeErrorLog(Exception e, String errorText, ErrorLoggerInfo errorLogInfo) {
143         if (e != null)
144             logger.error("Exception occurred", e);
145         if (errorLogInfo != null)
146             logger.error(errorLogInfo.getLoggerMessageType().toString(), errorLogInfo.getErrorSource(),
147                     errorLogInfo.getTargetEntity(), errorLogInfo.getTargetServiceName(), errorLogInfo.getErrorCode(),
148                     errorText);
149
150     }
151
152     public ObjectMapper createObjectMapper() {
153         return new ObjectMapper();
154     }
155
156     public Marshaller getMarshaller() {
157         return marshaller;
158     }
159
160 }