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