Merge "SSHApiCallNode sshExec API Impl"
[ccsdk/sli/plugins.git] / restapi-call-node / provider / src / main / java / org / onap / ccsdk / sli / plugins / restapicall / RestapiCallNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                      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.ccsdk.sli.plugins.restapicall;
23
24 import com.sun.jersey.api.client.ClientHandlerException;
25 import com.sun.jersey.api.client.UniformInterfaceException;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.net.SocketException;
29 import java.net.URI;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.security.KeyStore;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.Set;
41
42 import javax.net.ssl.HostnameVerifier;
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.net.ssl.KeyManagerFactory;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.SSLSession;
47 import javax.ws.rs.core.EntityTag;
48 import javax.ws.rs.core.MultivaluedMap;
49 import javax.ws.rs.core.UriBuilder;
50
51 import org.apache.commons.lang3.StringUtils;
52 import org.codehaus.jettison.json.JSONException;
53 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
54 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.sun.jersey.api.client.Client;
60 import com.sun.jersey.api.client.ClientResponse;
61 import com.sun.jersey.api.client.WebResource;
62 import com.sun.jersey.api.client.config.ClientConfig;
63 import com.sun.jersey.api.client.config.DefaultClientConfig;
64 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
65 import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
66 import com.sun.jersey.oauth.client.OAuthClientFilter;
67 import com.sun.jersey.oauth.signature.OAuthParameters;
68 import com.sun.jersey.oauth.signature.OAuthSecrets;
69 import com.sun.jersey.client.urlconnection.HTTPSProperties;
70
71 public class RestapiCallNode implements SvcLogicJavaPlugin {
72
73     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
74
75     private String uebServers;
76     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
77     protected RetryPolicyStore retryPolicyStore;
78
79     protected RetryPolicyStore getRetryPolicyStore() {
80         return retryPolicyStore;
81     }
82
83     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
84         this.retryPolicyStore = retryPolicyStore;
85     }
86
87     public RestapiCallNode() {
88
89     }
90
91      /**
92      * Allows Directed Graphs  the ability to interact with REST APIs.
93      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
94      * <table border="1">
95      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
96      *  <tbody>
97      *      <tr><td>templateFileName</td><td>Optional</td><td>full path to template file that can be used to build a request</td><td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td></tr>
98      *      <tr><td>restapiUrl</td><td>Mandatory</td><td>url to send the request to</td><td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td></tr>
99      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
100      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
101      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
102      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
103      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
104      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
105      *      <tr><td>contentType</td><td>Optional</td><td>http content type to set in the http header</td><td>usually application/json or application/xml</td></tr>
106      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
107      *      <tr><td>httpMethod</td><td>Optional</td><td>http method to use when sending the request</td><td>get post put delete patch</td></tr>
108      *      <tr><td>responsePrefix</td><td>Optional</td><td>location the response will be written to in context memory</td><td>tmp.restapi.result</td></tr>
109      *      <tr><td>listName[i]</td><td>Optional</td><td>Used for processing XML responses with repeating elements.</td>vpn-information.vrf-details<td></td></tr>
110      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
111      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
112      *      <tr><td>customHttpHeaders</td><td>Optional</td><td>a list additional http headers to be passed in, follow the format in the example</td><td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td></tr>
113      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
114      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
115      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
116      *  </tbody>
117      * </table>
118      * @param ctx Reference to context memory
119      * @throws SvcLogicException
120      * @since 11.0.2
121      * @see String#split(String, int)
122      */
123     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
124         sendRequest(paramMap, ctx, null);
125     }
126
127     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
128             throws SvcLogicException {
129
130         RetryPolicy retryPolicy = null;
131         HttpResponse r = new HttpResponse();
132         try {
133             Parameters p = getParameters(paramMap);
134             if (p.partner != null) {
135                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
136             }
137             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
138
139             String req = null;
140             if (p.templateFileName != null) {
141                 String reqTemplate = readFile(p.templateFileName);
142                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
143             } else if (p.requestBody != null) {
144                 req = p.requestBody;
145             }
146             r = sendHttpRequest(req, p);
147             setResponseStatus(ctx, p.responsePrefix, r);
148
149             if (p.dumpHeaders && r.headers != null) {
150                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
151                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
152                 }
153             }
154             
155             if (p.returnRequestPayload && req != null) {
156                 ctx.setAttribute(pp + "httpRequest", req);
157             }
158
159             if (r.body != null && r.body.trim().length() > 0) {
160                 ctx.setAttribute(pp + "httpResponse", r.body);
161
162                 if (p.convertResponse) {
163                     Map<String, String> mm = null;
164                     if (p.format == Format.XML)
165                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
166                     else if (p.format == Format.JSON)
167                         mm = JsonParser.convertToProperties(r.body);
168
169                     if (mm != null)
170                         for (Map.Entry<String,String> entry : mm.entrySet())
171                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
172                 }
173             }
174         } catch (SvcLogicException e) {
175             boolean shouldRetry = false;
176             if (e.getCause().getCause() instanceof SocketException) {
177                 shouldRetry = true;
178             }
179
180             log.error("Error sending the request: " + e.getMessage(), e);
181             String prefix = parseParam(paramMap, "responsePrefix", false, null);
182             if (retryPolicy == null || shouldRetry == false) {
183                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
184             } else {
185                 if (retryCount == null) {
186                     retryCount = 0;
187                 }
188                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
189                         " maximum retries.";
190                 log.debug(retryMessage);
191                 try {
192                     retryCount = retryCount + 1;
193                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
194                         URI uri = new URI(paramMap.get("restapiUrl"));
195                         String hostname = uri.getHost();
196                         String retryString = retryPolicy.getNextHostName(uri.toString());
197                         URI uriTwo = new URI(retryString);
198                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
199                                 uriTwo.getScheme()).build();
200                         paramMap.put("restapiUrl", retryUri.toString());
201                         log.debug("URL was set to {}", retryUri.toString());
202                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
203                             hostname, retryString);
204                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
205                         sendRequest(paramMap, ctx, retryCount);
206                     } else {
207                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
208                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
209                     }
210                 } catch (Exception ex) {
211                     log.error("Could not attempt retry.", ex);
212                     String retryErrorMessage =
213                             "Retry attempt has failed. No further retry shall be attempted, calling " +
214                                 "setFailureResponseStatus.";
215                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
216                 }
217             }
218         }
219
220         if (r != null && r.code >= 300)
221             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
222     }
223
224     protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
225         Parameters p = new Parameters();
226         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
227         p.requestBody = parseParam(paramMap, "requestBody", false, null);
228         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
229         validateUrl(p.restapiUrl);
230         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
231         p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
232         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
233         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
234         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
235         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
236         p.contentType = parseParam(paramMap, "contentType", false, null);
237         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
238         p.authtype = AuthType.fromString(parseParam(paramMap, "authType", false, "unspecified"));
239         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
240         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
241         p.listNameList = getListNameList(paramMap);
242         String skipSendingStr = paramMap.get("skipSending");
243         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
244         p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
245         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
246         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
247         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
248         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
249         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
250                 p.keyStorePassword != null;
251         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
252         p.partner = parseParam(paramMap, "partner", false, null);
253         p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
254         p.returnRequestPayload = Boolean.valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
255         return p;
256     }
257
258     private void validateUrl(String restapiUrl) throws SvcLogicException {
259         try {
260             URI.create(restapiUrl);
261         } catch (IllegalArgumentException e) {
262             throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
263         }
264     }
265
266     protected Set<String> getListNameList(Map<String, String> paramMap) {
267         Set<String> ll = new HashSet<>();
268         for (Map.Entry<String,String> entry : paramMap.entrySet())
269             if (entry.getKey().startsWith("listName"))
270                 ll.add(entry.getValue());
271         return ll;
272     }
273
274     protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
275             throws SvcLogicException {
276         String s = paramMap.get(name);
277
278         if (s == null || s.trim().length() == 0) {
279             if (!required)
280                 return def;
281             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
282         }
283
284         s = s.trim();
285         StringBuilder value = new StringBuilder();
286         int i = 0;
287         int i1 = s.indexOf('%');
288         while (i1 >= 0) {
289             int i2 = s.indexOf('%', i1 + 1);
290             if (i2 < 0)
291                 break;
292
293             String varName = s.substring(i1 + 1, i2);
294             String varValue = System.getenv(varName);
295             if (varValue == null)
296                 varValue = "%" + varName + "%";
297
298             value.append(s.substring(i, i1));
299             value.append(varValue);
300
301             i = i2 + 1;
302             i1 = s.indexOf('%', i);
303         }
304         value.append(s.substring(i));
305
306         log.info("Parameter {}: [{}]", name, value);
307         return value.toString();
308     }
309
310     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
311         throws SvcLogicException {
312         log.info("Building {} started", format);
313         long t1 = System.currentTimeMillis();
314
315         template = expandRepeats(ctx, template, 1);
316
317         Map<String, String> mm = new HashMap<>();
318         for (String s : ctx.getAttributeKeySet())
319             mm.put(s, ctx.getAttribute(s));
320
321         StringBuilder ss = new StringBuilder();
322         int i = 0;
323         while (i < template.length()) {
324             int i1 = template.indexOf("${", i);
325             if (i1 < 0) {
326                 ss.append(template.substring(i));
327                 break;
328             }
329
330             int i2 = template.indexOf('}', i1 + 2);
331             if (i2 < 0)
332                 throw new SvcLogicException("Template error: Matching } not found");
333
334             String var1 = template.substring(i1 + 2, i2);
335             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
336             // log.info(" " + var1 + ": " + value1);
337             if (value1 == null || value1.trim().length() == 0) {
338                 // delete the whole element (line)
339                 int i3 = template.lastIndexOf('\n', i1);
340                 if (i3 < 0)
341                     i3 = 0;
342                 int i4 = template.indexOf('\n', i1);
343                 if (i4 < 0)
344                     i4 = template.length();
345
346                 if (i < i3)
347                     ss.append(template.substring(i, i3));
348                 i = i4;
349             } else {
350                 ss.append(template.substring(i, i1)).append(value1);
351                 i = i2 + 1;
352             }
353         }
354
355         String req = format == Format.XML
356                 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
357
358         if (format == Format.JSON)
359             req = XmlJsonUtil.removeLastCommaJson(req);
360
361         long t2 = System.currentTimeMillis();
362         log.info("Building {} completed. Time: {}", format, (t2 - t1));
363
364         return req;
365     }
366
367     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
368         StringBuilder newTemplate = new StringBuilder();
369         int k = 0;
370         while (k < template.length()) {
371             int i1 = template.indexOf("${repeat:", k);
372             if (i1 < 0) {
373                 newTemplate.append(template.substring(k));
374                 break;
375             }
376
377             int i2 = template.indexOf(':', i1 + 9);
378             if (i2 < 0)
379                 throw new SvcLogicException(
380                         "Template error: Context variable name followed by : is required after repeat");
381
382             // Find the closing }, store in i3
383             int nn = 1;
384             int i3 = -1;
385             int i = i2;
386             while (nn > 0 && i < template.length()) {
387                 i3 = template.indexOf('}', i);
388                 if (i3 < 0)
389                     throw new SvcLogicException("Template error: Matching } not found");
390                 int i32 = template.indexOf('{', i);
391                 if (i32 >= 0 && i32 < i3) {
392                     nn++;
393                     i = i32 + 1;
394                 } else {
395                     nn--;
396                     i = i3 + 1;
397                 }
398             }
399
400             String var1 = template.substring(i1 + 9, i2);
401             String value1 = ctx.getAttribute(var1);
402             log.info("     {}:{}", var1, value1);
403             int n = 0;
404             try {
405                 n = Integer.parseInt(value1);
406             } catch (NumberFormatException e) {
407                 log.info("value1 not set or not a number, n will remain set at zero");
408             }
409
410             newTemplate.append(template.substring(k, i1));
411
412             String rpt = template.substring(i2 + 1, i3);
413
414             for (int ii = 0; ii < n; ii++) {
415                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
416                 if (ii == n - 1 && ss.trim().endsWith(",")) {
417                     int i4 = ss.lastIndexOf(',');
418                     if (i4 > 0)
419                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
420                 }
421                 newTemplate.append(ss);
422             }
423
424             k = i3 + 1;
425         }
426
427         if (k == 0)
428             return newTemplate.toString();
429
430         return expandRepeats(ctx, newTemplate.toString(), level + 1);
431     }
432
433     protected String readFile(String fileName) throws SvcLogicException {
434         try {
435             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
436             return new String(encoded, "UTF-8");
437         } catch (IOException | SecurityException e) {
438             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
439         }
440     }
441
442     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
443         Parameters p = new Parameters();
444         p.restapiUser = fp.user;
445         p.restapiPassword = fp.password;
446         p.oAuthConsumerKey = fp.oAuthConsumerKey;
447         p.oAuthVersion = fp.oAuthVersion;
448         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
449         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
450         p.authtype = fp.authtype;
451         return addAuthType(c,p);
452     }
453
454     protected Client addAuthType(Client client, Parameters p) throws SvcLogicException {
455         if (p.authtype == AuthType.Unspecified){
456             if (p.restapiUser != null && p.restapiPassword != null)
457                 client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
458             else if(p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
459                     && p.oAuthSignatureMethod != null) {
460                 OAuthParameters params = new OAuthParameters()
461                         .signatureMethod(p.oAuthSignatureMethod)
462                         .consumerKey(p.oAuthConsumerKey)
463                         .version(p.oAuthVersion);
464
465                 OAuthSecrets secrets = new OAuthSecrets()
466                         .consumerSecret(p.oAuthConsumerSecret);
467                 client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets));
468             }
469         } else {
470             if (p.authtype == AuthType.DIGEST) {
471                 if (p.restapiUser != null && p.restapiPassword != null) {
472                     client.addFilter(new HTTPDigestAuthFilter(p.restapiUser, p.restapiPassword));
473                 } else {
474                     throw new SvcLogicException("oAUTH authentication type selected but all restapiUser and restapiPassword " +
475                                                         "parameters doesn't exist", new Throwable());
476                 }
477             } else if (p.authtype == AuthType.BASIC){
478                 if (p.restapiUser != null && p.restapiPassword != null) {
479                     client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
480                 } else {
481                     throw new SvcLogicException("oAUTH authentication type selected but all restapiUser and restapiPassword " +
482                                                         "parameters doesn't exist", new Throwable());
483                 }
484             } else if(p.authtype == AuthType.OAUTH ) {
485                 if(p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
486                     OAuthParameters params = new OAuthParameters()
487                             .signatureMethod(p.oAuthSignatureMethod)
488                             .consumerKey(p.oAuthConsumerKey)
489                             .version(p.oAuthVersion);
490
491                     OAuthSecrets secrets = new OAuthSecrets()
492                             .consumerSecret(p.oAuthConsumerSecret);
493                     client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets));
494                 } else {
495                     throw new SvcLogicException("oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
496                                                         "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
497                 }
498             }
499         }
500         return client;
501     }
502
503     protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
504
505         ClientConfig config = new DefaultClientConfig();
506         SSLContext ssl = null;
507         if (p.ssl && p.restapiUrl.startsWith("https"))
508             ssl = createSSLContext(p);
509         if (ssl != null) {
510             HostnameVerifier hostnameVerifier = (hostname, session) -> true;
511
512             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
513                     new HTTPSProperties(hostnameVerifier, ssl));
514         }
515
516         logProperties(config.getProperties());
517
518         Client client = Client.create(config);
519         client.setConnectTimeout(5000);
520         WebResource webResource = addAuthType(client,p).resource(p.restapiUrl);
521
522         log.info("Sending request:");
523         log.info(request);
524         long t1 = System.currentTimeMillis();
525
526         HttpResponse r = new HttpResponse();
527         r.code = 200;
528
529         if (!p.skipSending) {
530             String tt = p.format == Format.XML ? "application/xml" : "application/json";
531             String tt1 = tt + ";charset=UTF-8";
532             if (p.contentType != null) {
533                 tt = p.contentType;
534                 tt1 = p.contentType;
535             }
536
537             WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
538             if(p.format == Format.NONE){
539                 webResourceBuilder = webResource.header("","");
540             }
541
542             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
543                 String[] keyValuePairs = p.customHttpHeaders.split(",");
544                 for (String singlePair : keyValuePairs) {
545                     int equalPosition = singlePair.indexOf('=');
546                     webResourceBuilder.header(singlePair.substring(0, equalPosition),
547                             singlePair.substring(equalPosition + 1, singlePair.length()));
548                 }
549             }
550
551             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
552
553             ClientResponse response;
554
555             try {
556                 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
557             } catch (UniformInterfaceException | ClientHandlerException e) {
558                 throw new SvcLogicException("Exception while sending http request to client "
559                     + e.getLocalizedMessage(), e);
560             }
561
562             r.code = response.getStatus();
563             r.headers = response.getHeaders();
564             EntityTag etag = response.getEntityTag();
565             if (etag != null)
566                 r.message = etag.getValue();
567             if (response.hasEntity() && r.code != 204)
568                 r.body = response.getEntity(String.class);
569         }
570
571         long t2 = System.currentTimeMillis();
572         log.info("Response received. Time: {}", (t2 - t1));
573         log.info("HTTP response code: {}", r.code);
574         log.info("HTTP response message: {}", r.message);
575         logHeaders(r.headers);
576         log.info("HTTP response: {}", r.body);
577
578         return r;
579     }
580
581     protected SSLContext createSSLContext(Parameters p) {
582         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
583             System.setProperty("jsse.enableSNIExtension", "false");
584             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
585             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
586
587             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
588
589             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
590             KeyStore ks = KeyStore.getInstance("PKCS12");
591             char[] pwd = p.keyStorePassword.toCharArray();
592             ks.load(in, pwd);
593             kmf.init(ks, pwd);
594
595             SSLContext ctx = SSLContext.getInstance("TLS");
596             ctx.init(kmf.getKeyManagers(), null, null);
597             return ctx;
598         } catch (Exception e) {
599             log.error("Error creating SSLContext: {}", e.getMessage(), e);
600         }
601         return null;
602     }
603
604     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
605         HttpResponse resp) {
606         resp.code = 500;
607         resp.message = errorMessage;
608         String pp = prefix != null ? prefix + '.' : "";
609         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
610         ctx.setAttribute(pp + "response-message", resp.message);
611     }
612
613     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
614         String pp = prefix != null ? prefix + '.' : "";
615         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
616         ctx.setAttribute(pp + "response-message", r.message);
617     }
618
619     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
620         HttpResponse r = null;
621         try {
622             FileParam p = getFileParameters(paramMap);
623             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
624
625             r = sendHttpData(data, p);
626             setResponseStatus(ctx, p.responsePrefix, r);
627
628         } catch (SvcLogicException | IOException e) {
629             log.error("Error sending the request: {}", e.getMessage(), e);
630
631             r = new HttpResponse();
632             r.code = 500;
633             r.message = e.getMessage();
634             String prefix = parseParam(paramMap, "responsePrefix", false, null);
635             setResponseStatus(ctx, prefix, r);
636         }
637
638         if (r != null && r.code >= 300)
639             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
640     }
641
642     private static class FileParam {
643
644         public String fileName;
645         public String url;
646         public String user;
647         public String password;
648         public HttpMethod httpMethod;
649         public String responsePrefix;
650         public boolean skipSending;
651         public String oAuthConsumerKey;
652         public String oAuthConsumerSecret;
653         public String oAuthSignatureMethod;
654         public String oAuthVersion;
655         public AuthType authtype;
656     }
657
658     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
659         FileParam p = new FileParam();
660         p.fileName = parseParam(paramMap, "fileName", true, null);
661         p.url = parseParam(paramMap, "url", true, null);
662         p.user = parseParam(paramMap, "user", false, null);
663         p.password = parseParam(paramMap, "password", false, null);
664         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
665         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
666         String skipSendingStr = paramMap.get("skipSending");
667         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
668         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
669         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
670         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
671         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
672         p.authtype = AuthType.fromString(parseParam(paramMap, "authType", false, "unspecified"));
673         return p;
674     }
675
676     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
677         Client client = Client.create();
678         client.setConnectTimeout(5000);
679         client.setFollowRedirects(true);
680         WebResource webResource = addAuthType(client,p).resource(p.url);
681
682         log.info("Sending file");
683         long t1 = System.currentTimeMillis();
684
685         HttpResponse r = new HttpResponse();
686         r.code = 200;
687
688         if (!p.skipSending) {
689             String tt = "application/octet-stream";
690
691             ClientResponse response;
692             try {
693                 if (p.httpMethod == HttpMethod.POST)
694                     response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
695                 else if (p.httpMethod == HttpMethod.PUT)
696                     response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
697                 else
698                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
699             } catch (UniformInterfaceException | ClientHandlerException e) {
700                 throw new SvcLogicException("Exception while sending http request to client " +
701                     e.getLocalizedMessage(), e);
702             }
703
704             r.code = response.getStatus();
705             r.headers = response.getHeaders();
706             EntityTag etag = response.getEntityTag();
707             if (etag != null)
708                 r.message = etag.getValue();
709             if (response.hasEntity() && r.code != 204)
710                 r.body = response.getEntity(String.class);
711
712             if (r.code == 301) {
713                 String newUrl = response.getHeaders().getFirst("Location");
714
715                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
716
717                 webResource = client.resource(newUrl);
718
719                 try {
720                     if (p.httpMethod == HttpMethod.POST)
721                         response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
722                     else if (p.httpMethod == HttpMethod.PUT)
723                         response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
724                     else
725                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
726                 } catch (UniformInterfaceException | ClientHandlerException e) {
727                     throw new SvcLogicException("Exception while sending http request to client " +
728                         e.getLocalizedMessage(), e);
729                 }
730
731                 r.code = response.getStatus();
732                 etag = response.getEntityTag();
733                 if (etag != null)
734                     r.message = etag.getValue();
735                 if (response.hasEntity() && r.code != 204)
736                     r.body = response.getEntity(String.class);
737             }
738         }
739
740         long t2 = System.currentTimeMillis();
741         log.info("Response received. Time: {}", (t2 - t1));
742         log.info("HTTP response code: {}", r.code);
743         log.info("HTTP response message: {}", r.message);
744         logHeaders(r.headers);
745         log.info("HTTP response: {}", r.body);
746
747         return r;
748     }
749
750     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
751         HttpResponse r;
752         try {
753             UebParam p = getUebParameters(paramMap);
754
755             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
756
757             String req;
758
759             if (p.templateFileName == null) {
760                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
761                 p.templateFileName = defaultUebTemplateFileName;
762             }
763
764             String reqTemplate = readFile(p.templateFileName);
765             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
766             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
767
768             r = postOnUeb(req, p);
769             setResponseStatus(ctx, p.responsePrefix, r);
770             if (r.body != null)
771                 ctx.setAttribute(pp + "httpResponse", r.body);
772
773         } catch (SvcLogicException e) {
774             log.error("Error sending the request: {}", e.getMessage(), e);
775
776             r = new HttpResponse();
777             r.code = 500;
778             r.message = e.getMessage();
779             String prefix = parseParam(paramMap, "responsePrefix", false, null);
780             setResponseStatus(ctx, prefix, r);
781         }
782
783         if (r.code >= 300)
784             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
785     }
786
787     private static class UebParam {
788
789         public String topic;
790         public String templateFileName;
791         public String rootVarName;
792         public String responsePrefix;
793         public boolean skipSending;
794     }
795
796     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
797         UebParam p = new UebParam();
798         p.topic = parseParam(paramMap, "topic", true, null);
799         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
800         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
801         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
802         String skipSendingStr = paramMap.get("skipSending");
803         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
804         return p;
805     }
806
807     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
808         String[] urls = uebServers.split(" ");
809         for (int i = 0; i < urls.length; i++) {
810             if (!urls[i].endsWith("/"))
811                 urls[i] += "/";
812             urls[i] += "events/" + p.topic;
813         }
814
815         Client client = Client.create();
816         client.setConnectTimeout(5000);
817         WebResource webResource = client.resource(urls[0]);
818
819         log.info("UEB URL: {}", urls[0]);
820         log.info("Sending request:");
821         log.info(request);
822         long t1 = System.currentTimeMillis();
823
824         HttpResponse r = new HttpResponse();
825         r.code = 200;
826
827         if (!p.skipSending) {
828             String tt = "application/json";
829             String tt1 = tt + ";charset=UTF-8";
830
831             ClientResponse response;
832
833             try {
834                 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
835             } catch (UniformInterfaceException | ClientHandlerException e) {
836                 throw new SvcLogicException("Exception while posting http request to client " +
837                     e.getLocalizedMessage(), e);
838             }
839
840             r.code = response.getStatus();
841             r.headers = response.getHeaders();
842             if (response.hasEntity())
843                 r.body = response.getEntity(String.class);
844         }
845
846         long t2 = System.currentTimeMillis();
847         log.info("Response received. Time: {}", (t2 - t1));
848         log.info("HTTP response code: {}", r.code);
849         logHeaders(r.headers);
850         log.info("HTTP response:\n {}", r.body);
851
852         return r;
853     }
854
855     protected void logProperties(Map<String, Object> mm) {
856         List<String> ll = new ArrayList<>();
857         for (Object o : mm.keySet())
858             ll.add((String) o);
859         Collections.sort(ll);
860
861         log.info("Properties:");
862         for (String name : ll)
863             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
864     }
865
866     protected void logHeaders(MultivaluedMap<String, String> mm) {
867         log.info("HTTP response headers:");
868
869         if (mm == null)
870             return;
871
872         List<String> ll = new ArrayList<>();
873         for (Object o : mm.keySet())
874             ll.add((String) o);
875         Collections.sort(ll);
876
877         for (String name : ll)
878             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
879     }
880
881     public void setUebServers(String uebServers) {
882         this.uebServers = uebServers;
883     }
884
885     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
886         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
887     }
888 }