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