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.
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20 * ============LICENSE_END=========================================================
23 package org.onap.appc.ccadaptor;
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.sun.jersey.api.client.Client;
28 import com.sun.jersey.api.client.ClientResponse;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.core.util.Base64;
31 import java.io.BufferedReader;
32 import java.io.ByteArrayInputStream;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.InputStreamReader;
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);
51 private String configUrl;
52 private String configUser;
53 private String configPassword;
54 private String auditUrl;
55 private String auditUser;
56 private String auditPassword;
57 private String configCallbackUrl;
58 private String auditCallbackUrl;
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", "");
74 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
75 HttpResponse r = new HttpResponse();
77 log.debug("ConfigComponentAdaptor.configure - key = " + key);
78 log.debug("key = {}", key);
79 log.debug("Parameters:");
80 for (Entry<String, String> paramEntrySet : parameters.entrySet()) {
81 log.debug(" {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue());
84 String parmval = parameters.get("config-component-configUrl");
85 if ((parmval != null) && (parmval.length() > 0)) {
86 log.debug("Overwriting URL with {}", parmval);
90 parmval = parameters.get("config-component-configPassword");
91 if ((parmval != null) && (parmval.length() > 0)) {
92 log.debug("Overwriting configPassword with {}", parmval);
93 configPassword = parmval;
96 parmval = parameters.get("config-component-configUser");
97 if ((parmval != null) && (parmval.length() > 0)) {
98 log.debug("Overwriting configUser id with {}", parmval);
102 String action = parameters.get("action");
104 String chg = ctx.getAttribute(
105 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
106 if (chg != null && "prepare".equalsIgnoreCase(action)) {
107 return prepare(ctx, "CHANGE", "change");
109 if (chg != null && "activate".equalsIgnoreCase(action)) {
110 return activate(ctx, true);
113 String scale = ctx.getAttribute(
114 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
115 if (scale != null && "prepare".equalsIgnoreCase(action)) {
116 return prepare(ctx, "CHANGE", "scale");
118 if (scale != null && "activate".equalsIgnoreCase(action)) {
119 return activate(ctx, true);
122 if ("prepare".equalsIgnoreCase(action)) {
123 return prepare(ctx, "BASE", "create");
125 if ("activate".equalsIgnoreCase(action)) {
126 return activate(ctx, false);
129 if ("backup".equalsIgnoreCase(action)) {
130 return prepare(ctx, "BACKUP", "backup");
132 if ("restorebackup".equalsIgnoreCase(action)) {
133 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
135 if ("deletebackup".equalsIgnoreCase(action)) {
136 return prepare(ctx, "DELETEBACKUP", "deletebackup");
138 if ("audit".equalsIgnoreCase(action)) {
139 return audit(ctx, "FULL");
141 if ("getrunningconfig".equalsIgnoreCase(action)) {
142 return audit(ctx, "RUNNING");
145 if ((key.equals("put")) || (key.equals("get"))) {
146 String loginId = parameters.get("loginId");
147 String host = parameters.get("host");
148 String password = parameters.get("password");
149 password = EncryptionTool.getInstance().decrypt(password);
150 String fullPathFileName = parameters.get("fullPathFileName");
152 if (key.equals("put")) {
153 data = parameters.get("data");
156 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
157 log.debug("SCP: SshJcraftWrapper has been instantiated");
160 if ("put".equals(key)) {
161 log.debug("Command is for put: Length of data is: {}", data.length());
162 InputStream is = new ByteArrayInputStream(data.getBytes());
163 log.debug("SCP: Doing a put: fullPathFileName={}", fullPathFileName);
164 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
166 log.debug("Sleeping for 180 seconds....");
167 Thread.sleep(1000L * 180);
168 log.debug("Woke up....");
169 } catch (java.lang.InterruptedException ee) {
170 log.error("Sleep interrupted", ee);
171 Thread.currentThread().interrupt();
173 } else { // Must be a get
174 log.debug("SCP: Doing a get: fullPathFileName={}", fullPathFileName);
175 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
176 log.debug("Got the response and putting into the ctx object");
177 ctx.setAttribute("fileContents", response);
178 log.debug("SCP: Closing the SFTP connection");
180 sshJcraftWrapper = null;
181 return (setResponseStatus(ctx, r));
182 } catch (IOException e) {
183 log.error("Exception occurred while using sshJcraftWrapper", e);
184 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
185 r.message = e.getMessage();
186 sshJcraftWrapper = null;
187 return (setResponseStatus(ctx, r));
190 if (key.equals("cli")) {
191 String loginId = parameters.get("loginId");
192 String host = parameters.get("host");
193 String password = parameters.get("password");
194 password = EncryptionTool.getInstance().decrypt(password);
195 String cliCommand = parameters.get("cli");
196 String portNumber = parameters.get("portNumber");
197 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
199 log.debug("CLI: Attempting to login: host={} loginId={} password={} portNumber={}", host, loginId,
200 password, portNumber);
201 sshJcraftWrapper.connect(host, loginId, password); //what about portNum?
203 log.debug("Sending 'sdc'");
204 sshJcraftWrapper.send("sdc", ":");
205 log.debug("Sending 1");
206 sshJcraftWrapper.send("1", ":");
207 log.debug("Sending 1, the second time");
208 sshJcraftWrapper.send("1", "#");
209 log.debug("Sending paging-options disable");
210 sshJcraftWrapper.send("paging-options disable", "#");
211 log.debug("Sending show config");
212 String response = sshJcraftWrapper.send("show config", "#");
214 log.debug("response is now:'{}'", response);
215 log.debug("Populating the ctx object with the response");
216 ctx.setAttribute("cliOutput", response);
217 sshJcraftWrapper.closeConnection();
219 sshJcraftWrapper = null;
220 return (setResponseStatus(ctx, r));
221 } catch (IOException e) {
222 log.error("Exception occurred while using sshJcraftWrapper", e);
223 sshJcraftWrapper.closeConnection();
224 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
225 r.message = e.getMessage();
226 sshJcraftWrapper = null;
227 return (setResponseStatus(ctx, r));
230 if (key.equals("escapeSql")) {
231 String data = parameters.get("artifactContents");
232 log.debug("ConfigComponentAdaptor.configure - escapeSql");
233 data = escapeMySql(data);
234 ctx.setAttribute("escapedData", data);
235 return (setResponseStatus(ctx, r));
237 if (key.equals("GetCliRunningConfig")) {
238 log.debug("key was: GetCliRunningConfig: ");
239 String User_name = parameters.get("User_name");
240 String Host_ip_address = parameters.get("Host_ip_address");
241 String Password = parameters.get("Password");
242 Password = EncryptionTool.getInstance().decrypt(Password);
243 String Port_number = parameters.get("Port_number");
244 String Get_config_template = parameters.get("Get_config_template");
245 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
246 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
248 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
249 + User_name + " Password=" + Password + " Port_number=" + Port_number);
250 StringBuffer sb = new StringBuffer();
251 String response = "";
252 String CliResponse = "";
253 boolean showConfigFlag = false;
255 .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
256 log.debug("GetCliRunningConfig: On the VNF device");
257 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
258 String command = null;
260 while (st.hasMoreTokens()) {
261 String line = st.nextToken();
262 log.debug("line={}", line);
263 if (line.indexOf("Request:") != -1) {
264 log.debug("Found a Request line: line={}", line);
265 command = getStringBetweenQuotes(line);
266 log.debug("Sending command={}", command);
267 sshJcraftWrapper.send(command);
268 log.debug("command has been sent");
269 if (line.indexOf("show config") != -1) {
270 showConfigFlag = true;
271 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
274 if (line.indexOf("Response: Ends_With") != -1) {
275 log.debug("Found a Response line: line={}", line);
276 String delemeter = getStringBetweenQuotes(line);
277 log.debug("The delemeter={}", delemeter);
278 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command);
279 response += tmpResponse;
280 if (showConfigFlag) {
281 showConfigFlag = false;
282 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
283 while (st2.hasMoreTokens()) {
284 String line2 = st2.nextToken();
285 if (line2.indexOf("#") == -1) {
286 CliResponse += line2 + "\n";
292 } catch (NoSuchElementException e) {
293 log.error(e.getMessage(), e);
295 log.debug("CliResponse=\n{}", CliResponse);
296 ctx.setAttribute("cliOutput", CliResponse);
297 sshJcraftWrapper.closeConnection();
299 sshJcraftWrapper = null;
300 return (setResponseStatus(ctx, r));
301 } catch (IOException e) {
302 log.error("Exception occurred while using sshJcraftWrapper", e);
303 sshJcraftWrapper.closeConnection();
304 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
305 r.message = e.getMessage();
306 sshJcraftWrapper = null;
307 return (setResponseStatus(ctx, r));
310 if (key.equals("xml-download")) {
311 log.debug("key was: xml-download");
312 String User_name = parameters.get("User_name");
313 String Host_ip_address = parameters.get("Host_ip_address");
314 String Password = parameters.get("Password");
315 Password = EncryptionTool.getInstance().decrypt(Password);
316 String Port_number = parameters.get("Port_number");
317 String Contents = parameters.get("Contents");
318 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>";
319 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 ]]>]]>";
320 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
322 log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
323 Host_ip_address, Password, Port_number);
324 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
327 .connect(Host_ip_address, User_name, Password, 30000, Integer.parseInt(Port_number), "netconf"); // what about prompt "]]>]]>"?
328 String NetconfHelloCmd = netconfHelloCmd;
329 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
330 log.debug("Sending the hello command");
331 sshJcraftWrapper.send(NetconfHelloCmd);
332 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
333 log.debug("Sending xmlCmd cmd");
334 String xmlCmd = Contents;
335 String messageId = "1";
336 messageId = "\"" + messageId + "\"";
337 String loadConfigurationString =
338 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
340 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
341 + xmlCmd + "</config> </edit-config> </rpc>";
342 loadConfigurationString = loadConfigurationString + "]]>]]>";
343 sshJcraftWrapper.send(loadConfigurationString);
344 log.debug("After sending loadConfigurationString");
345 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
346 if (response.indexOf("rpc-error") != -1) {
347 log.debug("Error from device: Response from device had 'rpc-error'");
348 log.debug("response=\n{}\n", response);
349 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
350 r.message = response;
352 log.debug(":LoadConfiguration was a success, sending commit cmd");
353 sshJcraftWrapper.send(commitCmd);
354 log.debug(":After sending commitCmd");
355 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
356 if (response.indexOf("rpc-error") != -1) {
357 log.debug("Error from device: Response from device had 'rpc-error'");
358 log.debug("response=\n{}\n", response);
359 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
360 r.message = response;
362 log.debug(":Looks like a success");
363 log.debug("response=\n{}\n", response);
367 sshJcraftWrapper.send(terminateConnectionCmd);
368 sshJcraftWrapper.closeConnection();
369 sshJcraftWrapper = null;
370 return (setResponseStatus(ctx, r));
371 } catch (Exception e) {
372 log.error("Caught an Exception", e);
373 sshJcraftWrapper.closeConnection();
374 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
375 r.message = e.getMessage();
376 sshJcraftWrapper = null;
377 log.debug("Returning error message");
378 return (setResponseStatus(ctx, r));
381 if (key.equals("xml-getrunningconfig")) {
382 log.debug("key was: : xml-getrunningconfig");
383 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";
384 String Host_ip_address = parameters.get("Host_ip_address");
385 String User_name = parameters.get("User_name");
386 String Password = parameters.get("Password");
387 Password = EncryptionTool.getInstance().decrypt(Password);
388 String Port_number = parameters.get("Port_number");
389 String Protocol = parameters.get("Protocol");
390 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>";
391 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 ]]>]]>";
392 log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
393 Host_ip_address, Password, Port_number);
394 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
396 String NetconfHelloCmd = netconfHelloCmd;
398 .connect(Host_ip_address, User_name, Password, 30000, Integer.parseInt(Port_number),
399 "netconf"); //What about prompt "]]>]]>" here?
400 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
401 log.debug(":Sending the hello command");
402 sshJcraftWrapper.send(NetconfHelloCmd);
403 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
404 log.debug("Sending get running config command");
405 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
406 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
407 log.debug("Response from getRunningconfigCmd={}", response);
408 response = trimResponse(response);
409 ctx.setAttribute("xmlRunningConfigOutput", response);
410 sshJcraftWrapper.send(terminateConnectionCmd);
411 sshJcraftWrapper.closeConnection();
413 sshJcraftWrapper = null;
414 return (setResponseStatus(ctx, r));
415 } catch (Exception e) {
416 log.error("Caught an Exception", e);
417 sshJcraftWrapper.closeConnection();
418 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
419 r.message = e.getMessage();
420 sshJcraftWrapper = null;
421 log.debug("Returning error message");
422 return (setResponseStatus(ctx, r));
425 if (key.equals("DownloadCliConfig")) {
426 log.debug("key was: DownloadCliConfig: ");
427 String User_name = parameters.get("User_name");
428 String Host_ip_address = parameters.get("Host_ip_address");
429 String Password = parameters.get("Password");
430 Password = EncryptionTool.getInstance().decrypt(Password);
431 String Port_number = parameters.get("Port_number");
432 String Download_config_template = parameters.get("Download_config_template");
433 String Config_contents = parameters.get("Config_contents");
434 log.debug("Contents of the 'Config_contents' are: {}", Config_contents);
435 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
436 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
437 int timeout = 4 * 60 * 1000;
439 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
440 + User_name + " Password=" + Password + " Port_number=" + Port_number);
441 StringBuffer sb = new StringBuffer();
442 String response = "";
443 String CliResponse = "";
445 .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
446 log.debug("DownloadCliConfig: On the VNF device");
447 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
448 String command = null;
449 String executeConfigContentsDelemeter = null;
451 while (st.hasMoreTokens()) {
452 String line = st.nextToken();
453 log.debug("line={}", line);
454 if (line.indexOf("Request:") != -1) {
455 log.debug("Found a Request line: line={}", line);
456 command = getStringBetweenQuotes(line);
457 log.debug("Sending command={}", command);
458 sshJcraftWrapper.send(command);
459 log.debug("command has been sent");
460 } else if ((line.indexOf("Response: Ends_With") != -1) && (
461 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
462 log.debug("Found a Response line: line={}", line);
463 String delimiter = getStringBetweenQuotes(line);
464 log.debug("The delimiter={}", delimiter);
465 String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
466 response += tmpResponse;
467 CliResponse += tmpResponse;
468 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
469 log.debug("Found a 'Execute_config_contents Response:' line={}", line);
470 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
471 log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
472 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
473 while (st2.hasMoreTokens()) {
474 String cmd = st2.nextToken();
475 log.debug("Config_contents: cmd={}", cmd);
476 sshJcraftWrapper.send(cmd);
477 String tmpResponse = sshJcraftWrapper
478 .receiveUntil(executeConfigContentsDelemeter, timeout, command);
479 CliResponse += tmpResponse;
483 } catch (NoSuchElementException e) {
484 log.error(e.getMessage(), e);
486 sshJcraftWrapper.closeConnection();
487 sshJcraftWrapper = null;
488 log.debug(":Escaping all the single and double quotes in the response");
489 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
490 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
491 log.debug("CliResponse=\n{}" + CliResponse);
492 ctx.setAttribute("cliOutput", CliResponse);
494 return (setResponseStatus(ctx, r));
495 } catch (IOException e) {
496 log.error(e.getMessage() + e);
497 sshJcraftWrapper.closeConnection();
498 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
499 r.message = e.getMessage();
500 sshJcraftWrapper = null;
501 log.debug("DownloadCliConfig: Returning error message");
502 return (setResponseStatus(ctx, r));
506 log.debug("Unsupported action - {}", action);
507 return ConfigStatus.FAILURE;
510 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
511 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
512 String ndTemplate = readFile(templateName);
513 String nd = buildNetworkData2(ctx, ndTemplate, operation);
515 String reqTemplate = readFile("/config-request.xml");
516 Map<String, String> param = new HashMap<String, String>();
517 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
518 param.put("request-type", requestType);
519 param.put("callback-url", configCallbackUrl);
520 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
521 param.put("action", "GenerateOnly");
523 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
524 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
525 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
526 param.put("network-data", nd);
530 req = buildXmlRequest(param, reqTemplate);
531 } catch (Exception e) {
532 log.error("Error building the XML request: ", e);
534 HttpResponse r = new HttpResponse();
535 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
536 r.message = e.getMessage();
537 return setResponseStatus(ctx, r);
540 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
541 return setResponseStatus(ctx, r);
544 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
545 String reqTemplate = readFile("/config-request.xml");
546 Map<String, String> param = new HashMap<String, String>();
547 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
548 param.put("callback-url", configCallbackUrl);
549 param.put("action", change ? "DownloadChange" : "DownloadBase");
550 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
554 req = buildXmlRequest(param, reqTemplate);
555 } catch (Exception e) {
556 log.error("Error building the XML request: ", e);
558 HttpResponse r = new HttpResponse();
559 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
560 r.message = e.getMessage();
561 return setResponseStatus(ctx, r);
564 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
565 return setResponseStatus(ctx, r);
568 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
569 String reqTemplate = readFile("/audit-request.xml");
570 Map<String, String> param = new HashMap<String, String>();
571 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
572 param.put("callback-url", auditCallbackUrl);
573 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
574 param.put("audit-level", auditLevel);
578 req = buildXmlRequest(param, reqTemplate);
579 } catch (Exception e) {
580 log.error("Error building the XML request: ", e);
582 HttpResponse r = new HttpResponse();
583 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
584 r.message = e.getMessage();
585 return setResponseStatus(ctx, r);
588 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
589 return setResponseStatus(ctx, r);
593 public ConfigStatus activate(String key, SvcLogicContext ctx) {
594 return ConfigStatus.SUCCESS;
598 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
599 return ConfigStatus.SUCCESS;
602 private String escapeMySql(String input) {
607 input = input.replace("\\", "\\\\");
608 input = input.replace("\'", "\\'");
613 private String readFile(String fileName) {
614 InputStream is = getClass().getResourceAsStream(fileName);
615 InputStreamReader isr = new InputStreamReader(is);
616 BufferedReader in = new BufferedReader(isr);
617 StringBuilder ss = new StringBuilder();
619 String s = in.readLine();
621 ss.append(s).append('\n');
624 } catch (IOException e) {
625 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
629 } catch (Exception e) {
630 log.warn("Could not close BufferedReader", e);
634 } catch (Exception e) {
635 log.warn("Could not close InputStreamReader", e);
639 } catch (Exception e) {
640 log.warn("Could not close InputStream", e);
643 return ss.toString();
646 private String buildXmlRequest(Map<String, String> param, String template) {
647 StringBuilder ss = new StringBuilder();
649 while (i < template.length()) {
650 int i1 = template.indexOf("${", i);
652 ss.append(template.substring(i));
656 int i2 = template.indexOf('}', i1 + 2);
658 throw new RuntimeException("Template error: Matching } not found");
661 String var1 = template.substring(i1 + 2, i2);
662 String value1 = param.get(var1);
663 if (value1 == null || value1.trim().length() == 0) {
664 // delete the whole element (line)
665 int i3 = template.lastIndexOf('\n', i1);
669 int i4 = template.indexOf('\n', i1);
671 i4 = template.length();
675 ss.append(template.substring(i, i3));
679 ss.append(template.substring(i, i1)).append(value1);
684 return ss.toString();
687 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
688 log.info("Building XML started");
689 long t1 = System.currentTimeMillis();
691 template = expandRepeats(ctx, template, 1);
693 Map<String, String> mm = new HashMap<>();
694 for (String s : ctx.getAttributeKeySet()) {
695 mm.put(s, ctx.getAttribute(s));
697 mm.put("operation", operation);
699 StringBuilder ss = new StringBuilder();
701 while (i < template.length()) {
702 int i1 = template.indexOf("${", i);
704 ss.append(template.substring(i));
708 int i2 = template.indexOf('}', i1 + 2);
710 throw new RuntimeException("Template error: Matching } not found");
713 String var1 = template.substring(i1 + 2, i2);
714 String value1 = XmlUtil.getXml(mm, var1);
715 if (value1 == null || value1.trim().length() == 0) {
716 int i3 = template.lastIndexOf('\n', i1);
720 int i4 = template.indexOf('\n', i1);
722 i4 = template.length();
726 ss.append(template.substring(i, i3));
730 ss.append(template.substring(i, i1)).append(value1);
735 long t2 = System.currentTimeMillis();
736 log.info("Building XML completed. Time: " + (t2 - t1));
738 return ss.toString();
741 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
742 StringBuilder newTemplate = new StringBuilder();
744 while (k < template.length()) {
745 int i1 = template.indexOf("${repeat:", k);
747 newTemplate.append(template.substring(k));
751 int i2 = template.indexOf(':', i1 + 9);
753 throw new RuntimeException(
754 "Template error: Context variable name followed by : is required after repeat");
757 // Find the closing }, store in i3
761 while (nn > 0 && i < template.length()) {
762 i3 = template.indexOf('}', i);
764 throw new RuntimeException("Template error: Matching } not found");
766 int i32 = template.indexOf('{', i);
767 if (i32 >= 0 && i32 < i3) {
776 String var1 = template.substring(i1 + 9, i2);
777 String value1 = ctx.getAttribute(var1);
778 log.info(" " + var1 + ": " + value1);
781 n = Integer.parseInt(value1);
782 } catch (Exception e) {
786 newTemplate.append(template.substring(k, i1));
788 String rpt = template.substring(i2 + 1, i3);
790 for (int ii = 0; ii < n; ii++) {
791 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
792 newTemplate.append(ss);
799 return newTemplate.toString();
802 return expandRepeats(ctx, newTemplate.toString(), level + 1);
805 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
807 Client client = Client.create();
808 client.setConnectTimeout(5000);
809 WebResource webResource = client.resource(url);
811 log.info("SENDING...............");
812 log.info(xmlRequest);
814 String authString = user + ":" + password;
815 byte[] authEncBytes = Base64.encode(authString);
816 String authStringEnc = new String(authEncBytes);
817 authString = "Basic " + authStringEnc;
819 ClientResponse response =
820 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
821 ClientResponse.class, xmlRequest);
823 int code = response.getStatus();
824 String message = null;
826 log.info("RESPONSE...............");
827 log.info("HTTP response code: " + code);
828 log.info("HTTP response message: " + message);
831 HttpResponse r = new HttpResponse();
836 } catch (Exception e) {
837 log.error("Error sending the request: ", e);
839 HttpResponse r = new HttpResponse();
840 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
841 r.message = e.getMessage();
846 private static class HttpResponse {
849 public String message;
852 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
853 ctx.setAttribute("error-code", String.valueOf(r.code));
854 ctx.setAttribute("error-message", r.message);
856 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
859 private String getStringBetweenQuotes(String string) {
860 log.debug("string=" + string);
862 int start = string.indexOf('\"');
863 int end = string.lastIndexOf('\"');
864 retString = string.substring(start + 1, end);
865 log.debug("retString=" + retString);
869 public static String _readFile(String fileName) {
870 StringBuffer strBuff = new StringBuffer();
873 BufferedReader in = new BufferedReader(new FileReader(fileName));
874 while ((line = in.readLine()) != null) {
875 strBuff.append(line + "\n");
878 } catch (IOException e) {
879 log.error("Caught an IOException in method readFile()", e);
881 return (strBuff.toString());
884 private String trimResponse(String response) {
885 StringTokenizer line = new StringTokenizer(response, "\n");
886 StringBuffer sb = new StringBuffer();
887 boolean captureText = false;
888 while (line.hasMoreTokens()) {
889 String token = line.nextToken();
890 if (token.indexOf("<configuration xmlns=") != -1) {
894 sb.append(token + "\n");
896 if (token.indexOf("</configuration>") != -1) {
900 return (sb.toString());
903 public static void main(String args[]) throws Exception {
904 Properties props = null;
905 System.out.println("*************************Hello*****************************");
906 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
907 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
908 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
909 String key = "GetCliRunningConfig";
910 Map<String, String> parameters = new HashMap();
911 parameters.put("Host_ip_address", "000.00.000.00");
912 parameters.put("User_name", "root");
913 parameters.put("Password", "!bootstrap");
914 parameters.put("Port_number", "22");
915 parameters.put("Get_config_template", Get_config_template);
916 SvcLogicContext ctx = null;
917 System.out.println("*************************TRACE 1*****************************");
918 cca.configure(key, parameters, ctx);