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