ConfigComponentAdaptor sonar fixes part 1
[appc.git] / appc-config / appc-config-adaptor / provider / src / main / java / org / onap / appc / ccadaptor / ConfigComponentAdaptor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * =============================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.appc.ccadaptor;
24
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.sun.jersey.api.client.Client;
28 import com.sun.jersey.api.client.ClientResponse;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.core.util.Base64;
31 import java.io.BufferedReader;
32 import java.io.ByteArrayInputStream;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.InputStreamReader;
37 import java.net.HttpURLConnection;
38 import java.util.HashMap;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.NoSuchElementException;
42 import java.util.Properties;
43 import java.util.StringTokenizer;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
46
47 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
48
49     private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
50     private static final String ACTION_PARAM = "action";
51     private static final String ACTION_PREPARE = "prepare";
52     private static final String ACTION_ACTIVATE = "activate";
53     private static final String PUT_KEY = "put";
54     private static final String GET_KEY = "get";
55     private static final String CLI_KEY = "cli";
56     private static final String SSH_JCRAFT_WRAPPER_EXCEPTION_STR = "Exception occurred while using sshJcraftWrapper";
57     private static final String CLI_OUTPUT_PARAM = "cliOutput";
58     private static final String ESCAPE_SQL_KEY = "escapeSql";
59     private static final String GET_CLI_RUNNING_CONFIG_KEY = "GetCliRunningConfig";
60     private static final String USERNAME_PARAM = "User_name";
61     private static final String HOST_IP_PARAM = "Host_ip_address";
62     private static final String PASSWORD_PARAM = "Password";
63     private static final String PORT_NUMBER = "Port_number";
64     private static final String XML_DOWNLOAD_KEY = "xml-download";
65     private static final String PROMPT_STR = "]]>]]>";
66     private static final String RPC_REPLY_END_TAG = "</rpc-reply>";
67     private static final String RESPONSE_STR = "response=\n{}\n";
68     private static final String XML_GET_RUNNING_CONF_KEY = "xml-getrunningconfig";
69     private static final String DOWNLOAD_CLI_CONFIG_KEY = "DownloadCliConfig";
70
71
72     private String configUrl;
73     private String configUser;
74     private String configPassword;
75     private String auditUrl;
76     private String auditUser;
77     private String auditPassword;
78     private String configCallbackUrl;
79     private String auditCallbackUrl;
80
81     public ConfigComponentAdaptor(Properties props) {
82         if (props != null) {
83             configUrl = props.getProperty("configComponent.url", "");
84             configUser = props.getProperty("configComponent.user", "");
85             configPassword = props.getProperty("configComponent.passwd", "");
86             auditUrl = props.getProperty("auditComponent.url", "");
87             auditUser = props.getProperty("auditComponent.user", "");
88             auditPassword = props.getProperty("auditComponent.passwd", "");
89             configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
90             auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
91         }
92     }
93
94     @Override
95     public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
96         HttpResponse r = new HttpResponse();
97         r.code = 200;
98         log.debug("ConfigComponentAdaptor.configure - key = " + key);
99         log.debug("key = {}", key);
100         log.debug("Parameters:");
101         for (Entry<String, String> paramEntrySet : parameters.entrySet()) {
102             log.debug("    {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue());
103         }
104
105         String parmval = parameters.get("config-component-configUrl");
106         if (!nullOrEmpty(parmval)) {
107             log.debug("Overwriting URL with {}", parmval);
108             configUrl = parmval;
109         }
110
111         parmval = parameters.get("config-component-configPassword");
112         if (!nullOrEmpty(parmval)) {
113             log.debug("Overwriting configPassword with {}", parmval);
114             configPassword = parmval;
115         }
116
117         parmval = parameters.get("config-component-configUser");
118         if (!nullOrEmpty(parmval)) {
119             log.debug("Overwriting configUser id with {}", parmval);
120             configUser = parmval;
121         }
122
123         String action = parameters.get(ACTION_PARAM);
124
125         String chg = ctx.getAttribute(
126             "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
127         if (chg != null && areEqual(action, ACTION_PREPARE)) {
128             return prepare(ctx, "CHANGE", "change");
129         }
130         if (chg != null && areEqual(action, ACTION_ACTIVATE)) {
131             return activate(ctx, true);
132         }
133
134         String scale = ctx.getAttribute(
135             "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
136         if (scale != null && areEqual(action, ACTION_PREPARE)) {
137             return prepare(ctx, "CHANGE", "scale");
138         }
139         if (scale != null && areEqual(action, ACTION_ACTIVATE)) {
140             return activate(ctx, true);
141         }
142
143         if (areEqual(action, ACTION_PREPARE)) {
144             return prepare(ctx, "BASE", "create");
145         }
146         if (areEqual(action, ACTION_ACTIVATE)) {
147             return activate(ctx, false);
148         }
149
150         if ("backup".equalsIgnoreCase(action)) {
151             return prepare(ctx, "BACKUP", "backup");
152         }
153         if ("restorebackup".equalsIgnoreCase(action)) {
154             return prepare(ctx, "RESTOREBACKUP", "restorebackup");
155         }
156         if ("deletebackup".equalsIgnoreCase(action)) {
157             return prepare(ctx, "DELETEBACKUP", "deletebackup");
158         }
159         if ("audit".equalsIgnoreCase(action)) {
160             return audit(ctx, "FULL");
161         }
162         if ("getrunningconfig".equalsIgnoreCase(action)) {
163             return audit(ctx, "RUNNING");
164         }
165
166         if ((key.equals(PUT_KEY)) || (key.equals(GET_KEY))) {
167             String loginId = parameters.get("loginId");
168             String host = parameters.get("host");
169             String password = parameters.get("password");
170             password = EncryptionTool.getInstance().decrypt(password);
171             String fullPathFileName = parameters.get("fullPathFileName");
172
173             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
174             log.debug("SCP: SshJcraftWrapper has been instantiated");
175
176             try {
177                 if (key.equals(PUT_KEY)) {
178                     String data = parameters.get("data");
179                     log.debug("Command is for put: Length of data is: {}", data.length());
180                     InputStream is = new ByteArrayInputStream(data.getBytes());
181                     log.debug("SCP: Doing a put: fullPathFileName={}", fullPathFileName);
182                     sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
183                     trySleepFor(1000L * 180);
184                 } else {  // Must be a get
185                     log.debug("SCP: Doing a get: fullPathFileName={}", fullPathFileName);
186                     String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
187                     log.debug("Got the response and putting into the ctx object");
188                     ctx.setAttribute("fileContents", response);
189                     log.debug("SCP: Closing the SFTP connection");
190                 }
191                 return setResponseStatus(ctx, r);
192             } catch (IOException e) {
193                 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
194                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
195                 r.message = e.getMessage();
196                 return setResponseStatus(ctx, r);
197             }
198         }
199         if (key.equals(CLI_KEY)) {
200             String loginId = parameters.get("loginId");
201             String host = parameters.get("host");
202             String password = parameters.get("password");
203             password = EncryptionTool.getInstance().decrypt(password);
204             String portNumber = parameters.get("portNumber");
205             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
206             try {
207                 log.debug("CLI: Attempting to login: host={} loginId={} password={} portNumber={}", host, loginId,
208                     password, portNumber);
209                 sshJcraftWrapper.connect(host, loginId, password); //what about portNum?
210
211                 log.debug("Sending 'sdc'");
212                 sshJcraftWrapper.send("sdc", ":");
213                 log.debug("Sending 1");
214                 sshJcraftWrapper.send("1", ":");
215                 log.debug("Sending 1, the second time");
216                 sshJcraftWrapper.send("1", "#");
217                 log.debug("Sending paging-options disable");
218                 sshJcraftWrapper.send("paging-options disable", "#");
219                 log.debug("Sending show config");
220                 String response = sshJcraftWrapper.send("show config", "#");
221
222                 log.debug("response is now:'{}'", response);
223                 log.debug("Populating the ctx object with the response");
224                 ctx.setAttribute(CLI_OUTPUT_PARAM, response);
225                 sshJcraftWrapper.closeConnection();
226                 r.code = 200;
227                 return setResponseStatus(ctx, r);
228             } catch (IOException e) {
229                 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
230                 sshJcraftWrapper.closeConnection();
231                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
232                 r.message = e.getMessage();
233                 return setResponseStatus(ctx, r);
234             }
235         }
236         if (key.equals(ESCAPE_SQL_KEY)) {
237             String data = parameters.get("artifactContents");
238             log.debug("ConfigComponentAdaptor.configure - escapeSql");
239             data = escapeMySql(data);
240             ctx.setAttribute("escapedData", data);
241             return setResponseStatus(ctx, r);
242         }
243         if (key.equals(GET_CLI_RUNNING_CONFIG_KEY)) {
244             log.debug("key was: " + GET_CLI_RUNNING_CONFIG_KEY);
245             String username = parameters.get(USERNAME_PARAM);
246             String hostIpAddress = parameters.get(HOST_IP_PARAM);
247             String password = parameters.get(PASSWORD_PARAM);
248             password = EncryptionTool.getInstance().decrypt(password);
249             String portNumber = parameters.get(PORT_NUMBER);
250             String getConfigTemplate = parameters.get("Get_config_template");
251             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
252             log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
253             try {
254                 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name="
255                     + username + " Password=" + password + " Port_number=" + portNumber);
256
257
258                 boolean showConfigFlag = false;
259                 sshJcraftWrapper
260                     .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber));
261                 log.debug("GetCliRunningConfig: On the VNF device");
262                 StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n");
263                 String command = null;
264                 StringBuilder cliResponse = new StringBuilder();
265
266                 // shouldn't this be used somewhere?
267                 StringBuilder response = new StringBuilder();
268                 try {
269                     while (st.hasMoreTokens()) {
270                         String line = st.nextToken();
271                         log.debug("line={}", line);
272                         if (line.contains("Request:")) {
273                             log.debug("Found a Request line: line={}", line);
274                             command = getStringBetweenQuotes(line);
275                             log.debug("Sending command={}", command);
276                             sshJcraftWrapper.send(command);
277                             log.debug("command has been sent");
278                             if (line.contains("show config")) {
279                                 showConfigFlag = true;
280                                 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
281                             }
282                         }
283                         if (line.contains("Response: Ends_With")) {
284                             log.debug("Found a Response line: line={}", line);
285                             String delemeter = getStringBetweenQuotes(line);
286                             log.debug("The delemeter={}", delemeter);
287                             String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command);
288                             response.append(tmpResponse);
289                             if (showConfigFlag) {
290                                 showConfigFlag = false;
291                                 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
292                                 while (st2.hasMoreTokens()) {
293                                     String line2 = st2.nextToken();
294                                     if (!line2.contains("#")) {
295                                         cliResponse.append(line2).append('\n');
296                                     }
297                                 }
298                             }
299                         }
300                     }
301                 } catch (NoSuchElementException e) {
302                     log.error(e.getMessage(), e);
303                 }
304                 log.debug("CliResponse=\n{}", cliResponse.toString());
305                 ctx.setAttribute(CLI_OUTPUT_PARAM, cliResponse.toString());
306                 sshJcraftWrapper.closeConnection();
307                 r.code = 200;
308                 return setResponseStatus(ctx, r);
309             } catch (IOException e) {
310                 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
311                 sshJcraftWrapper.closeConnection();
312                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
313                 r.message = e.getMessage();
314                 return setResponseStatus(ctx, r);
315             }
316         }
317         if (key.equals(XML_DOWNLOAD_KEY)) {
318             log.debug("key was: " + XML_DOWNLOAD_KEY);
319             String userName = parameters.get(USERNAME_PARAM);
320             String hostIpAddress = parameters.get(HOST_IP_PARAM);
321             String password = parameters.get(PASSWORD_PARAM);
322             password = EncryptionTool.getInstance().decrypt(password);
323             String portNumber = parameters.get(PORT_NUMBER);
324             String contents = parameters.get("Contents");
325             String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n  <capabilities>\n   <capability>urn:ietf:params:netconf:base:1.0</capability>\n  <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
326             String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
327             String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
328
329             log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", userName,
330                 hostIpAddress, password, portNumber);
331             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
332             try {
333                 // what about prompt "]]>]]>"?
334                 sshJcraftWrapper
335                     .connect(hostIpAddress, userName, password, 30000, Integer.parseInt(portNumber), "netconf");
336
337                 netconfHelloCmd += PROMPT_STR;
338                 log.debug("Sending the hello command");
339                 sshJcraftWrapper.send(netconfHelloCmd);
340                 String response;
341                 log.debug("Sending xmlCmd cmd");
342                 String messageId = "1";
343                 messageId = "\"" + messageId + "\"";
344                 String loadConfigurationString =
345                     "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
346                         + messageId
347                         + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
348                         + contents + "</config> </edit-config> </rpc>";
349                 loadConfigurationString = loadConfigurationString + PROMPT_STR;
350                 sshJcraftWrapper.send(loadConfigurationString);
351                 log.debug("After sending loadConfigurationString");
352                 response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 600000, "");
353                 if (response.contains("rpc-error")) {
354                     log.debug("Error from device: Response from device had 'rpc-error'");
355                     log.debug(RESPONSE_STR, response);
356                     r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
357                     r.message = response;
358                 } else {
359                     log.debug(":LoadConfiguration was a success, sending commit cmd");
360                     sshJcraftWrapper.send(commitCmd);
361                     log.debug(":After sending commitCmd");
362                     response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, "");
363                     handleRpcError(r, response);
364                 }
365                 sshJcraftWrapper.send(terminateConnectionCmd);
366                 sshJcraftWrapper.closeConnection();
367                 return setResponseStatus(ctx, r);
368             } catch (Exception e) {
369                 log.error("Caught an Exception", e);
370                 sshJcraftWrapper.closeConnection();
371                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
372                 r.message = e.getMessage();
373                 log.debug("Returning error message");
374                 return setResponseStatus(ctx, r);
375             }
376         }
377         if (key.equals(XML_GET_RUNNING_CONF_KEY)) {
378             log.debug("key was: : xml-getrunningconfig");
379             String xmlGetRunningConfigCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\">  <get-config> <source> <running /> </source> </get-config> </rpc>\n";
380             String hostIpAddress = parameters.get(HOST_IP_PARAM);
381             String username = parameters.get(USERNAME_PARAM);
382             String password = parameters.get(PASSWORD_PARAM);
383             password = EncryptionTool.getInstance().decrypt(password);
384             String portNumber = parameters.get(PORT_NUMBER);
385             String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n  <capabilities>\n   <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
386             String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
387             log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", username,
388                 hostIpAddress, password, portNumber);
389             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
390             try {
391
392                 sshJcraftWrapper
393                     .connect(hostIpAddress, username, password, 30000, Integer.parseInt(portNumber),
394                         "netconf"); //What about prompt "]]>]]>" here?
395                 netconfHelloCmd += PROMPT_STR;
396                 log.debug(":Sending the hello command");
397                 sshJcraftWrapper.send(netconfHelloCmd);
398                 String response;
399                 log.debug("Sending get running config command");
400                 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
401                 response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, "");
402                 log.debug("Response from getRunningconfigCmd={}", response);
403                 response = trimResponse(response);
404                 ctx.setAttribute("xmlRunningConfigOutput", response);
405                 sshJcraftWrapper.send(terminateConnectionCmd);
406                 sshJcraftWrapper.closeConnection();
407                 r.code = 200;
408                 return setResponseStatus(ctx, r);
409             } catch (Exception e) {
410                 log.error("Caught an Exception", e);
411                 sshJcraftWrapper.closeConnection();
412                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
413                 r.message = e.getMessage();
414                 log.debug("Returning error message");
415                 return setResponseStatus(ctx, r);
416             }
417         }
418         if (key.equals(DOWNLOAD_CLI_CONFIG_KEY)) {
419             log.debug("key was: DownloadCliConfig: ");
420             String username = parameters.get(USERNAME_PARAM);
421             String hostIpAddress = parameters.get(HOST_IP_PARAM);
422             String password = parameters.get(PASSWORD_PARAM);
423             password = EncryptionTool.getInstance().decrypt(password);
424             String portNumber = parameters.get(PORT_NUMBER);
425             String downloadConfigTemplate = parameters.get("Download_config_template");
426             String configContents = parameters.get("Config_contents");
427             log.debug("Contents of the 'Config_contents' are: {}", configContents);
428             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
429             log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
430             int timeout = 4 * 60 * 1000;
431             try {
432                 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name="
433                     + username + " Password=" + password + " Port_number=" + portNumber);
434
435                 StringBuilder cliResponse = new StringBuilder();
436
437                 // shouldn't this be used somewhere?
438                 StringBuilder response = new StringBuilder();
439
440                 sshJcraftWrapper
441                     .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber));
442                 log.debug("DownloadCliConfig: On the VNF device");
443                 StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n");
444                 String command = null;
445                 String executeConfigContentsDelemeter;
446                 try {
447                     while (st.hasMoreTokens()) {
448                         String line = st.nextToken();
449                         log.debug("line={}", line);
450                         if (line.contains("Request:")) {
451                             log.debug("Found a Request line: line={}", line);
452                             command = getStringBetweenQuotes(line);
453                             log.debug("Sending command={}", command);
454                             sshJcraftWrapper.send(command);
455                             log.debug("command has been sent");
456                         } else if ((line.contains("Response: Ends_With")) && (
457                             !line.contains("Execute_config_contents Response: Ends_With"))) {
458                             log.debug("Found a Response line: line={}", line);
459                             String delimiter = getStringBetweenQuotes(line);
460                             log.debug("The delimiter={}", delimiter);
461                             String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
462                             response.append(tmpResponse);
463                             cliResponse.append(tmpResponse);
464                         } else if (line.contains("Execute_config_contents Response: Ends_With")) {
465                             log.debug("Found a 'Execute_config_contents Response:' line={}", line);
466                             executeConfigContentsDelemeter = getStringBetweenQuotes(line);
467                             log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
468                             StringTokenizer st2 = new StringTokenizer(configContents, "\n");
469                             while (st2.hasMoreTokens()) {
470                                 String cmd = st2.nextToken();
471                                 log.debug("Config_contents: cmd={}", cmd);
472                                 sshJcraftWrapper.send(cmd);
473                                 String tmpResponse = sshJcraftWrapper
474                                     .receiveUntil(executeConfigContentsDelemeter, timeout, command);
475                                 cliResponse.append(tmpResponse);
476                             }
477                         }
478                     }
479                 } catch (NoSuchElementException e) {
480                     log.error(e.getMessage(), e);
481                 }
482                 sshJcraftWrapper.closeConnection();
483                 log.debug(":Escaping all the single and double quotes in the response");
484
485                 String escapedCliResponse = cliResponse
486                     .toString()
487                     .replaceAll("\"", "\\\\\"")
488                     .replaceAll("\'", "\\\\'");
489
490                 log.debug("CliResponse=\n{}" + escapedCliResponse);
491                 ctx.setAttribute(CLI_OUTPUT_PARAM, escapedCliResponse);
492                 r.code = 200;
493                 return setResponseStatus(ctx, r);
494             } catch (IOException e) {
495                 log.error(e.getMessage() + e);
496                 sshJcraftWrapper.closeConnection();
497                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
498                 r.message = e.getMessage();
499                 log.debug("DownloadCliConfig: Returning error message");
500                 return setResponseStatus(ctx, r);
501             }
502         }
503
504         log.debug("Unsupported action - {}", action);
505         return ConfigStatus.FAILURE;
506     }
507
508     private boolean areEqual(String action, String actionPrepare) {
509         return action != null && action.equalsIgnoreCase(actionPrepare);
510     }
511
512     private boolean nullOrEmpty(String parmval) {
513         return parmval != null && parmval.length() > 0;
514     }
515
516     private void handleRpcError(HttpResponse r, String response) {
517         if (response.contains("rpc-error")) {
518             log.debug("Error from device: Response from device had 'rpc-error'");
519             log.debug(RESPONSE_STR, response);
520             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
521             r.message = response;
522         } else {
523             log.debug(":Looks like a success");
524             log.debug(RESPONSE_STR, response);
525             r.code = 200;
526         }
527     }
528
529     private void trySleepFor(long length) {
530         try {
531             log.debug("Sleeping for 180 seconds....");
532             Thread.sleep(length);
533             log.debug("Woke up....");
534         } catch (InterruptedException ee) {
535             log.error("Sleep interrupted", ee);
536             Thread.currentThread().interrupt();
537         }
538     }
539
540     private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
541         String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
542         String ndTemplate = readFile(templateName);
543         String nd = buildNetworkData2(ctx, ndTemplate, operation);
544
545         String reqTemplate = readFile("/config-request.xml");
546         Map<String, String> param = new HashMap<String, String>();
547         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
548         param.put("request-type", requestType);
549         param.put("callback-url", configCallbackUrl);
550         if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
551             param.put(ACTION_PARAM, "GenerateOnly");
552         }
553         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
554         param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
555         param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
556         param.put("network-data", nd);
557
558         String req = null;
559         try {
560             req = buildXmlRequest(param, reqTemplate);
561         } catch (Exception e) {
562             log.error("Error building the XML request: ", e);
563
564             HttpResponse r = new HttpResponse();
565             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
566             r.message = e.getMessage();
567             return setResponseStatus(ctx, r);
568         }
569
570         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
571         return setResponseStatus(ctx, r);
572     }
573
574     private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
575         String reqTemplate = readFile("/config-request.xml");
576         Map<String, String> param = new HashMap<String, String>();
577         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
578         param.put("callback-url", configCallbackUrl);
579         param.put(ACTION_PARAM, change ? "DownloadChange" : "DownloadBase");
580         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
581
582         String req = null;
583         try {
584             req = buildXmlRequest(param, reqTemplate);
585         } catch (Exception e) {
586             log.error("Error building the XML request: ", e);
587
588             HttpResponse r = new HttpResponse();
589             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
590             r.message = e.getMessage();
591             return setResponseStatus(ctx, r);
592         }
593
594         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
595         return setResponseStatus(ctx, r);
596     }
597
598     private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
599         String reqTemplate = readFile("/audit-request.xml");
600         Map<String, String> param = new HashMap<String, String>();
601         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
602         param.put("callback-url", auditCallbackUrl);
603         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
604         param.put("audit-level", auditLevel);
605
606         String req = null;
607         try {
608             req = buildXmlRequest(param, reqTemplate);
609         } catch (Exception e) {
610             log.error("Error building the XML request: ", e);
611
612             HttpResponse r = new HttpResponse();
613             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
614             r.message = e.getMessage();
615             return setResponseStatus(ctx, r);
616         }
617
618         HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
619         return setResponseStatus(ctx, r);
620     }
621
622     @Override
623     public ConfigStatus activate(String key, SvcLogicContext ctx) {
624         return ConfigStatus.SUCCESS;
625     }
626
627     @Override
628     public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
629         return ConfigStatus.SUCCESS;
630     }
631
632     private String escapeMySql(String input) {
633         if (input == null) {
634             return null;
635         }
636
637         input = input.replace("\\", "\\\\");
638         input = input.replace("\'", "\\'");
639         return input;
640
641     }
642
643     private String readFile(String fileName) {
644         InputStream is = getClass().getResourceAsStream(fileName);
645         InputStreamReader isr = new InputStreamReader(is);
646         BufferedReader in = new BufferedReader(isr);
647         StringBuilder ss = new StringBuilder();
648         try {
649             String s = in.readLine();
650             while (s != null) {
651                 ss.append(s).append('\n');
652                 s = in.readLine();
653             }
654         } catch (IOException e) {
655             throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
656         } finally {
657             try {
658                 in.close();
659             } catch (Exception e) {
660                 log.warn("Could not close BufferedReader", e);
661             }
662             try {
663                 isr.close();
664             } catch (Exception e) {
665                 log.warn("Could not close InputStreamReader", e);
666             }
667             try {
668                 is.close();
669             } catch (Exception e) {
670                 log.warn("Could not close InputStream", e);
671             }
672         }
673         return ss.toString();
674     }
675
676     private String buildXmlRequest(Map<String, String> param, String template) {
677         StringBuilder ss = new StringBuilder();
678         int i = 0;
679         while (i < template.length()) {
680             int i1 = template.indexOf("${", i);
681             if (i1 < 0) {
682                 ss.append(template.substring(i));
683                 break;
684             }
685
686             int i2 = template.indexOf('}', i1 + 2);
687             if (i2 < 0) {
688                 throw new RuntimeException("Template error: Matching } not found");
689             }
690
691             String var1 = template.substring(i1 + 2, i2);
692             String value1 = param.get(var1);
693             if (value1 == null || value1.trim().length() == 0) {
694                 // delete the whole element (line)
695                 int i3 = template.lastIndexOf('\n', i1);
696                 if (i3 < 0) {
697                     i3 = 0;
698                 }
699                 int i4 = template.indexOf('\n', i1);
700                 if (i4 < 0) {
701                     i4 = template.length();
702                 }
703
704                 if (i < i3) {
705                     ss.append(template.substring(i, i3));
706                 }
707                 i = i4;
708             } else {
709                 ss.append(template.substring(i, i1)).append(value1);
710                 i = i2 + 1;
711             }
712         }
713
714         return ss.toString();
715     }
716
717     private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
718         log.info("Building XML started");
719         long t1 = System.currentTimeMillis();
720
721         template = expandRepeats(ctx, template, 1);
722
723         Map<String, String> mm = new HashMap<>();
724         for (String s : ctx.getAttributeKeySet()) {
725             mm.put(s, ctx.getAttribute(s));
726         }
727         mm.put("operation", operation);
728
729         StringBuilder ss = new StringBuilder();
730         int i = 0;
731         while (i < template.length()) {
732             int i1 = template.indexOf("${", i);
733             if (i1 < 0) {
734                 ss.append(template.substring(i));
735                 break;
736             }
737
738             int i2 = template.indexOf('}', i1 + 2);
739             if (i2 < 0) {
740                 throw new RuntimeException("Template error: Matching } not found");
741             }
742
743             String var1 = template.substring(i1 + 2, i2);
744             String value1 = XmlUtil.getXml(mm, var1);
745             if (value1 == null || value1.trim().length() == 0) {
746                 int i3 = template.lastIndexOf('\n', i1);
747                 if (i3 < 0) {
748                     i3 = 0;
749                 }
750                 int i4 = template.indexOf('\n', i1);
751                 if (i4 < 0) {
752                     i4 = template.length();
753                 }
754
755                 if (i < i3) {
756                     ss.append(template.substring(i, i3));
757                 }
758                 i = i4;
759             } else {
760                 ss.append(template.substring(i, i1)).append(value1);
761                 i = i2 + 1;
762             }
763         }
764
765         long t2 = System.currentTimeMillis();
766         log.info("Building XML completed. Time: " + (t2 - t1));
767
768         return ss.toString();
769     }
770
771     private String expandRepeats(SvcLogicContext ctx, String template, int level) {
772         StringBuilder newTemplate = new StringBuilder();
773         int k = 0;
774         while (k < template.length()) {
775             int i1 = template.indexOf("${repeat:", k);
776             if (i1 < 0) {
777                 newTemplate.append(template.substring(k));
778                 break;
779             }
780
781             int i2 = template.indexOf(':', i1 + 9);
782             if (i2 < 0) {
783                 throw new RuntimeException(
784                     "Template error: Context variable name followed by : is required after repeat");
785             }
786
787             // Find the closing }, store in i3
788             int nn = 1;
789             int i3 = -1;
790             int i = i2;
791             while (nn > 0 && i < template.length()) {
792                 i3 = template.indexOf('}', i);
793                 if (i3 < 0) {
794                     throw new RuntimeException("Template error: Matching } not found");
795                 }
796                 int i32 = template.indexOf('{', i);
797                 if (i32 >= 0 && i32 < i3) {
798                     nn++;
799                     i = i32 + 1;
800                 } else {
801                     nn--;
802                     i = i3 + 1;
803                 }
804             }
805
806             String var1 = template.substring(i1 + 9, i2);
807             String value1 = ctx.getAttribute(var1);
808             log.info("     " + var1 + ": " + value1);
809             int n = 0;
810             try {
811                 n = Integer.parseInt(value1);
812             } catch (Exception e) {
813                 n = 0;
814             }
815
816             newTemplate.append(template.substring(k, i1));
817
818             String rpt = template.substring(i2 + 1, i3);
819
820             for (int ii = 0; ii < n; ii++) {
821                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
822                 newTemplate.append(ss);
823             }
824
825             k = i3 + 1;
826         }
827
828         if (k == 0) {
829             return newTemplate.toString();
830         }
831
832         return expandRepeats(ctx, newTemplate.toString(), level + 1);
833     }
834
835     private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
836         try {
837             Client client = Client.create();
838             client.setConnectTimeout(5000);
839             WebResource webResource = client.resource(url);
840
841             log.info("SENDING...............");
842             log.info(xmlRequest);
843
844             String authString = user + ":" + password;
845             byte[] authEncBytes = Base64.encode(authString);
846             String authStringEnc = new String(authEncBytes);
847             authString = "Basic " + authStringEnc;
848
849             ClientResponse response =
850                 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
851                     ClientResponse.class, xmlRequest);
852
853             int code = response.getStatus();
854             String message = null;
855
856             log.info("RESPONSE...............");
857             log.info("HTTP response code: " + code);
858             log.info("HTTP response message: " + message);
859             log.info("");
860
861             HttpResponse r = new HttpResponse();
862             r.code = code;
863             r.message = message;
864             return r;
865
866         } catch (Exception e) {
867             log.error("Error sending the request: ", e);
868
869             HttpResponse r = new HttpResponse();
870             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
871             r.message = e.getMessage();
872             return r;
873         }
874     }
875
876     private static class HttpResponse {
877
878         public int code;
879         public String message;
880     }
881
882     private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
883         ctx.setAttribute("error-code", String.valueOf(r.code));
884         ctx.setAttribute("error-message", r.message);
885
886         return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
887     }
888
889     private String getStringBetweenQuotes(String string) {
890         log.debug("string=" + string);
891         String retString;
892         int start = string.indexOf('\"');
893         int end = string.lastIndexOf('\"');
894         retString = string.substring(start + 1, end);
895         log.debug("retString=" + retString);
896         return retString;
897     }
898
899     public static String _readFile(String fileName) {
900         StringBuffer strBuff = new StringBuffer();
901         String line;
902         try {
903             BufferedReader in = new BufferedReader(new FileReader(fileName));
904             while ((line = in.readLine()) != null) {
905                 strBuff.append(line + "\n");
906             }
907             in.close();
908         } catch (IOException e) {
909             log.error("Caught an IOException in method readFile()", e);
910         }
911         return (strBuff.toString());
912     }
913
914     private String trimResponse(String response) {
915         StringTokenizer line = new StringTokenizer(response, "\n");
916         StringBuffer sb = new StringBuffer();
917         boolean captureText = false;
918         while (line.hasMoreTokens()) {
919             String token = line.nextToken();
920             if (token.indexOf("<configuration xmlns=") != -1) {
921                 captureText = true;
922             }
923             if (captureText) {
924                 sb.append(token + "\n");
925             }
926             if (token.indexOf("</configuration>") != -1) {
927                 captureText = false;
928             }
929         }
930         return (sb.toString());
931     }
932
933     public static void main(String args[]) throws Exception {
934         Properties props = null;
935         System.out.println("*************************Hello*****************************");
936         ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
937         String Get_config_template = _readFile("/home/userID/data/Get_config_template");
938         String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
939         String key = "GetCliRunningConfig";
940         Map<String, String> parameters = new HashMap();
941         parameters.put("Host_ip_address", "000.00.000.00");
942         parameters.put("User_name", "root");
943         parameters.put("Password", "!bootstrap");
944         parameters.put("Port_number", "22");
945         parameters.put("Get_config_template", Get_config_template);
946         SvcLogicContext ctx = null;
947         System.out.println("*************************TRACE 1*****************************");
948         cca.configure(key, parameters, ctx);
949     }
950
951 }