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