62233273b129c493c608a3578888fc1df38491c9
[so.git] /
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                 MsoLogger.setServiceName(getClass().getSimpleName());
70
71                 String sdncRequestId = request.getSdncRequestId();
72                 String sdncService = request.getSdncService();
73                 String sdncOperation = request.getSdncOperation();
74
75                 TypedRequestTunables rt = new TypedRequestTunables(sdncRequestId, myUrlSuffix);
76                 rt.setServiceKey(sdncService, sdncOperation);
77                 TypedRequestTunables mappedTunables;
78                 try {
79                         mappedTunables = mapTunables.setTunables(rt);
80                 } catch(SDNCAdapterException e) {
81                         bpRestCallback.send(request.getBPNotificationUrl(), e.getMessage());
82                         return;
83                 }
84                 if (!mappedTunables.getError().isEmpty()) {
85                         // Note that the error was logged and alarmed by setTunables()
86                         SDNCServiceError error = new SDNCServiceError(request.getSdncRequestId(),
87                                 String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), mappedTunables.getError(), "Y");
88                         bpRestCallback.send(request.getBPNotificationUrl(), error.toJson());
89                         return;
90                 }
91
92                 String xml = genSdncReq(request, mappedTunables);
93
94                 long sdncStartTime = System.currentTimeMillis();                
95                 SDNCResponseCommon response = connector.send(xml, mappedTunables);
96
97                 long bpStartTime = System.currentTimeMillis();
98                 boolean callbackSuccess = bpRestCallback.send(request.getBPNotificationUrl(), response.toJson());
99         }
100
101         private Element addChild(Element parent, String tag) {
102                 Element child = parent.getOwnerDocument().createElement(tag);
103                 parent.appendChild(child);
104                 return child;
105         }
106
107         private void addTextChild(Element parent, String tag, String text) {
108                 if (text != null) {
109                         Element child = parent.getOwnerDocument().createElement(tag);
110                         child.setTextContent(text);
111                         parent.appendChild(child);
112                 }
113         }
114
115         private String genSdncReq(SDNCServiceRequest request, TypedRequestTunables rt) {
116                 Document doc;
117
118                 try {
119                         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
120                         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
121
122                         doc = documentBuilder.newDocument();
123                         Element root = doc.createElementNS(rt.getNamespace(), "input");
124                         doc.appendChild(root);
125
126                         Element hdr = addChild(root, rt.getHeaderName());
127                         addTextChild(hdr, "svc-request-id", rt.getReqId());
128                         addTextChild(hdr, "svc-notification-url", rt.getMyUrl());
129
130                         RequestInformation requestInfo = request.getRequestInformation();
131                         Element requestInformation = addChild(root, "request-information");
132                         addTextChild(requestInformation, "request-id", requestInfo.getRequestId());
133                 
134                         
135                         if(requestInfo.getRequestAction()!= null) {
136                                 addTextChild(requestInformation, "request-action",
137                                                 requestInfo.getRequestAction());
138                         }
139                         if(requestInfo.getRequestSubAction()!= null) {
140                                 addTextChild(requestInformation, "request-sub-action",
141                                                 requestInfo.getRequestSubAction());
142                         }
143                         if(requestInfo.getOrderNumber() != null &&
144                                         !requestInfo.getOrderNumber().isEmpty() ) {
145                                 addTextChild(requestInformation, "order-number",
146                                                 requestInfo.getOrderNumber());
147                         }
148                         
149                         if(requestInfo.getOrderVersion() != null &&
150                                         !requestInfo.getOrderVersion().isEmpty() ) {
151                                 addTextChild(requestInformation, "order-version",
152                                                 requestInfo.getOrderVersion());
153                         }
154                         
155                         
156                         addTextChild(requestInformation, "source", requestInfo.getSource());
157                         addTextChild(requestInformation, "notification-url", requestInfo.getNotificationUrl());
158
159                         Element serviceInformation = addChild(root, "service-information");
160                         addTextChild(serviceInformation, "service-type", request.getServiceInformation().getServiceType());
161                         addTextChild(serviceInformation, "service-instance-id", request.getServiceInformation().getServiceInstanceId());
162                         addTextChild(serviceInformation, "subscriber-name", request.getServiceInformation().getSubscriberName());
163                         addTextChild(serviceInformation, "subscriber-global-id", request.getServiceInformation().getSubscriberGlobalId());
164
165                         Element agnosticServiceInformation = addChild(root, "agnostic-service-information");
166                         addTextChild(agnosticServiceInformation, "operation", request.getSdncOperation());
167                         addTextChild(agnosticServiceInformation, "service", request.getSdncService());
168
169                         // anydata is mandatory in the SDNC schema, so if the data we got is null,
170                         // set use an empty string instead to ensure we generate an empty element.
171
172                         String anydata = request.getSdncServiceData();
173                         if (anydata == null) {
174                                 anydata = "";
175                         }
176
177                         // content-type is also mandatory.
178
179                         String contentType = request.getSdncServiceDataType();
180
181                         if (contentType == null || contentType.isEmpty()) {
182                                 if (anydata.isEmpty()) {
183                                         contentType = "XML";
184                                 } else {
185                                         if (anydata.startsWith("<")) {
186                                                 contentType = "XML";
187                                         } else {
188                                                 contentType = "JSON";
189                                         }
190                                 }
191                         }
192
193                         addTextChild(agnosticServiceInformation, "content-type", contentType);
194                         addTextChild(agnosticServiceInformation, "anydata", anydata);
195                 } catch (Exception e) {
196                         logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC",
197                                         MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e);
198                         return null;
199                 }
200
201                 String xml;
202
203                 try {
204                         StringWriter writer = new StringWriter();
205                         TransformerFactory factory = TransformerFactory.newInstance();
206                         factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");
207                         factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
208                         Transformer transformer = factory.newTransformer();
209                         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
210                         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
211                         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
212                         transformer.transform(new DOMSource(doc), new StreamResult(writer));
213                         xml = writer.toString();
214                 } catch (Exception e) {
215                         logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), MsoLogger.ErrorCode.DataError.getValue(),
216                                         "Exception - domToStr", e);
217                         return null;
218                 }
219
220                 logger.trace("Formatted SDNC service request XML:\n {}", xml);
221                 return xml;
222         }
223 }