e52a426b4db740adf43b74a5b0601777622e0273
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / openecomp / mso / adapters / sdnc / sdncrest / SDNCServiceRequestTask.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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                         addTextChild(requestInformation, "source", request.getRequestInformation().getSource());
142                         addTextChild(requestInformation, "notification-url", request.getRequestInformation().getNotificationUrl());
143
144                         Element serviceInformation = addChild(root, "service-information");
145                         addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
146                         addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId());
147                         addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
148                         addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId());
149
150                         Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
151                         addTextChild(agnosticServiceInformation, "operation", request.getSDNCOperation());
152                         addTextChild(agnosticServiceInformation, "service", request.getSDNCService());
153
154                         // anydata is mandatory in the SDNC schema, so if the data we got is null,
155                         // set use an empty string instead to ensure we generate an empty element.
156
157                         String anydata = request.getSDNCServiceData();
158                         if (anydata == null) {
159                                 anydata = "";
160                         }
161
162                         // content-type is also mandatory.
163
164                         String contentType = request.getSDNCServiceDataType();
165
166                         if (contentType == null || contentType.isEmpty()) {
167                                 if (anydata.isEmpty()) {
168                                         contentType = "XML";
169                                 } else {
170                                         if (anydata.startsWith("<")) {
171                                                 contentType = "XML";
172                                         } else {
173                                                 contentType = "JSON";
174                                         }
175                                 }
176                         }
177
178                         addTextChild(agnosticServiceInformation, "content-type", contentType);
179                         addTextChild(agnosticServiceInformation, "anydata", anydata);
180                 } catch (Exception e) {
181                         LOGGER.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "",
182                                         MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e);
183                         return null;
184                 }
185
186                 String xml;
187
188                 try {
189                         StringWriter writer = new StringWriter();
190                         Transformer transformer = TransformerFactory.newInstance().newTransformer();
191                         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
192                         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
193                         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
194                         transformer.transform(new DOMSource(doc), new StreamResult(writer));
195                         xml = writer.toString();
196                 } catch (Exception e) {
197                         LOGGER.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "",
198                                 MsoLogger.ErrorCode.DataError, "Exception - domToStr", e);
199                         return(null);
200                 }
201
202                 LOGGER.debug("Formatted SDNC service request XML:\n" + xml);
203                 return xml;
204         }
205 }