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