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