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.openecomp.sdnc.sli.SvcLogicAdaptor;
41 import org.openecomp.sdnc.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");
168 if (key.equals("put"))
169 data = parameters.get("data");
171 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
172 log.debug("SCP: SshJcraftWrapper has been instantiated");
173 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
176 if (key.equals("put"))
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 else // Must be a get
196 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
197 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
198 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
199 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
200 ctx.setAttribute("fileContents", response);
201 log.debug("SCP: Closing the SFTP connection");
203 sshJcraftWrapper = null;
204 return (setResponseStatus(ctx, r));
206 catch (IOException e)
208 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
209 log.debug(fnName + " : Caught a IOException e=" + e);
210 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
211 r.message = e.getMessage();
212 sshJcraftWrapper = null;
213 return (setResponseStatus(ctx, r));
216 if (key.equals("cli"))
218 String loginId = parameters.get("loginId");
219 String host = parameters.get("host");
220 String password = parameters.get("password");
221 password = EncryptionTool.getInstance().decrypt(password);
222 String cliCommand = parameters.get("cli");
223 String portNumber = parameters.get("portNumber");
224 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
227 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password +
228 " portNumber=" + portNumber);
229 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
230 " password=" + password + " portNumber=" + portNumber);
231 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
233 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
234 String response = sshJcraftWrapper.send("sdc", ":");
235 DebugLog.printAriDebug(fnName, "Sending 1");
236 response = sshJcraftWrapper.send("1", ":");
237 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
238 response = sshJcraftWrapper.send("1", "#");
239 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
240 response = sshJcraftWrapper.send("paging-options disable", "#");
241 DebugLog.printAriDebug(fnName, "Sending show config");
242 response = sshJcraftWrapper.send("show config", "#");
244 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
245 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
246 ctx.setAttribute("cliOutput", response);
247 sshJcraftWrapper.closeConnection();
249 sshJcraftWrapper = null;
250 return (setResponseStatus(ctx, r));
252 catch (IOException e)
254 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
255 log.debug(fnName + " : Caught a IOException e=" + e);
256 sshJcraftWrapper.closeConnection();
257 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
258 r.message = e.getMessage();
259 sshJcraftWrapper = null;
260 DebugLog.printAriDebug(fnName, "Returning error message");
261 return (setResponseStatus(ctx, r));
264 if (key.equals("escapeSql"))
266 String data = parameters.get("artifactContents");
267 log.debug("ConfigComponentAdaptor.configure - escapeSql");
268 data = escapeMySql(data);
269 ctx.setAttribute("escapedData", data);
270 return (setResponseStatus(ctx, r));
272 if(key.equals("GetCliRunningConfig"))
274 debugLog.printRTAriDebug (fnName, "key was: GetCliRunningConfig: ");
275 log.debug("key was: GetCliRunningConfig: ");
276 String User_name = parameters.get("User_name");
277 String Host_ip_address = parameters.get("Host_ip_address");
278 String Password = parameters.get("Password");
279 Password = EncryptionTool.getInstance().decrypt(Password);
280 String Port_number = parameters.get("Port_number");
281 String Get_config_template = parameters.get("Get_config_template");
282 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
283 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
284 debugLog.printRTAriDebug (fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
287 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name="+User_name +
288 " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
289 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address +
290 " User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
291 StringBuffer sb = new StringBuffer();
292 String response = "";
293 String CliResponse = "";
294 boolean showConfigFlag = false;
295 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
296 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
297 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
298 String command = null;
301 while (st.hasMoreTokens())
303 String line = st.nextToken();
304 DebugLog.printAriDebug(fnName, "line="+line);
305 if (line.indexOf("Request:") != -1)
307 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
308 command = getStringBetweenQuotes(line);
309 DebugLog.printAriDebug(fnName, "Sending command="+command);
310 sshJcraftWrapper.send(command);
311 DebugLog.printAriDebug(fnName, "command has been sent");
312 if (line.indexOf("show config") != -1)
314 showConfigFlag = true;
315 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
316 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
319 if (line.indexOf("Response: Ends_With") != -1)
321 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
322 String delemeter = getStringBetweenQuotes(line);
323 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
324 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30*1000, command);
325 response += tmpResponse;
328 showConfigFlag = false;
329 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
330 // Strip off the last line which is the command prompt from the VNF device.
331 while (st2.hasMoreTokens())
333 String line2 = st2.nextToken();
334 if (line2.indexOf("#") == -1)
335 CliResponse += line2 +"\n";
341 catch (NoSuchElementException e)
343 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
345 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
346 ctx.setAttribute("cliOutput", CliResponse);
347 sshJcraftWrapper.closeConnection();
349 sshJcraftWrapper = null;
350 return(setResponseStatus(ctx, r));
354 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e="+e);
355 log.debug(fnName +" : GetCliRunningConfig: Caught a IOException e="+e);
356 sshJcraftWrapper.closeConnection();
357 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
358 r.message = e.getMessage();
359 sshJcraftWrapper = null;
360 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
361 return(setResponseStatus(ctx, r));
364 if(key.equals("xml-download"))
366 log(fnName, "key was: xml-download");
367 String User_name = parameters.get("User_name");
368 String Host_ip_address = parameters.get("Host_ip_address");
369 String Password = parameters.get("Password");
370 Password = EncryptionTool.getInstance().decrypt(Password);
371 String Port_number = parameters.get("Port_number");
372 String Contents = parameters.get("Contents");
373 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>";
374 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 ]]>]]>";
375 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
377 log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
378 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
381 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
382 String NetconfHelloCmd = netconfHelloCmd;
383 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
384 log(fnName, "Sending the hello command");
385 sshJcraftWrapper.send(NetconfHelloCmd);
386 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
387 log(fnName, "Sending xmlCmd cmd");
388 String xmlCmd = Contents;
389 String messageId = "1";
390 messageId= "\"" +messageId+"\"";
391 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>";
392 loadConfigurationString = loadConfigurationString +"]]>]]>";
393 sshJcraftWrapper.send(loadConfigurationString);
394 DebugLog.printAriDebug(fnName,":After sending loadConfigurationString");
395 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
396 if (response.indexOf("rpc-error") != -1)
398 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
399 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
400 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
401 r.message = response;
405 DebugLog.printAriDebug(fnName,":LoadConfiguration was a success, sending commit cmd");
406 sshJcraftWrapper.send(commitCmd);
407 DebugLog.printAriDebug(fnName,":After sending commitCmd");
408 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
409 if (response.indexOf("rpc-error") != -1)
411 DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'");
412 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
413 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
414 r.message = response;
418 DebugLog.printAriDebug(fnName,":Looks like a success");
419 DebugLog.printAriDebug(fnName,"response=\n"+response +"\n");
423 sshJcraftWrapper.send(terminateConnectionCmd);
424 sshJcraftWrapper.closeConnection();
425 sshJcraftWrapper = null;
426 return(setResponseStatus(ctx, r));
430 log(fnName, "Caught an Exception, e="+e);
431 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
432 sshJcraftWrapper.closeConnection();
433 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
434 r.message = e.getMessage();
435 sshJcraftWrapper = null;
436 log(fnName, "Returning error message");
437 return (setResponseStatus(ctx, r));
440 if(key.equals("xml-getrunningconfig"))
442 log(fnName, "key was: : xml-getrunningconfig");
443 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";
444 String Host_ip_address = parameters.get("Host_ip_address");
445 String User_name = parameters.get("User_name");
446 String Password = parameters.get("Password");
447 Password = EncryptionTool.getInstance().decrypt(Password);
448 String Port_number = parameters.get("Port_number");
449 String Protocol = parameters.get("Protocol");
450 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>";
451 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 ]]>]]>";
452 log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
453 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
456 String NetconfHelloCmd = netconfHelloCmd;
457 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf");
458 NetconfHelloCmd = NetconfHelloCmd +"]]>]]>";
459 log(fnName, ":Sending the hello command");
460 sshJcraftWrapper.send(NetconfHelloCmd);
461 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
462 log(fnName, "Sending get running config command");
463 sshJcraftWrapper.send(xmlGetRunningConfigCmd +"]]>]]>\n");
464 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
465 DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response);
466 response = trimResponse(response);
467 ctx.setAttribute("xmlRunningConfigOutput", response);
468 sshJcraftWrapper.send(terminateConnectionCmd);
469 sshJcraftWrapper.closeConnection();
471 sshJcraftWrapper = null;
472 return(setResponseStatus(ctx, r));
476 log(fnName, "Caught an Exception, e="+e);
477 log(fnName, "StackTrace="+DebugLog.getStackTraceString(e));
478 sshJcraftWrapper.closeConnection();
479 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
480 r.message = e.getMessage();
481 sshJcraftWrapper = null;
482 log(fnName, "Returning error message");
483 return (setResponseStatus(ctx, r));
486 if(key.equals("DownloadCliConfig"))
488 debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: ");
489 log.debug("key was: DownloadCliConfig: ");
490 String User_name = parameters.get("User_name");
491 String Host_ip_address = parameters.get("Host_ip_address");
492 String Password = parameters.get("Password");
493 Password = EncryptionTool.getInstance().decrypt(Password);
494 String Port_number = parameters.get("Port_number");
495 String Download_config_template = parameters.get("Download_config_template");
496 String Config_contents = parameters.get("Config_contents");
497 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: "+Config_contents);
498 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
499 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
500 debugLog.printRTAriDebug (fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
501 int timeout = 4*60*1000;
504 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name="+User_name +
505 " Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number);
506 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address +
507 " User_name="+User_name+" Password="+Password+" Port_number="+Port_number);
508 StringBuffer sb = new StringBuffer();
509 String response = "";
510 String CliResponse = "";
511 sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
512 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
513 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
514 String command = null;
515 String executeConfigContentsDelemeter = null;
518 while (st.hasMoreTokens())
520 String line = st.nextToken();
521 DebugLog.printAriDebug(fnName, "line="+line);
522 if (line.indexOf("Request:") != -1)
524 DebugLog.printAriDebug(fnName, "Found a Request line: line="+line);
525 command = getStringBetweenQuotes(line);
526 DebugLog.printAriDebug(fnName, "Sending command="+command);
527 sshJcraftWrapper.send(command);
528 DebugLog.printAriDebug(fnName, "command has been sent");
530 else if ((line.indexOf("Response: Ends_With") != -1) && (line.indexOf("Execute_config_contents Response: Ends_With") == -1))
532 DebugLog.printAriDebug(fnName, "Found a Response line: line="+line);
533 String delemeter = getStringBetweenQuotes(line);
534 DebugLog.printAriDebug(fnName, "The delemeter="+delemeter);
535 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
536 response += tmpResponse;
537 CliResponse += tmpResponse;
539 else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1)
541 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line="+line);
542 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
543 DebugLog.printAriDebug(fnName, "executeConfigContentsDelemeter="+executeConfigContentsDelemeter);
544 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
545 while (st2.hasMoreTokens())
547 String cmd = st2.nextToken();
548 DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd);
549 sshJcraftWrapper.send(cmd);
550 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command);
551 CliResponse += tmpResponse;
556 catch (NoSuchElementException e)
558 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e);
560 sshJcraftWrapper.closeConnection();
561 sshJcraftWrapper = null;
562 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
563 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
564 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
565 DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse);
566 ctx.setAttribute("cliOutput", CliResponse);
568 return(setResponseStatus(ctx, r));
572 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e="+e);
573 log.debug(fnName +" : DownloadCliConfig: Caught a IOException e="+e);
574 sshJcraftWrapper.closeConnection();
575 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
576 r.message = e.getMessage();
577 sshJcraftWrapper = null;
578 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
579 return(setResponseStatus(ctx, r));
583 debugLog.printRTAriDebug (fnName, "Unsupported action - " + action);
584 log.error("Unsupported action - " + action);
585 return ConfigStatus.FAILURE;
588 private void log (String fileName, String messg)
590 debugLog.printRTAriDebug (fileName, messg);
591 log.debug(fileName +": "+messg);
594 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation)
596 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
597 String ndTemplate = readFile(templateName);
598 String nd = buildNetworkData2(ctx, ndTemplate, operation);
600 String reqTemplate = readFile("/config-request.xml");
601 Map<String, String> param = new HashMap<String, String>();
602 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
603 param.put("request-type", requestType);
604 param.put("callback-url", configCallbackUrl);
605 if (operation.equals("create") || operation.equals("change") || operation.equals("scale"))
606 param.put("action", "GenerateOnly");
607 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
608 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
609 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
610 param.put("network-data", nd);
615 req = buildXmlRequest(param, reqTemplate);
619 log.error("Error building the XML request: ", e);
621 HttpResponse r = new HttpResponse();
622 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
623 r.message = e.getMessage();
624 return setResponseStatus(ctx, r);
627 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
628 return setResponseStatus(ctx, r);
631 private ConfigStatus activate(SvcLogicContext ctx, boolean change)
633 String reqTemplate = readFile("/config-request.xml");
634 Map<String, String> param = new HashMap<String, String>();
635 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
636 param.put("callback-url", configCallbackUrl);
637 param.put("action", change ? "DownloadChange" : "DownloadBase");
638 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
643 req = buildXmlRequest(param, reqTemplate);
647 log.error("Error building the XML request: ", e);
649 HttpResponse r = new HttpResponse();
650 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
651 r.message = e.getMessage();
652 return setResponseStatus(ctx, r);
655 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
656 return setResponseStatus(ctx, r);
659 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel)
661 String reqTemplate = readFile("/audit-request.xml");
662 Map<String, String> param = new HashMap<String, String>();
663 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
664 param.put("callback-url", auditCallbackUrl);
665 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
666 param.put("audit-level", auditLevel);
671 req = buildXmlRequest(param, reqTemplate);
675 log.error("Error building the XML request: ", e);
677 HttpResponse r = new HttpResponse();
678 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
679 r.message = e.getMessage();
680 return setResponseStatus(ctx, r);
683 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
684 return setResponseStatus(ctx, r);
688 public ConfigStatus activate(String key, SvcLogicContext ctx)
690 return ConfigStatus.SUCCESS;
694 public ConfigStatus deactivate(String key, SvcLogicContext ctx)
696 return ConfigStatus.SUCCESS;
699 private String escapeMySql(String input)
704 input = input.replace("\\", "\\\\");
705 input = input.replace("\'", "\\'");
710 private String readFile(String fileName)
712 InputStream is = getClass().getResourceAsStream(fileName);
713 InputStreamReader isr = new InputStreamReader(is);
714 BufferedReader in = new BufferedReader(isr);
715 StringBuilder ss = new StringBuilder();
718 String s = in.readLine();
721 ss.append(s).append('\n');
725 catch (IOException e)
727 System.out.println("Error reading " + fileName + ": " + e.getMessage());
728 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
738 log.warn("Could not close BufferedReader", e);
746 log.warn("Could not close InputStreamReader", e);
754 log.warn("Could not close InputStream", e);
757 return ss.toString();
760 private String buildXmlRequest(Map<String, String> param, String template)
762 StringBuilder ss = new StringBuilder();
764 while (i < template.length())
766 int i1 = template.indexOf("${", i);
769 ss.append(template.substring(i));
773 int i2 = template.indexOf('}', i1 + 2);
775 throw new RuntimeException("Template error: Matching } not found");
777 String var1 = template.substring(i1 + 2, i2);
778 String value1 = param.get(var1);
779 if (value1 == null || value1.trim().length() == 0)
781 // delete the whole element (line)
782 int i3 = template.lastIndexOf('\n', i1);
785 int i4 = template.indexOf('\n', i1);
787 i4 = template.length();
790 ss.append(template.substring(i, i3));
795 ss.append(template.substring(i, i1)).append(value1);
800 return ss.toString();
803 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation)
805 log.info("Building XML started");
806 long t1 = System.currentTimeMillis();
808 template = expandRepeats(ctx, template, 1);
810 Map<String, String> mm = new HashMap<>();
811 for (String s : ctx.getAttributeKeySet())
812 mm.put(s, ctx.getAttribute(s));
813 mm.put("operation", operation);
815 StringBuilder ss = new StringBuilder();
817 while (i < template.length())
819 int i1 = template.indexOf("${", i);
822 ss.append(template.substring(i));
826 int i2 = template.indexOf('}', i1 + 2);
828 throw new RuntimeException("Template error: Matching } not found");
830 String var1 = template.substring(i1 + 2, i2);
831 String value1 = XmlUtil.getXml(mm, var1);
832 if (value1 == null || value1.trim().length() == 0)
834 // delete the whole element (line)
835 int i3 = template.lastIndexOf('\n', i1);
838 int i4 = template.indexOf('\n', i1);
840 i4 = template.length();
843 ss.append(template.substring(i, i3));
848 ss.append(template.substring(i, i1)).append(value1);
853 long t2 = System.currentTimeMillis();
854 log.info("Building XML completed. Time: " + (t2 - t1));
856 return ss.toString();
859 private String expandRepeats(SvcLogicContext ctx, String template, int level)
861 StringBuilder newTemplate = new StringBuilder();
863 while (k < template.length())
865 int i1 = template.indexOf("${repeat:", k);
868 newTemplate.append(template.substring(k));
872 int i2 = template.indexOf(':', i1 + 9);
874 throw new RuntimeException(
875 "Template error: Context variable name followed by : is required after repeat");
877 // Find the closing }, store in i3
881 while (nn > 0 && i < template.length())
883 i3 = template.indexOf('}', i);
885 throw new RuntimeException("Template error: Matching } not found");
886 int i32 = template.indexOf('{', i);
887 if (i32 >= 0 && i32 < i3)
899 String var1 = template.substring(i1 + 9, i2);
900 String value1 = ctx.getAttribute(var1);
901 log.info(" " + var1 + ": " + value1);
905 n = Integer.parseInt(value1);
912 newTemplate.append(template.substring(k, i1));
914 String rpt = template.substring(i2 + 1, i3);
916 for (int ii = 0; ii < n; ii++)
918 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
919 newTemplate.append(ss);
926 return newTemplate.toString();
928 return expandRepeats(ctx, newTemplate.toString(), level + 1);
931 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password)
935 Client client = Client.create();
936 client.setConnectTimeout(5000);
937 WebResource webResource = client.resource(url);
939 log.info("SENDING...............");
940 log.info(xmlRequest);
942 String authString = user + ":" + password;
943 byte[] authEncBytes = Base64.encode(authString);
944 String authStringEnc = new String(authEncBytes);
945 authString = "Basic " + authStringEnc;
947 ClientResponse response =
948 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
949 ClientResponse.class, xmlRequest);
951 int code = response.getStatus();
952 String message = null;
954 log.info("RESPONSE...............");
955 log.info("HTTP response code: " + code);
956 log.info("HTTP response message: " + message);
959 HttpResponse r = new HttpResponse();
967 log.error("Error sending the request: ", e);
969 HttpResponse r = new HttpResponse();
970 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
971 r.message = e.getMessage();
976 private static class HttpResponse
980 public String message;
983 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r)
985 ctx.setAttribute("error-code", String.valueOf(r.code));
986 ctx.setAttribute("error-message", r.message);
988 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
991 private String getStringBetweenQuotes(String string)
993 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
994 DebugLog.printAriDebug(fnName, "string="+string);
995 String retString = null;
996 int start = string.indexOf("\"");
997 int end = string.lastIndexOf("\"");
998 retString = string.substring(start+1, end);
999 DebugLog.printAriDebug(fnName, "retString="+retString);
1003 public static String _readFile(String fileName)
1005 StringBuffer strBuff = new StringBuffer();
1009 BufferedReader in = new BufferedReader(new FileReader(fileName));
1010 while ((line = in.readLine()) != null)
1012 strBuff.append(line+"\n");
1016 catch (IOException e)
1018 System.out.println("Caught an IOException in method readFile(): e="+e.toString());
1020 return (strBuff.toString());
1023 private String trimResponse(String response)
1025 StringTokenizer line = new StringTokenizer(response, "\n");
1026 StringBuffer sb = new StringBuffer();
1027 boolean captureText = false;
1028 while (line.hasMoreTokens())
1030 String token = line.nextToken();
1031 if (token.indexOf("<configuration xmlns=") != -1)
1034 sb.append(token +"\n");
1035 if (token.indexOf("</configuration>") != -1)
1036 captureText = false;
1038 return(sb.toString());
1041 public static void main (String args[]) throws Exception
1043 Properties props = null;
1044 System.out.println("*************************Hello*****************************");
1045 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
1046 String Get_config_template = _readFile ("/home/userID/data/Get_config_template");
1047 String Download_config_template = _readFile ("/home/userID/data/Download_config_template_2");
1048 String key = "GetCliRunningConfig";
1049 Map<String, String> parameters = new HashMap();
1050 parameters.put("Host_ip_address", "000.00.000.00");
1051 parameters.put("User_name", "root");
1052 parameters.put("Password", "!bootstrap");
1053 parameters.put("Port_number", "22");
1054 parameters.put("Get_config_template", Get_config_template);
1056 SvcLogicContext ctx = null;
1057 System.out.println("*************************TRACE 1*****************************");
1058 cca.configure(key, parameters, ctx);