Update java files with correct license text
[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, Integer.parseInt(portNumber));
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),
328                         "netconf");
329                 String NetconfHelloCmd = netconfHelloCmd;
330                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
331                 log.debug("Sending the hello command");
332                 sshJcraftWrapper.send(NetconfHelloCmd);
333                 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
334                 log.debug("Sending xmlCmd cmd");
335                 String xmlCmd = Contents;
336                 String messageId = "1";
337                 messageId = "\"" + messageId + "\"";
338                 String loadConfigurationString =
339                     "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
340                         + messageId
341                         + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
342                         + xmlCmd + "</config> </edit-config> </rpc>";
343                 loadConfigurationString = loadConfigurationString + "]]>]]>";
344                 sshJcraftWrapper.send(loadConfigurationString);
345                 log.debug("After sending loadConfigurationString");
346                 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
347                 if (response.indexOf("rpc-error") != -1) {
348                     log.debug("Error from device: Response from device had 'rpc-error'");
349                     log.debug("response=\n{}\n", response);
350                     r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
351                     r.message = response;
352                 } else {
353                     log.debug(":LoadConfiguration was a success, sending commit cmd");
354                     sshJcraftWrapper.send(commitCmd);
355                     log.debug(":After sending commitCmd");
356                     response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
357                     if (response.indexOf("rpc-error") != -1) {
358                         log.debug("Error from device: Response from device had 'rpc-error'");
359                         log.debug("response=\n{}\n", response);
360                         r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
361                         r.message = response;
362                     } else {
363                         log.debug(":Looks like a success");
364                         log.debug("response=\n{}\n", response);
365                         r.code = 200;
366                     }
367                 }
368                 sshJcraftWrapper.send(terminateConnectionCmd);
369                 sshJcraftWrapper.closeConnection();
370                 sshJcraftWrapper = null;
371                 return (setResponseStatus(ctx, r));
372             } catch (Exception e) {
373                 log.error("Caught an Exception", e);
374                 sshJcraftWrapper.closeConnection();
375                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
376                 r.message = e.getMessage();
377                 sshJcraftWrapper = null;
378                 log.debug("Returning error message");
379                 return (setResponseStatus(ctx, r));
380             }
381         }
382         if (key.equals("xml-getrunningconfig")) {
383             log.debug("key was: : xml-getrunningconfig");
384             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";
385             String Host_ip_address = parameters.get("Host_ip_address");
386             String User_name = parameters.get("User_name");
387             String Password = parameters.get("Password");
388             Password = EncryptionTool.getInstance().decrypt(Password);
389             String Port_number = parameters.get("Port_number");
390             String Protocol = parameters.get("Protocol");
391             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>";
392             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 ]]>]]>";
393             log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
394                 Host_ip_address, Password, Port_number);
395             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
396             try {
397                 String NetconfHelloCmd = netconfHelloCmd;
398                 sshJcraftWrapper
399                     .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
400                         "netconf");
401                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
402                 log.debug(":Sending the hello command");
403                 sshJcraftWrapper.send(NetconfHelloCmd);
404                 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
405                 log.debug("Sending get running config command");
406                 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
407                 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
408                 log.debug("Response from getRunningconfigCmd={}", response);
409                 response = trimResponse(response);
410                 ctx.setAttribute("xmlRunningConfigOutput", response);
411                 sshJcraftWrapper.send(terminateConnectionCmd);
412                 sshJcraftWrapper.closeConnection();
413                 r.code = 200;
414                 sshJcraftWrapper = null;
415                 return (setResponseStatus(ctx, r));
416             } catch (Exception e) {
417                 log.error("Caught an Exception", e);
418                 sshJcraftWrapper.closeConnection();
419                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
420                 r.message = e.getMessage();
421                 sshJcraftWrapper = null;
422                 log.debug("Returning error message");
423                 return (setResponseStatus(ctx, r));
424             }
425         }
426         if (key.equals("DownloadCliConfig")) {
427             log.debug("key was: DownloadCliConfig: ");
428             String User_name = parameters.get("User_name");
429             String Host_ip_address = parameters.get("Host_ip_address");
430             String Password = parameters.get("Password");
431             Password = EncryptionTool.getInstance().decrypt(Password);
432             String Port_number = parameters.get("Port_number");
433             String Download_config_template = parameters.get("Download_config_template");
434             String Config_contents = parameters.get("Config_contents");
435             log.debug("Contents of the 'Config_contents' are: {}", Config_contents);
436             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
437             log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
438             int timeout = 4 * 60 * 1000;
439             try {
440                 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
441                     + User_name + " Password=" + Password + " Port_number=" + Port_number);
442                 StringBuffer sb = new StringBuffer();
443                 String response = "";
444                 String CliResponse = "";
445                 sshJcraftWrapper
446                     .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
447                 log.debug("DownloadCliConfig: On the VNF device");
448                 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
449                 String command = null;
450                 String executeConfigContentsDelemeter = null;
451                 try {
452                     while (st.hasMoreTokens()) {
453                         String line = st.nextToken();
454                         log.debug("line={}", line);
455                         if (line.indexOf("Request:") != -1) {
456                             log.debug("Found a Request line: line={}", line);
457                             command = getStringBetweenQuotes(line);
458                             log.debug("Sending command={}", command);
459                             sshJcraftWrapper.send(command);
460                             log.debug("command has been sent");
461                         } else if ((line.indexOf("Response: Ends_With") != -1) && (
462                             line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
463                             log.debug("Found a Response line: line={}", line);
464                             String delimiter = getStringBetweenQuotes(line);
465                             log.debug("The delimiter={}", delimiter);
466                             String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
467                             response += tmpResponse;
468                             CliResponse += tmpResponse;
469                         } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
470                             log.debug("Found a 'Execute_config_contents Response:' line={}", line);
471                             executeConfigContentsDelemeter = getStringBetweenQuotes(line);
472                             log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
473                             StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
474                             while (st2.hasMoreTokens()) {
475                                 String cmd = st2.nextToken();
476                                 log.debug("Config_contents: cmd={}", cmd);
477                                 sshJcraftWrapper.send(cmd);
478                                 String tmpResponse = sshJcraftWrapper
479                                     .receiveUntil(executeConfigContentsDelemeter, timeout, command);
480                                 CliResponse += tmpResponse;
481                             }
482                         }
483                     }
484                 } catch (NoSuchElementException e) {
485                     log.error(e.getMessage(), e);
486                 }
487                 sshJcraftWrapper.closeConnection();
488                 sshJcraftWrapper = null;
489                 log.debug(":Escaping all the single and double quotes in the response");
490                 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
491                 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
492                 log.debug("CliResponse=\n{}" + CliResponse);
493                 ctx.setAttribute("cliOutput", CliResponse);
494                 r.code = 200;
495                 return (setResponseStatus(ctx, r));
496             } catch (IOException e) {
497                 log.error(e.getMessage() + e);
498                 sshJcraftWrapper.closeConnection();
499                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
500                 r.message = e.getMessage();
501                 sshJcraftWrapper = null;
502                 log.debug("DownloadCliConfig: Returning error message");
503                 return (setResponseStatus(ctx, r));
504             }
505         }
506
507         log.debug("Unsupported action - {}", action);
508         return ConfigStatus.FAILURE;
509     }
510
511     private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
512         String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
513         String ndTemplate = readFile(templateName);
514         String nd = buildNetworkData2(ctx, ndTemplate, operation);
515
516         String reqTemplate = readFile("/config-request.xml");
517         Map<String, String> param = new HashMap<String, String>();
518         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
519         param.put("request-type", requestType);
520         param.put("callback-url", configCallbackUrl);
521         if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
522             param.put("action", "GenerateOnly");
523         }
524         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
525         param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
526         param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
527         param.put("network-data", nd);
528
529         String req = null;
530         try {
531             req = buildXmlRequest(param, reqTemplate);
532         } catch (Exception e) {
533             log.error("Error building the XML request: ", e);
534
535             HttpResponse r = new HttpResponse();
536             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
537             r.message = e.getMessage();
538             return setResponseStatus(ctx, r);
539         }
540
541         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
542         return setResponseStatus(ctx, r);
543     }
544
545     private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
546         String reqTemplate = readFile("/config-request.xml");
547         Map<String, String> param = new HashMap<String, String>();
548         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
549         param.put("callback-url", configCallbackUrl);
550         param.put("action", change ? "DownloadChange" : "DownloadBase");
551         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
552
553         String req = null;
554         try {
555             req = buildXmlRequest(param, reqTemplate);
556         } catch (Exception e) {
557             log.error("Error building the XML request: ", e);
558
559             HttpResponse r = new HttpResponse();
560             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
561             r.message = e.getMessage();
562             return setResponseStatus(ctx, r);
563         }
564
565         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
566         return setResponseStatus(ctx, r);
567     }
568
569     private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
570         String reqTemplate = readFile("/audit-request.xml");
571         Map<String, String> param = new HashMap<String, String>();
572         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
573         param.put("callback-url", auditCallbackUrl);
574         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
575         param.put("audit-level", auditLevel);
576
577         String req = null;
578         try {
579             req = buildXmlRequest(param, reqTemplate);
580         } catch (Exception e) {
581             log.error("Error building the XML request: ", e);
582
583             HttpResponse r = new HttpResponse();
584             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
585             r.message = e.getMessage();
586             return setResponseStatus(ctx, r);
587         }
588
589         HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
590         return setResponseStatus(ctx, r);
591     }
592
593     @Override
594     public ConfigStatus activate(String key, SvcLogicContext ctx) {
595         return ConfigStatus.SUCCESS;
596     }
597
598     @Override
599     public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
600         return ConfigStatus.SUCCESS;
601     }
602
603     private String escapeMySql(String input) {
604         if (input == null) {
605             return null;
606         }
607
608         input = input.replace("\\", "\\\\");
609         input = input.replace("\'", "\\'");
610         return input;
611
612     }
613
614     private String readFile(String fileName) {
615         InputStream is = getClass().getResourceAsStream(fileName);
616         InputStreamReader isr = new InputStreamReader(is);
617         BufferedReader in = new BufferedReader(isr);
618         StringBuilder ss = new StringBuilder();
619         try {
620             String s = in.readLine();
621             while (s != null) {
622                 ss.append(s).append('\n');
623                 s = in.readLine();
624             }
625         } catch (IOException e) {
626             throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
627         } finally {
628             try {
629                 in.close();
630             } catch (Exception e) {
631                 log.warn("Could not close BufferedReader", e);
632             }
633             try {
634                 isr.close();
635             } catch (Exception e) {
636                 log.warn("Could not close InputStreamReader", e);
637             }
638             try {
639                 is.close();
640             } catch (Exception e) {
641                 log.warn("Could not close InputStream", e);
642             }
643         }
644         return ss.toString();
645     }
646
647     private String buildXmlRequest(Map<String, String> param, String template) {
648         StringBuilder ss = new StringBuilder();
649         int i = 0;
650         while (i < template.length()) {
651             int i1 = template.indexOf("${", i);
652             if (i1 < 0) {
653                 ss.append(template.substring(i));
654                 break;
655             }
656
657             int i2 = template.indexOf('}', i1 + 2);
658             if (i2 < 0) {
659                 throw new RuntimeException("Template error: Matching } not found");
660             }
661
662             String var1 = template.substring(i1 + 2, i2);
663             String value1 = param.get(var1);
664             if (value1 == null || value1.trim().length() == 0) {
665                 // delete the whole element (line)
666                 int i3 = template.lastIndexOf('\n', i1);
667                 if (i3 < 0) {
668                     i3 = 0;
669                 }
670                 int i4 = template.indexOf('\n', i1);
671                 if (i4 < 0) {
672                     i4 = template.length();
673                 }
674
675                 if (i < i3) {
676                     ss.append(template.substring(i, i3));
677                 }
678                 i = i4;
679             } else {
680                 ss.append(template.substring(i, i1)).append(value1);
681                 i = i2 + 1;
682             }
683         }
684
685         return ss.toString();
686     }
687
688     private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
689         log.info("Building XML started");
690         long t1 = System.currentTimeMillis();
691
692         template = expandRepeats(ctx, template, 1);
693
694         Map<String, String> mm = new HashMap<>();
695         for (String s : ctx.getAttributeKeySet()) {
696             mm.put(s, ctx.getAttribute(s));
697         }
698         mm.put("operation", operation);
699
700         StringBuilder ss = new StringBuilder();
701         int i = 0;
702         while (i < template.length()) {
703             int i1 = template.indexOf("${", i);
704             if (i1 < 0) {
705                 ss.append(template.substring(i));
706                 break;
707             }
708
709             int i2 = template.indexOf('}', i1 + 2);
710             if (i2 < 0) {
711                 throw new RuntimeException("Template error: Matching } not found");
712             }
713
714             String var1 = template.substring(i1 + 2, i2);
715             String value1 = XmlUtil.getXml(mm, var1);
716             if (value1 == null || value1.trim().length() == 0) {
717                 int i3 = template.lastIndexOf('\n', i1);
718                 if (i3 < 0) {
719                     i3 = 0;
720                 }
721                 int i4 = template.indexOf('\n', i1);
722                 if (i4 < 0) {
723                     i4 = template.length();
724                 }
725
726                 if (i < i3) {
727                     ss.append(template.substring(i, i3));
728                 }
729                 i = i4;
730             } else {
731                 ss.append(template.substring(i, i1)).append(value1);
732                 i = i2 + 1;
733             }
734         }
735
736         long t2 = System.currentTimeMillis();
737         log.info("Building XML completed. Time: " + (t2 - t1));
738
739         return ss.toString();
740     }
741
742     private String expandRepeats(SvcLogicContext ctx, String template, int level) {
743         StringBuilder newTemplate = new StringBuilder();
744         int k = 0;
745         while (k < template.length()) {
746             int i1 = template.indexOf("${repeat:", k);
747             if (i1 < 0) {
748                 newTemplate.append(template.substring(k));
749                 break;
750             }
751
752             int i2 = template.indexOf(':', i1 + 9);
753             if (i2 < 0) {
754                 throw new RuntimeException(
755                     "Template error: Context variable name followed by : is required after repeat");
756             }
757
758             // Find the closing }, store in i3
759             int nn = 1;
760             int i3 = -1;
761             int i = i2;
762             while (nn > 0 && i < template.length()) {
763                 i3 = template.indexOf('}', i);
764                 if (i3 < 0) {
765                     throw new RuntimeException("Template error: Matching } not found");
766                 }
767                 int i32 = template.indexOf('{', i);
768                 if (i32 >= 0 && i32 < i3) {
769                     nn++;
770                     i = i32 + 1;
771                 } else {
772                     nn--;
773                     i = i3 + 1;
774                 }
775             }
776
777             String var1 = template.substring(i1 + 9, i2);
778             String value1 = ctx.getAttribute(var1);
779             log.info("     " + var1 + ": " + value1);
780             int n = 0;
781             try {
782                 n = Integer.parseInt(value1);
783             } catch (Exception e) {
784                 n = 0;
785             }
786
787             newTemplate.append(template.substring(k, i1));
788
789             String rpt = template.substring(i2 + 1, i3);
790
791             for (int ii = 0; ii < n; ii++) {
792                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
793                 newTemplate.append(ss);
794             }
795
796             k = i3 + 1;
797         }
798
799         if (k == 0) {
800             return newTemplate.toString();
801         }
802
803         return expandRepeats(ctx, newTemplate.toString(), level + 1);
804     }
805
806     private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
807         try {
808             Client client = Client.create();
809             client.setConnectTimeout(5000);
810             WebResource webResource = client.resource(url);
811
812             log.info("SENDING...............");
813             log.info(xmlRequest);
814
815             String authString = user + ":" + password;
816             byte[] authEncBytes = Base64.encode(authString);
817             String authStringEnc = new String(authEncBytes);
818             authString = "Basic " + authStringEnc;
819
820             ClientResponse response =
821                 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
822                     ClientResponse.class, xmlRequest);
823
824             int code = response.getStatus();
825             String message = null;
826
827             log.info("RESPONSE...............");
828             log.info("HTTP response code: " + code);
829             log.info("HTTP response message: " + message);
830             log.info("");
831
832             HttpResponse r = new HttpResponse();
833             r.code = code;
834             r.message = message;
835             return r;
836
837         } catch (Exception e) {
838             log.error("Error sending the request: ", e);
839
840             HttpResponse r = new HttpResponse();
841             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
842             r.message = e.getMessage();
843             return r;
844         }
845     }
846
847     private static class HttpResponse {
848
849         public int code;
850         public String message;
851     }
852
853     private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
854         ctx.setAttribute("error-code", String.valueOf(r.code));
855         ctx.setAttribute("error-message", r.message);
856
857         return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
858     }
859
860     private String getStringBetweenQuotes(String string) {
861         log.debug("string=" + string);
862         String retString;
863         int start = string.indexOf('\"');
864         int end = string.lastIndexOf('\"');
865         retString = string.substring(start + 1, end);
866         log.debug("retString=" + retString);
867         return retString;
868     }
869
870     public static String _readFile(String fileName) {
871         StringBuffer strBuff = new StringBuffer();
872         String line;
873         try {
874             BufferedReader in = new BufferedReader(new FileReader(fileName));
875             while ((line = in.readLine()) != null) {
876                 strBuff.append(line + "\n");
877             }
878             in.close();
879         } catch (IOException e) {
880             log.error("Caught an IOException in method readFile()", e);
881         }
882         return (strBuff.toString());
883     }
884
885     private String trimResponse(String response) {
886         StringTokenizer line = new StringTokenizer(response, "\n");
887         StringBuffer sb = new StringBuffer();
888         boolean captureText = false;
889         while (line.hasMoreTokens()) {
890             String token = line.nextToken();
891             if (token.indexOf("<configuration xmlns=") != -1) {
892                 captureText = true;
893             }
894             if (captureText) {
895                 sb.append(token + "\n");
896             }
897             if (token.indexOf("</configuration>") != -1) {
898                 captureText = false;
899             }
900         }
901         return (sb.toString());
902     }
903
904     public static void main(String args[]) throws Exception {
905         Properties props = null;
906         System.out.println("*************************Hello*****************************");
907         ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
908         String Get_config_template = _readFile("/home/userID/data/Get_config_template");
909         String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
910         String key = "GetCliRunningConfig";
911         Map<String, String> parameters = new HashMap();
912         parameters.put("Host_ip_address", "000.00.000.00");
913         parameters.put("User_name", "root");
914         parameters.put("Password", "!bootstrap");
915         parameters.put("Port_number", "22");
916         parameters.put("Get_config_template", Get_config_template);
917         SvcLogicContext ctx = null;
918         System.out.println("*************************TRACE 1*****************************");
919         cca.configure(key, parameters, ctx);
920     }
921
922 }