d0973d3c44884926a25a6c29c30f92d8f80335fc
[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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.adapters.sdnc.sdncrest;
24
25 import java.io.StringWriter;
26
27 import javax.xml.XMLConstants;
28 import javax.xml.parsers.DocumentBuilder;
29 import javax.xml.parsers.DocumentBuilderFactory;
30 import javax.xml.transform.OutputKeys;
31 import javax.xml.transform.Transformer;
32 import javax.xml.transform.TransformerFactory;
33 import javax.xml.transform.dom.DOMSource;
34 import javax.xml.transform.stream.StreamResult;
35
36 import org.apache.http.HttpStatus;
37 import org.onap.so.adapters.sdnc.exception.SDNCAdapterException;
38 import org.onap.so.adapters.sdncrest.RequestInformation;
39 import org.onap.so.adapters.sdncrest.SDNCResponseCommon;
40 import org.onap.so.adapters.sdncrest.SDNCServiceError;
41 import org.onap.so.adapters.sdncrest.SDNCServiceRequest;
42 import org.onap.so.logger.MessageEnum;
43 import org.onap.so.logger.MsoLogger;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.scheduling.annotation.Async;
48 import org.springframework.stereotype.Component;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51
52 @Component
53 public class SDNCServiceRequestTask {
54         private static final Logger logger =  LoggerFactory.getLogger(SDNCServiceRequestTask.class);
55
56         @Autowired
57         private SDNCServiceRequestConnector connector;
58         
59         @Autowired
60         MapTypedRequestTunablesData mapTunables;
61         
62         @Autowired
63         private BPRestCallback bpRestCallback;
64
65         @Async
66         public void runRequest(SDNCServiceRequest request,String msoRequestId,String msoServiceInstanceId,String myUrlSuffix)
67         {
68                 MsoLogger.setLogContext(msoRequestId, msoServiceInstanceId);
69
70                 String sdncRequestId = request.getSdncRequestId();
71                 String sdncService = request.getSdncService();
72                 String sdncOperation = request.getSdncOperation();
73
74                 TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix);
75                 rt.setServiceKey(sdncService, sdncOperation);
76                 TypedRequestTunables mappedTunables;
77                 try {
78                         mappedTunables = mapTunables.setTunables(rt);
79                 } catch(SDNCAdapterException e) {
80                         bpRestCallback.send(request.getBPNotificationUrl(), e.getMessage());
81                         return;
82                 }
83                 if (!mappedTunables.getError().isEmpty()) {
84                         // Note that the error was logged and alarmed by setTunables()
85                         SDNCServiceError error = new SDNCServiceError(request.getSdncRequestId(),
86                                 String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), mappedTunables.getError(), "Y");
87                         bpRestCallback.send(request.getBPNotificationUrl(), error.toJson());
88                         return;
89                 }
90
91                 String xml = genSdncReq(request, mappedTunables);
92
93                 long sdncStartTime = System.currentTimeMillis();                
94                 SDNCResponseCommon response = connector.send(xml, mappedTunables);
95
96                 long bpStartTime = System.currentTimeMillis();
97                 boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson());
98         }
99
100         private Element addChild(Element parent, String tag) {
101                 Element child = parent.getOwnerDocument().createElement(tag);
102                 parent.appendChild(child);
103                 return child;
104         }
105
106         private void addTextChild(Element parent, String tag, String text) {
107                 if (text != null) {
108                         Element child = parent.getOwnerDocument().createElement(tag);
109                         child.setTextContent(text);
110                         parent.appendChild(child);
111                 }
112         }
113
114         private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) {
115                 Document doc;
116
117                 try {
118                         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
119                         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
120
121                         doc = documentBuilder.newDocument();
122                         Element root = doc.createElementNS(rt.getNamespace(), "input");
123                         doc.appendChild(root);
124
125                         Element hdr = addChild(root, rt.getHeaderName());
126                         addTextChild(hdr, "svc-request-id", rt.getReqId());
127                         addTextChild(hdr, "svc-notification-url", rt.getMyUrl());
128
129                         RequestInformation requestInfo = request.getRequestInformation();
130                         Element requestInformation = addChild(root, "request-information");
131                         addTextChild(requestInformation, "request-id", requestInfo.getRequestId());
132                 
133                         
134                         if(requestInfo.getRequestAction()!= null) {
135                                 addTextChild(requestInformation, "request-action",
136                                                 requestInfo.getRequestAction());
137                         }
138                         if(requestInfo.getRequestSubAction()!= null) {
139                                 addTextChild(requestInformation, "request-sub-action",
140                                                 requestInfo.getRequestSubAction());
141                         }
142                         if(requestInfo.getOrderNumber() != null &&
143                                         !requestInfo.getOrderNumber().isEmpty() ) {
144                                 addTextChild(requestInformation, "order-number",
145                                                 requestInfo.getOrderNumber());
146                         }
147                         
148                         if(requestInfo.getOrderVersion() != null &&
149                                         !requestInfo.getOrderVersion().isEmpty() ) {
150                                 addTextChild(requestInformation, "order-version",
151                                                 requestInfo.getOrderVersion());
152                         }
153                         
154                         
155                         addTextChild(requestInformation, "source", requestInfo.getSource());
156                         addTextChild(requestInformation, "notification-url", requestInfo.getNotificationUrl());
157
158                         Element serviceInformation = addChild(root, "service-information");
159                         addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
160                         addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId());
161                         addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
162                         addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId());
163
164                         Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
165                         addTextChild(agnosticServiceInformation, "operation", request.getSdncOperation());
166                         addTextChild(agnosticServiceInformation, "service", request.getSdncService());
167
168                         // anydata is mandatory in the SDNC schema, so if the data we got is null,
169                         // set use an empty string instead to ensure we generate an empty element.
170
171                         String anydata = request.getSdncServiceData();
172                         if (anydata == null) {
173                                 anydata = "";
174                         }
175
176                         // content-type is also mandatory.
177
178                         String contentType = request.getSdncServiceDataType();
179
180                         if (contentType == null || contentType.isEmpty()) {
181                                 if (anydata.isEmpty()) {
182                                         contentType = "XML";
183                                 } else {
184                                         if (anydata.startsWith("<")) {
185                                                 contentType = "XML";
186                                         } else {
187                                                 contentType = "JSON";
188                                         }
189                                 }
190                         }
191
192                         addTextChild(agnosticServiceInformation, "content-type", contentType);
193                         addTextChild(agnosticServiceInformation, "anydata", anydata);
194                 } catch (Exception e) {
195                         logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
196                                         MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
197                         return null;
198                 }
199
200                 String xml;
201
202                 try {
203                         StringWriter writer = new StringWriter();
204                         TransformerFactory factory = TransformerFactory.newInstance();
205                         factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");
206                         factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
207                         Transformer transformer = factory.newTransformer();
208                         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
209                         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
210                         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
211                         transformer.transform(new DOMSource(doc), new StreamResult(writer));
212                         xml = writer.toString();
213                 } catch (Exception e) {
214                         logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), MsoLogger.ErrorCode.DataError.getValue(),
215                                         "Exception - domToStr", e);
216                         return null;
217                 }
218
219                 logger.trace("Formatted SDNC service request XML:\n {}", xml);
220                 return xml;
221         }
222 }