AT&T 1712 and 1802 release code
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / openecomp / mso / adapters / sdnc / sdncrest / SDNCServiceRequestTask.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 package org.openecomp.mso.adapters.sdnc.sdncrest;
21
22 import org.openecomp.mso.adapters.sdncrest.SDNCErrorCommon;
23 import org.openecomp.mso.adapters.sdncrest.SDNCResponseCommon;
24 import org.openecomp.mso.adapters.sdncrest.SDNCServiceError;
25 import org.openecomp.mso.adapters.sdncrest.SDNCServiceRequest;
26 import org.openecomp.mso.logger.MessageEnum;
27 import org.openecomp.mso.logger.MsoLogger;
28 import org.apache.http.HttpStatus;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Element;
31
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Transformer;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.dom.DOMSource;
38 import javax.xml.transform.stream.StreamResult;
39 import java.io.StringWriter;
40
41 public class SDNCServiceRequestTask implements Runnable {
42         private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
43
44         private final SDNCServiceRequest request;
45         private final String msoRequestId;
46         private final String msoServiceInstanceId;
47         private final String myUrlSuffix;
48
49         public SDNCServiceRequestTask(SDNCServiceRequest request,
50                         String msoRequestId, String msoServiceInstanceId,
51                         String myUrlSuffix) {
52                 this.request = request;
53                 this.msoRequestId = msoRequestId;
54                 this.msoServiceInstanceId = msoServiceInstanceId;
55                 this.myUrlSuffix = myUrlSuffix;
56         }
57
58         @Override
59         public void run()
60         {
61                 MsoLogger.setLogContext(msoRequestId, msoServiceInstanceId);
62                 MsoLogger.setServiceName(getClass().getSimpleName());
63
64                 LOGGER.debug(getClass().getSimpleName() + ".run()"
65                         + " entered with request: " + request.toJson());
66
67                 String sdncRequestId = request.getSDNCRequestId();
68                 String sdncService = request.getSDNCService();
69                 String sdncOperation = request.getSDNCOperation();
70
71                 TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix);
72                 rt.setServiceKey(sdncService, sdncOperation);
73
74                 if (!rt.setTunables()) {
75                         // Note that the error was logged and alarmed by setTunables()
76                         SDNCServiceError error = new SDNCServiceError(request.getSDNCRequestId(),
77                                 String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), rt.getError(), "Y");
78                         BPRestCallback callback = new BPRestCallback();
79                         callback.send(request.getBPNotificationUrl(), error.toJson());
80                         return;
81                 }
82
83                 String xml = genSdncReq(request, rt);
84
85                 long sdncStartTime = System.currentTimeMillis();
86                 SDNCConnector connector = new SDNCServiceRequestConnector();
87                 SDNCResponseCommon response = connector.send(xml, rt);
88
89                 if (response instanceof SDNCErrorCommon) {
90                         LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
91                                 "Received success response from SDNC", "SDNC", sdncService + "." + sdncOperation, null);
92                 } else {
93                         LOGGER.recordMetricEvent(sdncStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
94                                 "Received error response from SDNC", "SDNC", sdncService + "." + sdncOperation, null);
95                 }
96
97                 long bpStartTime = System.currentTimeMillis();
98                 BPRestCallback callback = new BPRestCallback();
99                 boolean callbackSuccess = callback.send(request.getBPNotificationUrl(), response.toJson());
100
101                 if (callbackSuccess) {
102                         LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
103                                 "Sent notification", "BPMN", request.getBPNotificationUrl(), null);
104                 } else {
105                         LOGGER.recordMetricEvent(bpStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
106                                 "Failed to send notification", "BPMN", request.getBPNotificationUrl(), null);
107                 }
108         }
109
110         private Element addChild(Element parent, String tag) {
111                 Element child = parent.getOwnerDocument().createElement(tag);
112                 parent.appendChild(child);
113                 return child;
114         }
115
116         private void addTextChild(Element parent, String tag, String text) {
117                 if (text != null) {
118                         Element child = parent.getOwnerDocument().createElement(tag);
119                         child.setTextContent(text);
120                         parent.appendChild(child);
121                 }
122         }
123
124         private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) {
125                 Document doc;
126
127                 try {
128                         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
129                         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
130
131                         doc = documentBuilder.newDocument();
132                         Element root = doc.createElementNS(rt.getNamespace(), "input");
133                         doc.appendChild(root);
134
135                         Element hdr = addChild(root, rt.getHeaderName());
136                         addTextChild(hdr, "svc-request-id", rt.getReqId());
137                         addTextChild(hdr, "svc-notification-url", rt.getMyUrl());
138
139                         Element requestInformation = addChild(root, "request-information");
140                         addTextChild(requestInformation, "request-id", request.getRequestInformation().getRequestId());
141                         if(request.getRequestInformation().getRequestAction()!= null) {
142                                 addTextChild(requestInformation, "request-action",
143                                                 request.getRequestInformation().getRequestAction());
144                         }
145                         if(request.getRequestInformation().getRequestSubAction()!= null) {
146                                 addTextChild(requestInformation, "request-sub-action",
147                                                 request.getRequestInformation().getRequestSubAction());
148                         }
149                         addTextChild(requestInformation, "source", request.getRequestInformation().getSource());
150                         addTextChild(requestInformation, "notification-url", request.getRequestInformation().getNotificationUrl());
151
152                         Element serviceInformation = addChild(root, "service-information");
153                         addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
154                         addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId());
155                         addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
156                         addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId());
157
158                         Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
159                         addTextChild(agnosticServiceInformation, "operation", request.getSDNCOperation());
160                         addTextChild(agnosticServiceInformation, "service", request.getSDNCService());
161
162                         // anydata is mandatory in the SDNC schema, so if the data we got is null,
163                         // set use an empty string instead to ensure we generate an empty element.
164
165                         String anydata = request.getSDNCServiceData();
166                         if (anydata == null) {
167                                 anydata = "";
168                         }
169
170                         // content-type is also mandatory.
171
172                         String contentType = request.getSDNCServiceDataType();
173
174                         if (contentType == null || contentType.isEmpty()) {
175                                 if (anydata.isEmpty()) {
176                                         contentType = "XML";
177                                 } else {
178                                         if (anydata.startsWith("<")) {
179                                                 contentType = "XML";
180                                         } else {
181                                                 contentType = "JSON";
182                                         }
183                                 }
184                         }
185
186                         addTextChild(agnosticServiceInformation, "content-type", contentType);
187                         addTextChild(agnosticServiceInformation, "anydata", anydata);
188                 } catch (Exception e) {
189                         LOGGER.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "",
190                                         MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e);
191                         return null;
192                 }
193
194                 String xml;
195
196                 try {
197                         StringWriter writer = new StringWriter();
198                         Transformer transformer = TransformerFactory.newInstance().newTransformer();
199                         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
200                         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
201                         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
202                         transformer.transform(new DOMSource(doc), new StreamResult(writer));
203                         xml = writer.toString();
204                 } catch (Exception e) {
205                         LOGGER.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "",
206                                 MsoLogger.ErrorCode.DataError, "Exception - domToStr", e);
207                         return null;
208                 }
209
210                 LOGGER.debug("Formatted SDNC service request XML:\n" + xml);
211                 return xml;
212         }
213 }