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