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