2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.appc.ccadaptor;
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;
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;
44 public class ConfigComponentAdaptor implements SvcLogicAdaptor
47 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
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();
59 public ConfigComponentAdaptor(Properties props)
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", "");
80 configCallbackUrl = "";
81 auditCallbackUrl = "";
86 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx)
88 String fnName = "ConfigComponentAdaptor.configure";
89 HttpResponse r = new HttpResponse();
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())
97 log.debug(" " + parmName + " = " + parameters.get(parmName));
98 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
101 String parmval = parameters.get("config-component-configUrl");
102 if ((parmval != null) && (parmval.length() > 0))
104 log.debug("Overwriting URL with " + parmval);
108 parmval = parameters.get("config-component-configPassword");
109 if ((parmval != null) && (parmval.length() > 0))
111 log.debug("Overwriting configPassword with " + parmval);
112 configPassword = parmval;
115 parmval = parameters.get("config-component-configUser");
116 if ((parmval != null) && (parmval.length() > 0))
118 log.debug("Overwriting configUser id with " + parmval);
119 configUser = parmval;
122 String action = parameters.get("action");
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);
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);
138 if ("prepare".equalsIgnoreCase(action))
139 return prepare(ctx, "BASE", "create");
140 if ("activate".equalsIgnoreCase(action))
141 return activate(ctx, false);
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");
154 if ((key.equals("put")) || (key.equals("get")))
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");
163 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
164 log.debug("SCP: SshJcraftWrapper has been instantiated");
165 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
168 if (key.equals("put"))
170 data = parameters.get("data");
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);
179 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
180 Thread.sleep(1000 * 180);
181 debugLog.printRTAriDebug(fnName, "Woke up....");
183 catch (java.lang.InterruptedException ee)
185 boolean ignore = true;
188 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
189 log.debug(fnName + " Command is for put: data is null");
192 else // Must be a get
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");
201 sshJcraftWrapper = null;
202 return (setResponseStatus(ctx, r));
204 catch (IOException e)
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));
214 if (key.equals("cli"))
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();
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));
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", "#");
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();
247 sshJcraftWrapper = null;
248 return (setResponseStatus(ctx, r));
250 catch (IOException e)
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));
262 if (key.equals("escapeSql"))
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));
270 if(key.equals("GetCliRunningConfig"))
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");
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;
299 while (st.hasMoreTokens())
301 String line = st.nextToken();
302 DebugLog.printAriDebug(fnName, "line="+line);
303 if (line.indexOf("Request:") != -1)
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)
312 showConfigFlag = true;
313 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
314 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
317 if (line.indexOf("Response: Ends_With") != -1)
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;
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())
331 String line2 = st2.nextToken();
332 if (line2.indexOf("#") == -1)
333 CliResponse += line2 +"\n";
339 catch (NoSuchElementException e)
341 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
343 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
344 ctx.setAttribute("cliOutput", CliResponse);
345 sshJcraftWrapper.closeConnection();
347 sshJcraftWrapper = null;
348 return(setResponseStatus(ctx, r));
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));
362 if(key.equals("xml-download"))
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 ]]>]]>";
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();
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)
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;
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)
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;
416 DebugLog.printAriDebug(fnName,":Looks like a success");
417 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
421 sshJcraftWrapper.send(terminateConnectionCmd);
422 sshJcraftWrapper.closeConnection();
423 sshJcraftWrapper = null;
424 return(setResponseStatus(ctx, r));
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));
438 if(key.equals("xml-getrunningconfig"))
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();
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();
469 sshJcraftWrapper = null;
470 return(setResponseStatus(ctx, r));
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));
484 if(key.equals("DownloadCliConfig"))
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;
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;
516 while (st.hasMoreTokens())
518 String line = st.nextToken();
519 DebugLog.printAriDebug(fnName, "line="+line);
520 if (line.indexOf("Request:") != -1)
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");
528 else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1))
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;
537 else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1)
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())
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;
554 catch (NoSuchElementException e)
556 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
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);
566 return(setResponseStatus(ctx, r));
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));
581 debugLog.printRTAriDebug (fnName, "Unsupported action - " + action);
582 log.error("Unsupported action - " + action);
583 return ConfigStatus.FAILURE;
586 private void log (String fileName, String messg)
588 debugLog.printRTAriDebug (fileName, messg);
589 log.debug(fileName +": "+messg);
592 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation)
594 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
595 String ndTemplate = readFile(templateName);
596 String nd = buildNetworkData2(ctx, ndTemplate, operation);
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);
613 req = buildXmlRequest(param, reqTemplate);
617 log.error("Error building the XML request: ", e);
619 HttpResponse r = new HttpResponse();
620 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
621 r.message = e.getMessage();
622 return setResponseStatus(ctx, r);
625 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
626 return setResponseStatus(ctx, r);
629 private ConfigStatus activate(SvcLogicContext ctx, boolean change)
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"));
641 req = buildXmlRequest(param, reqTemplate);
645 log.error("Error building the XML request: ", e);
647 HttpResponse r = new HttpResponse();
648 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
649 r.message = e.getMessage();
650 return setResponseStatus(ctx, r);
653 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
654 return setResponseStatus(ctx, r);
657 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel)
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);
669 req = buildXmlRequest(param, reqTemplate);
673 log.error("Error building the XML request: ", e);
675 HttpResponse r = new HttpResponse();
676 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
677 r.message = e.getMessage();
678 return setResponseStatus(ctx, r);
681 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
682 return setResponseStatus(ctx, r);
686 public ConfigStatus activate(String key, SvcLogicContext ctx)
688 return ConfigStatus.SUCCESS;
692 public ConfigStatus deactivate(String key, SvcLogicContext ctx)
694 return ConfigStatus.SUCCESS;
697 private String escapeMySql(String input)
702 input = input.replace("\\", "\\\\");
703 input = input.replace("\'", "\\'");
708 private String readFile(String fileName)
710 InputStream is = getClass().getResourceAsStream(fileName);
711 InputStreamReader isr = new InputStreamReader(is);
712 BufferedReader in = new BufferedReader(isr);
713 StringBuilder ss = new StringBuilder();
716 String s = in.readLine();
719 ss.append(s).append('\n');
723 catch (IOException e)
725 System.out.println("Error reading " + fileName + ": " + e.getMessage());
726 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
736 log.warn("Could not close BufferedReader", e);
744 log.warn("Could not close InputStreamReader", e);
752 log.warn("Could not close InputStream", e);
755 return ss.toString();
758 private String buildXmlRequest(Map<String, String> param, String template)
760 StringBuilder ss = new StringBuilder();
762 while (i < template.length())
764 int i1 = template.indexOf("${", i);
767 ss.append(template.substring(i));
771 int i2 = template.indexOf('}', i1 + 2);
773 throw new RuntimeException("Template error: Matching } not found");
775 String var1 = template.substring(i1 + 2, i2);
776 String value1 = param.get(var1);
777 if (value1 == null || value1.trim().length() == 0)
779 // delete the whole element (line)
780 int i3 = template.lastIndexOf('\n', i1);
783 int i4 = template.indexOf('\n', i1);
785 i4 = template.length();
788 ss.append(template.substring(i, i3));
793 ss.append(template.substring(i, i1)).append(value1);
798 return ss.toString();
801 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation)
803 log.info("Building XML started");
804 long t1 = System.currentTimeMillis();
806 template = expandRepeats(ctx, template, 1);
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);
813 StringBuilder ss = new StringBuilder();
815 while (i < template.length())
817 int i1 = template.indexOf("${", i);
820 ss.append(template.substring(i));
824 int i2 = template.indexOf('}', i1 + 2);
826 throw new RuntimeException("Template error: Matching } not found");
828 String var1 = template.substring(i1 + 2, i2);
829 String value1 = XmlUtil.getXml(mm, var1);
830 if (value1 == null || value1.trim().length() == 0)
832 // delete the whole element (line)
833 int i3 = template.lastIndexOf('\n', i1);
836 int i4 = template.indexOf('\n', i1);
838 i4 = template.length();
841 ss.append(template.substring(i, i3));
846 ss.append(template.substring(i, i1)).append(value1);
851 long t2 = System.currentTimeMillis();
852 log.info("Building XML completed. Time: " + (t2 - t1));
854 return ss.toString();
857 private String expandRepeats(SvcLogicContext ctx, String template, int level)
859 StringBuilder newTemplate = new StringBuilder();
861 while (k < template.length())
863 int i1 = template.indexOf("${repeat:", k);
866 newTemplate.append(template.substring(k));
870 int i2 = template.indexOf(':', i1 + 9);
872 throw new RuntimeException(
873 "Template error: Context variable name followed by : is required after repeat");
875 // Find the closing }, store in i3
879 while (nn > 0 && i < template.length())
881 i3 = template.indexOf('}', i);
883 throw new RuntimeException("Template error: Matching } not found");
884 int i32 = template.indexOf('{', i);
885 if (i32 >= 0 && i32 < i3)
897 String var1 = template.substring(i1 + 9, i2);
898 String value1 = ctx.getAttribute(var1);
899 log.info(" " + var1 + ": " + value1);
903 n = Integer.parseInt(value1);
910 newTemplate.append(template.substring(k, i1));
912 String rpt = template.substring(i2 + 1, i3);
914 for (int ii = 0; ii < n; ii++)
916 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
917 newTemplate.append(ss);
924 return newTemplate.toString();
926 return expandRepeats(ctx, newTemplate.toString(), level + 1);
929 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password)
933 Client client = Client.create();
934 client.setConnectTimeout(5000);
935 WebResource webResource = client.resource(url);
937 log.info("SENDING...............");
938 log.info(xmlRequest);
940 String authString = user + ":" + password;
941 byte[] authEncBytes = Base64.encode(authString);
942 String authStringEnc = new String(authEncBytes);
943 authString = "Basic " + authStringEnc;
945 ClientResponse response =
946 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
947 ClientResponse.class, xmlRequest);
949 int code = response.getStatus();
950 String message = null;
952 log.info("RESPONSE...............");
953 log.info("HTTP response code: " + code);
954 log.info("HTTP response message: " + message);
957 HttpResponse r = new HttpResponse();
965 log.error("Error sending the request: ", e);
967 HttpResponse r = new HttpResponse();
968 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
969 r.message = e.getMessage();
974 private static class HttpResponse
978 public String message;
981 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r)
983 ctx.setAttribute("error-code", String.valueOf(r.code));
984 ctx.setAttribute("error-message", r.message);
986 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
989 private String getStringBetweenQuotes(String string)
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);
1001 public static String _readFile(String fileName)
1003 StringBuffer strBuff = new StringBuffer();
1005 try (BufferedReader in = new BufferedReader(new FileReader(fileName)))
1007 while ((line = in.readLine()) != null)
1009 strBuff.append(line+"\n");
1012 catch (IOException e)
1014 System.out.println("Caught an IOException in method readFile(): e="+e.toString());
1016 return (strBuff.toString());
1019 private String trimResponse(String response)
1021 StringTokenizer line = new StringTokenizer(response, "\n");
1022 StringBuffer sb = new StringBuffer();
1023 boolean captureText = false;
1024 while (line.hasMoreTokens())
1026 String token = line.nextToken();
1027 if (token.indexOf("<configuration xmlns=") != -1)
1030 sb.append(token +"\n");
1031 if (token.indexOf("</configuration>") != -1)
1032 captureText = false;
1034 return(sb.toString());
1037 public static void main (String args[]) throws Exception
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);
1052 SvcLogicContext ctx = null;
1053 System.out.println("*************************TRACE 1*****************************");
1054 cca.configure(key, parameters, ctx);