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