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 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;
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;
44 public class ConfigComponentAdaptor implements SvcLogicAdaptor
46 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
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();
58 public ConfigComponentAdaptor(Properties props)
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", "");
79 configCallbackUrl = "";
80 auditCallbackUrl = "";
85 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx)
87 String fnName = "ConfigComponentAdaptor.configure";
88 HttpResponse r = new HttpResponse();
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())
96 log.debug(" " + parmName + " = " + parameters.get(parmName));
97 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
100 String parmval = parameters.get("config-component-configUrl");
101 if ((parmval != null) && (parmval.length() > 0))
103 log.debug("Overwriting URL with " + parmval);
107 parmval = parameters.get("config-component-configPassword");
108 if ((parmval != null) && (parmval.length() > 0))
110 log.debug("Overwriting configPassword with " + parmval);
111 configPassword = parmval;
114 parmval = parameters.get("config-component-configUser");
115 if ((parmval != null) && (parmval.length() > 0))
117 log.debug("Overwriting configUser id with " + parmval);
118 configUser = parmval;
121 String action = parameters.get("action");
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);
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);
137 if ("prepare".equalsIgnoreCase(action))
138 return prepare(ctx, "BASE", "create");
139 if ("activate".equalsIgnoreCase(action))
140 return activate(ctx, false);
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");
153 if ((key.equals("put")) || (key.equals("get")))
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");
161 if (key.equals("put"))
162 data = parameters.get("data");
164 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
165 log.debug("SCP: SshJcraftWrapper has been instantiated");
166 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
169 if (key.equals("put"))
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);
178 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
179 Thread.sleep(1000 * 180);
180 debugLog.printRTAriDebug(fnName, "Woke up....");
182 catch (java.lang.InterruptedException ee)
184 boolean ignore = true;
187 else // Must be a get
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");
196 sshJcraftWrapper = null;
197 return (setResponseStatus(ctx, r));
199 catch (IOException e)
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));
209 if (key.equals("cli"))
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();
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));
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", "#");
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();
242 sshJcraftWrapper = null;
243 return (setResponseStatus(ctx, r));
245 catch (IOException e)
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));
257 if (key.equals("escapeSql"))
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));
265 if(key.equals("GetCliRunningConfig"))
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");
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;
292 while (st.hasMoreTokens())
294 String line = st.nextToken();
295 DebugLog.printAriDebug(fnName, "line="+line);
296 if (line.indexOf("Request:") != -1)
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)
305 showConfigFlag = true;
306 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
307 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
310 if (line.indexOf("Response: Ends_With") != -1)
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;
319 showConfigFlag = false;
320 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
321 while (st2.hasMoreTokens())
323 String line2 = st2.nextToken();
324 if (line2.indexOf("#") == -1)
325 CliResponse += line2 +"\n";
331 catch (NoSuchElementException e)
333 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
335 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
336 ctx.setAttribute("cliOutput", CliResponse);
337 sshJcraftWrapper.closeConnection();
339 sshJcraftWrapper = null;
340 return(setResponseStatus(ctx, r));
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));
354 if(key.equals("xml-download"))
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 ]]>]]>";
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();
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)
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;
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)
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;
408 DebugLog.printAriDebug(fnName,":Looks like a success");
409 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
413 sshJcraftWrapper.send(terminateConnectionCmd);
414 sshJcraftWrapper.closeConnection();
415 sshJcraftWrapper = null;
416 return(setResponseStatus(ctx, r));
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));
430 if(key.equals("xml-getrunningconfig"))
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();
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();
461 sshJcraftWrapper = null;
462 return(setResponseStatus(ctx, r));
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));
476 if(key.equals("DownloadCliConfig"))
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;
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;
506 while (st.hasMoreTokens())
508 String line = st.nextToken();
509 DebugLog.printAriDebug(fnName, "line="+line);
510 if (line.indexOf("Request:") != -1)
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");
518 else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1))
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;
527 else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1)
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())
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;
544 catch (NoSuchElementException e)
546 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
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);
556 return(setResponseStatus(ctx, r));
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));
571 debugLog.printRTAriDebug (fnName, "Unsupported action - " + action);
572 log.error("Unsupported action - " + action);
573 return ConfigStatus.FAILURE;
576 private void log (String fileName, String messg)
578 debugLog.printRTAriDebug (fileName, messg);
579 log.debug(fileName +": "+messg);
582 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation)
584 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
585 String ndTemplate = readFile(templateName);
586 String nd = buildNetworkData2(ctx, ndTemplate, operation);
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);
603 req = buildXmlRequest(param, reqTemplate);
607 log.error("Error building the XML request: ", e);
609 HttpResponse r = new HttpResponse();
610 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
611 r.message = e.getMessage();
612 return setResponseStatus(ctx, r);
615 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
616 return setResponseStatus(ctx, r);
619 private ConfigStatus activate(SvcLogicContext ctx, boolean change)
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"));
631 req = buildXmlRequest(param, reqTemplate);
635 log.error("Error building the XML request: ", e);
637 HttpResponse r = new HttpResponse();
638 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
639 r.message = e.getMessage();
640 return setResponseStatus(ctx, r);
643 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
644 return setResponseStatus(ctx, r);
647 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel)
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);
659 req = buildXmlRequest(param, reqTemplate);
663 log.error("Error building the XML request: ", e);
665 HttpResponse r = new HttpResponse();
666 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
667 r.message = e.getMessage();
668 return setResponseStatus(ctx, r);
671 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
672 return setResponseStatus(ctx, r);
676 public ConfigStatus activate(String key, SvcLogicContext ctx)
678 return ConfigStatus.SUCCESS;
682 public ConfigStatus deactivate(String key, SvcLogicContext ctx)
684 return ConfigStatus.SUCCESS;
687 private String escapeMySql(String input)
692 input = input.replace("\\", "\\\\");
693 input = input.replace("\'", "\\'");
698 private String readFile(String fileName)
700 InputStream is = getClass().getResourceAsStream(fileName);
701 InputStreamReader isr = new InputStreamReader(is);
702 BufferedReader in = new BufferedReader(isr);
703 StringBuilder ss = new StringBuilder();
706 String s = in.readLine();
709 ss.append(s).append('\n');
713 catch (IOException e)
715 System.out.println("Error reading " + fileName + ": " + e.getMessage());
716 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
726 log.warn("Could not close BufferedReader", e);
734 log.warn("Could not close InputStreamReader", e);
742 log.warn("Could not close InputStream", e);
745 return ss.toString();
748 private String buildXmlRequest(Map<String, String> param, String template)
750 StringBuilder ss = new StringBuilder();
752 while (i < template.length())
754 int i1 = template.indexOf("${", i);
757 ss.append(template.substring(i));
761 int i2 = template.indexOf('}', i1 + 2);
763 throw new RuntimeException("Template error: Matching } not found");
765 String var1 = template.substring(i1 + 2, i2);
766 String value1 = param.get(var1);
767 if (value1 == null || value1.trim().length() == 0)
769 // delete the whole element (line)
770 int i3 = template.lastIndexOf('\n', i1);
773 int i4 = template.indexOf('\n', i1);
775 i4 = template.length();
778 ss.append(template.substring(i, i3));
783 ss.append(template.substring(i, i1)).append(value1);
788 return ss.toString();
791 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation)
793 log.info("Building XML started");
794 long t1 = System.currentTimeMillis();
796 template = expandRepeats(ctx, template, 1);
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);
803 StringBuilder ss = new StringBuilder();
805 while (i < template.length())
807 int i1 = template.indexOf("${", i);
810 ss.append(template.substring(i));
814 int i2 = template.indexOf('}', i1 + 2);
816 throw new RuntimeException("Template error: Matching } not found");
818 String var1 = template.substring(i1 + 2, i2);
819 String value1 = XmlUtil.getXml(mm, var1);
820 if (value1 == null || value1.trim().length() == 0)
822 int i3 = template.lastIndexOf('\n', i1);
825 int i4 = template.indexOf('\n', i1);
827 i4 = template.length();
830 ss.append(template.substring(i, i3));
835 ss.append(template.substring(i, i1)).append(value1);
840 long t2 = System.currentTimeMillis();
841 log.info("Building XML completed. Time: " + (t2 - t1));
843 return ss.toString();
846 private String expandRepeats(SvcLogicContext ctx, String template, int level)
848 StringBuilder newTemplate = new StringBuilder();
850 while (k < template.length())
852 int i1 = template.indexOf("${repeat:", k);
855 newTemplate.append(template.substring(k));
859 int i2 = template.indexOf(':', i1 + 9);
861 throw new RuntimeException(
862 "Template error: Context variable name followed by : is required after repeat");
864 // Find the closing }, store in i3
868 while (nn > 0 && i < template.length())
870 i3 = template.indexOf('}', i);
872 throw new RuntimeException("Template error: Matching } not found");
873 int i32 = template.indexOf('{', i);
874 if (i32 >= 0 && i32 < i3)
886 String var1 = template.substring(i1 + 9, i2);
887 String value1 = ctx.getAttribute(var1);
888 log.info(" " + var1 + ": " + value1);
892 n = Integer.parseInt(value1);
899 newTemplate.append(template.substring(k, i1));
901 String rpt = template.substring(i2 + 1, i3);
903 for (int ii = 0; ii < n; ii++)
905 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
906 newTemplate.append(ss);
913 return newTemplate.toString();
915 return expandRepeats(ctx, newTemplate.toString(), level + 1);
918 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password)
922 Client client = Client.create();
923 client.setConnectTimeout(5000);
924 WebResource webResource = client.resource(url);
926 log.info("SENDING...............");
927 log.info(xmlRequest);
929 String authString = user + ":" + password;
930 byte[] authEncBytes = Base64.encode(authString);
931 String authStringEnc = new String(authEncBytes);
932 authString = "Basic " + authStringEnc;
934 ClientResponse response =
935 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
936 ClientResponse.class, xmlRequest);
938 int code = response.getStatus();
939 String message = null;
941 log.info("RESPONSE...............");
942 log.info("HTTP response code: " + code);
943 log.info("HTTP response message: " + message);
946 HttpResponse r = new HttpResponse();
954 log.error("Error sending the request: ", e);
956 HttpResponse r = new HttpResponse();
957 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
958 r.message = e.getMessage();
963 private static class HttpResponse
967 public String message;
970 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r)
972 ctx.setAttribute("error-code", String.valueOf(r.code));
973 ctx.setAttribute("error-message", r.message);
975 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
978 private String getStringBetweenQuotes(String string)
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);
990 public static String _readFile(String fileName)
992 StringBuffer strBuff = new StringBuffer();
996 BufferedReader in = new BufferedReader(new FileReader(fileName));
997 while ((line = in.readLine()) != null)
999 strBuff.append(line+"\n");
1003 catch (IOException e)
1005 System.out.println("Caught an IOException in method readFile(): e="+e.toString());
1007 return (strBuff.toString());
1010 private String trimResponse(String response)
1012 StringTokenizer line = new StringTokenizer(response, "\n");
1013 StringBuffer sb = new StringBuffer();
1014 boolean captureText = false;
1015 while (line.hasMoreTokens())
1017 String token = line.nextToken();
1018 if (token.indexOf("<configuration xmlns=") != -1)
1021 sb.append(token +"\n");
1022 if (token.indexOf("</configuration>") != -1)
1023 captureText = false;
1025 return(sb.toString());
1028 public static void main (String args[]) throws Exception
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);