Removed MsoLogger class
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / client / sdnc / SdnCommonTasks.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 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.client.sdnc;
24
25 import java.util.ArrayList;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.http.HttpStatus;
31 import org.onap.so.client.exception.BadResponseException;
32 import org.onap.so.client.exception.MapperException;
33 import org.onap.so.logger.ErrorCode;
34 import org.onap.so.logger.MessageEnum;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.http.HttpHeaders;
38 import org.springframework.http.MediaType;
39 import org.springframework.stereotype.Component;
40 import org.springframework.util.CollectionUtils;
41
42 import com.fasterxml.jackson.annotation.JsonInclude;
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45
46 @Component
47 public class SdnCommonTasks {
48
49     private static final Logger logger = LoggerFactory.getLogger(SDNCClient.class);
50     private static final String RESPONSE_CODE = "response-code";
51     private static final String RESPONSE_MESSAGE = "response-message";
52     private static final String NO_RESPONSE_FROM_SDNC = "Error did not receive a response from SDNC.";
53     private static final String BAD_RESPONSE_FROM_SDNC = "Error received a bad response from SDNC.";
54     private static final String SDNC_CODE_NOT_0_OR_IN_200_299 = "Error from SDNC: %s";
55     private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON = "ERROR: Could not convert SDNC pojo to json string.";
56
57     /***
58      * 
59      * @param request
60      * @return
61      * @throws MapperException
62      */
63     public String buildJsonRequest(Object request) throws MapperException {
64         String jsonRequest;
65         ObjectMapper objMapper = new ObjectMapper();
66         objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
67         try {
68             jsonRequest = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
69         } catch (JsonProcessingException e) {
70             logger.error("{} {} {} {} {}", MessageEnum.JAXB_EXCEPTION.toString(),
71                 COULD_NOT_CONVERT_SDNC_POJO_TO_JSON,
72                     "BPMN", ErrorCode.DataError.getValue(), e.getMessage());
73             throw new MapperException(COULD_NOT_CONVERT_SDNC_POJO_TO_JSON);
74         }
75         jsonRequest = "{\"input\":" + jsonRequest + "}";
76         logger.info(jsonRequest);
77         return jsonRequest;
78     }
79
80     /***
81      * 
82      * @param auth
83      * @return
84      */
85     public HttpHeaders getHttpHeaders(String auth) {
86         HttpHeaders httpHeader = new HttpHeaders();
87         httpHeader.set("Authorization", auth);
88         httpHeader.setContentType(MediaType.APPLICATION_JSON);
89         List<MediaType> acceptMediaTypes = new ArrayList<MediaType>();
90         acceptMediaTypes.add(MediaType.APPLICATION_JSON);
91         httpHeader.setAccept(acceptMediaTypes);
92         return httpHeader;
93     }
94
95     /***
96      * 
97      * @param output
98      * @return
99      * @throws BadResponseException
100      */
101         public String validateSDNResponse(LinkedHashMap<String, Object> output) throws BadResponseException {
102                 if (CollectionUtils.isEmpty(output)) {
103                         logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN",
104                                         ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC);
105                         throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
106                 }
107         LinkedHashMap<String, Object> embeddedResponse =(LinkedHashMap<String, Object>) output.get("output");
108         String responseCode = "";
109         String responseMessage = "";
110         if (embeddedResponse != null) {
111                 responseCode = (String) embeddedResponse.get(RESPONSE_CODE);
112             responseMessage = (String) embeddedResponse.get(RESPONSE_MESSAGE);
113         }
114         ObjectMapper objMapper = new ObjectMapper();
115         String jsonResponse;
116                 try {
117                         jsonResponse = objMapper.writeValueAsString(output);
118                         logger.debug(jsonResponse);
119                 } catch (JsonProcessingException e) {
120                         logger.warn("Could not convert SDNC Response to String", e);
121                         jsonResponse = "";
122                 }
123                 logger.info("ResponseCode: {} ResponseMessage: {}", responseCode, responseMessage);
124                 int code = StringUtils.isNotEmpty(responseCode) ? Integer.parseInt(responseCode) : 0;
125                 if (isHttpCodeSuccess(code)) {
126                         logger.info("Successful Response from SDNC");
127                         return jsonResponse;
128                 } else {
129                         String errorMessage = String.format(SDNC_CODE_NOT_0_OR_IN_200_299, responseMessage);
130         logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), errorMessage, "BPMN",
131             ErrorCode.DataError.getValue(), errorMessage);
132         throw new BadResponseException(errorMessage);
133                 }
134         }
135     
136     /***
137      * 
138      * @param output
139      * @return
140      * @throws BadResponseException
141      */
142     public String validateSDNGetResponse(LinkedHashMap<String, Object> output) throws BadResponseException {
143         if (CollectionUtils.isEmpty(output)) {
144             logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN",
145                     ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC);
146             throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
147         }
148         ObjectMapper objMapper = new ObjectMapper();
149         logger.debug("Using object mapper");
150         String stringOutput = "";
151         try {
152                 stringOutput = objMapper.writeValueAsString(output);
153         }
154         catch (Exception e) {
155             logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), BAD_RESPONSE_FROM_SDNC,
156                 "BPMN", ErrorCode.UnknownError.getValue(),
157                 BAD_RESPONSE_FROM_SDNC);
158             throw new BadResponseException(BAD_RESPONSE_FROM_SDNC);
159         }
160         logger.debug("Received from GET request: {}", stringOutput);
161         return stringOutput;
162     }
163         
164
165     private boolean isHttpCodeSuccess(int code) {
166         return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0;
167     }
168 }