2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.
19 * ============LICENSE_END=========================================================
22 package org.onap.appc.ccadaptor;
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.sun.jersey.api.client.Client;
27 import com.sun.jersey.api.client.ClientResponse;
28 import com.sun.jersey.api.client.WebResource;
29 import com.sun.jersey.core.util.Base64;
30 import java.io.BufferedReader;
31 import java.io.ByteArrayInputStream;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.UncheckedIOException;
37 import java.net.HttpURLConnection;
38 import java.util.HashMap;
40 import java.util.Map.Entry;
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);
50 DebugLog debugLog = new DebugLog();
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;
60 public ConfigComponentAdaptor(Properties props) {
62 configUrl = props.getProperty("configComponent.url", "");
63 configUser = props.getProperty("configComponent.user", "");
64 configPassword = props.getProperty("configComponent.passwd", "");
65 auditUrl = props.getProperty("auditComponent.url", "");
66 auditUser = props.getProperty("auditComponent.user", "");
67 auditPassword = props.getProperty("auditComponent.passwd", "");
68 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
69 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
77 configCallbackUrl = "";
78 auditCallbackUrl = "";
83 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
84 String fnName = "ConfigComponentAdaptor.configure";
85 HttpResponse r = new HttpResponse();
87 log.debug("ConfigComponentAdaptor.configure - key = " + key);
88 debugLog.printRTAriDebug(fnName, "key = " + key);
89 log.debug("Parameters:");
90 debugLog.printRTAriDebug(fnName, "Parameters:");
91 for (String parmName : parameters.keySet()) {
92 log.debug(" " + parmName + " = " + parameters.get(parmName));
93 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
96 String parmval = parameters.get("config-component-configUrl");
97 if ((parmval != null) && (parmval.length() > 0)) {
98 log.debug("Overwriting URL with " + parmval);
102 parmval = parameters.get("config-component-configPassword");
103 if ((parmval != null) && (parmval.length() > 0)) {
104 log.debug("Overwriting configPassword with " + parmval);
105 configPassword = parmval;
108 parmval = parameters.get("config-component-configUser");
109 if ((parmval != null) && (parmval.length() > 0)) {
110 log.debug("Overwriting configUser id with " + parmval);
111 configUser = parmval;
114 String action = parameters.get("action");
116 String chg = ctx.getAttribute(
117 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
118 if (chg != null && "prepare".equalsIgnoreCase(action)) {
119 return prepare(ctx, "CHANGE", "change");
121 if (chg != null && "activate".equalsIgnoreCase(action)) {
122 return activate(ctx, true);
125 String scale = ctx.getAttribute(
126 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
127 if (scale != null && "prepare".equalsIgnoreCase(action)) {
128 return prepare(ctx, "CHANGE", "scale");
130 if (scale != null && "activate".equalsIgnoreCase(action)) {
131 return activate(ctx, true);
134 if ("prepare".equalsIgnoreCase(action)) {
135 return prepare(ctx, "BASE", "create");
137 if ("activate".equalsIgnoreCase(action)) {
138 return activate(ctx, false);
141 if ("backup".equalsIgnoreCase(action)) {
142 return prepare(ctx, "BACKUP", "backup");
144 if ("restorebackup".equalsIgnoreCase(action)) {
145 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
147 if ("deletebackup".equalsIgnoreCase(action)) {
148 return prepare(ctx, "DELETEBACKUP", "deletebackup");
150 if ("audit".equalsIgnoreCase(action)) {
151 return audit(ctx, "FULL");
153 if ("getrunningconfig".equalsIgnoreCase(action)) {
154 return audit(ctx, "RUNNING");
157 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");
165 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
166 log.debug("SCP: SshJcraftWrapper has been instantiated");
167 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
169 if (key.equals("put")) {
170 data = parameters.get("data");
172 debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
173 InputStream is = new ByteArrayInputStream(data.getBytes());
174 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
175 debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
176 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
178 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
179 Thread.sleep(1000 * 180);
180 debugLog.printRTAriDebug(fnName, "Woke up....");
181 } catch (java.lang.InterruptedException ee) {
182 boolean ignore = true;
185 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
186 log.debug(fnName + " Command is for put: data is null");
188 } else // Must be a get
190 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
191 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
192 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
193 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
194 ctx.setAttribute("fileContents", response);
195 log.debug("SCP: Closing the SFTP connection");
197 sshJcraftWrapper = null;
198 return (setResponseStatus(ctx, r));
199 } catch (IOException e) {
200 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
201 log.debug(fnName + " : Caught a IOException e=" + e);
202 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
203 r.message = e.getMessage();
204 sshJcraftWrapper = null;
205 return (setResponseStatus(ctx, r));
208 if (key.equals("cli")) {
209 String loginId = parameters.get("loginId");
210 String host = parameters.get("host");
211 String password = parameters.get("password");
212 password = EncryptionTool.getInstance().decrypt(password);
213 String cliCommand = parameters.get("cli");
214 String portNumber = parameters.get("portNumber");
215 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
217 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId +
218 " portNumber=" + portNumber);
219 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
220 " portNumber=" + portNumber);
221 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
223 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
224 String response = sshJcraftWrapper.send("sdc", ":");
225 DebugLog.printAriDebug(fnName, "Sending 1");
226 response = sshJcraftWrapper.send("1", ":");
227 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
228 response = sshJcraftWrapper.send("1", "#");
229 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
230 response = sshJcraftWrapper.send("paging-options disable", "#");
231 DebugLog.printAriDebug(fnName, "Sending show config");
232 response = sshJcraftWrapper.send("show config", "#");
234 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
235 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
236 ctx.setAttribute("cliOutput", response);
237 sshJcraftWrapper.closeConnection();
239 sshJcraftWrapper = null;
240 return (setResponseStatus(ctx, r));
241 } catch (IOException e) {
242 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
243 log.debug(fnName + " : Caught a IOException e=" + e);
244 sshJcraftWrapper.closeConnection();
245 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
246 r.message = e.getMessage();
247 sshJcraftWrapper = null;
248 DebugLog.printAriDebug(fnName, "Returning error message");
249 return (setResponseStatus(ctx, r));
252 if (key.equals("escapeSql")) {
253 String data = parameters.get("artifactContents");
254 log.debug("ConfigComponentAdaptor.configure - escapeSql");
255 data = escapeMySql(data);
256 ctx.setAttribute("escapedData", data);
257 return (setResponseStatus(ctx, r));
259 if (key.equals("GetCliRunningConfig")) {
260 debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
261 log.debug("key was: GetCliRunningConfig: ");
262 String User_name = parameters.get("User_name");
263 String Host_ip_address = parameters.get("Host_ip_address");
264 String Password = parameters.get("Password");
265 Password = EncryptionTool.getInstance().decrypt(Password);
266 String Port_number = parameters.get("Port_number");
267 String Get_config_template = parameters.get("Get_config_template");
268 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
269 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
270 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
272 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
273 " Host_ip_address=" + Host_ip_address + " Port_number="
275 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
276 " User_name=" + User_name + " Port_number=" + Port_number);
277 StringBuffer sb = new StringBuffer();
278 String response = "";
279 String CliResponse = "";
280 boolean showConfigFlag = false;
281 sshJcraftWrapper.connect(Host_ip_address,
286 Integer.parseInt(Port_number));
287 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
288 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
289 String command = null;
291 while (st.hasMoreTokens()) {
292 String line = st.nextToken();
293 DebugLog.printAriDebug(fnName, "line=" + line);
294 if (line.indexOf("Request:") != -1) {
295 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
296 command = getStringBetweenQuotes(line);
297 DebugLog.printAriDebug(fnName, "Sending command=" + command);
298 sshJcraftWrapper.send(command);
299 DebugLog.printAriDebug(fnName, "command has been sent");
300 if (line.indexOf("show config") != -1) {
301 showConfigFlag = true;
302 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
303 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
306 if (line.indexOf("Response: Ends_With") != -1) {
307 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
308 String delemeter = getStringBetweenQuotes(line);
309 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
310 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30 * 1000, command);
311 response += tmpResponse;
312 if (showConfigFlag) {
313 showConfigFlag = false;
314 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
315 // Strip off the last line which is the command prompt from the VNF device.
316 while (st2.hasMoreTokens()) {
317 String line2 = st2.nextToken();
318 if (line2.indexOf("#") == -1) {
319 CliResponse += line2 + "\n";
325 } catch (NoSuchElementException e) {
326 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
328 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
329 ctx.setAttribute("cliOutput", CliResponse);
330 sshJcraftWrapper.closeConnection();
332 sshJcraftWrapper = null;
333 return (setResponseStatus(ctx, r));
334 } catch (IOException e) {
335 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
336 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
337 sshJcraftWrapper.closeConnection();
338 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
339 r.message = e.getMessage();
340 sshJcraftWrapper = null;
341 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
342 return (setResponseStatus(ctx, r));
345 if (key.equals("xml-download")) {
346 log(fnName, "key was: xml-download");
347 String User_name = parameters.get("User_name");
348 String Host_ip_address = parameters.get("Host_ip_address");
349 String Password = parameters.get("Password");
350 Password = EncryptionTool.getInstance().decrypt(Password);
351 String Port_number = parameters.get("Port_number");
352 String Contents = parameters.get("Contents");
353 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>";
354 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 ]]>]]>";
355 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\"> <commit/> </rpc>\n ]]>]]>";
358 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
359 + " Port_number=" + Port_number);
360 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
362 sshJcraftWrapper.connect(Host_ip_address,
367 Integer.parseInt(Port_number),
369 String NetconfHelloCmd = netconfHelloCmd;
370 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
371 log(fnName, "Sending the hello command");
372 sshJcraftWrapper.send(NetconfHelloCmd);
373 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
374 log(fnName, "Sending xmlCmd cmd");
375 String xmlCmd = Contents;
376 String messageId = "1";
377 messageId = "\"" + messageId + "\"";
378 String loadConfigurationString =
379 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
381 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
382 + xmlCmd + "</config> </edit-config> </rpc>";
383 loadConfigurationString = loadConfigurationString + "]]>]]>";
384 sshJcraftWrapper.send(loadConfigurationString);
385 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
386 response = sshJcraftWrapper.receiveUntil("]]>]]>", 600000, "");
387 if (response.indexOf("rpc-error") != -1) {
388 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
389 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
390 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
391 r.message = response;
393 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
394 sshJcraftWrapper.send(commitCmd);
395 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
396 response = sshJcraftWrapper.receiveUntil("]]>]]>", 180000, "");
397 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;
403 DebugLog.printAriDebug(fnName, ":Looks like a success");
404 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
408 sshJcraftWrapper.send(terminateConnectionCmd);
409 sshJcraftWrapper.closeConnection();
410 sshJcraftWrapper = null;
411 return (setResponseStatus(ctx, r));
412 } catch (Exception e) {
413 log(fnName, "Caught an Exception, e=" + e);
414 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
415 sshJcraftWrapper.closeConnection();
416 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
417 r.message = e.getMessage();
418 sshJcraftWrapper = null;
419 log(fnName, "Returning error message");
420 return (setResponseStatus(ctx, r));
423 if (key.equals("xml-getrunningconfig")) {
424 log(fnName, "key was: : xml-getrunningconfig");
425 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";
426 String Host_ip_address = parameters.get("Host_ip_address");
427 String User_name = parameters.get("User_name");
428 String Password = parameters.get("Password");
429 Password = EncryptionTool.getInstance().decrypt(Password);
430 String Port_number = parameters.get("Port_number");
431 String Protocol = parameters.get("Protocol");
432 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>";
433 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 ]]>]]>";
435 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
436 + " Port_number=" + Port_number);
437 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
439 String NetconfHelloCmd = netconfHelloCmd;
440 sshJcraftWrapper.connect(Host_ip_address,
445 Integer.parseInt(Port_number),
447 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
448 log(fnName, ":Sending the hello command");
449 sshJcraftWrapper.send(NetconfHelloCmd);
450 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
451 log(fnName, "Sending get running config command");
452 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
453 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
454 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
455 response = trimResponse(response);
456 ctx.setAttribute("xmlRunningConfigOutput", response);
457 sshJcraftWrapper.send(terminateConnectionCmd);
458 sshJcraftWrapper.closeConnection();
460 sshJcraftWrapper = null;
461 return (setResponseStatus(ctx, r));
462 } catch (Exception e) {
463 log(fnName, "Caught an Exception, e=" + e);
464 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
465 sshJcraftWrapper.closeConnection();
466 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
467 r.message = e.getMessage();
468 sshJcraftWrapper = null;
469 log(fnName, "Returning error message");
470 return (setResponseStatus(ctx, r));
473 if (key.equals("DownloadCliConfig")) {
474 debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
475 log.debug("key was: DownloadCliConfig: ");
476 String User_name = parameters.get("User_name");
477 String Host_ip_address = parameters.get("Host_ip_address");
478 String Password = parameters.get("Password");
479 Password = EncryptionTool.getInstance().decrypt(Password);
480 String Port_number = parameters.get("Port_number");
481 String Download_config_template = parameters.get("Download_config_template");
482 String Config_contents = parameters.get("Config_contents");
483 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
484 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
485 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
486 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
487 int timeout = 4 * 60 * 1000;
489 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
490 " Host_ip_address=" + Host_ip_address + " Port_number="
492 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
493 " User_name=" + User_name + " Port_number=" + Port_number);
494 StringBuffer sb = new StringBuffer();
495 String response = "";
496 String CliResponse = "";
497 sshJcraftWrapper.connect(Host_ip_address,
502 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;
508 while (st.hasMoreTokens()) {
509 String line = st.nextToken();
510 DebugLog.printAriDebug(fnName, "line=" + line);
511 if (line.indexOf("Request:") != -1) {
512 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
513 command = getStringBetweenQuotes(line);
514 DebugLog.printAriDebug(fnName, "Sending command=" + command);
515 sshJcraftWrapper.send(command);
516 DebugLog.printAriDebug(fnName, "command has been sent");
517 } else if ((line.indexOf("Response: Ends_With") != -1) && (
518 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
519 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
520 String delemeter = getStringBetweenQuotes(line);
521 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
522 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
523 response += tmpResponse;
524 CliResponse += tmpResponse;
525 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
526 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
527 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
528 DebugLog.printAriDebug(fnName,
529 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
530 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
531 while (st2.hasMoreTokens()) {
532 String cmd = st2.nextToken();
533 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
534 sshJcraftWrapper.send(cmd);
535 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
538 CliResponse += tmpResponse;
542 } catch (NoSuchElementException e) {
543 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
545 sshJcraftWrapper.closeConnection();
546 sshJcraftWrapper = null;
547 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
548 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
549 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
550 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
551 ctx.setAttribute("cliOutput", CliResponse);
553 return (setResponseStatus(ctx, r));
554 } catch (IOException e) {
555 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
556 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
557 sshJcraftWrapper.closeConnection();
558 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
559 r.message = e.getMessage();
560 sshJcraftWrapper = null;
561 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
562 return (setResponseStatus(ctx, r));
566 debugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
567 log.error("Unsupported action - " + action);
568 return ConfigStatus.FAILURE;
571 private void log(String fileName, String messg) {
572 debugLog.printRTAriDebug(fileName, messg);
573 log.debug(fileName + ": " + messg);
576 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
577 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
578 String ndTemplate = readFile(templateName);
579 String nd = buildNetworkData2(ctx, ndTemplate, operation);
581 String reqTemplate = readFile("/config-request.xml");
582 Map<String, String> param = new HashMap<String, String>();
583 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
584 param.put("request-type", requestType);
585 param.put("callback-url", configCallbackUrl);
586 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
587 param.put("action", "GenerateOnly");
589 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
590 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
591 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
592 param.put("network-data", nd);
596 req = buildXmlRequest(param, reqTemplate);
597 } catch (Exception e) {
598 log.error("Error building the XML request: ", e);
600 HttpResponse r = new HttpResponse();
601 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
602 r.message = e.getMessage();
603 return setResponseStatus(ctx, r);
606 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
607 return setResponseStatus(ctx, r);
610 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
611 String reqTemplate = readFile("/config-request.xml");
612 Map<String, String> param = new HashMap<String, String>();
613 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
614 param.put("callback-url", configCallbackUrl);
615 param.put("action", change ? "DownloadChange" : "DownloadBase");
616 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
620 req = buildXmlRequest(param, reqTemplate);
621 } catch (Exception e) {
622 log.error("Error building the XML request: ", e);
624 HttpResponse r = new HttpResponse();
625 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
626 r.message = e.getMessage();
627 return setResponseStatus(ctx, r);
630 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
631 return setResponseStatus(ctx, r);
634 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
635 String reqTemplate = readFile("/audit-request.xml");
636 Map<String, String> param = new HashMap<String, String>();
637 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
638 param.put("callback-url", auditCallbackUrl);
639 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
640 param.put("audit-level", auditLevel);
644 req = buildXmlRequest(param, reqTemplate);
645 } catch (Exception e) {
646 log.error("Error building the XML request: ", e);
648 HttpResponse r = new HttpResponse();
649 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
650 r.message = e.getMessage();
651 return setResponseStatus(ctx, r);
654 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
655 return setResponseStatus(ctx, r);
659 public ConfigStatus activate(String key, SvcLogicContext ctx) {
660 return ConfigStatus.SUCCESS;
664 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
665 return ConfigStatus.SUCCESS;
668 private String escapeMySql(String input) {
673 input = input.replace("\\", "\\\\");
674 input = input.replace("\'", "\\'");
679 private String readFile(String fileName) {
680 InputStream is = getClass().getResourceAsStream(fileName);
681 InputStreamReader isr = new InputStreamReader(is);
682 BufferedReader in = new BufferedReader(isr);
683 StringBuilder ss = new StringBuilder();
685 String s = in.readLine();
687 ss.append(s).append('\n');
690 } catch (IOException e) {
691 System.out.println("Error reading " + fileName + ": " + e.getMessage());
692 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
696 } catch (Exception e) {
697 log.warn("Could not close BufferedReader", e);
701 } catch (Exception e) {
702 log.warn("Could not close InputStreamReader", e);
706 } catch (Exception e) {
707 log.warn("Could not close InputStream", e);
710 return ss.toString();
713 private String buildXmlRequest(Map<String, String> param, String template) {
714 StringBuilder ss = new StringBuilder();
716 while (i < template.length()) {
717 int i1 = template.indexOf("${", i);
719 ss.append(template.substring(i));
723 int i2 = template.indexOf('}', i1 + 2);
725 throw new RuntimeException("Template error: Matching } not found");
728 String var1 = template.substring(i1 + 2, i2);
729 String value1 = param.get(var1);
730 if (value1 == null || value1.trim().length() == 0) {
731 // delete the whole element (line)
732 int i3 = template.lastIndexOf('\n', i1);
736 int i4 = template.indexOf('\n', i1);
738 i4 = template.length();
742 ss.append(template.substring(i, i3));
746 ss.append(template.substring(i, i1)).append(value1);
751 return ss.toString();
754 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
755 log.info("Building XML started");
756 long t1 = System.currentTimeMillis();
758 template = expandRepeats(ctx, template, 1);
760 Map<String, String> mm = new HashMap<>();
761 for (String s : ctx.getAttributeKeySet()) {
762 mm.put(s, ctx.getAttribute(s));
764 mm.put("operation", operation);
766 StringBuilder ss = new StringBuilder();
768 while (i < template.length()) {
769 int i1 = template.indexOf("${", i);
771 ss.append(template.substring(i));
775 int i2 = template.indexOf('}', i1 + 2);
777 throw new RuntimeException("Template error: Matching } not found");
780 String var1 = template.substring(i1 + 2, i2);
781 String value1 = XmlUtil.getXml(mm, var1);
782 if (value1 == null || value1.trim().length() == 0) {
783 // delete the whole element (line)
784 int i3 = template.lastIndexOf('\n', i1);
788 int i4 = template.indexOf('\n', i1);
790 i4 = template.length();
794 ss.append(template.substring(i, i3));
798 ss.append(template.substring(i, i1)).append(value1);
803 long t2 = System.currentTimeMillis();
804 log.info("Building XML completed. Time: " + (t2 - t1));
806 return ss.toString();
809 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
810 StringBuilder newTemplate = new StringBuilder();
812 while (k < template.length()) {
813 int i1 = template.indexOf("${repeat:", k);
815 newTemplate.append(template.substring(k));
819 int i2 = template.indexOf(':', i1 + 9);
821 throw new RuntimeException(
822 "Template error: Context variable name followed by : is required after repeat");
825 // Find the closing }, store in i3
829 while (nn > 0 && i < template.length()) {
830 i3 = template.indexOf('}', i);
832 throw new RuntimeException("Template error: Matching } not found");
834 int i32 = template.indexOf('{', i);
835 if (i32 >= 0 && i32 < i3) {
844 String var1 = template.substring(i1 + 9, i2);
845 String value1 = ctx.getAttribute(var1);
846 log.info(" " + var1 + ": " + value1);
849 n = Integer.parseInt(value1);
850 } catch (Exception e) {
854 newTemplate.append(template.substring(k, i1));
856 String rpt = template.substring(i2 + 1, i3);
858 for (int ii = 0; ii < n; ii++) {
859 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
860 newTemplate.append(ss);
867 return newTemplate.toString();
870 return expandRepeats(ctx, newTemplate.toString(), level + 1);
873 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
875 Client client = Client.create();
876 client.setConnectTimeout(5000);
877 WebResource webResource = client.resource(url);
879 log.info("SENDING...............");
880 log.info(xmlRequest);
882 String authString = user + ":" + password;
883 byte[] authEncBytes = Base64.encode(authString);
884 String authStringEnc = new String(authEncBytes);
885 authString = "Basic " + authStringEnc;
887 ClientResponse response =
888 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
889 ClientResponse.class, xmlRequest);
891 int code = response.getStatus();
892 String message = null;
894 log.info("RESPONSE...............");
895 log.info("HTTP response code: " + code);
896 log.info("HTTP response message: " + message);
899 HttpResponse r = new HttpResponse();
904 } catch (Exception e) {
905 log.error("Error sending the request: ", e);
907 HttpResponse r = new HttpResponse();
908 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
909 r.message = e.getMessage();
914 private static class HttpResponse {
918 public String message;
921 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
922 ctx.setAttribute("error-code", String.valueOf(r.code));
923 ctx.setAttribute("error-message", r.message);
925 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
928 private String getStringBetweenQuotes(String string) {
929 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
930 DebugLog.printAriDebug(fnName, "string=" + string);
931 String retString = null;
932 int start = string.indexOf("\"");
933 int end = string.lastIndexOf("\"");
934 retString = string.substring(start + 1, end);
935 DebugLog.printAriDebug(fnName, "retString=" + retString);
939 public static String _readFile(String fileName) {
940 StringBuffer strBuff = new StringBuffer();
942 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
943 while ((line = in.readLine()) != null) {
944 strBuff.append(line + "\n");
946 } catch (IOException e) {
947 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
949 return (strBuff.toString());
952 private String trimResponse(String response) {
953 StringTokenizer line = new StringTokenizer(response, "\n");
954 StringBuffer sb = new StringBuffer();
955 boolean captureText = false;
956 while (line.hasMoreTokens()) {
957 String token = line.nextToken();
958 if (token.indexOf("<configuration xmlns=") != -1) {
962 sb.append(token + "\n");
964 if (token.indexOf("</configuration>") != -1) {
968 return (sb.toString());
971 public static void main(String args[]) throws Exception {
972 Properties props = null;
973 System.out.println("*************************Hello*****************************");
974 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
975 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
976 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
977 String key = "GetCliRunningConfig";
978 Map<String, String> parameters = new HashMap();
979 parameters.put("Host_ip_address", "000.00.000.00");
980 parameters.put("User_name", "root");
981 parameters.put("Password", "!bootstrap");
982 parameters.put("Port_number", "22");
983 parameters.put("Get_config_template", Get_config_template);
985 SvcLogicContext ctx = null;
986 System.out.println("*************************TRACE 1*****************************");
987 cca.configure(key, parameters, ctx);