2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.so.apihandlerinfra.exceptions;
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;
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;
42 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
43 import org.onap.so.logger.MessageEnum;
45 import org.onap.so.logger.MsoLogger;
46 import org.onap.so.serviceinstancebeans.RequestError;
47 import org.onap.so.serviceinstancebeans.ServiceException;
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;
57 public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
59 private static Logger logger = LoggerFactory.getLogger(ApiExceptionMapper.class);
62 private final JAXBContext context;
63 private final Marshaller marshaller;
66 private HttpHeaders headers;
68 public ApiExceptionMapper() {
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);
78 public Response toResponse(ApiException exception) {
80 return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build();
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();
91 if (errorText.length() > 1999) {
92 errorText = errorText.substring(0, 1999);
97 List<MediaType> typeList = Optional.ofNullable(headers.getAcceptableMediaTypes()).orElse(new ArrayList<>());
98 List<String> typeListString = typeList.stream().map(item -> item.toString()).collect(Collectors.toList());
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;
105 type = MediaType.APPLICATION_JSON_TYPE;
108 return buildServiceErrorResponse(errorText,messageId,variables, type);
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);
122 re.setServiceException(se);
123 String requestErrorStr;
125 ObjectMapper mapper = createObjectMapper();
127 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
128 mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
130 if (MediaType.APPLICATION_JSON_TYPE.equals(type)) {
131 requestErrorStr = mapper.writeValueAsString(re);
133 StringWriter sw = new StringWriter();
134 this.getMarshaller().marshal(re, sw);
135 requestErrorStr = sw.toString();
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 MsoLogger.ErrorCode.DataError.getValue(), errorMsg, e);
144 return requestErrorStr;
147 protected void writeErrorLog(Exception e, String errorText, ErrorLoggerInfo errorLogInfo) {
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);
155 public ObjectMapper createObjectMapper(){
156 return new ObjectMapper();
159 public Marshaller getMarshaller() {