2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.so.adapters.sdnc.sdncrest;
24 import java.io.StringReader;
25 import java.net.HttpURLConnection;
26 import java.net.SocketTimeoutException;
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;
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;
65 * Sends requests to SDNC and processes the responses.
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();
73 private Environment env;
75 public SDNCResponseCommon send(String content, TypedRequestTunables rt) {
76 LOGGER.debug("SDNC URL: " + rt.getSdncUrl());
77 LOGGER.debug("SDNC Request Body:\n" + content);
79 HttpRequestBase method = null;
80 HttpResponse httpResponse = null;
83 int timeout = Integer.parseInt(rt.getTimeout());
85 RequestConfig requestConfig = RequestConfig.custom()
86 .setSocketTimeout(timeout)
87 .setConnectTimeout(timeout)
88 .setConnectionRequestTimeout(timeout)
91 HttpClient client = HttpClientBuilder.create().build();
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));
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));
103 } else if ("GET".equals(rt.getReqMethod())) {
104 HttpGet httpGet = new HttpGet(rt.getSdncUrl());
105 httpGet.setConfig(requestConfig);
107 } else if ("DELETE".equals(rt.getReqMethod())) {
108 HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl());
109 httpDelete.setConfig(requestConfig);
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());
118 method.setHeader("Authorization", authorization);
119 method.setHeader("Accept", "application/yang.data+xml");
122 LOGGER.debug("method is NULL:");
127 httpResponse = client.execute(method);
129 String responseContent = null;
130 if (httpResponse.getEntity() != null) {
131 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
134 int statusCode = httpResponse.getStatusLine().getStatusCode();
135 String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
137 LOGGER.debug("SDNC Response: " + statusCode + " " + statusMessage
138 + (responseContent == null ? "" : System.lineSeparator() + responseContent));
140 if (httpResponse.getStatusLine().getStatusCode() >= 300) {
141 String errMsg = "SDNC returned " + statusCode + " " + statusMessage;
143 String errors = analyzeErrors(responseContent);
144 if (errors != null) {
145 errMsg += " " + errors;
149 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
150 return createErrorResponse(statusCode, errMsg, rt);
159 LOGGER.debug("method is NULL:");
164 LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
165 return createResponseFromContent(statusCode, statusMessage, responseContent, rt);
167 } catch (SocketTimeoutException | ConnectTimeoutException e) {
168 String errMsg = "Request to SDNC timed out";
170 return createErrorResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg, rt);
172 } catch (Exception e) {
173 String errMsg = "Error processing request to SDNC";
175 return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg, rt);
178 if (httpResponse != null) {
180 EntityUtils.consume(httpResponse.getEntity());
181 } catch (Exception e) {
182 LOGGER.debug("Exception:", e);
186 if (method != null) {
189 } catch (Exception e) {
190 LOGGER.debug("Exception:", e);
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);
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);
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
218 protected abstract SDNCResponseCommon createResponseFromContent(int statusCode,
219 String statusMessage, String responseContent, TypedRequestTunables rt);
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
229 protected abstract SDNCErrorCommon createErrorResponse(int statusCode,
230 String errMsg, TypedRequestTunables rt);
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.
237 * xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf"
239 * If an error (or errors) can be obtained from the content, then the result
240 * is a string in this format:
242 * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ...
244 * If no error could be obtained from the content, then the result is null.
246 * The subclass can override this method to provide another implementation.
248 protected String analyzeErrors(String content) {
249 if (content == null || content.isEmpty()) {
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
257 // <errors xmlns="urn:ietf:params:xml:ns:yang:ietf-restconf">
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 "</input>".</error-message>
265 StringBuilder output = null;
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);
278 for (int i = 0; i < errors.getLength(); i++)
280 Element error = (Element) errors.item(i);
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);
293 String errorTag = xpath.evaluate( "error-tag", error);
294 if (!info.isEmpty()) {
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);
304 String errorMessage = xpath.evaluate("error-message", error);
305 if (!info.isEmpty()) {
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);
314 if (!info.isEmpty()) {
315 if (output == null) {
316 output = new StringBuilder("[" + info + "]");
318 output.append(" [").append(info).append("]");
322 } catch (Exception e) {
323 LOGGER.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "",
324 MsoLogger.ErrorCode.DataError, "Exception while analyzing errors", e);
327 return output.toString();