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