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