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