2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.client.sdnc.sync;
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;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.List;
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;
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;
66 //SDNCAdapter to SDNC Rest Client
67 public class SDNCSyncRpcClient implements Runnable {
69 private MsoPropertiesFactory msoPropertiesFactory;
71 private SDNCRequest bpelRequest;
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";
78 public SDNCSyncRpcClient(SDNCRequest bpelRequest,MsoPropertiesFactory msoPropFactory) {
79 this.bpelRequest = bpelRequest;
80 msoPropertiesFactory = msoPropFactory;
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 = "";
94 msoLogger.debug("BPEL Request:" + bpelRequest.toString());
95 RequestTunables rt = new RequestTunables(bpelReqId, msoAction, operation, action, msoPropertiesFactory);
97 rt.setSdncaNotificationUrl(SDNCAdapterPortTypeImpl.getProperty(Constants.MY_URL_PROP, Constants.DEFAULT_MY_URL,msoPropertiesFactory));
99 if ("POST".equals(rt.getReqMethod())) {
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();
109 } else if("PUT".equals(rt.getReqMethod())) {
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();
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());
129 public static SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt, MsoPropertiesFactory msoPropertiesFactoryp) {
131 HttpURLConnection con = null;
132 DataOutputStream out = null;
133 BufferedReader in = null;
134 SDNCResponse sdncResp = new SDNCResponse(rt.getReqId());
135 StringBuffer response = new StringBuffer();
137 msoLogger.info(MessageEnum.RA_SEND_REQUEST_SDNC, rt.toString(), "SDNC", "");
138 msoLogger.debug("SDNC Request Body:\n" + sdncReqBody);
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);
149 String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
150 con.setRequestProperty ("Authorization", basicAuth);
151 con.setRequestMethod(rt.getReqMethod());
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);
164 sdncResp.setRespCode(con.getResponseCode());
165 sdncResp.setRespMsg(con.getResponseMessage());
167 if (con.getResponseCode()>= 200 && con.getResponseCode()<=299) {
168 in = new BufferedReader(new InputStreamReader(con.getInputStream()));
170 //Not parsing the response -it contains a responseHdr section and data section
171 while ((inputLine = in.readLine()) != null) {
172 response.append(inputLine);
177 sdncResp.setSdncResp(response.toString());
178 msoLogger.info(MessageEnum.RA_RESPONSE_FROM_SDNC, sdncResp.toString(), "SDNC", "");
180 } catch (Exception e) {
181 msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception processing request to SDNC", e);
183 sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
184 String respMsg = "Error processing request to SDNC. ";
185 String sdncErrMsg = null;
187 if (e instanceof java.net.SocketTimeoutException ) {
188 sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT);
189 respMsg = "Request to SDNC timed out. ";
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();
198 XPathFactory xpathFactory = XPathFactory.newInstance();
199 XPath xpath = xpathFactory.newXPath();
200 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
201 dbf.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true);
205 db = dbf.newDocumentBuilder();
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);
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);
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);
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);
234 } catch (Exception e2) {
235 msoLogger.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while analyse error", e2);
238 } catch (Exception e1) {
239 msoLogger.error (MessageEnum.RA_ERROR_GET_RESPONSE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception while get SDNC response", e1);
243 if (e.getMessage() != null) {
244 respMsg = respMsg + e.getMessage();
246 if (sdncErrMsg != null) {
247 respMsg = respMsg + sdncErrMsg;
250 sdncResp.setRespMsg(respMsg);
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);
262 public void validateSDNCResponse (String sdncResponse){
264 msoLogger.debug ("Starting validate sdnc response");
265 String responseMessage = "";
266 String responseCode = "";
267 if (sdncResponse != null || !sdncResponse.equals("")){
269 msoLogger.debug ("Got the SDNC Response: " + sdncResponse);
270 JSONObject jsonObj = new JSONObject(sdncResponse);
271 msoLogger.debug ("jsonObj has been created");
273 JSONObject requestData = jsonObj.getJSONObject("v1:RequestData");
274 JSONObject output = requestData.getJSONObject("output");
276 responseMessage = output.getString("response-message");
277 responseCode = output.getString("response-code");
278 } catch (Exception ex) {
279 msoLogger.debug("Response not in lower hyphen");
281 if(responseMessage.equals("")&&responseCode.equals("")){
283 responseMessage = output.getString("ResponseMessage");
284 responseCode = output.getString("ResponseCode");
285 } catch (Exception ex) {
286 msoLogger.debug("Response does not exist");
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);
297 if(responseCode.equals("")){
301 int code = Integer.parseInt(responseCode);
302 if(code >=200 && code <=299 || code ==0){
303 msoLogger.debug ("Successful Response from SDNC");
306 msg = "Error from SDNC: Code is not 200-299 or 0.";
307 msoLogger.debug(msg);
308 throw new IllegalStateException(msg);
310 } catch (Exception ex) {
311 msg = "Validate SDNC Response has failed.";
312 msoLogger.debug(msg);
313 throw new IllegalStateException(msg);