rest api call node target entity
[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  * Modifications Copyright © 2018 IBM.
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.ccsdk.sli.plugins.restapicall;
24
25 import static java.lang.Boolean.valueOf;
26 import static javax.ws.rs.client.Entity.entity;
27 import static org.onap.ccsdk.sli.plugins.restapicall.AuthType.fromString;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.net.SocketException;
32 import java.net.URI;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.KeyStore;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Properties;
45 import java.util.Set;
46 import javax.net.ssl.HttpsURLConnection;
47 import javax.net.ssl.KeyManagerFactory;
48 import javax.net.ssl.SSLContext;
49 import javax.ws.rs.ProcessingException;
50 import javax.ws.rs.client.Client;
51 import javax.ws.rs.client.ClientBuilder;
52 import javax.ws.rs.client.Entity;
53 import javax.ws.rs.client.Invocation;
54 import javax.ws.rs.client.WebTarget;
55 import javax.ws.rs.core.EntityTag;
56 import javax.ws.rs.core.Feature;
57 import javax.ws.rs.core.MediaType;
58 import javax.ws.rs.core.MultivaluedMap;
59 import javax.ws.rs.core.Response;
60 import javax.ws.rs.core.UriBuilder;
61 import org.apache.commons.lang3.StringUtils;
62 import org.codehaus.jettison.json.JSONException;
63 import org.codehaus.jettison.json.JSONObject;
64 import org.glassfish.jersey.client.ClientProperties;
65 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
66 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
67 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
68 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
69 import org.glassfish.jersey.media.multipart.MultiPart;
70 import org.glassfish.jersey.media.multipart.MultiPartFeature;
71 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
72 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
73 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
74 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
75 import org.onap.logging.filter.base.MetricLogClientFilter;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 public class RestapiCallNode implements SvcLogicJavaPlugin {
80
81     protected static final String PARTNERS_FILE_NAME = "partners.json";
82     protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
83     protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
84     protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
85     protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
86     protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
87
88     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
89     private String uebServers;
90     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
91
92     private String responseReceivedMessage = "Response received. Time: {}";
93     private String responseHttpCodeMessage = "HTTP response code: {}";
94     private String requestPostingException = "Exception while posting http request to client ";
95     protected static final String skipSendingMessage = "skipSending";
96     protected static final String responsePrefix = "responsePrefix";
97     protected static final String restapiUrlString = "restapiUrl";
98     protected static final String restapiUserKey = "restapiUser";
99     protected static final String restapiPasswordKey = "restapiPassword";
100     protected Integer httpConnectTimeout;
101     protected Integer httpReadTimeout;
102
103     protected HashMap<String, PartnerDetails> partnerStore;
104
105     public RestapiCallNode() {
106         String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
107         try {
108             String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
109             JSONObject partners = new JSONObject(jsonString);
110             partnerStore = new HashMap<>();
111             loadPartners(partners);
112             log.info("Partners support enabled");
113         } catch (Exception e) {
114             log.warn("Partners file could not be read, Partner support will not be enabled.", e);
115         }
116
117         try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
118             Properties props = new Properties();
119             props.load(in);
120             uebServers = props.getProperty("servers");
121             log.info("UEB support enabled");
122         } catch (Exception e) {
123             log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
124         }
125         httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
126         httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
127     }
128
129     protected void loadPartners(JSONObject partners) {
130         Iterator<String> keys = partners.keys();
131         String partnerUserKey = "user";
132         String partnerPasswordKey = "password";
133         String partnerUrlKey = "url";
134
135         while (keys.hasNext()) {
136             String partnerKey = keys.next();
137             try {
138                 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
139                 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
140                     String url = null;
141                     if (partnerObject.has(partnerUrlKey)) {
142                         url = partnerObject.getString(partnerUrlKey);
143                     }
144                     String userName = partnerObject.getString(partnerUserKey);
145                     String password = partnerObject.getString(partnerPasswordKey);
146                     PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
147                     partnerStore.put(partnerKey, details);
148                     log.info("mapped partner using partner key " + partnerKey);
149                 } else {
150                     log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
151                 }
152             } catch (JSONException e) {
153                 log.info("Couldn't map the partner using partner key " + partnerKey, e);
154             }
155         }
156     }
157
158     /* Unobfuscate param value */
159     private static String getObfuscatedVal(String paramValue) {
160         String resValue = paramValue;
161         if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
162         {
163             String paramStr = paramValue.substring(2, paramValue.length()-1);
164             if (paramStr  != null && paramStr.length() > 0)
165             {
166                 String val = System.getenv(paramStr);
167                 if (val != null && val.length() > 0)
168                 {
169                     resValue=val;
170                     log.info("Obfuscated value RESET for param value:" + paramValue);
171                 }
172             }
173         }
174         return resValue;
175     }
176
177     /**
178      * Returns parameters from the parameter map.
179      *
180      * @param paramMap parameter map
181      * @param p parameters instance
182      * @return parameters filed instance
183      * @throws SvcLogicException when svc logic exception occurs
184      */
185     public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
186
187         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
188         p.requestBody = parseParam(paramMap, "requestBody", false, null);
189         p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
190         p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
191         if (p.restapiUrlSuffix != null) {
192             p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
193         }
194
195         p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
196         validateUrl(p.restapiUrl);
197
198         p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
199         p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
200         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
201         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
202         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
203         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
204         p.contentType = parseParam(paramMap, "contentType", false, null);
205         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
206         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
207         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
208         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
209         p.listNameList = getListNameList(paramMap);
210         String skipSendingStr = paramMap.get(skipSendingMessage);
211         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
212         p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
213         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
214         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
215         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
216         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
217         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
218             && p.keyStorePassword != null;
219         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
220         p.partner = parseParam(paramMap, "partner", false, null);
221         p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
222         p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
223         p.accept = parseParam(paramMap, "accept", false, null);
224         p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
225         p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
226         return p;
227     }
228
229     /**
230      * Validates the given URL in the parameters.
231      *
232      * @param restapiUrl rest api URL
233      * @throws SvcLogicException when URL validation fails
234      */
235     private static void validateUrl(String restapiUrl) throws SvcLogicException {
236         if (restapiUrl.contains(",")) {
237             String[] urls = restapiUrl.split(",");
238             for (String url : urls) {
239                 validateUrl(url);
240             }
241         } else {
242             try {
243                 URI.create(restapiUrl);
244             } catch (IllegalArgumentException e) {
245                 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
246             }
247         }
248     }
249
250     /**
251      * Returns the list of list name.
252      *
253      * @param paramMap parameters map
254      * @return list of list name
255      */
256     private static Set<String> getListNameList(Map<String, String> paramMap) {
257         Set<String> ll = new HashSet<>();
258         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
259             if (entry.getKey().startsWith("listName")) {
260                 ll.add(entry.getValue());
261             }
262         }
263         return ll;
264     }
265
266     /**
267      * Parses the parameter string map of property, validates if required, assigns default value if
268      * present and returns the value.
269      *
270      * @param paramMap string param map
271      * @param name name of the property
272      * @param required if value required
273      * @param def default value
274      * @return value of the property
275      * @throws SvcLogicException if required parameter value is empty
276      */
277     public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
278         throws SvcLogicException {
279         String s = paramMap.get(name);
280
281         if (s == null || s.trim().length() == 0) {
282             if (!required) {
283                 return def;
284             }
285             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
286         }
287
288         s = s.trim();
289         StringBuilder value = new StringBuilder();
290         int i = 0;
291         int i1 = s.indexOf('%');
292         while (i1 >= 0) {
293             int i2 = s.indexOf('%', i1 + 1);
294             if (i2 < 0) {
295                 break;
296             }
297
298             String varName = s.substring(i1 + 1, i2);
299             String varValue = System.getenv(varName);
300             if (varValue == null) {
301                 varValue = "%" + varName + "%";
302             }
303
304             value.append(s.substring(i, i1));
305             value.append(varValue);
306
307             i = i2 + 1;
308             i1 = s.indexOf('%', i);
309         }
310         value.append(s.substring(i));
311
312         log.info("Parameter {}: [{}]", name, maskPassword(name, value));
313
314         return value.toString();
315     }
316
317     private static Object maskPassword(String name, Object value) {
318         String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
319         for (String pwdName : pwdNames) {
320             if (name.contains(pwdName)) {
321                 return "**********";
322             }
323         }
324         return value;
325     }
326
327     /**
328      * Allows Directed Graphs the ability to interact with REST APIs.
329      *
330      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
331      *        <table border="1">
332      *        <thead>
333      *        <th>parameter</th>
334      *        <th>Mandatory/Optional</th>
335      *        <th>description</th>
336      *        <th>example values</th></thead> <tbody>
337      *        <tr>
338      *        <td>templateFileName</td>
339      *        <td>Optional</td>
340      *        <td>full path to template file that can be used to build a request</td>
341      *        <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
342      *        </tr>
343      *        <tr>
344      *        <td>restapiUrl</td>
345      *        <td>Mandatory</td>
346      *        <td>url to send the request to</td>
347      *        <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
348      *        </tr>
349      *        <tr>
350      *        <td>restapiUser</td>
351      *        <td>Optional</td>
352      *        <td>user name to use for http basic authentication</td>
353      *        <td>sdnc_ws</td>
354      *        </tr>
355      *        <tr>
356      *        <td>restapiPassword</td>
357      *        <td>Optional</td>
358      *        <td>unencrypted password to use for http basic authentication</td>
359      *        <td>plain_password</td>
360      *        </tr>
361      *        <tr>
362      *        <td>oAuthConsumerKey</td>
363      *        <td>Optional</td>
364      *        <td>Consumer key to use for http oAuth authentication</td>
365      *        <td>plain_key</td>
366      *        </tr>
367      *        <tr>
368      *        <td>oAuthConsumerSecret</td>
369      *        <td>Optional</td>
370      *        <td>Consumer secret to use for http oAuth authentication</td>
371      *        <td>plain_secret</td>
372      *        </tr>
373      *        <tr>
374      *        <td>oAuthSignatureMethod</td>
375      *        <td>Optional</td>
376      *        <td>Consumer method to use for http oAuth authentication</td>
377      *        <td>method</td>
378      *        </tr>
379      *        <tr>
380      *        <td>oAuthVersion</td>
381      *        <td>Optional</td>
382      *        <td>Version http oAuth authentication</td>
383      *        <td>version</td>
384      *        </tr>
385      *        <tr>
386      *        <td>contentType</td>
387      *        <td>Optional</td>
388      *        <td>http content type to set in the http header</td>
389      *        <td>usually application/json or application/xml</td>
390      *        </tr>
391      *        <tr>
392      *        <td>format</td>
393      *        <td>Optional</td>
394      *        <td>should match request body format</td>
395      *        <td>json or xml</td>
396      *        </tr>
397      *        <tr>
398      *        <td>httpMethod</td>
399      *        <td>Optional</td>
400      *        <td>http method to use when sending the request</td>
401      *        <td>get post put delete patch</td>
402      *        </tr>
403      *        <tr>
404      *        <td>responsePrefix</td>
405      *        <td>Optional</td>
406      *        <td>location the response will be written to in context memory</td>
407      *        <td>tmp.restapi.result</td>
408      *        </tr>
409      *        <tr>
410      *        <td>listName[i]</td>
411      *        <td>Optional</td>
412      *        <td>Used for processing XML responses with repeating
413      *        elements.</td>vpn-information.vrf-details
414      *        <td></td>
415      *        </tr>
416      *        <tr>
417      *        <td>skipSending</td>
418      *        <td>Optional</td>
419      *        <td></td>
420      *        <td>true or false</td>
421      *        </tr>
422      *        <tr>
423      *        <td>convertResponse</td>
424      *        <td>Optional</td>
425      *        <td>whether the response should be converted</td>
426      *        <td>true or false</td>
427      *        </tr>
428      *        <tr>
429      *        <td>customHttpHeaders</td>
430      *        <td>Optional</td>
431      *        <td>a list additional http headers to be passed in, follow the format in the example</td>
432      *        <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
433      *        </tr>
434      *        <tr>
435      *        <td>dumpHeaders</td>
436      *        <td>Optional</td>
437      *        <td>when true writes http header content to context memory</td>
438      *        <td>true or false</td>
439      *        </tr>
440      *        <tr>
441      *        <td>partner</td>
442      *        <td>Optional</td>
443      *        <td>used to retrieve username, password and url if partner store exists</td>
444      *        <td>aaf</td>
445      *        </tr>
446      *        <tr>
447      *        <td>returnRequestPayload</td>
448      *        <td>Optional</td>
449      *        <td>used to return payload built in the request</td>
450      *        <td>true or false</td>
451      *        </tr>
452      *        </tbody>
453      *        </table>
454      * @param ctx Reference to context memory
455      * @throws SvcLogicException
456      * @since 11.0.2
457      * @see String#split(String, int)
458      */
459     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
460         sendRequest(paramMap, ctx, null);
461     }
462
463     protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
464         throws SvcLogicException {
465
466         HttpResponse r = new HttpResponse();
467         try {
468             handlePartner(paramMap);
469             Parameters p = getParameters(paramMap, new Parameters());
470             if (p.restapiUrl.contains(",") && retryPolicy == null) {
471                 String[] urls = p.restapiUrl.split(",");
472                 retryPolicy = new RetryPolicy(urls, urls.length * 2);
473                 p.restapiUrl = urls[0];
474             }
475             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
476
477             String req = null;
478             if (p.templateFileName != null) {
479                 String reqTemplate = readFile(p.templateFileName);
480                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
481             } else if (p.requestBody != null) {
482                 req = p.requestBody;
483             }
484             r = sendHttpRequest(req, p);
485             setResponseStatus(ctx, p.responsePrefix, r);
486
487             if (p.dumpHeaders && r.headers != null) {
488                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
489                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
490                 }
491             }
492
493             if (p.returnRequestPayload && req != null) {
494                 ctx.setAttribute(pp + "httpRequest", req);
495             }
496
497             if (r.body != null && r.body.trim().length() > 0) {
498                 ctx.setAttribute(pp + "httpResponse", r.body);
499
500                 if (p.convertResponse) {
501                     Map<String, String> mm = null;
502                     if (p.format == Format.XML) {
503                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
504                     } else if (p.format == Format.JSON) {
505                         mm = JsonParser.convertToProperties(r.body);
506                     }
507
508                     if (mm != null) {
509                         for (Map.Entry<String, String> entry : mm.entrySet()) {
510                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
511                         }
512                     }
513                 }
514             }
515         } catch (SvcLogicException e) {
516             boolean shouldRetry = false;
517             if (e.getCause().getCause() instanceof SocketException) {
518                 shouldRetry = true;
519             }
520
521             log.error("Error sending the request: " + e.getMessage(), e);
522             String prefix = parseParam(paramMap, responsePrefix, false, null);
523             if (retryPolicy == null || !shouldRetry) {
524                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
525             } else {
526                 log.debug(retryPolicy.getRetryMessage());
527                 try {
528                     // calling getNextHostName increments the retry count so it should be called before shouldRetry
529                     String retryString = retryPolicy.getNextHostName();
530                     if (retryPolicy.shouldRetry()) {
531                         paramMap.put(restapiUrlString, retryString);
532                         log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
533                             retryString);
534                         sendRequest(paramMap, ctx, retryPolicy);
535                     } else {
536                         log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
537                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
538                     }
539                 } catch (Exception ex) {
540                     String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
541                         + "has failed with error message " + ex.getMessage();
542                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
543                 }
544             }
545         }
546
547         if (r != null && r.code >= 300) {
548             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
549         }
550     }
551
552     protected void handlePartner(Map<String, String> paramMap) {
553         String partner = paramMap.get("partner");
554         if (partner != null && partner.length() > 0) {
555             PartnerDetails details = partnerStore.get(partner);
556             paramMap.put(restapiUserKey, details.username);
557             paramMap.put(restapiPasswordKey, details.password);
558             if (paramMap.get(restapiUrlString) == null) {
559                 paramMap.put(restapiUrlString, details.url);
560             }
561         }
562     }
563
564     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
565         log.info("Building {} started", format);
566         long t1 = System.currentTimeMillis();
567         String originalTemplate = template;
568
569         template = expandRepeats(ctx, template, 1);
570
571         Map<String, String> mm = new HashMap<>();
572         for (String s : ctx.getAttributeKeySet()) {
573             mm.put(s, ctx.getAttribute(s));
574         }
575
576         StringBuilder ss = new StringBuilder();
577         int i = 0;
578         while (i < template.length()) {
579             int i1 = template.indexOf("${", i);
580             if (i1 < 0) {
581                 ss.append(template.substring(i));
582                 break;
583             }
584
585             int i2 = template.indexOf('}', i1 + 2);
586             if (i2 < 0) {
587                 throw new SvcLogicException("Template error: Matching } not found");
588             }
589
590             String var1 = template.substring(i1 + 2, i2);
591             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
592             if (value1 == null || value1.trim().length() == 0) {
593                 // delete the whole element (line)
594                 int i3 = template.lastIndexOf('\n', i1);
595                 if (i3 < 0) {
596                     i3 = 0;
597                 }
598                 int i4 = template.indexOf('\n', i1);
599                 if (i4 < 0) {
600                     i4 = template.length();
601                 }
602
603                 if (i < i3) {
604                     ss.append(template.substring(i, i3));
605                 }
606                 i = i4;
607             } else {
608                 ss.append(template.substring(i, i1)).append(value1);
609                 i = i2 + 1;
610             }
611         }
612
613         String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
614             : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
615
616         if (format == Format.JSON) {
617             req = XmlJsonUtil.removeLastCommaJson(req);
618         }
619
620         long t2 = System.currentTimeMillis();
621         log.info("Building {} completed. Time: {}", format, t2 - t1);
622
623         return req;
624     }
625
626     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
627         StringBuilder newTemplate = new StringBuilder();
628         int k = 0;
629         while (k < template.length()) {
630             int i1 = template.indexOf("${repeat:", k);
631             if (i1 < 0) {
632                 newTemplate.append(template.substring(k));
633                 break;
634             }
635
636             int i2 = template.indexOf(':', i1 + 9);
637             if (i2 < 0) {
638                 throw new SvcLogicException(
639                     "Template error: Context variable name followed by : is required after repeat");
640             }
641
642             // Find the closing }, store in i3
643             int nn = 1;
644             int i3 = -1;
645             int i = i2;
646             while (nn > 0 && i < template.length()) {
647                 i3 = template.indexOf('}', i);
648                 if (i3 < 0) {
649                     throw new SvcLogicException("Template error: Matching } not found");
650                 }
651                 int i32 = template.indexOf('{', i);
652                 if (i32 >= 0 && i32 < i3) {
653                     nn++;
654                     i = i32 + 1;
655                 } else {
656                     nn--;
657                     i = i3 + 1;
658                 }
659             }
660
661             String var1 = template.substring(i1 + 9, i2);
662             String value1 = ctx.getAttribute(var1);
663             log.info("     {}:{}", var1, value1);
664             int n = 0;
665             try {
666                 n = Integer.parseInt(value1);
667             } catch (NumberFormatException e) {
668                 log.info("value1 not set or not a number, n will remain set at zero");
669             }
670
671             newTemplate.append(template.substring(k, i1));
672
673             String rpt = template.substring(i2 + 1, i3);
674
675             for (int ii = 0; ii < n; ii++) {
676                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
677                 if (ii == n - 1 && ss.trim().endsWith(",")) {
678                     int i4 = ss.lastIndexOf(',');
679                     if (i4 > 0) {
680                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
681                     }
682                 }
683                 newTemplate.append(ss);
684             }
685
686             k = i3 + 1;
687         }
688
689         if (k == 0) {
690             return newTemplate.toString();
691         }
692
693         return expandRepeats(ctx, newTemplate.toString(), level + 1);
694     }
695
696     protected String readFile(String fileName) throws SvcLogicException {
697         try {
698             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
699             return new String(encoded, "UTF-8");
700         } catch (IOException | SecurityException e) {
701             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
702         }
703     }
704
705     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
706         Parameters p = new Parameters();
707         p.restapiUser = fp.user;
708         p.restapiPassword = fp.password;
709         p.oAuthConsumerKey = fp.oAuthConsumerKey;
710         p.oAuthVersion = fp.oAuthVersion;
711         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
712         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
713         p.authtype = fp.authtype;
714         return addAuthType(c, p);
715     }
716
717     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
718         if (p.authtype == AuthType.Unspecified) {
719             if (p.restapiUser != null && p.restapiPassword != null) {
720                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
721             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
722                 Feature oAuth1Feature =
723                     OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
724                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
725                 client.register(oAuth1Feature);
726
727             }
728         } else {
729             if (p.authtype == AuthType.DIGEST) {
730                 if (p.restapiUser != null && p.restapiPassword != null) {
731                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
732                 } else {
733                     throw new SvcLogicException(
734                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
735                             + "parameters doesn't exist",
736                         new Throwable());
737                 }
738             } else if (p.authtype == AuthType.BASIC) {
739                 if (p.restapiUser != null && p.restapiPassword != null) {
740                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
741                 } else {
742                     throw new SvcLogicException(
743                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
744                             + "parameters doesn't exist",
745                         new Throwable());
746                 }
747             } else if (p.authtype == AuthType.OAUTH) {
748                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
749                     Feature oAuth1Feature = OAuth1ClientSupport
750                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
751                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
752                     client.register(oAuth1Feature);
753                 } else {
754                     throw new SvcLogicException(
755                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
756                             + "and oAuthSignatureMethod parameters doesn't exist",
757                         new Throwable());
758                 }
759             }
760         }
761         return client;
762     }
763
764     /**
765      * Receives the http response for the http request sent.
766      *
767      * @param request request msg
768      * @param p parameters
769      * @return HTTP response
770      * @throws SvcLogicException when sending http request fails
771      */
772     public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
773
774         SSLContext ssl = null;
775         if (p.ssl && p.restapiUrl.startsWith("https")) {
776             ssl = createSSLContext(p);
777         }
778         Client client;
779
780         if (ssl != null) {
781             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
782             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
783         } else {
784             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
785         }
786         setClientTimeouts(client);
787         // Needed to support additional HTTP methods such as PATCH
788         client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
789         client.register(new MetricLogClientFilter());
790         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
791
792         long t1 = System.currentTimeMillis();
793
794         HttpResponse r = new HttpResponse();
795         r.code = 200;
796         String accept = p.accept;
797         if (accept == null) {
798             accept = p.format == Format.XML ? "application/xml" : "application/json";
799         }
800
801         String contentType = p.contentType;
802         if (contentType == null) {
803             contentType = accept + ";charset=UTF-8";
804         }
805
806         if (!p.skipSending && !p.multipartFormData) {
807
808             Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
809
810             if (p.format == Format.NONE) {
811                 invocationBuilder.header("", "");
812             }
813
814             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
815                 String[] keyValuePairs = p.customHttpHeaders.split(",");
816                 for (String singlePair : keyValuePairs) {
817                     int equalPosition = singlePair.indexOf('=');
818                     invocationBuilder.header(singlePair.substring(0, equalPosition),
819                         singlePair.substring(equalPosition + 1, singlePair.length()));
820                 }
821             }
822
823             invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
824
825             Response response;
826
827             try {
828                 // When the HTTP operation has no body do not set the content-type
829                 //setting content-type has caused errors with some servers when no body is present
830                 if (request == null) {
831                     response = invocationBuilder.method(p.httpMethod.toString());
832                 } else {
833                     log.info("Sending request below to url " + p.restapiUrl);
834                     log.info(request);
835                     response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
836                 }
837             } catch (ProcessingException | IllegalStateException e) {
838                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
839             }
840
841             r.code = response.getStatus();
842             r.headers = response.getStringHeaders();
843             EntityTag etag = response.getEntityTag();
844             if (etag != null) {
845                 r.message = etag.getValue();
846             }
847             if (response.hasEntity() && r.code != 204) {
848                 r.body = response.readEntity(String.class);
849             }
850         } else if (!p.skipSending && p.multipartFormData) {
851
852             WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
853
854             MultiPart multiPart = new MultiPart();
855             multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
856
857             FileDataBodyPart fileDataBodyPart =
858                 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
859             multiPart.bodyPart(fileDataBodyPart);
860
861
862             Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
863
864             if (p.format == Format.NONE) {
865                 invocationBuilder.header("", "");
866             }
867
868             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
869                 String[] keyValuePairs = p.customHttpHeaders.split(",");
870                 for (String singlePair : keyValuePairs) {
871                     int equalPosition = singlePair.indexOf('=');
872                     invocationBuilder.header(singlePair.substring(0, equalPosition),
873                         singlePair.substring(equalPosition + 1, singlePair.length()));
874                 }
875             }
876
877             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
878
879             Response response;
880
881             try {
882                 response =
883                     invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
884             } catch (ProcessingException | IllegalStateException e) {
885                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
886             }
887
888             r.code = response.getStatus();
889             r.headers = response.getStringHeaders();
890             EntityTag etag = response.getEntityTag();
891             if (etag != null) {
892                 r.message = etag.getValue();
893             }
894             if (response.hasEntity() && r.code != 204) {
895                 r.body = response.readEntity(String.class);
896             }
897
898         }
899
900         long t2 = System.currentTimeMillis();
901         log.info(responseReceivedMessage, t2 - t1);
902         log.info(responseHttpCodeMessage, r.code);
903         log.info("HTTP response message: {}", r.message);
904         logHeaders(r.headers);
905         log.info("HTTP response: {}", r.body);
906
907         return r;
908     }
909
910     protected SSLContext createSSLContext(Parameters p) {
911         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
912             System.setProperty("jsse.enableSNIExtension", "false");
913             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
914             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
915
916             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
917
918             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
919             KeyStore ks = KeyStore.getInstance("PKCS12");
920             char[] pwd = p.keyStorePassword.toCharArray();
921             ks.load(in, pwd);
922             kmf.init(ks, pwd);
923
924             SSLContext ctx = SSLContext.getInstance("TLS");
925             ctx.init(kmf.getKeyManagers(), null, null);
926             return ctx;
927         } catch (Exception e) {
928             log.error("Error creating SSLContext: {}", e.getMessage(), e);
929         }
930         return null;
931     }
932
933     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
934         HttpResponse resp) {
935         resp.code = 500;
936         resp.message = errorMessage;
937         String pp = prefix != null ? prefix + '.' : "";
938         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
939         ctx.setAttribute(pp + "response-message", resp.message);
940     }
941
942     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
943         String pp = prefix != null ? prefix + '.' : "";
944         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
945         ctx.setAttribute(pp + "response-message", r.message);
946     }
947
948     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
949         HttpResponse r = null;
950         try {
951             FileParam p = getFileParameters(paramMap);
952             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
953
954             r = sendHttpData(data, p);
955             setResponseStatus(ctx, p.responsePrefix, r);
956
957         } catch (SvcLogicException | IOException e) {
958             log.error("Error sending the request: {}", e.getMessage(), e);
959
960             r = new HttpResponse();
961             r.code = 500;
962             r.message = e.getMessage();
963             String prefix = parseParam(paramMap, responsePrefix, false, null);
964             setResponseStatus(ctx, prefix, r);
965         }
966
967         if (r != null && r.code >= 300) {
968             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
969         }
970     }
971
972     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
973         FileParam p = new FileParam();
974         p.fileName = parseParam(paramMap, "fileName", true, null);
975         p.url = parseParam(paramMap, "url", true, null);
976         p.user = parseParam(paramMap, "user", false, null);
977         p.password = parseParam(paramMap, "password", false, null);
978         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
979         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
980         String skipSendingStr = paramMap.get(skipSendingMessage);
981         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
982         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
983         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
984         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
985         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
986         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
987         return p;
988     }
989
990     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
991         HttpResponse r;
992         try {
993             UebParam p = getUebParameters(paramMap);
994
995             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
996
997             String req;
998
999             if (p.templateFileName == null) {
1000                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1001                 p.templateFileName = defaultUebTemplateFileName;
1002             }
1003
1004             String reqTemplate = readFile(p.templateFileName);
1005             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1006             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1007
1008             r = postOnUeb(req, p);
1009             setResponseStatus(ctx, p.responsePrefix, r);
1010             if (r.body != null) {
1011                 ctx.setAttribute(pp + "httpResponse", r.body);
1012             }
1013
1014         } catch (SvcLogicException e) {
1015             log.error("Error sending the request: {}", e.getMessage(), e);
1016
1017             r = new HttpResponse();
1018             r.code = 500;
1019             r.message = e.getMessage();
1020             String prefix = parseParam(paramMap, responsePrefix, false, null);
1021             setResponseStatus(ctx, prefix, r);
1022         }
1023
1024         if (r.code >= 300) {
1025             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1026         }
1027     }
1028
1029     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
1030
1031         Client client = ClientBuilder.newBuilder().build();
1032         setClientTimeouts(client);
1033         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
1034         WebTarget webTarget = addAuthType(client, p).target(p.url);
1035
1036         log.info("Sending file");
1037         long t1 = System.currentTimeMillis();
1038
1039         HttpResponse r = new HttpResponse();
1040         r.code = 200;
1041
1042         if (!p.skipSending) {
1043             String tt = "application/octet-stream";
1044             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
1045
1046             Response response;
1047
1048             try {
1049                 if (p.httpMethod == HttpMethod.POST) {
1050                     response = invocationBuilder.post(Entity.entity(data, tt));
1051                 } else if (p.httpMethod == HttpMethod.PUT) {
1052                     response = invocationBuilder.put(Entity.entity(data, tt));
1053                 } else {
1054                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1055                 }
1056             } catch (ProcessingException e) {
1057                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1058             }
1059
1060             r.code = response.getStatus();
1061             r.headers = response.getStringHeaders();
1062             EntityTag etag = response.getEntityTag();
1063             if (etag != null) {
1064                 r.message = etag.getValue();
1065             }
1066             if (response.hasEntity() && r.code != 204) {
1067                 r.body = response.readEntity(String.class);
1068             }
1069
1070             if (r.code == 301) {
1071                 String newUrl = response.getStringHeaders().getFirst("Location");
1072
1073                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
1074
1075                 webTarget = client.target(newUrl);
1076                 invocationBuilder = webTarget.request(tt).accept(tt);
1077
1078                 try {
1079                     if (p.httpMethod == HttpMethod.POST) {
1080                         response = invocationBuilder.post(Entity.entity(data, tt));
1081                     } else if (p.httpMethod == HttpMethod.PUT) {
1082                         response = invocationBuilder.put(Entity.entity(data, tt));
1083                     } else {
1084                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1085                     }
1086                 } catch (ProcessingException e) {
1087                     throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1088                 }
1089
1090                 r.code = response.getStatus();
1091                 etag = response.getEntityTag();
1092                 if (etag != null) {
1093                     r.message = etag.getValue();
1094                 }
1095                 if (response.hasEntity() && r.code != 204) {
1096                     r.body = response.readEntity(String.class);
1097                 }
1098             }
1099         }
1100
1101         long t2 = System.currentTimeMillis();
1102         log.info(responseReceivedMessage, t2 - t1);
1103         log.info(responseHttpCodeMessage, r.code);
1104         log.info("HTTP response message: {}", r.message);
1105         logHeaders(r.headers);
1106         log.info("HTTP response: {}", r.body);
1107
1108         return r;
1109     }
1110
1111     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1112         UebParam p = new UebParam();
1113         p.topic = parseParam(paramMap, "topic", true, null);
1114         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1115         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1116         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1117         String skipSendingStr = paramMap.get(skipSendingMessage);
1118         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1119         return p;
1120     }
1121
1122     protected void logProperties(Map<String, Object> mm) {
1123         List<String> ll = new ArrayList<>();
1124         for (Object o : mm.keySet()) {
1125             ll.add((String) o);
1126         }
1127         Collections.sort(ll);
1128
1129         log.info("Properties:");
1130         for (String name : ll) {
1131             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1132         }
1133     }
1134
1135     protected void logHeaders(MultivaluedMap<String, String> mm) {
1136         log.info("HTTP response headers:");
1137
1138         if (mm == null) {
1139             return;
1140         }
1141
1142         List<String> ll = new ArrayList<>();
1143         for (Object o : mm.keySet()) {
1144             ll.add((String) o);
1145         }
1146         Collections.sort(ll);
1147
1148         for (String name : ll) {
1149             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1150         }
1151     }
1152
1153     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1154         String[] urls = uebServers.split(" ");
1155         for (int i = 0; i < urls.length; i++) {
1156             if (!urls[i].endsWith("/")) {
1157                 urls[i] += "/";
1158             }
1159             urls[i] += "events/" + p.topic;
1160         }
1161
1162         Client client = ClientBuilder.newBuilder().build();
1163         setClientTimeouts(client);
1164         WebTarget webTarget = client.target(urls[0]);
1165
1166         log.info("UEB URL: {}", urls[0]);
1167         log.info("Sending request:");
1168         log.info(request);
1169         long t1 = System.currentTimeMillis();
1170
1171         HttpResponse r = new HttpResponse();
1172         r.code = 200;
1173
1174         if (!p.skipSending) {
1175             String tt = "application/json";
1176             String tt1 = tt + ";charset=UTF-8";
1177
1178             Response response;
1179             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1180
1181             try {
1182                 response = invocationBuilder.post(Entity.entity(request, tt1));
1183             } catch (ProcessingException e) {
1184                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1185             }
1186             r.code = response.getStatus();
1187             r.headers = response.getStringHeaders();
1188             if (response.hasEntity()) {
1189                 r.body = response.readEntity(String.class);
1190             }
1191         }
1192
1193         long t2 = System.currentTimeMillis();
1194         log.info(responseReceivedMessage, t2 - t1);
1195         log.info(responseHttpCodeMessage, r.code);
1196         logHeaders(r.headers);
1197         log.info("HTTP response:\n {}", r.body);
1198
1199         return r;
1200     }
1201
1202     public void setUebServers(String uebServers) {
1203         this.uebServers = uebServers;
1204     }
1205
1206     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1207         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1208     }
1209
1210     protected void setClientTimeouts(Client client) {
1211         client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1212         client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1213     }
1214
1215     protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1216         String stringValue = System.getProperty(propertyName);
1217         if (stringValue != null && stringValue.length() > 0) {
1218             try {
1219                 return Integer.valueOf(stringValue);
1220             } catch (NumberFormatException e) {
1221                 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1222             }
1223         }
1224         return defaultValue;
1225     }
1226
1227
1228     private static class FileParam {
1229
1230         public String fileName;
1231         public String url;
1232         public String user;
1233         public String password;
1234         public HttpMethod httpMethod;
1235         public String responsePrefix;
1236         public boolean skipSending;
1237         public String oAuthConsumerKey;
1238         public String oAuthConsumerSecret;
1239         public String oAuthSignatureMethod;
1240         public String oAuthVersion;
1241         public AuthType authtype;
1242     }
1243
1244     private static class UebParam {
1245
1246         public String topic;
1247         public String templateFileName;
1248         public String rootVarName;
1249         public String responsePrefix;
1250         public boolean skipSending;
1251     }
1252 }

© 2017 ONAP. Copyright © The Linux Foundation ®. All Rights Reserved.
The Linux Foundation has registered trademarks and uses trademarks.
For a list of trademarks of The Linux Foundation, please see our Trademark Usage page.
Linux is a registered trademark of Linus Torvalds.
Privacy Policy and Terms of Use