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