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.openecomp.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.regex.Matcher;
34 import java.util.regex.Pattern;
35 import java.util.StringTokenizer;
36 import java.util.NoSuchElementException;
37 import java.io.StringReader;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import com.sun.jersey.api.client.Client;
43 import com.sun.jersey.api.client.ClientResponse;
44 import com.sun.jersey.api.client.WebResource;
45 import com.sun.jersey.core.util.Base64;
46 import org.jdom.input.SAXBuilder;
47 import com.att.eelf.configuration.EELFLogger;
48 import com.att.eelf.configuration.EELFManager;
50 public class ConfigComponentAdaptor implements SvcLogicAdaptor
53 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
55 private String configUrl = null;
56 private String configUser = null;
57 private String configPassword = null;
58 private String auditUrl = null;
59 private String auditUser = null;
60 private String auditPassword = null;
61 private String configCallbackUrl = null;
62 private String auditCallbackUrl = null;
63 DebugLog debugLog = new DebugLog();
65 public ConfigComponentAdaptor(Properties props)
69 configUrl = props.getProperty("configComponent.url", "");
70 configUser = props.getProperty("configComponent.user", "");
71 configPassword = props.getProperty("configComponent.passwd", "");
72 auditUrl = props.getProperty("auditComponent.url", "");
73 auditUser = props.getProperty("auditComponent.user", "");
74 auditPassword = props.getProperty("auditComponent.passwd", "");
75 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
76 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
86 configCallbackUrl = "";
87 auditCallbackUrl = "";
92 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx)
94 String fnName = "ConfigComponentAdaptor.configure";
95 HttpResponse r = new HttpResponse();
97 log.debug("ConfigComponentAdaptor.configure - key = " + key);
98 debugLog.printRTAriDebug(fnName, "key = " + key);
99 log.debug("Parameters:");
100 debugLog.printRTAriDebug(fnName, "Parameters:");
101 for (String parmName : parameters.keySet())
103 log.debug(" " + parmName + " = " + parameters.get(parmName));
104 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
107 String parmval = parameters.get("config-component-configUrl");
108 if ((parmval != null) && (parmval.length() > 0))
110 log.debug("Overwriting URL with " + parmval);
114 parmval = parameters.get("config-component-configPassword");
115 if ((parmval != null) && (parmval.length() > 0))
117 log.debug("Overwriting configPassword with " + parmval);
118 configPassword = parmval;
121 parmval = parameters.get("config-component-configUser");
122 if ((parmval != null) && (parmval.length() > 0))
124 log.debug("Overwriting configUser id with " + parmval);
125 configUser = parmval;
128 String action = parameters.get("action");
130 String chg = ctx.getAttribute(
131 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
132 if (chg != null && "prepare".equalsIgnoreCase(action))
133 return prepare(ctx, "CHANGE", "change");
134 if (chg != null && "activate".equalsIgnoreCase(action))
135 return activate(ctx, true);
137 String scale = ctx.getAttribute(
138 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
139 if (scale != null && "prepare".equalsIgnoreCase(action))
140 return prepare(ctx, "CHANGE", "scale");
141 if (scale != null && "activate".equalsIgnoreCase(action))
142 return activate(ctx, true);
144 if ("prepare".equalsIgnoreCase(action))
145 return prepare(ctx, "BASE", "create");
146 if ("activate".equalsIgnoreCase(action))
147 return activate(ctx, false);
149 if ("backup".equalsIgnoreCase(action))
150 return prepare(ctx, "BACKUP", "backup");
151 if ("restorebackup".equalsIgnoreCase(action))
152 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
153 if ("deletebackup".equalsIgnoreCase(action))
154 return prepare(ctx, "DELETEBACKUP", "deletebackup");
155 if ("audit".equalsIgnoreCase(action))
156 return audit(ctx, "FULL");
157 if ("getrunningconfig".equalsIgnoreCase(action))
158 return audit(ctx, "RUNNING");
160 if ((key.equals("put")) || (key.equals("get")))
162 String loginId = parameters.get("loginId");
163 String host = parameters.get("host");
164 String password = parameters.get("password");
165 password = EncryptionTool.getInstance().decrypt(password);
166 String fullPathFileName = parameters.get("fullPathFileName");
169 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
170 log.debug("SCP: SshJcraftWrapper has been instantiated");
171 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
174 if (key.equals("put"))
176 data = parameters.get("data");
178 debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
179 InputStream is = new ByteArrayInputStream(data.getBytes());
180 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
181 debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
182 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
185 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
186 Thread.sleep(1000 * 180);
187 debugLog.printRTAriDebug(fnName, "Woke up....");
189 catch (java.lang.InterruptedException ee)
191 boolean ignore = true;
194 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
195 log.debug(fnName + " Command is for put: data is null");
198 else // Must be a get
200 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
201 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
202 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
203 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
204 ctx.setAttribute("fileContents", response);
205 log.debug("SCP: Closing the SFTP connection");
207 sshJcraftWrapper = null;
208 return (setResponseStatus(ctx, r));
210 catch (IOException e)
212 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
213 log.debug(fnName + " : Caught a IOException e=" + e);
214 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
215 r.message = e.getMessage();
216 sshJcraftWrapper = null;
217 return (setResponseStatus(ctx, r));
220 if (key.equals("cli"))
222 String loginId = parameters.get("loginId");
223 String host = parameters.get("host");
224 String password = parameters.get("password");
225 password = EncryptionTool.getInstance().decrypt(password);
226 String cliCommand = parameters.get("cli");
227 String portNumber = parameters.get("portNumber");
228 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
231 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password +
232 " portNumber=" + portNumber);
233 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
234 " password=" + password + " portNumber=" + portNumber);
235 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
237 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
238 String response = sshJcraftWrapper.send("sdc", ":");
239 DebugLog.printAriDebug(fnName, "Sending 1");
240 response = sshJcraftWrapper.send("1", ":");
241 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
242 response = sshJcraftWrapper.send("1", "#");
243 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
244 response = sshJcraftWrapper.send("paging-options disable", "#");
245 DebugLog.printAriDebug(fnName, "Sending show config");
246 response = sshJcraftWrapper.send("show config", "#");
248 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
249 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
250 ctx.setAttribute("cliOutput", response);
251 sshJcraftWrapper.closeConnection();
253 sshJcraftWrapper = null;
254 return (setResponseStatus(ctx, r));
256 catch (IOException e)
258 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
259 log.debug(fnName + " : Caught a IOException e=" + e);
260 sshJcraftWrapper.closeConnection();
261 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
262 r.message = e.getMessage();
263 sshJcraftWrapper = null;
264 DebugLog.printAriDebug(fnName, "Returning error message");
265 return (setResponseStatus(ctx, r));
268 if (key.equals("escapeSql"))
270 String data = parameters.get("artifactContents");
271 log.debug("ConfigComponentAdaptor.configure - escapeSql");
272 data = escapeMySql(data);
273 ctx.setAttribute("escapedData", data);
274 return (setResponseStatus(ctx, r));
276 if(key.equals("GetCliRunningConfig"))
278 debugLog.printRTAriDebug (fnName, "key was: GetCliRunningConfig: ");
279 log.debug("key was: GetCliRunningConfig: ");
280 String User_name = parameters.get("User_name");
281 String Host_ip_address = parameters.get("Host_ip_address");
282 String Password = parameters.get("Password");
283 Password = EncryptionTool.getInstance().decrypt(Password);
284 String Port_number = parameters.get("Port_number");
285 String Get_config_template = parameters.get("Get_config_template");
286 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
287 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
288 debugLog.printRTAriDebug (fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
291 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name="+User_name +
292 " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
293 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address +
294 " User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
295 StringBuffer sb = new StringBuffer();
296 String response = "";
297 String CliResponse = "";
298 boolean showConfigFlag = false;
299 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
300 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
301 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
302 String command = null;
305 while (st.hasMoreTokens())
307 String line = st.nextToken();
308 DebugLog.printAriDebug(fnName, "line="+line);
309 if (line.indexOf("Request:") != -1)
311 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
312 command = getStringBetweenQuotes(line);
313 DebugLog.printAriDebug(fnName, "Sending command="+command);
314 sshJcraftWrapper.send(command);
315 DebugLog.printAriDebug(fnName, "command has been sent");
316 if (line.indexOf("show config") != -1)
318 showConfigFlag = true;
319 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
320 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
323 if (line.indexOf("Response: Ends_With") != -1)
325 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
326 String delemeter = getStringBetweenQuotes(line);
327 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
328 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30*1000, command);
329 response += tmpResponse;
332 showConfigFlag = false;
333 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
334 // Strip off the last line which is the command prompt from the VNF device.
335 while (st2.hasMoreTokens())
337 String line2 = st2.nextToken();
338 if (line2.indexOf("#") == -1)
339 CliResponse += line2 +"\n";
345 catch (NoSuchElementException e)
347 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
349 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
350 ctx.setAttribute("cliOutput", CliResponse);
351 sshJcraftWrapper.closeConnection();
353 sshJcraftWrapper = null;
354 return(setResponseStatus(ctx, r));
358 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e="+e);
359 log.debug(fnName +" : GetCliRunningConfig: Caught a IOException e="+e);
360 sshJcraftWrapper.closeConnection();
361 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
362 r.message = e.getMessage();
363 sshJcraftWrapper = null;
364 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
365 return(setResponseStatus(ctx, r));
368 if(key.equals("xml-download"))
370 log(fnName, "key was: xml-download");
371 String User_name = parameters.get("User_name");
372 String Host_ip_address = parameters.get("Host_ip_address");
373 String Password = parameters.get("Password");
374 Password = EncryptionTool.getInstance().decrypt(Password);
375 String Port_number = parameters.get("Port_number");
376 String Contents = parameters.get("Contents");
377 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>";
378 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 ]]>]]>";
379 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
381 log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
382 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
385 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
386 String NetconfHelloCmd = netconfHelloCmd;
387 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
388 log(fnName, "Sending the hello command");
389 sshJcraftWrapper.send(NetconfHelloCmd);
390 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
391 log(fnName, "Sending xmlCmd cmd");
392 String xmlCmd = Contents;
393 String messageId = "1";
394 messageId= "\"" +messageId+"\"";
395 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>";
396 loadConfigurationString = loadConfigurationString +"]]>]]>";
397 sshJcraftWrapper.send(loadConfigurationString);
398 DebugLog.printAriDebug(fnName,":After sending loadConfigurationString");
399 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
400 if (response.indexOf("rpc-error") != -1)
402 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
403 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
404 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
405 r.message = response;
409 DebugLog.printAriDebug(fnName,":LoadConfiguration was a success, sending commit cmd");
410 sshJcraftWrapper.send(commitCmd);
411 DebugLog.printAriDebug(fnName,":After sending commitCmd");
412 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
413 if (response.indexOf("rpc-error") != -1)
415 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
416 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
417 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
418 r.message = response;
422 DebugLog.printAriDebug(fnName,":Looks like a success");
423 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
427 sshJcraftWrapper.send(terminateConnectionCmd);
428 sshJcraftWrapper.closeConnection();
429 sshJcraftWrapper = null;
430 return(setResponseStatus(ctx, r));
434 log(fnName, "Caught an Exception, e="+e);
435 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
436 sshJcraftWrapper.closeConnection();
437 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
438 r.message = e.getMessage();
439 sshJcraftWrapper = null;
440 log(fnName, "Returning error message");
441 return (setResponseStatus(ctx, r));
444 if(key.equals("xml-getrunningconfig"))
446 log(fnName, "key was: : xml-getrunningconfig");
447 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";
448 String Host_ip_address = parameters.get("Host_ip_address");
449 String User_name = parameters.get("User_name");
450 String Password = parameters.get("Password");
451 Password = EncryptionTool.getInstance().decrypt(Password);
452 String Port_number = parameters.get("Port_number");
453 String Protocol = parameters.get("Protocol");
454 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>";
455 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 ]]>]]>";
456 log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
457 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
460 String NetconfHelloCmd = netconfHelloCmd;
461 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
462 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
463 log(fnName, ":Sending the hello command");
464 sshJcraftWrapper.send(NetconfHelloCmd);
465 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
466 log(fnName, "Sending get running config command");
467 sshJcraftWrapper.send(xmlGetRunningConfigCmd +"]]>]]>\n");
468 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
469 DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response);
470 response = trimResponse(response);
471 ctx.setAttribute("xmlRunningConfigOutput", response);
472 sshJcraftWrapper.send(terminateConnectionCmd);
473 sshJcraftWrapper.closeConnection();
475 sshJcraftWrapper = null;
476 return(setResponseStatus(ctx, r));
480 log(fnName, "Caught an Exception, e="+e);
481 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
482 sshJcraftWrapper.closeConnection();
483 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
484 r.message = e.getMessage();
485 sshJcraftWrapper = null;
486 log(fnName, "Returning error message");
487 return (setResponseStatus(ctx, r));
490 if(key.equals("DownloadCliConfig"))
492 debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: ");
493 log.debug("key was: DownloadCliConfig: ");
494 String User_name = parameters.get("User_name");
495 String Host_ip_address = parameters.get("Host_ip_address");
496 String Password = parameters.get("Password");
497 Password = EncryptionTool.getInstance().decrypt(Password);
498 String Port_number = parameters.get("Port_number");
499 String Download_config_template = parameters.get("Download_config_template");
500 String Config_contents = parameters.get("Config_contents");
501 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: "+Config_contents);
502 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
503 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
504 debugLog.printRTAriDebug (fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
505 int timeout = 4*60*1000;
508 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name="+User_name +
509 " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
510 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address +
511 " User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
512 StringBuffer sb = new StringBuffer();
513 String response = "";
514 String CliResponse = "";
515 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
516 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
517 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
518 String command = null;
519 String executeConfigContentsDelemeter = null;
522 while (st.hasMoreTokens())
524 String line = st.nextToken();
525 DebugLog.printAriDebug(fnName, "line="+line);
526 if (line.indexOf("Request:") != -1)
528 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
529 command = getStringBetweenQuotes(line);
530 DebugLog.printAriDebug(fnName, "Sending command="+command);
531 sshJcraftWrapper.send(command);
532 DebugLog.printAriDebug(fnName, "command has been sent");
534 else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1))
536 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
537 String delemeter = getStringBetweenQuotes(line);
538 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
539 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
540 response += tmpResponse;
541 CliResponse += tmpResponse;
543 else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1)
545 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line="+line);
546 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
547 DebugLog.printAriDebug(fnName, "executeConfigContentsDelemeter="+executeConfigContentsDelemeter);
548 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
549 while (st2.hasMoreTokens())
551 String cmd = st2.nextToken();
552 DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd);
553 sshJcraftWrapper.send(cmd);
554 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command);
555 CliResponse += tmpResponse;
560 catch (NoSuchElementException e)
562 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
564 sshJcraftWrapper.closeConnection();
565 sshJcraftWrapper = null;
566 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
567 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
568 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
569 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
570 ctx.setAttribute("cliOutput", CliResponse);
572 return(setResponseStatus(ctx, r));
576 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e="+e);
577 log.debug(fnName +" : DownloadCliConfig: Caught a IOException e="+e);
578 sshJcraftWrapper.closeConnection();
579 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
580 r.message = e.getMessage();
581 sshJcraftWrapper = null;
582 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
583 return(setResponseStatus(ctx, r));
587 debugLog.printRTAriDebug (fnName, "Unsupported action - " + action);
588 log.error("Unsupported action - " + action);
589 return ConfigStatus.FAILURE;
592 private void log (String fileName, String messg)
594 debugLog.printRTAriDebug (fileName, messg);
595 log.debug(fileName +": "+messg);
598 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation)
600 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
601 String ndTemplate = readFile(templateName);
602 String nd = buildNetworkData2(ctx, ndTemplate, operation);
604 String reqTemplate = readFile("/config-request.xml");
605 Map<String, String> param = new HashMap<String, String>();
606 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
607 param.put("request-type", requestType);
608 param.put("callback-url", configCallbackUrl);
609 if (operation.equals("create") || operation.equals("change") || operation.equals("scale"))
610 param.put("action", "GenerateOnly");
611 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
612 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
613 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
614 param.put("network-data", nd);
619 req = buildXmlRequest(param, reqTemplate);
623 log.error("Error building the XML request: ", e);
625 HttpResponse r = new HttpResponse();
626 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
627 r.message = e.getMessage();
628 return setResponseStatus(ctx, r);
631 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
632 return setResponseStatus(ctx, r);
635 private ConfigStatus activate(SvcLogicContext ctx, boolean change)
637 String reqTemplate = readFile("/config-request.xml");
638 Map<String, String> param = new HashMap<String, String>();
639 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
640 param.put("callback-url", configCallbackUrl);
641 param.put("action", change ? "DownloadChange" : "DownloadBase");
642 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
647 req = buildXmlRequest(param, reqTemplate);
651 log.error("Error building the XML request: ", e);
653 HttpResponse r = new HttpResponse();
654 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
655 r.message = e.getMessage();
656 return setResponseStatus(ctx, r);
659 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
660 return setResponseStatus(ctx, r);
663 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel)
665 String reqTemplate = readFile("/audit-request.xml");
666 Map<String, String> param = new HashMap<String, String>();
667 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
668 param.put("callback-url", auditCallbackUrl);
669 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
670 param.put("audit-level", auditLevel);
675 req = buildXmlRequest(param, reqTemplate);
679 log.error("Error building the XML request: ", e);
681 HttpResponse r = new HttpResponse();
682 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
683 r.message = e.getMessage();
684 return setResponseStatus(ctx, r);
687 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
688 return setResponseStatus(ctx, r);
692 public ConfigStatus activate(String key, SvcLogicContext ctx)
694 return ConfigStatus.SUCCESS;
698 public ConfigStatus deactivate(String key, SvcLogicContext ctx)
700 return ConfigStatus.SUCCESS;
703 private String escapeMySql(String input)
708 input = input.replace("\\", "\\\\");
709 input = input.replace("\'", "\\'");
714 private String readFile(String fileName)
716 InputStream is = getClass().getResourceAsStream(fileName);
717 InputStreamReader isr = new InputStreamReader(is);
718 BufferedReader in = new BufferedReader(isr);
719 StringBuilder ss = new StringBuilder();
722 String s = in.readLine();
725 ss.append(s).append('\n');
729 catch (IOException e)
731 System.out.println("Error reading " + fileName + ": " + e.getMessage());
732 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
742 log.warn("Could not close BufferedReader", e);
750 log.warn("Could not close InputStreamReader", e);
758 log.warn("Could not close InputStream", e);
761 return ss.toString();
764 private String buildXmlRequest(Map<String, String> param, String template)
766 StringBuilder ss = new StringBuilder();
768 while (i < template.length())
770 int i1 = template.indexOf("${", i);
773 ss.append(template.substring(i));
777 int i2 = template.indexOf('}', i1 + 2);
779 throw new RuntimeException("Template error: Matching } not found");
781 String var1 = template.substring(i1 + 2, i2);
782 String value1 = param.get(var1);
783 if (value1 == null || value1.trim().length() == 0)
785 // delete the whole element (line)
786 int i3 = template.lastIndexOf('\n', i1);
789 int i4 = template.indexOf('\n', i1);
791 i4 = template.length();
794 ss.append(template.substring(i, i3));
799 ss.append(template.substring(i, i1)).append(value1);
804 return ss.toString();
807 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation)
809 log.info("Building XML started");
810 long t1 = System.currentTimeMillis();
812 template = expandRepeats(ctx, template, 1);
814 Map<String, String> mm = new HashMap<>();
815 for (String s : ctx.getAttributeKeySet())
816 mm.put(s, ctx.getAttribute(s));
817 mm.put("operation", operation);
819 StringBuilder ss = new StringBuilder();
821 while (i < template.length())
823 int i1 = template.indexOf("${", i);
826 ss.append(template.substring(i));
830 int i2 = template.indexOf('}', i1 + 2);
832 throw new RuntimeException("Template error: Matching } not found");
834 String var1 = template.substring(i1 + 2, i2);
835 String value1 = XmlUtil.getXml(mm, var1);
836 if (value1 == null || value1.trim().length() == 0)
838 // delete the whole element (line)
839 int i3 = template.lastIndexOf('\n', i1);
842 int i4 = template.indexOf('\n', i1);
844 i4 = template.length();
847 ss.append(template.substring(i, i3));
852 ss.append(template.substring(i, i1)).append(value1);
857 long t2 = System.currentTimeMillis();
858 log.info("Building XML completed. Time: " + (t2 - t1));
860 return ss.toString();
863 private String expandRepeats(SvcLogicContext ctx, String template, int level)
865 StringBuilder newTemplate = new StringBuilder();
867 while (k < template.length())
869 int i1 = template.indexOf("${repeat:", k);
872 newTemplate.append(template.substring(k));
876 int i2 = template.indexOf(':', i1 + 9);
878 throw new RuntimeException(
879 "Template error: Context variable name followed by : is required after repeat");
881 // Find the closing }, store in i3
885 while (nn > 0 && i < template.length())
887 i3 = template.indexOf('}', i);
889 throw new RuntimeException("Template error: Matching } not found");
890 int i32 = template.indexOf('{', i);
891 if (i32 >= 0 && i32 < i3)
903 String var1 = template.substring(i1 + 9, i2);
904 String value1 = ctx.getAttribute(var1);
905 log.info(" " + var1 + ": " + value1);
909 n = Integer.parseInt(value1);
916 newTemplate.append(template.substring(k, i1));
918 String rpt = template.substring(i2 + 1, i3);
920 for (int ii = 0; ii < n; ii++)
922 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
923 newTemplate.append(ss);
930 return newTemplate.toString();
932 return expandRepeats(ctx, newTemplate.toString(), level + 1);
935 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password)
939 Client client = Client.create();
940 client.setConnectTimeout(5000);
941 WebResource webResource = client.resource(url);
943 log.info("SENDING...............");
944 log.info(xmlRequest);
946 String authString = user + ":" + password;
947 byte[] authEncBytes = Base64.encode(authString);
948 String authStringEnc = new String(authEncBytes);
949 authString = "Basic " + authStringEnc;
951 ClientResponse response =
952 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
953 ClientResponse.class, xmlRequest);
955 int code = response.getStatus();
956 String message = null;
958 log.info("RESPONSE...............");
959 log.info("HTTP response code: " + code);
960 log.info("HTTP response message: " + message);
963 HttpResponse r = new HttpResponse();
971 log.error("Error sending the request: ", e);
973 HttpResponse r = new HttpResponse();
974 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
975 r.message = e.getMessage();
980 private static class HttpResponse
984 public String message;
987 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r)
989 ctx.setAttribute("error-code", String.valueOf(r.code));
990 ctx.setAttribute("error-message", r.message);
992 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
995 private String getStringBetweenQuotes(String string)
997 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
998 DebugLog.printAriDebug(fnName, "string="+string);
999 String retString = null;
1000 int start = string.indexOf("\"");
1001 int end = string.lastIndexOf("\"");
1002 retString = string.substring(start+1, end);
1003 DebugLog.printAriDebug(fnName, "retString="+retString);
1007 public static String _readFile(String fileName)
1009 StringBuffer strBuff = new StringBuffer();
1011 try (BufferedReader in = new BufferedReader(new FileReader(fileName)))
1013 while ((line = in.readLine()) != null)
1015 strBuff.append(line+"\n");
1018 catch (IOException e)
1020 System.out.println("Caught an IOException in method readFile(): e="+e.toString());
1022 return (strBuff.toString());
1025 private String trimResponse(String response)
1027 StringTokenizer line = new StringTokenizer(response, "\n");
1028 StringBuffer sb = new StringBuffer();
1029 boolean captureText = false;
1030 while (line.hasMoreTokens())
1032 String token = line.nextToken();
1033 if (token.indexOf("<configuration xmlns=") != -1)
1036 sb.append(token +"\n");
1037 if (token.indexOf("</configuration>") != -1)
1038 captureText = false;
1040 return(sb.toString());
1043 public static void main (String args[]) throws Exception
1045 Properties props = null;
1046 System.out.println("*************************Hello*****************************");
1047 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1048 String Get_config_template = _readFile ("/home/userID/data/Get_config_template");
1049 String Download_config_template = _readFile ("/home/userID/data/Download_config_template_2");
1050 String key = "GetCliRunningConfig";
1051 Map<String, String> parameters = new HashMap();
1052 parameters.put("Host_ip_address", "000.00.000.00");
1053 parameters.put("User_name", "root");
1054 parameters.put("Password", "!bootstrap");
1055 parameters.put("Port_number", "22");
1056 parameters.put("Get_config_template", Get_config_template);
1058 SvcLogicContext ctx = null;
1059 System.out.println("*************************TRACE 1*****************************");
1060 cca.configure(key, parameters, ctx);