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