Merge "fixed major sonar isue in CreatNetworkNotification"
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / onap / so / adapters / sdnc / sdncrest / SDNCServiceRequestConnector.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (C) 2018 IBM.
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.adapters.sdnc.sdncrest;
25
26 import java.io.IOException;
27 import java.io.StringReader;
28 import java.net.HttpURLConnection;
29 import java.text.ParseException;
30 import java.util.ArrayList;
31 import java.util.List;
32
33 import javax.xml.XMLConstants;
34 import javax.xml.parsers.DocumentBuilderFactory;
35 import javax.xml.parsers.ParserConfigurationException;
36
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.SDNCServiceResponse;
41 import org.onap.so.logger.MsoLogger;
42 import org.springframework.stereotype.Component;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.SAXException;
47
48 /**
49  * SDNCConnector for "agnostic" API services.
50  */
51
52 @Component
53 public class SDNCServiceRequestConnector extends SDNCConnector {
54
55     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,SDNCServiceRequestConnector.class);
56         @Override
57         protected SDNCResponseCommon createResponseFromContent(int statusCode, String statusMessage,
58                         String responseContent, TypedRequestTunables rt) {
59                 try {
60                         return parseResponseContent(responseContent);
61                 } catch (ParseException e) {
62                         LOGGER.error(e);
63                         return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
64                 }catch (Exception e) {
65                         LOGGER.error(e);
66                         return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt);
67                 }
68         }
69
70         @Override
71         protected SDNCErrorCommon createErrorResponse(int statusCode, String errMsg,
72                         TypedRequestTunables rt) {
73                 return new SDNCServiceError(rt.getReqId(), String.valueOf(statusCode), errMsg, "Y");
74         }
75
76         /**
77          * Parses SDNC synchronous service response content or service notification content.
78          * If the content can be parsed and contains all required elements, then an object
79          * is returned.  The type of the returned object depends on the response code
80          * contained in the content.  For 2XX response codes, an SDNCServiceResponse is
81          * returned.  Otherwise, an SDNCServiceError is returned.  If the content cannot
82          * be parsed, or if the content does not contain all required elements, a parse
83          * exception is thrown.  This method performs no logging or alarming.
84          * @throws ParseException on error
85          */
86         public static SDNCResponseCommon parseResponseContent(String responseContent)
87                         throws ParseException,ParserConfigurationException, SAXException, IOException{
88
89                         // Note: this document builder is not namespace-aware, so namespaces are ignored.
90                         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
91                         documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
92                     documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
93                     documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
94                         InputSource source = new InputSource(new StringReader(responseContent));
95                         Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
96
97                         // Find the configuration-response-common child under the root element.
98                         // The root element is expected to be an "output" element, but we don't really care.
99
100                         Element root = doc.getDocumentElement();
101                         Element configurationResponseCommon = null;
102
103                         for (Element child : SDNCAdapterUtils.childElements(root)) {
104                                 if ("configuration-response-common".equals(child.getNodeName())) {
105                                         configurationResponseCommon = child;
106                                         break;
107                                 }
108                         }
109
110                         if (configurationResponseCommon == null) {
111                                 throw new ParseException("No configuration-response-common element in SDNC response", 0);
112                         }
113
114                         // Process the children of configuration-response-common.
115
116                         String responseCode = null;
117                         String responseMessage = null;
118                         String svcRequestId = null;
119                         String ackFinalIndicator = null;
120                         List<Element> responseParameters = new ArrayList<>();
121
122                         for (Element child : SDNCAdapterUtils.childElements(configurationResponseCommon)) {
123                                 if ("response-code".equals(child.getNodeName())) {
124                                         responseCode = child.getTextContent();
125                                 } else if ("response-message".equals(child.getNodeName())) {
126                                         responseMessage = child.getTextContent();
127                                 } else if ("svc-request-id".equals(child.getNodeName())) {
128                                         svcRequestId = child.getTextContent();
129                                 } else if ("ack-final-indicator".equals(child.getNodeName())) {
130                                         ackFinalIndicator = child.getTextContent();
131                                 } else if ("response-parameters".equals(child.getNodeName())) {
132                     responseParameters.add(child);
133                                 }
134                         }
135
136                         // svc-request-id is mandatory.
137
138                         if (svcRequestId == null || svcRequestId.isEmpty()) {
139                                 throw new ParseException("No svc-request-id in SDNC response", 0);
140                         }
141
142                         // response-code is mandatory.
143
144                         if (responseCode == null || responseCode.isEmpty()) {
145                                 throw new ParseException("No response-code in SDNC response", 0);
146                         }
147
148                         // ack-final-indicator is optional: default to "Y".
149
150                         if (ackFinalIndicator == null || ackFinalIndicator.trim().isEmpty()) {
151                                 ackFinalIndicator = "Y";
152                         }
153
154                         if (!"Y".equals(ackFinalIndicator) && !"N".equals(ackFinalIndicator)) {
155                                 throw new ParseException("Invalid ack-final-indicator in SDNC response: '" + ackFinalIndicator + "'", 0);
156                         }
157
158                         // response-message is optional.  If the value is empty, omit it from the response object.
159
160                         if (responseMessage != null && responseMessage.isEmpty()) {
161                                 responseMessage = null;
162                         }
163
164                         // If the response code in the message from SDNC was not 2XX, return SDNCServiceError.
165
166                         if (!responseCode.matches("2[0-9][0-9]") && !("0").equals(responseCode)) {
167                                 // Not a 2XX response.  Return SDNCServiceError.
168                                 return new SDNCServiceError(svcRequestId, responseCode, responseMessage, ackFinalIndicator);
169                         }
170
171                         // Create a success response object.
172
173                         SDNCServiceResponse response = new SDNCServiceResponse(svcRequestId,
174                                 responseCode, responseMessage, ackFinalIndicator);
175
176             // Process any response-parameters that might be present.
177
178             for (Element element : responseParameters) {
179                 String tagName = null;
180                 String tagValue = null;
181
182                 for (Element child : SDNCAdapterUtils.childElements(element)) {
183                     if ("tag-name".equals(child.getNodeName())) {
184                         tagName = child.getTextContent();
185                     } else if ("tag-value".equals(child.getNodeName())) {
186                         tagValue = child.getTextContent();
187                     }
188                 }
189
190                 // tag-name is mandatory
191
192                 if (tagName == null) {
193                     throw new ParseException("Missing tag-name in SDNC response parameter", 0);
194                 }
195
196                 // tag-value is optional.  If absent, make it an empty string so we don't
197                 // end up with null values in the parameter map.
198
199                 if (tagValue == null) {
200                     tagValue = "";
201                 }
202
203                 response.addParam(tagName, tagValue);
204             }
205
206                         return response;
207                 
208         }
209 }