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