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