various bugfixes for casablanca
[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  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.client.sdnc;
22
23 import java.util.ArrayList;
24 import java.util.LinkedHashMap;
25 import java.util.List;
26
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.http.HttpStatus;
29 import org.onap.so.client.exception.BadResponseException;
30 import org.onap.so.client.exception.MapperException;
31 import org.onap.so.logger.MessageEnum;
32 import org.onap.so.logger.MsoLogger;
33 import org.springframework.http.HttpHeaders;
34 import org.springframework.http.MediaType;
35 import org.springframework.stereotype.Component;
36 import org.springframework.util.CollectionUtils;
37
38 import com.fasterxml.jackson.annotation.JsonInclude;
39 import com.fasterxml.jackson.core.JsonProcessingException;
40 import com.fasterxml.jackson.databind.ObjectMapper;
41
42 @Component
43 public class SdnCommonTasks {
44
45     private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCClient.class);
46     private static final String RESPONSE_CODE = "response-code";
47     private static final String RESPONSE_MESSAGE = "response-message";
48     private static final String NO_RESPONSE_FROM_SDNC = "Error did not receive a response from SDNC.";
49     private static final String BAD_RESPONSE_FROM_SDNC = "Error received a bad response from SDNC.";
50     private static final String SDNC_CODE_NOT_0_OR_IN_200_299 = "Error from SDNC: %s";
51     private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON = "ERROR: Could not convert SDNC pojo to json string.";
52
53     /***
54      * 
55      * @param request
56      * @return
57      * @throws MapperException
58      */
59     public String buildJsonRequest(Object request) throws MapperException {
60         String jsonRequest;
61         ObjectMapper objMapper = new ObjectMapper();
62         objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
63         try {
64             jsonRequest = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
65         } catch (JsonProcessingException e) {
66             msoLogger.error(MessageEnum.JAXB_EXCEPTION, COULD_NOT_CONVERT_SDNC_POJO_TO_JSON, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, e.getMessage());
67             throw new MapperException(COULD_NOT_CONVERT_SDNC_POJO_TO_JSON);
68         }
69         jsonRequest = "{\"input\":" + jsonRequest + "}";
70         msoLogger.info(jsonRequest);
71         return jsonRequest;
72     }
73
74     /***
75      * 
76      * @param auth
77      * @return
78      */
79     public HttpHeaders getHttpHeaders(String auth) {
80         HttpHeaders httpHeader = new HttpHeaders();
81         httpHeader.set("Authorization", auth);
82         httpHeader.setContentType(MediaType.APPLICATION_JSON);
83         List<MediaType> acceptMediaTypes = new ArrayList<MediaType>();
84         acceptMediaTypes.add(MediaType.APPLICATION_JSON);
85         httpHeader.setAccept(acceptMediaTypes);
86         return httpHeader;
87     }
88
89     /***
90      * 
91      * @param output
92      * @return
93      * @throws BadResponseException
94      */
95         public String validateSDNResponse(LinkedHashMap<?, ?> output) throws BadResponseException {
96                 if (CollectionUtils.isEmpty(output)) {
97                         msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN",
98                                         MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC);
99                         throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
100                 }
101         LinkedHashMap<?, ?> embeddedResponse =(LinkedHashMap<?, ?>) output.get("output");
102         String responseCode = "";
103         String responseMessage = "";
104         if (embeddedResponse != null) {
105                 responseCode = (String) embeddedResponse.get(RESPONSE_CODE);
106             responseMessage = (String) embeddedResponse.get(RESPONSE_MESSAGE);
107         }
108         
109                 msoLogger.info("ResponseCode: " + responseCode + " ResponseMessage: " + responseMessage);
110                 int code = StringUtils.isNotEmpty(responseCode) ? Integer.parseInt(responseCode) : 0;
111                 if (isHttpCodeSuccess(code)) {
112                         msoLogger.info("Successful Response from SDNC");
113                         return responseMessage;
114                 } else {
115                         String errorMessage = String.format(SDNC_CODE_NOT_0_OR_IN_200_299, responseMessage);
116                         msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, errorMessage, "BPMN", MsoLogger.getServiceName(),
117                                         MsoLogger.ErrorCode.DataError, errorMessage);
118                         throw new BadResponseException(errorMessage);
119                 }
120         }
121     
122     /***
123      * 
124      * @param output
125      * @return
126      * @throws BadResponseException
127      */
128     public String validateSDNGetResponse(LinkedHashMap<?, ?> output) throws BadResponseException {
129         if (CollectionUtils.isEmpty(output)) {
130             msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC);
131             throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
132         }
133         ObjectMapper objMapper = new ObjectMapper();
134         msoLogger.debug("Using object mapper");
135         String stringOutput = "";
136         try {
137                 stringOutput = objMapper.writeValueAsString(output);
138         }
139         catch (Exception e) {
140                 msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, BAD_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, BAD_RESPONSE_FROM_SDNC);
141             throw new BadResponseException(BAD_RESPONSE_FROM_SDNC);
142         }
143         msoLogger.debug("Received from GET request: " + stringOutput);
144         return stringOutput;
145     }
146
147     private boolean isHttpCodeSuccess(int code) {
148         return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0;
149     }
150 }