2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
24 package org.onap.appc.ccadaptor;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.sun.jersey.api.client.Client;
29 import com.sun.jersey.api.client.ClientResponse;
30 import com.sun.jersey.api.client.WebResource;
31 import com.sun.jersey.core.util.Base64;
32 import java.io.BufferedReader;
33 import java.io.ByteArrayInputStream;
34 import java.io.FileReader;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.net.HttpURLConnection;
39 import java.util.HashMap;
41 import java.util.NoSuchElementException;
42 import java.util.Properties;
43 import java.util.StringTokenizer;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
47 public class ConfigComponentAdaptor implements SvcLogicAdaptor
49 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
51 private String configUrl = null;
52 private String configUser = null;
53 private String configPassword = null;
54 private String auditUrl = null;
55 private String auditUser = null;
56 private String auditPassword = null;
57 private String configCallbackUrl = null;
58 private String auditCallbackUrl = null;
59 DebugLog debugLog = new DebugLog();
61 public ConfigComponentAdaptor(Properties props)
65 configUrl = props.getProperty("configComponent.url", "");
66 configUser = props.getProperty("configComponent.user", "");
67 configPassword = props.getProperty("configComponent.passwd", "");
68 auditUrl = props.getProperty("auditComponent.url", "");
69 auditUser = props.getProperty("auditComponent.user", "");
70 auditPassword = props.getProperty("auditComponent.passwd", "");
71 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
72 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
82 configCallbackUrl = "";
83 auditCallbackUrl = "";
88 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx)
90 String fnName = "ConfigComponentAdaptor.configure";
91 HttpResponse r = new HttpResponse();
93 log.debug("ConfigComponentAdaptor.configure - key = " + key);
94 debugLog.printRTAriDebug(fnName, "key = " + key);
95 log.debug("Parameters:");
96 debugLog.printRTAriDebug(fnName, "Parameters:");
97 for (String parmName : parameters.keySet())
99 log.debug(" " + parmName + " = " + parameters.get(parmName));
100 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
103 String parmval = parameters.get("config-component-configUrl");
104 if ((parmval != null) && (parmval.length() > 0))
106 log.debug("Overwriting URL with " + parmval);
110 parmval = parameters.get("config-component-configPassword");
111 if ((parmval != null) && (parmval.length() > 0))
113 log.debug("Overwriting configPassword with " + parmval);
114 configPassword = parmval;
117 parmval = parameters.get("config-component-configUser");
118 if ((parmval != null) && (parmval.length() > 0))
120 log.debug("Overwriting configUser id with " + parmval);
121 configUser = parmval;
124 String action = parameters.get("action");
126 String chg = ctx.getAttribute(
127 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
128 if (chg != null && "prepare".equalsIgnoreCase(action))
129 return prepare(ctx, "CHANGE", "change");
130 if (chg != null && "activate".equalsIgnoreCase(action))
131 return activate(ctx, true);
133 String scale = ctx.getAttribute(
134 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
135 if (scale != null && "prepare".equalsIgnoreCase(action))
136 return prepare(ctx, "CHANGE", "scale");
137 if (scale != null && "activate".equalsIgnoreCase(action))
138 return activate(ctx, true);
140 if ("prepare".equalsIgnoreCase(action))
141 return prepare(ctx, "BASE", "create");
142 if ("activate".equalsIgnoreCase(action))
143 return activate(ctx, false);
145 if ("backup".equalsIgnoreCase(action))
146 return prepare(ctx, "BACKUP", "backup");
147 if ("restorebackup".equalsIgnoreCase(action))
148 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
149 if ("deletebackup".equalsIgnoreCase(action))
150 return prepare(ctx, "DELETEBACKUP", "deletebackup");
151 if ("audit".equalsIgnoreCase(action))
152 return audit(ctx, "FULL");
153 if ("getrunningconfig".equalsIgnoreCase(action))
154 return audit(ctx, "RUNNING");
156 if ((key.equals("put")) || (key.equals("get")))
158 String loginId = parameters.get("loginId");
159 String host = parameters.get("host");
160 String password = parameters.get("password");
161 password = EncryptionTool.getInstance().decrypt(password);
162 String fullPathFileName = parameters.get("fullPathFileName");
164 if (key.equals("put"))
165 data = parameters.get("data");
167 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
168 log.debug("SCP: SshJcraftWrapper has been instantiated");
169 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
172 if (key.equals("put"))
174 debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
175 InputStream is = new ByteArrayInputStream(data.getBytes());
176 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
177 debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
178 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
181 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
182 Thread.sleep(1000 * 180);
183 debugLog.printRTAriDebug(fnName, "Woke up....");
185 catch (java.lang.InterruptedException ee)
187 boolean ignore = true;
190 else // Must be a get
192 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
193 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
194 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
195 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
196 ctx.setAttribute("fileContents", response);
197 log.debug("SCP: Closing the SFTP connection");
199 sshJcraftWrapper = null;
200 return (setResponseStatus(ctx, r));
202 catch (IOException e)
204 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
205 log.debug(fnName + " : Caught a IOException e=" + e);
206 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
207 r.message = e.getMessage();
208 sshJcraftWrapper = null;
209 return (setResponseStatus(ctx, r));
212 if (key.equals("cli"))
214 String loginId = parameters.get("loginId");
215 String host = parameters.get("host");
216 String password = parameters.get("password");
217 password = EncryptionTool.getInstance().decrypt(password);
218 String cliCommand = parameters.get("cli");
219 String portNumber = parameters.get("portNumber");
220 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
223 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password +
224 " portNumber=" + portNumber);
225 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
226 " password=" + password + " portNumber=" + portNumber);
227 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
229 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
230 String response = sshJcraftWrapper.send("sdc", ":");
231 DebugLog.printAriDebug(fnName, "Sending 1");
232 response = sshJcraftWrapper.send("1", ":");
233 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
234 response = sshJcraftWrapper.send("1", "#");
235 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
236 response = sshJcraftWrapper.send("paging-options disable", "#");
237 DebugLog.printAriDebug(fnName, "Sending show config");
238 response = sshJcraftWrapper.send("show config", "#");
240 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
241 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
242 ctx.setAttribute("cliOutput", response);
243 sshJcraftWrapper.closeConnection();
245 sshJcraftWrapper = null;
246 return (setResponseStatus(ctx, r));
248 catch (IOException e)
250 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
251 log.debug(fnName + " : Caught a IOException e=" + e);
252 sshJcraftWrapper.closeConnection();
253 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
254 r.message = e.getMessage();
255 sshJcraftWrapper = null;
256 DebugLog.printAriDebug(fnName, "Returning error message");
257 return (setResponseStatus(ctx, r));
260 if (key.equals("escapeSql"))
262 String data = parameters.get("artifactContents");
263 log.debug("ConfigComponentAdaptor.configure - escapeSql");
264 data = escapeMySql(data);
265 ctx.setAttribute("escapedData", data);
266 return (setResponseStatus(ctx, r));
268 if(key.equals("GetCliRunningConfig"))
270 debugLog.printRTAriDebug (fnName, "key was: GetCliRunningConfig: ");
271 log.debug("key was: GetCliRunningConfig: ");
272 String User_name = parameters.get("User_name");
273 String Host_ip_address = parameters.get("Host_ip_address");
274 String Password = parameters.get("Password");
275 Password = EncryptionTool.getInstance().decrypt(Password);
276 String Port_number = parameters.get("Port_number");
277 String Get_config_template = parameters.get("Get_config_template");
278 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
279 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
280 debugLog.printRTAriDebug (fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
283 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
284 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address +" User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
285 StringBuffer sb = new StringBuffer();
286 String response = "";
287 String CliResponse = "";
288 boolean showConfigFlag = false;
289 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
290 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
291 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
292 String command = null;
295 while (st.hasMoreTokens())
297 String line = st.nextToken();
298 DebugLog.printAriDebug(fnName, "line="+line);
299 if (line.indexOf("Request:") != -1)
301 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
302 command = getStringBetweenQuotes(line);
303 DebugLog.printAriDebug(fnName, "Sending command="+command);
304 sshJcraftWrapper.send(command);
305 DebugLog.printAriDebug(fnName, "command has been sent");
306 if (line.indexOf("show config") != -1)
308 showConfigFlag = true;
309 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
310 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
313 if (line.indexOf("Response: Ends_With") != -1)
315 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
316 String delemeter = getStringBetweenQuotes(line);
317 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
318 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120*1000, command);
319 response += tmpResponse;
322 showConfigFlag = false;
323 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
324 while (st2.hasMoreTokens())
326 String line2 = st2.nextToken();
327 if (line2.indexOf("#") == -1)
328 CliResponse += line2 +"\n";
334 catch (NoSuchElementException e)
336 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
338 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
339 ctx.setAttribute("cliOutput", CliResponse);
340 sshJcraftWrapper.closeConnection();
342 sshJcraftWrapper = null;
343 return(setResponseStatus(ctx, r));
347 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e="+e);
348 log.debug(fnName +" : GetCliRunningConfig: Caught a IOException e="+e);
349 sshJcraftWrapper.closeConnection();
350 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
351 r.message = e.getMessage();
352 sshJcraftWrapper = null;
353 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
354 return(setResponseStatus(ctx, r));
357 if(key.equals("xml-download"))
359 log(fnName, "key was: xml-download");
360 String User_name = parameters.get("User_name");
361 String Host_ip_address = parameters.get("Host_ip_address");
362 String Password = parameters.get("Password");
363 Password = EncryptionTool.getInstance().decrypt(Password);
364 String Port_number = parameters.get("Port_number");
365 String Contents = parameters.get("Contents");
366 String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <capabilities>\n <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
367 String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
368 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
370 log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
371 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
374 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
375 String NetconfHelloCmd = netconfHelloCmd;
376 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
377 log(fnName, "Sending the hello command");
378 sshJcraftWrapper.send(NetconfHelloCmd);
379 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
380 log(fnName, "Sending xmlCmd cmd");
381 String xmlCmd = Contents;
382 String messageId = "1";
383 messageId= "\"" +messageId+"\"";
384 String loadConfigurationString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="+messageId+"> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"+xmlCmd+"</config> </edit-config> </rpc>";
385 loadConfigurationString = loadConfigurationString +"]]>]]>";
386 sshJcraftWrapper.send(loadConfigurationString);
387 DebugLog.printAriDebug(fnName,":After sending loadConfigurationString");
388 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
389 if (response.indexOf("rpc-error") != -1)
391 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
392 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
393 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
394 r.message = response;
398 DebugLog.printAriDebug(fnName,":LoadConfiguration was a success, sending commit cmd");
399 sshJcraftWrapper.send(commitCmd);
400 DebugLog.printAriDebug(fnName,":After sending commitCmd");
401 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
402 if (response.indexOf("rpc-error") != -1)
404 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
405 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
406 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
407 r.message = response;
411 DebugLog.printAriDebug(fnName,":Looks like a success");
412 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
416 sshJcraftWrapper.send(terminateConnectionCmd);
417 sshJcraftWrapper.closeConnection();
418 sshJcraftWrapper = null;
419 return(setResponseStatus(ctx, r));
423 log(fnName, "Caught an Exception, e="+e);
424 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
425 sshJcraftWrapper.closeConnection();
426 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
427 r.message = e.getMessage();
428 sshJcraftWrapper = null;
429 log(fnName, "Returning error message");
430 return (setResponseStatus(ctx, r));
433 if(key.equals("xml-getrunningconfig"))
435 log(fnName, "key was: : xml-getrunningconfig");
436 String xmlGetRunningConfigCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\"> <get-config> <source> <running /> </source> </get-config> </rpc>\n";
437 String Host_ip_address = parameters.get("Host_ip_address");
438 String User_name = parameters.get("User_name");
439 String Password = parameters.get("Password");
440 Password = EncryptionTool.getInstance().decrypt(Password);
441 String Port_number = parameters.get("Port_number");
442 String Protocol = parameters.get("Protocol");
443 String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <capabilities>\n <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
444 String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
445 log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
446 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
449 String NetconfHelloCmd = netconfHelloCmd;
450 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
451 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
452 log(fnName, ":Sending the hello command");
453 sshJcraftWrapper.send(NetconfHelloCmd);
454 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
455 log(fnName, "Sending get running config command");
456 sshJcraftWrapper.send(xmlGetRunningConfigCmd +"]]>]]>\n");
457 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
458 DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response);
459 response = trimResponse(response);
460 ctx.setAttribute("xmlRunningConfigOutput", response);
461 sshJcraftWrapper.send(terminateConnectionCmd);
462 sshJcraftWrapper.closeConnection();
464 sshJcraftWrapper = null;
465 return(setResponseStatus(ctx, r));
469 log(fnName, "Caught an Exception, e="+e);
470 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
471 sshJcraftWrapper.closeConnection();
472 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
473 r.message = e.getMessage();
474 sshJcraftWrapper = null;
475 log(fnName, "Returning error message");
476 return (setResponseStatus(ctx, r));
479 if(key.equals("DownloadCliConfig"))
481 debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: ");
482 log.debug("key was: DownloadCliConfig: ");
483 String User_name = parameters.get("User_name");
484 String Host_ip_address = parameters.get("Host_ip_address");
485 String Password = parameters.get("Password");
486 Password = EncryptionTool.getInstance().decrypt(Password);
487 String Port_number = parameters.get("Port_number");
488 String Download_config_template = parameters.get("Download_config_template");
489 String Config_contents = parameters.get("Config_contents");
490 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: "+Config_contents);
491 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
492 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
493 debugLog.printRTAriDebug (fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
494 int timeout = 4*60*1000;
497 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
498 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address +" User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
499 StringBuffer sb = new StringBuffer();
500 String response = "";
501 String CliResponse = "";
502 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
503 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
504 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
505 String command = null;
506 String executeConfigContentsDelemeter = null;
509 while (st.hasMoreTokens())
511 String line = st.nextToken();
512 DebugLog.printAriDebug(fnName, "line="+line);
513 if (line.indexOf("Request:") != -1)
515 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
516 command = getStringBetweenQuotes(line);
517 DebugLog.printAriDebug(fnName, "Sending command="+command);
518 sshJcraftWrapper.send(command);
519 DebugLog.printAriDebug(fnName, "command has been sent");
521 else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1))
523 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
524 String delemeter = getStringBetweenQuotes(line);
525 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
526 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
527 response += tmpResponse;
528 CliResponse += tmpResponse;
530 else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1)
532 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line="+line);
533 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
534 DebugLog.printAriDebug(fnName, "executeConfigContentsDelemeter="+executeConfigContentsDelemeter);
535 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
536 while (st2.hasMoreTokens())
538 String cmd = st2.nextToken();
539 DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd);
540 sshJcraftWrapper.send(cmd);
541 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command);
542 CliResponse += tmpResponse;
547 catch (NoSuchElementException e)
549 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
551 sshJcraftWrapper.closeConnection();
552 sshJcraftWrapper = null;
553 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
554 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
555 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
556 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
557 ctx.setAttribute("cliOutput", CliResponse);
559 return(setResponseStatus(ctx, r));
563 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e="+e);
564 log.debug(fnName +" : DownloadCliConfig: Caught a IOException e="+e);
565 sshJcraftWrapper.closeConnection();
566 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
567 r.message = e.getMessage();
568 sshJcraftWrapper = null;
569 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
570 return(setResponseStatus(ctx, r));
574 debugLog.printRTAriDebug (fnName, "Unsupported action - " + action);
575 log.error("Unsupported action - " + action);
576 return ConfigStatus.FAILURE;
579 private void log (String fileName, String messg)
581 debugLog.printRTAriDebug (fileName, messg);
582 log.debug(fileName +": "+messg);
585 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation)
587 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
588 String ndTemplate = readFile(templateName);
589 String nd = buildNetworkData2(ctx, ndTemplate, operation);
591 String reqTemplate = readFile("/config-request.xml");
592 Map<String, String> param = new HashMap<String, String>();
593 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
594 param.put("request-type", requestType);
595 param.put("callback-url", configCallbackUrl);
596 if (operation.equals("create") || operation.equals("change") || operation.equals("scale"))
597 param.put("action", "GenerateOnly");
598 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
599 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
600 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
601 param.put("network-data", nd);
606 req = buildXmlRequest(param, reqTemplate);
610 log.error("Error building the XML request: ", e);
612 HttpResponse r = new HttpResponse();
613 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
614 r.message = e.getMessage();
615 return setResponseStatus(ctx, r);
618 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
619 return setResponseStatus(ctx, r);
622 private ConfigStatus activate(SvcLogicContext ctx, boolean change)
624 String reqTemplate = readFile("/config-request.xml");
625 Map<String, String> param = new HashMap<String, String>();
626 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
627 param.put("callback-url", configCallbackUrl);
628 param.put("action", change ? "DownloadChange" : "DownloadBase");
629 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
634 req = buildXmlRequest(param, reqTemplate);
638 log.error("Error building the XML request: ", e);
640 HttpResponse r = new HttpResponse();
641 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
642 r.message = e.getMessage();
643 return setResponseStatus(ctx, r);
646 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
647 return setResponseStatus(ctx, r);
650 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel)
652 String reqTemplate = readFile("/audit-request.xml");
653 Map<String, String> param = new HashMap<String, String>();
654 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
655 param.put("callback-url", auditCallbackUrl);
656 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
657 param.put("audit-level", auditLevel);
662 req = buildXmlRequest(param, reqTemplate);
666 log.error("Error building the XML request: ", e);
668 HttpResponse r = new HttpResponse();
669 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
670 r.message = e.getMessage();
671 return setResponseStatus(ctx, r);
674 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
675 return setResponseStatus(ctx, r);
679 public ConfigStatus activate(String key, SvcLogicContext ctx)
681 return ConfigStatus.SUCCESS;
685 public ConfigStatus deactivate(String key, SvcLogicContext ctx)
687 return ConfigStatus.SUCCESS;
690 private String escapeMySql(String input)
695 input = input.replace("\\", "\\\\");
696 input = input.replace("\'", "\\'");
701 private String readFile(String fileName)
703 InputStream is = getClass().getResourceAsStream(fileName);
704 InputStreamReader isr = new InputStreamReader(is);
705 BufferedReader in = new BufferedReader(isr);
706 StringBuilder ss = new StringBuilder();
709 String s = in.readLine();
712 ss.append(s).append('\n');
716 catch (IOException e)
718 System.out.println("Error reading " + fileName + ": " + e.getMessage());
719 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
729 log.warn("Could not close BufferedReader", e);
737 log.warn("Could not close InputStreamReader", e);
745 log.warn("Could not close InputStream", e);
748 return ss.toString();
751 private String buildXmlRequest(Map<String, String> param, String template)
753 StringBuilder ss = new StringBuilder();
755 while (i < template.length())
757 int i1 = template.indexOf("${", i);
760 ss.append(template.substring(i));
764 int i2 = template.indexOf('}', i1 + 2);
766 throw new RuntimeException("Template error: Matching } not found");
768 String var1 = template.substring(i1 + 2, i2);
769 String value1 = param.get(var1);
770 if (value1 == null || value1.trim().length() == 0)
772 // delete the whole element (line)
773 int i3 = template.lastIndexOf('\n', i1);
776 int i4 = template.indexOf('\n', i1);
778 i4 = template.length();
781 ss.append(template.substring(i, i3));
786 ss.append(template.substring(i, i1)).append(value1);
791 return ss.toString();
794 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation)
796 log.info("Building XML started");
797 long t1 = System.currentTimeMillis();
799 template = expandRepeats(ctx, template, 1);
801 Map<String, String> mm = new HashMap<>();
802 for (String s : ctx.getAttributeKeySet())
803 mm.put(s, ctx.getAttribute(s));
804 mm.put("operation", operation);
806 StringBuilder ss = new StringBuilder();
808 while (i < template.length())
810 int i1 = template.indexOf("${", i);
813 ss.append(template.substring(i));
817 int i2 = template.indexOf('}', i1 + 2);
819 throw new RuntimeException("Template error: Matching } not found");
821 String var1 = template.substring(i1 + 2, i2);
822 String value1 = XmlUtil.getXml(mm, var1);
823 if (value1 == null || value1.trim().length() == 0)
825 int i3 = template.lastIndexOf('\n', i1);
828 int i4 = template.indexOf('\n', i1);
830 i4 = template.length();
833 ss.append(template.substring(i, i3));
838 ss.append(template.substring(i, i1)).append(value1);
843 long t2 = System.currentTimeMillis();
844 log.info("Building XML completed. Time: " + (t2 - t1));
846 return ss.toString();
849 private String expandRepeats(SvcLogicContext ctx, String template, int level)
851 StringBuilder newTemplate = new StringBuilder();
853 while (k < template.length())
855 int i1 = template.indexOf("${repeat:", k);
858 newTemplate.append(template.substring(k));
862 int i2 = template.indexOf(':', i1 + 9);
864 throw new RuntimeException(
865 "Template error: Context variable name followed by : is required after repeat");
867 // Find the closing }, store in i3
871 while (nn > 0 && i < template.length())
873 i3 = template.indexOf('}', i);
875 throw new RuntimeException("Template error: Matching } not found");
876 int i32 = template.indexOf('{', i);
877 if (i32 >= 0 && i32 < i3)
889 String var1 = template.substring(i1 + 9, i2);
890 String value1 = ctx.getAttribute(var1);
891 log.info(" " + var1 + ": " + value1);
895 n = Integer.parseInt(value1);
902 newTemplate.append(template.substring(k, i1));
904 String rpt = template.substring(i2 + 1, i3);
906 for (int ii = 0; ii < n; ii++)
908 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
909 newTemplate.append(ss);
916 return newTemplate.toString();
918 return expandRepeats(ctx, newTemplate.toString(), level + 1);
921 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password)
925 Client client = Client.create();
926 client.setConnectTimeout(5000);
927 WebResource webResource = client.resource(url);
929 log.info("SENDING...............");
930 log.info(xmlRequest);
932 String authString = user + ":" + password;
933 byte[] authEncBytes = Base64.encode(authString);
934 String authStringEnc = new String(authEncBytes);
935 authString = "Basic " + authStringEnc;
937 ClientResponse response =
938 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
939 ClientResponse.class, xmlRequest);
941 int code = response.getStatus();
942 String message = null;
944 log.info("RESPONSE...............");
945 log.info("HTTP response code: " + code);
946 log.info("HTTP response message: " + message);
949 HttpResponse r = new HttpResponse();
957 log.error("Error sending the request: ", e);
959 HttpResponse r = new HttpResponse();
960 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
961 r.message = e.getMessage();
966 private static class HttpResponse
970 public String message;
973 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r)
975 ctx.setAttribute("error-code", String.valueOf(r.code));
976 ctx.setAttribute("error-message", r.message);
978 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
981 private String getStringBetweenQuotes(String string)
983 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
984 DebugLog.printAriDebug(fnName, "string="+string);
985 String retString = null;
986 int start = string.indexOf("\"");
987 int end = string.lastIndexOf("\"");
988 retString = string.substring(start+1, end);
989 DebugLog.printAriDebug(fnName, "retString="+retString);
993 public static String _readFile(String fileName)
995 StringBuffer strBuff = new StringBuffer();
999 BufferedReader in = new BufferedReader(new FileReader(fileName));
1000 while ((line = in.readLine()) != null)
1002 strBuff.append(line+"\n");
1006 catch (IOException e)
1008 System.out.println("Caught an IOException in method readFile(): e="+e.toString());
1010 return (strBuff.toString());
1013 private String trimResponse(String response)
1015 StringTokenizer line = new StringTokenizer(response, "\n");
1016 StringBuffer sb = new StringBuffer();
1017 boolean captureText = false;
1018 while (line.hasMoreTokens())
1020 String token = line.nextToken();
1021 if (token.indexOf("<configuration xmlns=") != -1)
1024 sb.append(token +"\n");
1025 if (token.indexOf("</configuration>") != -1)
1026 captureText = false;
1028 return(sb.toString());
1031 public static void main (String args[]) throws Exception
1033 Properties props = null;
1034 System.out.println("*************************Hello*****************************");
1035 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1036 String Get_config_template = _readFile ("/home/userID/data/Get_config_template");
1037 String Download_config_template = _readFile ("/home/userID/data/Download_config_template_2");
1038 String key = "GetCliRunningConfig";
1039 Map<String, String> parameters = new HashMap();
1040 parameters.put("Host_ip_address", "000.00.000.00");
1041 parameters.put("User_name", "root");
1042 parameters.put("Password", "!bootstrap");
1043 parameters.put("Port_number", "22");
1044 parameters.put("Get_config_template", Get_config_template);
1045 SvcLogicContext ctx = null;
1046 System.out.println("*************************TRACE 1*****************************");
1047 cca.configure(key, parameters, ctx);