Merge "Sonar fix: TemplateNode.java"
[ccsdk/sli/plugins.git] / sshapi-call-node / provider / src / main / java / org / onap / ccsdk / sli / plugins / sshapicall / model / ParseParam.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2018 Samsung Electronics. All rights
8  *                      reserved.
9  * ================================================================================
10  * Modifications Copyright © 2018 IBM
11  * ================================================================================
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  *
16  *      http://www.apache.org/licenses/LICENSE-2.0
17  *
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.ccsdk.sli.plugins.sshapicall.model;
27
28 import com.google.common.base.Strings;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
32 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import java.io.ByteArrayInputStream;
37 import java.nio.charset.StandardCharsets;
38 import java.util.Collections;
39 import java.util.HashSet;
40 import java.util.Map;
41 import java.util.Properties;
42 import java.util.Set;
43
44 public class ParseParam {
45     private static final Logger log = LoggerFactory.getLogger(ParseParam.class);
46     /**
47      * Default SSH command timeout
48      */
49     private long dEF_timeout = 12000;
50     /**
51      * Default SSH connection port.
52      */
53     private int dEF_port = 22;
54     /**
55      * Default SSH command timeout
56      */
57     private final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
58     public final String SSH_ResponsePrefix = "ResponsePrefix";
59     /**
60      * Default SSH connection port.
61      */
62     private final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
63     private Parameters p = new Parameters();
64
65     public Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
66         p.sshapiUrl = parseParam(paramMap, "Url", true, null);
67         p.sshapiPort = Integer.parseInt(parseParam(paramMap, "Port", true, Integer.toString(dEF_port)));
68         p.sshapiUser = parseParam(paramMap, "User", false, null);
69         p.sshapiPassword = parseParam(paramMap, "Password", false, null);
70         p.sshKey = parseParam(paramMap, "SshKey", false, null);
71         p.sshExecTimeout = Long.parseLong(parseParam(paramMap, "ExecTimeout", false, Long.toString(dEF_timeout)));
72         p.sshWithRetry = Boolean.valueOf(parseParam(paramMap, "Retry", false, "false"));
73         p.cmd = parseParam(paramMap, "Cmd", true, null);
74         p.responsePrefix = parseParam(paramMap, SSH_ResponsePrefix, false, null);
75         p.responseType = Format.fromString(parseParam(paramMap, "ResponseType", false, "none"));
76         p.listNameList = getListNameList(paramMap);
77         p.convertResponse = Boolean.valueOf(parseParam(paramMap, "ConvertResponse", false, "true"));
78         p.authtype = AuthType.fromString(parseParam(paramMap, "AuthType", false, "unspecified"));
79
80         return p;
81     }
82
83     public String getStringParameters(Map<String, String> paramMap, String paramName) throws SvcLogicException {
84         return parseParam(paramMap, SSH_ResponsePrefix, false, null);
85     }
86
87     public void parseOutput (SvcLogicContext ctx, String outMessage) throws SvcLogicException {
88         if (p.convertResponse) {
89             if (p.responseType == Format.NONE) {
90                 classifyOutput(ctx, outMessage);
91             } else if (p.responseType == Format.JSON) {
92                 classifyOutput(ctx, outMessage);
93             } else if (p.responseType == Format.XML) {
94                 classifyOutput(ctx, outMessage, p.listNameList);
95             }
96         }
97     }
98
99     private void classifyOutput(SvcLogicContext ctx, String outMessage, Set<String> listNameList) throws SvcLogicException {
100         Map<String, String> mm = XmlParser.convertToProperties(outMessage, p.listNameList);
101         toCtx (ctx, mm);
102     }
103
104     private void toCtx (SvcLogicContext ctx, Map<String, String> mm) {
105         if (mm != null) {
106             for (Map.Entry<String, String> entry : mm.entrySet()) {
107                 if (p.responsePrefix != null) {
108                     ctx.setAttribute(p.responsePrefix + "." + entry.getKey(), entry.getValue());
109                     log.info("+++ " + p.responsePrefix + "." + entry.getKey() + ": [" + entry.getValue() + "]");
110                 } else {
111                     ctx.setAttribute(entry.getKey(), entry.getValue());
112                     log.info("+++ " + entry.getKey() + ": [" + entry.getValue() + "]");
113                 }
114             }
115         }
116     }
117
118     private void classifyOutput(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
119         try {
120             Map<String, String> mm = JsonParser.convertToProperties(outMessage);
121             toCtx (ctx, mm);
122         } catch (org.codehaus.jettison.json.JSONException e) {
123             log.info("Output not in JSON format");
124             putToProperties(ctx, p.responsePrefix);
125         } catch (Exception e) {
126             throw  new SvcLogicException("error parsing response file");
127         }
128     }
129
130     private void putToProperties(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
131
132         try {
133             Properties prop = new Properties();
134             prop.load(new ByteArrayInputStream(outMessage.getBytes(StandardCharsets.UTF_8)));
135             for (Object key : prop.keySet()) {
136                 String name = (String) key;
137                 String value = prop.getProperty(name);
138                 if (value != null && value.trim().length() > 0) {
139                     if (p.responsePrefix != null) {
140                         ctx.setAttribute(p.responsePrefix + "." + name, value.trim());
141                         log.info("+++ " + p.responsePrefix + "." + name + ": [" + value + "]");
142                     } else {
143                         ctx.setAttribute(name, value.trim());
144                         log.info("+++ " + name + ": [" + value + "]");
145                     }
146                 }
147             }
148         } catch (Exception e) {
149             throw  new SvcLogicException( "Error parsing response file.");
150         }
151     }
152
153     public String makeCommand (Map<String, String> params) {
154         JSONObject jsonPayload = new JSONObject();
155         final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, FILE_PARAMETERS_OPT_KEY};
156         parseParam(params, optionalTestParams, jsonPayload);
157         JSONObject envParams = (JSONObject) jsonPayload.remove(ENV_PARAMETERS_OPT_KEY);
158         JSONObject fileParams = (JSONObject) jsonPayload.remove(FILE_PARAMETERS_OPT_KEY);
159
160         StringBuilder constructedCommand = new StringBuilder();
161         constructedCommand.append(parseFileParam(fileParams)).append(p.cmd).append(" ").append(parseEnvParam(envParams));
162
163         return constructedCommand.toString();
164     }
165
166     private String parseEnvParam(JSONObject envParams) {
167         StringBuilder envParamBuilder = new StringBuilder();
168         if (envParams != null) {
169             for (Object key : envParams.keySet()) {
170                 if (envParamBuilder.length() > 0) {
171                     envParamBuilder.append(", ");
172                 }
173                 envParamBuilder.append(key + "=" + envParams.get((String) key));
174             }
175         }
176         return envParamBuilder.toString();
177     }
178
179     private String parseFileParam(JSONObject fileParams) {
180         StringBuilder fileParamBuilder = new StringBuilder();
181         if (fileParams != null) {
182             for (Object key : fileParams.keySet()) {
183                 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
184             }
185         }
186         return fileParamBuilder.toString();
187     }
188
189     private void parseParam(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload)
190             throws JSONException {
191
192         Set<String> optionalParamsSet = new HashSet<>();
193         Collections.addAll(optionalParamsSet, optionalTestParams);
194
195         //@formatter:off
196         params.entrySet()
197                 .stream()
198                 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
199                 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
200                 .forEach(entry -> parseParam(entry, jsonPayload));
201         //@formatter:on
202     }
203
204     private void parseParam(Map.Entry<String, String> params, JSONObject jsonPayload)
205             throws JSONException {
206         String key = params.getKey();
207         String payload = params.getValue();
208
209         switch (key) {
210             case ENV_PARAMETERS_OPT_KEY:
211                 JSONObject paramsJson = new JSONObject(payload);
212                 jsonPayload.put(key, paramsJson);
213                 break;
214
215             case FILE_PARAMETERS_OPT_KEY:
216                 jsonPayload.put(key, getFilePayload(payload));
217                 break;
218
219             default:
220                 break;
221         }
222     }
223
224     /**
225      * Return payload with escaped newlines
226      */
227     private JSONObject getFilePayload(String payload) {
228         String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
229         return new JSONObject(formattedPayload);
230     }
231
232     private Set<String> getListNameList(Map<String, String> paramMap) {
233         Set<String> ll = new HashSet<>();
234         for (Map.Entry<String,String> entry : paramMap.entrySet())
235             if (entry.getKey().startsWith("listName"))
236                 ll.add(entry.getValue());
237         return ll;
238     }
239
240     private String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
241             throws SvcLogicException {
242         String s = paramMap.get(name);
243
244         if (s == null || s.trim().length() == 0) {
245             if (!required)
246                 return def;
247             throw new SvcLogicException("Parameter " + name + " is required in sshapiCallNode");
248         }
249
250         s = s.trim();
251         StringBuilder value = new StringBuilder();
252         int i = 0;
253         int i1 = s.indexOf('%');
254         while (i1 >= 0) {
255             int i2 = s.indexOf('%', i1 + 1);
256             if (i2 < 0)
257                 break;
258
259             String varName = s.substring(i1 + 1, i2);
260             String varValue = System.getenv(varName);
261             if (varValue == null)
262                 varValue = "%" + varName + "%";
263
264             value.append(s.substring(i, i1));
265             value.append(varValue);
266
267             i = i2 + 1;
268             i1 = s.indexOf('%', i);
269         }
270         value.append(s.substring(i));
271
272         log.info("Parameter {}: [{}]", name, value);
273         return value.toString();
274     }
275 }