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