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