Containerization feature of SO
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / onap / so / adapters / sdnc / sdncrest / SDNCConnector.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  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.so.adapters.sdnc.sdncrest;
23
24 import java.io.StringReader;
25 import java.net.HttpURLConnection;
26 import java.net.SocketTimeoutException;
27
28 import javax.xml.XMLConstants;
29 import javax.xml.bind.DatatypeConverter;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.xpath.XPath;
32 import javax.xml.xpath.XPathConstants;
33 import javax.xml.xpath.XPathExpressionException;
34 import javax.xml.xpath.XPathFactory;
35
36 import org.apache.http.HttpResponse;
37 import org.apache.http.client.HttpClient;
38 import org.apache.http.client.config.RequestConfig;
39 import org.apache.http.client.methods.HttpDelete;
40 import org.apache.http.client.methods.HttpGet;
41 import org.apache.http.client.methods.HttpPost;
42 import org.apache.http.client.methods.HttpPut;
43 import org.apache.http.client.methods.HttpRequestBase;
44 import org.apache.http.conn.ConnectTimeoutException;
45 import org.apache.http.entity.ContentType;
46 import org.apache.http.entity.StringEntity;
47 import org.apache.http.impl.client.HttpClientBuilder;
48 import org.apache.http.util.EntityUtils;
49 import org.onap.so.adapters.sdnc.impl.Constants;
50 import org.onap.so.adapters.sdncrest.SDNCErrorCommon;
51 import org.onap.so.adapters.sdncrest.SDNCResponseCommon;
52 import org.onap.so.logger.MessageEnum;
53 import org.onap.so.logger.MsoAlarmLogger;
54 import org.onap.so.logger.MsoLogger;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.stereotype.Component;
57 import org.w3c.dom.Document;
58 import org.w3c.dom.Element;
59 import org.w3c.dom.NodeList;
60 import org.xml.sax.InputSource;
61 import org.onap.so.utils.CryptoUtils;
62 import org.springframework.core.env.Environment;
63
64 /**
65  * Sends requests to SDNC and processes the responses.
66  */
67 @Component
68 public abstract class SDNCConnector {
69         private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,SDNCConnector.class);
70         private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
71         
72         @Autowired
73         private Environment env;
74
75         public SDNCResponseCommon send(String content, TypedRequestTunables rt) {
76                 LOGGER.debug("SDNC URL: " + rt.getSdncUrl());
77                 LOGGER.debug("SDNC Request Body:\n" + content);
78
79                 HttpRequestBase method = null;
80                 HttpResponse httpResponse = null;
81
82                 try {
83                         int timeout = Integer.parseInt(rt.getTimeout());
84
85                         RequestConfig requestConfig = RequestConfig.custom()
86                                 .setSocketTimeout(timeout)
87                                 .setConnectTimeout(timeout)
88                                 .setConnectionRequestTimeout(timeout)
89                                 .build();
90
91                         HttpClient client = HttpClientBuilder.create().build();
92
93                         if ("POST".equals(rt.getReqMethod())) {
94                                 HttpPost httpPost = new HttpPost(rt.getSdncUrl());
95                                 httpPost.setConfig(requestConfig);
96                                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
97                                 method =  httpPost;
98                         } else if ("PUT".equals(rt.getReqMethod())) {
99                                 HttpPut httpPut = new HttpPut(rt.getSdncUrl());
100                                 httpPut.setConfig(requestConfig);
101                                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML));
102                                 method =  httpPut;
103                         } else if ("GET".equals(rt.getReqMethod())) {
104                                 HttpGet httpGet = new HttpGet(rt.getSdncUrl());
105                                 httpGet.setConfig(requestConfig);
106                                 method =  httpGet;
107                         } else if ("DELETE".equals(rt.getReqMethod())) {
108                                 HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl());
109                                 httpDelete.setConfig(requestConfig);
110                                 method =  httpDelete;
111                         }
112
113                 
114                         String userCredentials = CryptoUtils.decryptProperty(env.getProperty(Constants.SDNC_AUTH_PROP),
115                                         Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
116                         String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
117                         if(null != method) {
118                             method.setHeader("Authorization", authorization);
119                             method.setHeader("Accept", "application/yang.data+xml");
120                         }
121                         else {
122                             LOGGER.debug("method is NULL:");
123                         }
124
125                         
126
127                         httpResponse = client.execute(method);
128
129                         String responseContent = null;
130                         if (httpResponse.getEntity() != null) {
131                                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
132                         }
133
134                         int statusCode = httpResponse.getStatusLine().getStatusCode();
135                         String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
136
137                         LOGGER.debug("SDNC Response: " + statusCode + " " + statusMessage
138                                 + (responseContent == null ? "" : System.lineSeparator() + responseContent));
139
140                         if (httpResponse.getStatusLine().getStatusCode() >= 300) {
141                                 String errMsg = "SDNC returned " + statusCode + " " + statusMessage;
142
143                                 String errors = analyzeErrors(responseContent);
144                                 if (errors != null) {
145                                         errMsg += " " + errors;
146                                 }
147
148                                 logError(errMsg);
149                                 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
150                                 return createErrorResponse(statusCode, errMsg, rt);
151                         }
152
153                         httpResponse = null;
154                         
155                         if(null != method) {
156                     method.reset();
157                         }
158             else {
159                 LOGGER.debug("method is NULL:");
160             }
161
162                         method = null;
163
164                         LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
165                         return createResponseFromContent(statusCode, statusMessage, responseContent, rt);
166
167                 } catch (SocketTimeoutException | ConnectTimeoutException e) {
168                         String errMsg = "Request to SDNC timed out";
169                         logError(errMsg, e);
170                         return createErrorResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg, rt);
171
172                 } catch (Exception e) {
173                         String errMsg = "Error processing request to SDNC";
174                         logError(errMsg, e);
175                         return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg, rt);
176
177                 } finally {
178                         if (httpResponse != null) {
179                                 try {
180                                         EntityUtils.consume(httpResponse.getEntity());
181                                 } catch (Exception e) {
182                                     LOGGER.debug("Exception:", e);
183                                 }
184                         }
185
186                         if (method != null) {
187                                 try {
188                                         method.reset();
189                                 } catch (Exception e) {
190                                     LOGGER.debug("Exception:", e);
191                                 }
192                         }
193                 }
194         }
195
196         protected void logError(String errMsg) {
197                 LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "",
198                         MsoLogger.ErrorCode.AvailabilityError, errMsg);
199                 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
200         }
201
202         protected void logError(String errMsg, Throwable t) {
203                 LOGGER.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "",
204                         MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
205                 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
206         }
207
208         /**
209          * Generates a response object from content received from SDNC.  The response
210          * object may be a success response object or an error response object. This
211          * method must be overridden by the subclass to return the correct object type.
212          * @param statusCode the response status code from SDNC (e.g. 200)
213          * @param statusMessage the response status message from SDNC (e.g. "OK")
214          * @param responseContent the body of the response from SDNC (possibly null)
215          * @param rt request tunables
216          * @return a response object
217          */
218         protected abstract SDNCResponseCommon createResponseFromContent(int statusCode,
219                         String statusMessage, String responseContent, TypedRequestTunables rt);
220
221         /**
222          * Generates an error response object. This method must be overridden by the
223          * subclass to return the correct object type.
224          * @param statusCode the response status code (from SDNC, or internally generated)
225          * @param errMsg the error message (normally a verbose explanation of the error)
226          * @param rt request tunables
227          * @return an error response object
228          */
229         protected abstract SDNCErrorCommon createErrorResponse(int statusCode,
230                         String errMsg, TypedRequestTunables rt);
231
232         /**
233          * Called by the send() method to analyze errors that may be encoded in the
234          * content of non-2XX responses.  By default, this method tries to parse the
235          * content as a restconf error.
236          * <pre>
237          *     xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf"
238          * </pre>
239          * If an error (or errors) can be obtained from the content, then the result
240          * is a string in this format:
241          * <pre>
242          * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ...
243          * </pre>
244          * If no error could be obtained from the content, then the result is null.
245          * <p>
246          * The subclass can override this method to provide another implementation.
247          */
248         protected String analyzeErrors(String content) {
249                 if (content == null || content.isEmpty()) {
250                         return null;
251                 }
252
253                 // Confirmed with Andrew Shen on 11/1/16 that SDNC will send content like
254                 // this in error responses (non-2XX response codes) to "agnostic" service
255                 // requests.
256                 //
257                 // <errors xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf">
258                 //   <error>
259                 //     <error-type>protocol</error-type>
260                 //     <error-tag>malformed-message</error-tag>
261                 //     <error-message>Error parsing input: The element type "input" must be terminated by the matching end-tag "&lt;/input&gt;".</error-message>
262                 //   </error>
263                 // </errors>
264
265                 StringBuilder output = null;
266
267                 try {
268                         XPathFactory xpathFactory = XPathFactory.newInstance();
269                         XPath xpath = xpathFactory.newXPath();
270                         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
271                         documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
272                         documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
273                         documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
274                         InputSource source = new InputSource(new StringReader(content));
275                         Document doc = documentBuilderFactory.newDocumentBuilder().parse(source);
276                         NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET);
277
278                         for (int i = 0; i < errors.getLength(); i++)
279                         {
280                                 Element error = (Element) errors.item(i);
281
282                                 String info = "";
283
284                                 try {
285                                         String errorType = xpath.evaluate("error-type", error);
286                                         info += "error-type:" + errorType;
287                                 } catch (XPathExpressionException e) {
288                                     LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "",
289                                         MsoLogger.ErrorCode.DataError, "XPath Exception", e);
290                                 }
291
292                                 try {
293                                         String errorTag = xpath.evaluate( "error-tag", error);
294                                         if (!info.isEmpty()) {
295                                                 info += ", ";
296                                         }
297                                         info += "error-tag:" + errorTag;
298                                 } catch (XPathExpressionException e) {
299                                         LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "",
300                                                 MsoLogger.ErrorCode.DataError, "XPath Exception", e);
301                                 }
302
303                                 try {
304                                         String errorMessage = xpath.evaluate("error-message", error);
305                                         if (!info.isEmpty()) {
306                                                 info += ", ";
307                                         }
308                                         info += "error-message:" + errorMessage;
309                                 } catch (Exception e) {
310                                         LOGGER.error(MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "",
311                                                 MsoLogger.ErrorCode.DataError, "XPath Exception", e);
312                                 }
313
314                                 if (!info.isEmpty()) {
315                                         if (output == null) {
316                                                 output = new StringBuilder("[" + info + "]");
317                                         } else {
318                                                 output.append(" [").append(info).append("]");
319                                         }
320                                 }
321                         }
322                 } catch (Exception e) {
323                         LOGGER.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "",
324                                 MsoLogger.ErrorCode.DataError, "Exception while analyzing errors", e);
325                 }
326
327                 return output.toString();
328         }
329 }