AT&T 1712 and 1802 release code
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / openecomp / mso / client / sdnc / sync / SDNCSyncRpcClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 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.openecomp.mso.client.sdnc.sync;
22
23
24 import java.io.BufferedReader;
25 import java.io.DataOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.StringReader;
30 import java.net.HttpURLConnection;
31 import java.net.MalformedURLException;
32 import java.net.URL;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.xml.XMLConstants;
39 import javax.xml.bind.DatatypeConverter;
40 import javax.xml.parsers.DocumentBuilder;
41 import javax.xml.parsers.DocumentBuilderFactory;
42 import javax.xml.parsers.ParserConfigurationException;
43 import javax.xml.ws.BindingProvider;
44 import javax.xml.ws.handler.MessageContext;
45 import javax.xml.xpath.XPath;
46 import javax.xml.xpath.XPathConstants;
47 import javax.xml.xpath.XPathFactory;
48
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51 import org.w3c.dom.Node;
52 import org.w3c.dom.NodeList;
53 import org.xml.sax.InputSource;
54 import org.xml.sax.SAXException;
55 import org.json.JSONArray;
56 import org.json.JSONObject;
57 import org.openecomp.mso.client.sdnc.beans.SDNCRequest;
58 import org.openecomp.mso.client.sdnc.beans.SDNCSvcAction;
59 import org.openecomp.mso.client.sdnc.beans.SDNCSvcOperation;
60 import org.openecomp.mso.logger.MsoAlarmLogger;
61 import org.openecomp.mso.logger.MsoLogger;
62 import org.openecomp.mso.logger.MessageEnum;
63 import org.openecomp.mso.properties.MsoJavaProperties;
64 import org.openecomp.mso.properties.MsoPropertiesFactory;
65
66 //SDNCAdapter to SDNC Rest Client
67 public class SDNCSyncRpcClient implements Runnable {
68
69         private MsoPropertiesFactory msoPropertiesFactory;
70         
71         private SDNCRequest bpelRequest;
72
73         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
74         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger();
75         public static final String MSO_PROP_SDNC_ADAPTER="MSO_PROP_SDNC_ADAPTER";
76
77
78         public SDNCSyncRpcClient(SDNCRequest bpelRequest,MsoPropertiesFactory msoPropFactory) {
79                 this.bpelRequest = bpelRequest;
80                 msoPropertiesFactory = msoPropFactory;
81         }
82
83         @Override
84         public void run()
85         {
86                 String action = bpelRequest.getSvcAction().toString();
87                 String operation = bpelRequest.getSvcOperation().toString();
88                 String bpelReqId = bpelRequest.getRequestId();
89                 String msoAction = bpelRequest.getMsoAction();
90                 MsoLogger.setLogContext(SDNCRequestIdUtil.getSDNCOriginalRequestId (bpelReqId), bpelRequest.getSvcInstanceId());
91                 MsoLogger.setServiceName("SDNCRestClient");
92                 String sdncReqBody = "";
93
94                 msoLogger.debug("BPEL Request:" + bpelRequest.toString());
95                 RequestTunables rt = new RequestTunables(bpelReqId, msoAction, operation, action, msoPropertiesFactory);
96                 rt.setTunables();
97                 rt.setSdncaNotificationUrl(SDNCAdapterPortTypeImpl.getProperty(Constants.MY_URL_PROP, Constants.DEFAULT_MY_URL,msoPropertiesFactory));
98
99                 if ("POST".equals(rt.getReqMethod())) {
100                         try {
101                                 DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
102                                 InputSource is = new InputSource();
103                                 is.setCharacterStream(new StringReader(bpelRequest.getRequestData()));
104                                 Document reqDoc = db.parse(is);
105                                 sdncReqBody = Utils.genSdncReq(reqDoc, rt);
106                         }catch(Exception ex) {
107                                 throw new IllegalStateException();
108                         }
109                 } else if("PUT".equals(rt.getReqMethod())) {
110                         try {
111                                 DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
112                                 InputSource is = new InputSource();
113                                 is.setCharacterStream(new StringReader(bpelRequest.getRequestData()));
114                                 Document reqDoc = db.parse(is);
115                                 sdncReqBody = Utils.genSdncPutReq(reqDoc, rt);
116                         }catch(Exception ex) {
117                                 throw new IllegalStateException();
118                         }
119                 }
120                 long sdncStartTime = System.currentTimeMillis();
121                 SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt, msoPropertiesFactory);
122                 msoLogger.recordMetricEvent (sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from SDNC", "SDNC", action + "." + operation, null);
123                 msoLogger.debug ("Got the SDNC Code : " + sdncResp.getRespCode());
124                 msoLogger.debug ("Got the SDNC Response Message:" + sdncResp.getRespMsg());
125                 validateSDNCResponse(sdncResp.getSdncResp());
126                 return;
127         }
128
129         public static SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt, MsoPropertiesFactory msoPropertiesFactoryp) {
130                 URL url;
131                 HttpURLConnection con = null;
132                 DataOutputStream out = null;
133                 BufferedReader in = null;
134                 SDNCResponse sdncResp = new SDNCResponse(rt.getReqId());
135                 StringBuffer response = new StringBuffer();
136
137                 msoLogger.info(MessageEnum.RA_SEND_REQUEST_SDNC, rt.toString(), "SDNC", "");
138                 msoLogger.debug("SDNC Request Body:\n" + sdncReqBody);
139
140                 try {
141                         msoLogger.debug("url is: " + rt.getSdncUrl());
142                         url = new URL(rt.getSdncUrl());
143                         con = (HttpURLConnection) url.openConnection();
144                     con.setConnectTimeout(Integer.parseInt(SDNCAdapterPortTypeImpl.getProperty(Constants.SDNC_CONNECTTIME_PROP, "2000",msoPropertiesFactoryp)));
145                     con.setReadTimeout(Integer.parseInt(rt.getTimeout()));
146                         con.setRequestProperty("Accept", "application/json");
147                         String userCredentials = msoPropertiesFactoryp.getMsoJavaProperties(MSO_PROP_SDNC_ADAPTER).getEncryptedProperty(Constants.SDNC_AUTH_PROP, Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
148
149                         String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
150                         con.setRequestProperty ("Authorization", basicAuth);
151                     con.setRequestMethod(rt.getReqMethod());
152
153                     if ("POST".equals(rt.getReqMethod()) || "PUT".equals(rt.getReqMethod())) {
154                         con.setRequestProperty("Content-type", "application/json");
155                         con.setRequestProperty("Content-length",String.valueOf(sdncReqBody.length()));
156                                 con.setDoOutput(true);
157                                 out = new DataOutputStream(con.getOutputStream());
158                                 out.writeBytes(sdncReqBody);
159                                 out.flush();
160                                 out.close();
161                     }
162
163                         //Get response
164                         sdncResp.setRespCode(con.getResponseCode());
165                         sdncResp.setRespMsg(con.getResponseMessage());
166
167                         if (con.getResponseCode()>= 200 && con.getResponseCode()<=299) { 
168                                 in = new BufferedReader(new InputStreamReader(con.getInputStream()));   
169                                 String inputLine;
170                                 //Not parsing the response -it contains a responseHdr section and data section
171                                 while ((inputLine = in.readLine()) != null) {
172                                         response.append(inputLine);
173                                 }
174                                 in.close();
175                         }
176                         
177                         sdncResp.setSdncResp(response.toString());
178                         msoLogger.info(MessageEnum.RA_RESPONSE_FROM_SDNC, sdncResp.toString(), "SDNC", "");
179                         return(sdncResp);
180                 } catch (Exception e) {
181                         msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception processing request to SDNC", e);
182                         //default
183                         sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
184                         String respMsg = "Error processing request to SDNC. ";
185                         String sdncErrMsg = null;
186
187                         if (e instanceof java.net.SocketTimeoutException ) {
188                                 sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT);
189                                 respMsg = "Request to SDNC timed out. ";
190                         }
191                         if (con != null) {
192                                 try { //e1
193                                         if (con.getResponseCode() != HttpURLConnection.HTTP_OK) //seen in SocketException connection reset 
194                                                 sdncResp.setRespCode(con.getResponseCode());
195                                         respMsg = respMsg + con.getResponseMessage() + ". ";
196                                         InputStream is = con.getErrorStream();
197                                         if (is != null) {
198                                                 XPathFactory xpathFactory = XPathFactory.newInstance();
199                                             XPath xpath = xpathFactory.newXPath();
200                                                 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
201                         dbf.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true);
202                                                 DocumentBuilder db;
203                                                 Document doc = null;
204                                                 try { //e2
205                                                         db = dbf.newDocumentBuilder();
206                                                         doc = db.parse(is);
207                                                         NodeList errors = (NodeList)xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
208                                                         for (int i = 0; i < errors.getLength(); i++) {
209                                                                 Element error = (Element) errors.item(i);
210                                                                 String eType = null;
211                                                                 try {
212                                                                         eType = xpath.evaluate("error-type", error);
213                                                                         sdncErrMsg = ". SDNC Returned-[error-type:" + eType;
214                                                                 } catch (Exception e3) {
215                                                                     msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
216                                                                 }
217
218                                                                 String eTag = null;
219                                                                 try {
220                                                                         eTag = xpath.evaluate( "error-tag", error);
221                                                                         sdncErrMsg = sdncErrMsg + ", error-tag:" + eTag;
222                                                                 } catch (Exception e3) {
223                                                                         msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
224                                                                 }
225
226                                                                 String eMsg = null;
227                                                                 try {
228                                                                         eMsg = xpath.evaluate("error-message", error);
229                                                                         sdncErrMsg = sdncErrMsg + ", error-message:" + eMsg + "]";
230                                                                 } catch (Exception e3) {
231                                                                         msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
232                                                                 }
233                                                         }
234                                                 } catch (Exception e2) {
235                                                     msoLogger.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while analyse error", e2);
236                                                 }
237                                         } //is != null
238                                 } catch (Exception e1) {
239                                         msoLogger.error (MessageEnum.RA_ERROR_GET_RESPONSE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception while get SDNC response", e1);
240                                 }
241                         } //con != null
242
243                         if (e.getMessage() != null) {
244                 respMsg = respMsg + e.getMessage();
245             }
246                         if (sdncErrMsg != null) {
247                 respMsg = respMsg + sdncErrMsg;
248             }
249
250                         sdncResp.setRespMsg(respMsg);
251
252                         msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with SDNC", e);
253                         alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, respMsg);
254                         return(sdncResp);
255                 }
256                 finally {
257                         if (con != null) {
258                 con.disconnect();
259             }
260                 }
261         }
262         public void validateSDNCResponse (String sdncResponse){
263                 String msg;
264                 msoLogger.debug ("Starting validate sdnc response");
265                 String responseMessage = "";
266                 String responseCode = "";
267                 if (sdncResponse != null || !sdncResponse.equals("")){
268                         try{
269                                 msoLogger.debug ("Got the SDNC Response: " + sdncResponse);
270                                 JSONObject jsonObj = new JSONObject(sdncResponse);
271                                 msoLogger.debug ("jsonObj has been created");
272                                 
273                                 JSONObject requestData = jsonObj.getJSONObject("v1:RequestData");
274                                 JSONObject output =  requestData.getJSONObject("output");
275                                 try{
276                                         responseMessage = output.getString("response-message");
277                                         responseCode = output.getString("response-code");       
278                                 } catch (Exception ex) {
279                                         msoLogger.debug("Response not in lower hyphen");
280                                 }
281                                 if(responseMessage.equals("")&&responseCode.equals("")){
282                                         try{
283                                                 responseMessage = output.getString("ResponseMessage");
284                                                 responseCode = output.getString("ResponseCode");        
285                                         } catch (Exception ex) {
286                                                 msoLogger.debug("Response does not exist");
287                                         }
288                                 }
289                                 msoLogger.debug("ResponseMessage is: " + responseMessage);
290                                 msoLogger.debug("Response Code is: " + responseCode);
291                                 if(responseMessage.equals("")){
292                                         msg = "Error from SDNC: Response Message is empty.";
293                                         msoLogger.debug(msg);
294                                         throw new IllegalStateException(msg);
295                                 }
296                                 
297                                 if(responseCode.equals("")){
298                                         responseCode = "0";
299                                 }
300                                 
301                                 int code = Integer.parseInt(responseCode);
302                                 if(code >=200 && code <=299 || code ==0){
303                                         msoLogger.debug ("Successful Response from SDNC");
304         
305                                 } else {
306                                         msg = "Error from SDNC: Code is not 200-299 or 0.";
307                                         msoLogger.debug(msg);
308                                         throw new IllegalStateException(msg);
309                                 }
310                         } catch (Exception ex) {
311                                 msg = "Validate SDNC Response has failed.";
312                                 msoLogger.debug(msg);
313                                 throw new IllegalStateException(msg);
314                         }
315                 }
316         }
317 }