2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property.All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.appc.ccadaptor;
23 import com.att.eelf.configuration.EELFLogger;
24 import com.att.eelf.configuration.EELFManager;
25 import com.sun.jersey.api.client.Client;
26 import com.sun.jersey.api.client.ClientResponse;
27 import com.sun.jersey.api.client.WebResource;
28 import com.sun.jersey.core.util.Base64;
29 import java.io.BufferedReader;
30 import java.io.ByteArrayInputStream;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.net.HttpURLConnection;
36 import java.util.HashMap;
38 import java.util.NoSuchElementException;
39 import java.util.Properties;
40 import java.util.StringTokenizer;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
46 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
47 DebugLog debugLog = new DebugLog();
48 private String configUrl = null;
49 private String configUser = null;
50 private String configPassword = null;
51 private String auditUrl = null;
52 private String auditUser = null;
53 private String auditPassword = null;
54 private String configCallbackUrl = null;
55 private String auditCallbackUrl = null;
57 public ConfigComponentAdaptor(Properties props) {
59 configUrl = props.getProperty("configComponent.url", "");
60 configUser = props.getProperty("configComponent.user", "");
61 configPassword = props.getProperty("configComponent.passwd", "");
62 auditUrl = props.getProperty("auditComponent.url", "");
63 auditUser = props.getProperty("auditComponent.user", "");
64 auditPassword = props.getProperty("auditComponent.passwd", "");
65 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
66 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
74 configCallbackUrl = "";
75 auditCallbackUrl = "";
80 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
81 String fnName = "ConfigComponentAdaptor.configure";
82 HttpResponse r = new HttpResponse();
84 log.debug("ConfigComponentAdaptor.configure - key = " + key);
85 debugLog.printRTAriDebug(fnName, "key = " + key);
86 log.debug("Parameters:");
87 debugLog.printRTAriDebug(fnName, "Parameters:");
88 for (String parmName : parameters.keySet()) {
89 log.debug(" " + parmName + " = " + parameters.get(parmName));
90 debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName));
93 String parmval = parameters.get("config-component-configUrl");
94 if ((parmval != null) && (parmval.length() > 0)) {
95 log.debug("Overwriting URL with " + parmval);
99 parmval = parameters.get("config-component-configPassword");
100 if ((parmval != null) && (parmval.length() > 0)) {
101 log.debug("Overwriting configPassword with " + parmval);
102 configPassword = parmval;
105 parmval = parameters.get("config-component-configUser");
106 if ((parmval != null) && (parmval.length() > 0)) {
107 log.debug("Overwriting configUser id with " + parmval);
108 configUser = parmval;
111 String action = parameters.get("action");
113 String chg = ctx.getAttribute(
114 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
115 if (chg != null && "prepare".equalsIgnoreCase(action)) {
116 return prepare(ctx, "CHANGE", "change");
118 if (chg != null && "activate".equalsIgnoreCase(action)) {
119 return activate(ctx, true);
122 String scale = ctx.getAttribute(
123 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
124 if (scale != null && "prepare".equalsIgnoreCase(action)) {
125 return prepare(ctx, "CHANGE", "scale");
127 if (scale != null && "activate".equalsIgnoreCase(action)) {
128 return activate(ctx, true);
131 if ("prepare".equalsIgnoreCase(action)) {
132 return prepare(ctx, "BASE", "create");
134 if ("activate".equalsIgnoreCase(action)) {
135 return activate(ctx, false);
138 if ("backup".equalsIgnoreCase(action)) {
139 return prepare(ctx, "BACKUP", "backup");
141 if ("restorebackup".equalsIgnoreCase(action)) {
142 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
144 if ("deletebackup".equalsIgnoreCase(action)) {
145 return prepare(ctx, "DELETEBACKUP", "deletebackup");
147 if ("audit".equalsIgnoreCase(action)) {
148 return audit(ctx, "FULL");
150 if ("getrunningconfig".equalsIgnoreCase(action)) {
151 return audit(ctx, "RUNNING");
154 if ((key.equals("put")) || (key.equals("get"))) {
155 String loginId = parameters.get("loginId");
156 String host = parameters.get("host");
157 String password = parameters.get("password");
158 password = EncryptionTool.getInstance().decrypt(password);
159 String fullPathFileName = parameters.get("fullPathFileName");
162 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
163 log.debug("SCP: SshJcraftWrapper has been instantiated");
164 debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
166 if (key.equals("put")) {
167 data = parameters.get("data");
169 debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
170 InputStream is = new ByteArrayInputStream(data.getBytes());
171 log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
172 debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
173 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
175 debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
176 Thread.sleep(1000 * 180);
177 debugLog.printRTAriDebug(fnName, "Woke up....");
178 } catch (java.lang.InterruptedException ee) {
179 boolean ignore = true;
182 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
183 log.debug(fnName + " Command is for put: data is null");
185 } else // Must be a get
187 log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
188 debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
189 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
190 debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
191 ctx.setAttribute("fileContents", response);
192 log.debug("SCP: Closing the SFTP connection");
194 sshJcraftWrapper = null;
195 return (setResponseStatus(ctx, r));
196 } catch (IOException e) {
197 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
198 log.debug(fnName + " : Caught a IOException e=" + e);
199 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
200 r.message = e.getMessage();
201 sshJcraftWrapper = null;
202 return (setResponseStatus(ctx, r));
205 if (key.equals("cli")) {
206 String loginId = parameters.get("loginId");
207 String host = parameters.get("host");
208 String password = parameters.get("password");
209 password = EncryptionTool.getInstance().decrypt(password);
210 String cliCommand = parameters.get("cli");
211 String portNumber = parameters.get("portNumber");
212 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
214 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password +
215 " portNumber=" + portNumber);
216 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
217 " password=" + password + " portNumber=" + portNumber);
218 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
220 DebugLog.printAriDebug(fnName, "Sending 'sdc'");
221 String response = sshJcraftWrapper.send("sdc", ":");
222 DebugLog.printAriDebug(fnName, "Sending 1");
223 response = sshJcraftWrapper.send("1", ":");
224 DebugLog.printAriDebug(fnName, "Sending 1, the second time");
225 response = sshJcraftWrapper.send("1", "#");
226 DebugLog.printAriDebug(fnName, "Sending paging-options disable");
227 response = sshJcraftWrapper.send("paging-options disable", "#");
228 DebugLog.printAriDebug(fnName, "Sending show config");
229 response = sshJcraftWrapper.send("show config", "#");
231 DebugLog.printAriDebug(fnName, "response is now:'" + response + "'");
232 DebugLog.printAriDebug(fnName, "Populating the ctx object with the response");
233 ctx.setAttribute("cliOutput", response);
234 sshJcraftWrapper.closeConnection();
236 sshJcraftWrapper = null;
237 return (setResponseStatus(ctx, r));
238 } catch (IOException e) {
239 DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e);
240 log.debug(fnName + " : Caught a IOException e=" + e);
241 sshJcraftWrapper.closeConnection();
242 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
243 r.message = e.getMessage();
244 sshJcraftWrapper = null;
245 DebugLog.printAriDebug(fnName, "Returning error message");
246 return (setResponseStatus(ctx, r));
249 if (key.equals("escapeSql")) {
250 String data = parameters.get("artifactContents");
251 log.debug("ConfigComponentAdaptor.configure - escapeSql");
252 data = escapeMySql(data);
253 ctx.setAttribute("escapedData", data);
254 return (setResponseStatus(ctx, r));
256 if (key.equals("GetCliRunningConfig")) {
257 debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
258 log.debug("key was: GetCliRunningConfig: ");
259 String User_name = parameters.get("User_name");
260 String Host_ip_address = parameters.get("Host_ip_address");
261 String Password = parameters.get("Password");
262 Password = EncryptionTool.getInstance().decrypt(Password);
263 String Port_number = parameters.get("Port_number");
264 String Get_config_template = parameters.get("Get_config_template");
265 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
266 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
267 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
269 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
270 " Host_ip_address=" + Host_ip_address + " Password=" + Password + " Port_number="
272 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
273 " User_name=" + User_name + " Password=" + Password + " Port_number=" + Port_number);
274 StringBuffer sb = new StringBuffer();
275 String response = "";
276 String CliResponse = "";
277 boolean showConfigFlag = false;
278 sshJcraftWrapper.connect(Host_ip_address,
283 Integer.parseInt(Port_number));
284 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
285 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
286 String command = null;
288 while (st.hasMoreTokens()) {
289 String line = st.nextToken();
290 DebugLog.printAriDebug(fnName, "line=" + line);
291 if (line.indexOf("Request:") != -1) {
292 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
293 command = getStringBetweenQuotes(line);
294 DebugLog.printAriDebug(fnName, "Sending command=" + command);
295 sshJcraftWrapper.send(command);
296 DebugLog.printAriDebug(fnName, "command has been sent");
297 if (line.indexOf("show config") != -1) {
298 showConfigFlag = true;
299 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
300 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
303 if (line.indexOf("Response: Ends_With") != -1) {
304 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
305 String delemeter = getStringBetweenQuotes(line);
306 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
307 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30 * 1000, command);
308 response += tmpResponse;
309 if (showConfigFlag) {
310 showConfigFlag = false;
311 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
312 // Strip off the last line which is the command prompt from the VNF device.
313 while (st2.hasMoreTokens()) {
314 String line2 = st2.nextToken();
315 if (line2.indexOf("#") == -1) {
316 CliResponse += line2 + "\n";
322 } catch (NoSuchElementException e) {
323 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
325 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
326 ctx.setAttribute("cliOutput", CliResponse);
327 sshJcraftWrapper.closeConnection();
329 sshJcraftWrapper = null;
330 return (setResponseStatus(ctx, r));
331 } catch (IOException e) {
332 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
333 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
334 sshJcraftWrapper.closeConnection();
335 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
336 r.message = e.getMessage();
337 sshJcraftWrapper = null;
338 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message");
339 return (setResponseStatus(ctx, r));
342 if (key.equals("xml-download")) {
343 log(fnName, "key was: xml-download");
344 String User_name = parameters.get("User_name");
345 String Host_ip_address = parameters.get("Host_ip_address");
346 String Password = parameters.get("Password");
347 Password = EncryptionTool.getInstance().decrypt(Password);
348 String Port_number = parameters.get("Port_number");
349 String Contents = parameters.get("Contents");
350 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>";
351 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 ]]>]]>";
352 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
355 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" + Password
356 + " Port_number=" + Port_number);
357 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
359 sshJcraftWrapper.connect(Host_ip_address,
364 Integer.parseInt(Port_number),
366 String NetconfHelloCmd = netconfHelloCmd;
367 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
368 log(fnName, "Sending the hello command");
369 sshJcraftWrapper.send(NetconfHelloCmd);
370 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
371 log(fnName, "Sending xmlCmd cmd");
372 String xmlCmd = Contents;
373 String messageId = "1";
374 messageId = "\"" + messageId + "\"";
375 String loadConfigurationString =
376 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
378 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
379 + xmlCmd + "</config> </edit-config> </rpc>";
380 loadConfigurationString = loadConfigurationString + "]]>]]>";
381 sshJcraftWrapper.send(loadConfigurationString);
382 DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString");
383 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
384 if (response.indexOf("rpc-error") != -1) {
385 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
386 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
387 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
388 r.message = response;
390 DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
391 sshJcraftWrapper.send(commitCmd);
392 DebugLog.printAriDebug(fnName, ":After sending commitCmd");
393 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
394 if (response.indexOf("rpc-error") != -1) {
395 DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
396 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
397 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
398 r.message = response;
400 DebugLog.printAriDebug(fnName, ":Looks like a success");
401 DebugLog.printAriDebug(fnName, "response=\n" + response + "\n");
405 sshJcraftWrapper.send(terminateConnectionCmd);
406 sshJcraftWrapper.closeConnection();
407 sshJcraftWrapper = null;
408 return (setResponseStatus(ctx, r));
409 } catch (Exception e) {
410 log(fnName, "Caught an Exception, e=" + e);
411 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
412 sshJcraftWrapper.closeConnection();
413 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
414 r.message = e.getMessage();
415 sshJcraftWrapper = null;
416 log(fnName, "Returning error message");
417 return (setResponseStatus(ctx, r));
420 if (key.equals("xml-getrunningconfig")) {
421 log(fnName, "key was: : xml-getrunningconfig");
422 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";
423 String Host_ip_address = parameters.get("Host_ip_address");
424 String User_name = parameters.get("User_name");
425 String Password = parameters.get("Password");
426 Password = EncryptionTool.getInstance().decrypt(Password);
427 String Port_number = parameters.get("Port_number");
428 String Protocol = parameters.get("Protocol");
429 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>";
430 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 ]]>]]>";
432 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password="
433 + Password + " Port_number=" + Port_number);
434 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
436 String NetconfHelloCmd = netconfHelloCmd;
437 sshJcraftWrapper.connect(Host_ip_address,
442 Integer.parseInt(Port_number),
444 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
445 log(fnName, ":Sending the hello command");
446 sshJcraftWrapper.send(NetconfHelloCmd);
447 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
448 log(fnName, "Sending get running config command");
449 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
450 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
451 DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
452 response = trimResponse(response);
453 ctx.setAttribute("xmlRunningConfigOutput", response);
454 sshJcraftWrapper.send(terminateConnectionCmd);
455 sshJcraftWrapper.closeConnection();
457 sshJcraftWrapper = null;
458 return (setResponseStatus(ctx, r));
459 } catch (Exception e) {
460 log(fnName, "Caught an Exception, e=" + e);
461 log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e));
462 sshJcraftWrapper.closeConnection();
463 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
464 r.message = e.getMessage();
465 sshJcraftWrapper = null;
466 log(fnName, "Returning error message");
467 return (setResponseStatus(ctx, r));
470 if (key.equals("DownloadCliConfig")) {
471 debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
472 log.debug("key was: DownloadCliConfig: ");
473 String User_name = parameters.get("User_name");
474 String Host_ip_address = parameters.get("Host_ip_address");
475 String Password = parameters.get("Password");
476 Password = EncryptionTool.getInstance().decrypt(Password);
477 String Port_number = parameters.get("Port_number");
478 String Download_config_template = parameters.get("Download_config_template");
479 String Config_contents = parameters.get("Config_contents");
480 DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
481 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
482 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
483 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
484 int timeout = 4 * 60 * 1000;
486 DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
487 " Host_ip_address=" + Host_ip_address + " Password=" + Password + " Port_number="
489 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
490 " User_name=" + User_name + " Password=" + Password + " Port_number=" + Port_number);
491 StringBuffer sb = new StringBuffer();
492 String response = "";
493 String CliResponse = "";
494 sshJcraftWrapper.connect(Host_ip_address,
499 Integer.parseInt(Port_number));
500 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
501 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
502 String command = null;
503 String executeConfigContentsDelemeter = null;
505 while (st.hasMoreTokens()) {
506 String line = st.nextToken();
507 DebugLog.printAriDebug(fnName, "line=" + line);
508 if (line.indexOf("Request:") != -1) {
509 DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line);
510 command = getStringBetweenQuotes(line);
511 DebugLog.printAriDebug(fnName, "Sending command=" + command);
512 sshJcraftWrapper.send(command);
513 DebugLog.printAriDebug(fnName, "command has been sent");
514 } else if ((line.indexOf("Response: Ends_With") != -1) && (
515 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
516 DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line);
517 String delemeter = getStringBetweenQuotes(line);
518 DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter);
519 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
520 response += tmpResponse;
521 CliResponse += tmpResponse;
522 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
523 DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
524 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
525 DebugLog.printAriDebug(fnName,
526 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
527 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
528 while (st2.hasMoreTokens()) {
529 String cmd = st2.nextToken();
530 DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd);
531 sshJcraftWrapper.send(cmd);
532 String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter,
535 CliResponse += tmpResponse;
539 } catch (NoSuchElementException e) {
540 DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
542 sshJcraftWrapper.closeConnection();
543 sshJcraftWrapper = null;
544 DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response");
545 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
546 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
547 DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse);
548 ctx.setAttribute("cliOutput", CliResponse);
550 return (setResponseStatus(ctx, r));
551 } catch (IOException e) {
552 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
553 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
554 sshJcraftWrapper.closeConnection();
555 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
556 r.message = e.getMessage();
557 sshJcraftWrapper = null;
558 DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message");
559 return (setResponseStatus(ctx, r));
563 debugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
564 log.error("Unsupported action - " + action);
565 return ConfigStatus.FAILURE;
568 private void log(String fileName, String messg) {
569 debugLog.printRTAriDebug(fileName, messg);
570 log.debug(fileName + ": " + messg);
573 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
574 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
575 String ndTemplate = readFile(templateName);
576 String nd = buildNetworkData2(ctx, ndTemplate, operation);
578 String reqTemplate = readFile("/config-request.xml");
579 Map<String, String> param = new HashMap<String, String>();
580 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
581 param.put("request-type", requestType);
582 param.put("callback-url", configCallbackUrl);
583 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
584 param.put("action", "GenerateOnly");
586 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
587 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
588 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
589 param.put("network-data", nd);
593 req = buildXmlRequest(param, reqTemplate);
594 } catch (Exception e) {
595 log.error("Error building the XML request: ", e);
597 HttpResponse r = new HttpResponse();
598 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
599 r.message = e.getMessage();
600 return setResponseStatus(ctx, r);
603 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
604 return setResponseStatus(ctx, r);
607 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
608 String reqTemplate = readFile("/config-request.xml");
609 Map<String, String> param = new HashMap<String, String>();
610 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
611 param.put("callback-url", configCallbackUrl);
612 param.put("action", change ? "DownloadChange" : "DownloadBase");
613 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
617 req = buildXmlRequest(param, reqTemplate);
618 } catch (Exception e) {
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 audit(SvcLogicContext ctx, String auditLevel) {
632 String reqTemplate = readFile("/audit-request.xml");
633 Map<String, String> param = new HashMap<String, String>();
634 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
635 param.put("callback-url", auditCallbackUrl);
636 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
637 param.put("audit-level", auditLevel);
641 req = buildXmlRequest(param, reqTemplate);
642 } catch (Exception e) {
643 log.error("Error building the XML request: ", e);
645 HttpResponse r = new HttpResponse();
646 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
647 r.message = e.getMessage();
648 return setResponseStatus(ctx, r);
651 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
652 return setResponseStatus(ctx, r);
656 public ConfigStatus activate(String key, SvcLogicContext ctx) {
657 return ConfigStatus.SUCCESS;
661 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
662 return ConfigStatus.SUCCESS;
665 private String escapeMySql(String input) {
670 input = input.replace("\\", "\\\\");
671 input = input.replace("\'", "\\'");
676 private String readFile(String fileName) {
677 InputStream is = getClass().getResourceAsStream(fileName);
678 InputStreamReader isr = new InputStreamReader(is);
679 BufferedReader in = new BufferedReader(isr);
680 StringBuilder ss = new StringBuilder();
682 String s = in.readLine();
684 ss.append(s).append('\n');
687 } catch (IOException e) {
688 System.out.println("Error reading " + fileName + ": " + e.getMessage());
689 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
693 } catch (Exception e) {
694 log.warn("Could not close BufferedReader", e);
698 } catch (Exception e) {
699 log.warn("Could not close InputStreamReader", e);
703 } catch (Exception e) {
704 log.warn("Could not close InputStream", e);
707 return ss.toString();
710 private String buildXmlRequest(Map<String, String> param, String template) {
711 StringBuilder ss = new StringBuilder();
713 while (i < template.length()) {
714 int i1 = template.indexOf("${", i);
716 ss.append(template.substring(i));
720 int i2 = template.indexOf('}', i1 + 2);
722 throw new RuntimeException("Template error: Matching } not found");
725 String var1 = template.substring(i1 + 2, i2);
726 String value1 = param.get(var1);
727 if (value1 == null || value1.trim().length() == 0) {
728 // delete the whole element (line)
729 int i3 = template.lastIndexOf('\n', i1);
733 int i4 = template.indexOf('\n', i1);
735 i4 = template.length();
739 ss.append(template.substring(i, i3));
743 ss.append(template.substring(i, i1)).append(value1);
748 return ss.toString();
751 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
752 log.info("Building XML started");
753 long t1 = System.currentTimeMillis();
755 template = expandRepeats(ctx, template, 1);
757 Map<String, String> mm = new HashMap<>();
758 for (String s : ctx.getAttributeKeySet()) {
759 mm.put(s, ctx.getAttribute(s));
761 mm.put("operation", operation);
763 StringBuilder ss = new StringBuilder();
765 while (i < template.length()) {
766 int i1 = template.indexOf("${", i);
768 ss.append(template.substring(i));
772 int i2 = template.indexOf('}', i1 + 2);
774 throw new RuntimeException("Template error: Matching } not found");
777 String var1 = template.substring(i1 + 2, i2);
778 String value1 = XmlUtil.getXml(mm, var1);
779 if (value1 == null || value1.trim().length() == 0) {
780 // delete the whole element (line)
781 int i3 = template.lastIndexOf('\n', i1);
785 int i4 = template.indexOf('\n', i1);
787 i4 = template.length();
791 ss.append(template.substring(i, i3));
795 ss.append(template.substring(i, i1)).append(value1);
800 long t2 = System.currentTimeMillis();
801 log.info("Building XML completed. Time: " + (t2 - t1));
803 return ss.toString();
806 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
807 StringBuilder newTemplate = new StringBuilder();
809 while (k < template.length()) {
810 int i1 = template.indexOf("${repeat:", k);
812 newTemplate.append(template.substring(k));
816 int i2 = template.indexOf(':', i1 + 9);
818 throw new RuntimeException(
819 "Template error: Context variable name followed by : is required after repeat");
822 // Find the closing }, store in i3
826 while (nn > 0 && i < template.length()) {
827 i3 = template.indexOf('}', i);
829 throw new RuntimeException("Template error: Matching } not found");
831 int i32 = template.indexOf('{', i);
832 if (i32 >= 0 && i32 < i3) {
841 String var1 = template.substring(i1 + 9, i2);
842 String value1 = ctx.getAttribute(var1);
843 log.info(" " + var1 + ": " + value1);
846 n = Integer.parseInt(value1);
847 } catch (Exception e) {
851 newTemplate.append(template.substring(k, i1));
853 String rpt = template.substring(i2 + 1, i3);
855 for (int ii = 0; ii < n; ii++) {
856 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
857 newTemplate.append(ss);
864 return newTemplate.toString();
867 return expandRepeats(ctx, newTemplate.toString(), level + 1);
870 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
872 Client client = Client.create();
873 client.setConnectTimeout(5000);
874 WebResource webResource = client.resource(url);
876 log.info("SENDING...............");
877 log.info(xmlRequest);
879 String authString = user + ":" + password;
880 byte[] authEncBytes = Base64.encode(authString);
881 String authStringEnc = new String(authEncBytes);
882 authString = "Basic " + authStringEnc;
884 ClientResponse response =
885 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
886 ClientResponse.class, xmlRequest);
888 int code = response.getStatus();
889 String message = null;
891 log.info("RESPONSE...............");
892 log.info("HTTP response code: " + code);
893 log.info("HTTP response message: " + message);
896 HttpResponse r = new HttpResponse();
901 } catch (Exception e) {
902 log.error("Error sending the request: ", e);
904 HttpResponse r = new HttpResponse();
905 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
906 r.message = e.getMessage();
911 private static class HttpResponse {
915 public String message;
918 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
919 ctx.setAttribute("error-code", String.valueOf(r.code));
920 ctx.setAttribute("error-message", r.message);
922 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
925 private String getStringBetweenQuotes(String string) {
926 String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
927 DebugLog.printAriDebug(fnName, "string=" + string);
928 String retString = null;
929 int start = string.indexOf("\"");
930 int end = string.lastIndexOf("\"");
931 retString = string.substring(start + 1, end);
932 DebugLog.printAriDebug(fnName, "retString=" + retString);
936 public static String _readFile(String fileName) {
937 StringBuffer strBuff = new StringBuffer();
939 try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
940 while ((line = in.readLine()) != null) {
941 strBuff.append(line + "\n");
943 } catch (IOException e) {
944 System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
946 return (strBuff.toString());
949 private String trimResponse(String response) {
950 StringTokenizer line = new StringTokenizer(response, "\n");
951 StringBuffer sb = new StringBuffer();
952 boolean captureText = false;
953 while (line.hasMoreTokens()) {
954 String token = line.nextToken();
955 if (token.indexOf("<configuration xmlns=") != -1) {
959 sb.append(token + "\n");
961 if (token.indexOf("</configuration>") != -1) {
965 return (sb.toString());
968 public static void main(String args[]) throws Exception {
969 Properties props = null;
970 System.out.println("*************************Hello*****************************");
971 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
972 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
973 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
974 String key = "GetCliRunningConfig";
975 Map<String, String> parameters = new HashMap();
976 parameters.put("Host_ip_address", "000.00.000.00");
977 parameters.put("User_name", "root");
978 parameters.put("Password", "!bootstrap");
979 parameters.put("Port_number", "22");
980 parameters.put("Get_config_template", Get_config_template);
982 SvcLogicContext ctx = null;
983 System.out.println("*************************TRACE 1*****************************");
984 cca.configure(key, parameters, ctx);