aefb84c6065b0b397fe062cdab7886d64527aaf4
[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.json.JSONObject;
30 import org.onap.so.client.exception.BadResponseException;
31 import org.onap.so.client.exception.MapperException;
32 import org.onap.so.logger.MessageEnum;
33 import org.onap.so.logger.MsoLogger;
34 import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
35 import org.springframework.http.HttpEntity;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.MediaType;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.http.client.BufferingClientHttpRequestFactory;
40 import org.springframework.http.client.SimpleClientHttpRequestFactory;
41 import org.springframework.stereotype.Component;
42 import org.springframework.util.CollectionUtils;
43 import org.springframework.web.client.RestTemplate;
44
45 import com.fasterxml.jackson.annotation.JsonInclude;
46 import com.fasterxml.jackson.core.JsonProcessingException;
47 import com.fasterxml.jackson.databind.ObjectMapper;
48
49 @Component
50 public class SdnCommonTasks {
51
52     private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCClient.class);
53     private static final String RESPONSE_CODE = "response-code";
54     private static final String RESPONSE_MESSAGE = "response-message";
55     private static final String NO_RESPONSE_FROM_SDNC = "Error did not receive a response from SDNC.";
56     private static final String BAD_RESPONSE_FROM_SDNC = "Error received a bad response from SDNC.";
57     private static final String SDNC_CODE_NOT_0_OR_IN_200_299 = "Error from SDNC: %s";
58     private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON = "ERROR: Could not convert SDNC pojo to json string.";
59
60     /***
61      * 
62      * @param request
63      * @return
64      * @throws MapperException
65      */
66     public String buildJsonRequest(Object request) throws MapperException {
67         String jsonRequest;
68         ObjectMapper objMapper = new ObjectMapper();
69         objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
70         try {
71             jsonRequest = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
72         } catch (JsonProcessingException e) {
73             msoLogger.error(MessageEnum.JAXB_EXCEPTION, COULD_NOT_CONVERT_SDNC_POJO_TO_JSON, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, e.getMessage());
74             throw new MapperException(COULD_NOT_CONVERT_SDNC_POJO_TO_JSON);
75         }
76         jsonRequest = "{\"input\":" + jsonRequest + "}";
77         msoLogger.info(jsonRequest);
78         return jsonRequest;
79     }
80
81     /***
82      * 
83      * @param auth
84      * @return
85      */
86     public HttpHeaders getHttpHeaders(String auth) {
87         HttpHeaders httpHeader = new HttpHeaders();
88         httpHeader.set("Authorization", auth);
89         httpHeader.setContentType(MediaType.APPLICATION_JSON);
90         List<MediaType> acceptMediaTypes = new ArrayList<MediaType>();
91         acceptMediaTypes.add(MediaType.APPLICATION_JSON);
92         httpHeader.setAccept(acceptMediaTypes);
93         return httpHeader;
94     }
95
96     /***
97      * 
98      * @param output
99      * @return
100      * @throws BadResponseException
101      */
102     public String validateSDNResponse(LinkedHashMap<?, ?> output) throws BadResponseException {
103         if (CollectionUtils.isEmpty(output)) {
104             msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC);
105             throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
106         }
107         String responseCode = (String) output.get(RESPONSE_CODE);
108         String responseMessage = (String) output.get(RESPONSE_MESSAGE);
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(), MsoLogger.ErrorCode.DataError, errorMessage);
117             throw new BadResponseException(errorMessage);
118         }
119     }
120     
121     /***
122      * 
123      * @param output
124      * @return
125      * @throws BadResponseException
126      */
127     public String validateSDNGetResponse(LinkedHashMap<?, ?> output) throws BadResponseException {
128         if (CollectionUtils.isEmpty(output)) {
129             msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC);
130             throw new BadResponseException(NO_RESPONSE_FROM_SDNC);
131         }
132         ObjectMapper objMapper = new ObjectMapper();
133         msoLogger.debug("Using object mapper");
134         String stringOutput = "";
135         try {
136                 stringOutput = objMapper.writeValueAsString(output);
137         }
138         catch (Exception e) {
139                 msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, BAD_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, BAD_RESPONSE_FROM_SDNC);
140             throw new BadResponseException(BAD_RESPONSE_FROM_SDNC);
141         }
142         msoLogger.debug("Received from GET request: " + stringOutput);
143         return stringOutput;
144     }
145
146     private boolean isHttpCodeSuccess(int code) {
147         return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0;
148     }
149 }