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