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.Map.Entry;
39 import java.util.NoSuchElementException;
40 import java.util.Properties;
41 import java.util.StringTokenizer;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
45 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
47 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
49 private String configUrl;
50 private String configUser;
51 private String configPassword;
52 private String auditUrl;
53 private String auditUser;
54 private String auditPassword;
55 private String configCallbackUrl;
56 private String auditCallbackUrl;
58 public ConfigComponentAdaptor(Properties props) {
60 configUrl = props.getProperty("configComponent.url", "");
61 configUser = props.getProperty("configComponent.user", "");
62 configPassword = props.getProperty("configComponent.passwd", "");
63 auditUrl = props.getProperty("auditComponent.url", "");
64 auditUser = props.getProperty("auditComponent.user", "");
65 auditPassword = props.getProperty("auditComponent.passwd", "");
66 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
67 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
72 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
73 HttpResponse r = new HttpResponse();
75 log.debug("ConfigComponentAdaptor.configure - key = " + key);
76 log.debug("key = {}", key);
77 log.debug("Parameters:");
78 for (Entry<String, String> paramEntrySet : parameters.entrySet()) {
79 log.debug(" {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue());
82 String parmval = parameters.get("config-component-configUrl");
83 if ((parmval != null) && (parmval.length() > 0)) {
84 log.debug("Overwriting URL with {}", parmval);
88 parmval = parameters.get("config-component-configPassword");
89 if ((parmval != null) && (parmval.length() > 0)) {
90 log.debug("Overwriting configPassword with {}", parmval);
91 configPassword = parmval;
94 parmval = parameters.get("config-component-configUser");
95 if ((parmval != null) && (parmval.length() > 0)) {
96 log.debug("Overwriting configUser id with {}", parmval);
100 String action = parameters.get("action");
102 String chg = ctx.getAttribute(
103 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
104 if (chg != null && "prepare".equalsIgnoreCase(action)) {
105 return prepare(ctx, "CHANGE", "change");
107 if (chg != null && "activate".equalsIgnoreCase(action)) {
108 return activate(ctx, true);
111 String scale = ctx.getAttribute(
112 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
113 if (scale != null && "prepare".equalsIgnoreCase(action)) {
114 return prepare(ctx, "CHANGE", "scale");
116 if (scale != null && "activate".equalsIgnoreCase(action)) {
117 return activate(ctx, true);
120 if ("prepare".equalsIgnoreCase(action)) {
121 return prepare(ctx, "BASE", "create");
123 if ("activate".equalsIgnoreCase(action)) {
124 return activate(ctx, false);
127 if ("backup".equalsIgnoreCase(action)) {
128 return prepare(ctx, "BACKUP", "backup");
130 if ("restorebackup".equalsIgnoreCase(action)) {
131 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
133 if ("deletebackup".equalsIgnoreCase(action)) {
134 return prepare(ctx, "DELETEBACKUP", "deletebackup");
136 if ("audit".equalsIgnoreCase(action)) {
137 return audit(ctx, "FULL");
139 if ("getrunningconfig".equalsIgnoreCase(action)) {
140 return audit(ctx, "RUNNING");
143 if ((key.equals("put")) || (key.equals("get"))) {
144 String loginId = parameters.get("loginId");
145 String host = parameters.get("host");
146 String password = parameters.get("password");
147 password = EncryptionTool.getInstance().decrypt(password);
148 String fullPathFileName = parameters.get("fullPathFileName");
150 if (key.equals("put")) {
151 data = parameters.get("data");
154 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
155 log.debug("SCP: SshJcraftWrapper has been instantiated");
158 if ("put".equals(key)) {
159 log.debug("Command is for put: Length of data is: {}", data.length());
160 InputStream is = new ByteArrayInputStream(data.getBytes());
161 log.debug("SCP: Doing a put: fullPathFileName={}", fullPathFileName);
162 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
164 log.debug("Sleeping for 180 seconds....");
165 Thread.sleep(1000L * 180);
166 log.debug("Woke up....");
167 } catch (java.lang.InterruptedException ee) {
168 log.error("Sleep interrupted", ee);
169 Thread.currentThread().interrupt();
171 } else { // Must be a get
172 log.debug("SCP: Doing a get: fullPathFileName={}", fullPathFileName);
173 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
174 log.debug("Got the response and putting into the ctx object");
175 ctx.setAttribute("fileContents", response);
176 log.debug("SCP: Closing the SFTP connection");
178 sshJcraftWrapper = null;
179 return (setResponseStatus(ctx, r));
180 } catch (IOException e) {
181 log.error("Exception occurred while using sshJcraftWrapper", e);
182 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
183 r.message = e.getMessage();
184 sshJcraftWrapper = null;
185 return (setResponseStatus(ctx, r));
188 if (key.equals("cli")) {
189 String loginId = parameters.get("loginId");
190 String host = parameters.get("host");
191 String password = parameters.get("password");
192 password = EncryptionTool.getInstance().decrypt(password);
193 String cliCommand = parameters.get("cli");
194 String portNumber = parameters.get("portNumber");
195 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
197 log.debug("CLI: Attempting to login: host={} loginId={} password={} portNumber={}", host, loginId,
198 password, portNumber);
199 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
201 log.debug("Sending 'sdc'");
202 sshJcraftWrapper.send("sdc", ":");
203 log.debug("Sending 1");
204 sshJcraftWrapper.send("1", ":");
205 log.debug("Sending 1, the second time");
206 sshJcraftWrapper.send("1", "#");
207 log.debug("Sending paging-options disable");
208 sshJcraftWrapper.send("paging-options disable", "#");
209 log.debug("Sending show config");
210 String response = sshJcraftWrapper.send("show config", "#");
212 log.debug("response is now:'{}'", response);
213 log.debug("Populating the ctx object with the response");
214 ctx.setAttribute("cliOutput", response);
215 sshJcraftWrapper.closeConnection();
217 sshJcraftWrapper = null;
218 return (setResponseStatus(ctx, r));
219 } catch (IOException e) {
220 log.error("Exception occurred while using sshJcraftWrapper", e);
221 sshJcraftWrapper.closeConnection();
222 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
223 r.message = e.getMessage();
224 sshJcraftWrapper = null;
225 return (setResponseStatus(ctx, r));
228 if (key.equals("escapeSql")) {
229 String data = parameters.get("artifactContents");
230 log.debug("ConfigComponentAdaptor.configure - escapeSql");
231 data = escapeMySql(data);
232 ctx.setAttribute("escapedData", data);
233 return (setResponseStatus(ctx, r));
235 if (key.equals("GetCliRunningConfig")) {
236 log.debug("key was: GetCliRunningConfig: ");
237 String User_name = parameters.get("User_name");
238 String Host_ip_address = parameters.get("Host_ip_address");
239 String Password = parameters.get("Password");
240 Password = EncryptionTool.getInstance().decrypt(Password);
241 String Port_number = parameters.get("Port_number");
242 String Get_config_template = parameters.get("Get_config_template");
243 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
244 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
246 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
247 + User_name + " Password=" + Password + " Port_number=" + Port_number);
248 StringBuffer sb = new StringBuffer();
249 String response = "";
250 String CliResponse = "";
251 boolean showConfigFlag = false;
253 .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
254 log.debug("GetCliRunningConfig: On the VNF device");
255 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
256 String command = null;
258 while (st.hasMoreTokens()) {
259 String line = st.nextToken();
260 log.debug("line={}", line);
261 if (line.indexOf("Request:") != -1) {
262 log.debug("Found a Request line: line={}", line);
263 command = getStringBetweenQuotes(line);
264 log.debug("Sending command={}", command);
265 sshJcraftWrapper.send(command);
266 log.debug("command has been sent");
267 if (line.indexOf("show config") != -1) {
268 showConfigFlag = true;
269 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
272 if (line.indexOf("Response: Ends_With") != -1) {
273 log.debug("Found a Response line: line={}", line);
274 String delemeter = getStringBetweenQuotes(line);
275 log.debug("The delemeter={}", delemeter);
276 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command);
277 response += tmpResponse;
278 if (showConfigFlag) {
279 showConfigFlag = false;
280 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
281 while (st2.hasMoreTokens()) {
282 String line2 = st2.nextToken();
283 if (line2.indexOf("#") == -1) {
284 CliResponse += line2 + "\n";
290 } catch (NoSuchElementException e) {
291 log.error(e.getMessage(), e);
293 log.debug("CliResponse=\n{}", CliResponse);
294 ctx.setAttribute("cliOutput", CliResponse);
295 sshJcraftWrapper.closeConnection();
297 sshJcraftWrapper = null;
298 return (setResponseStatus(ctx, r));
299 } catch (IOException e) {
300 log.error("Exception occurred while using sshJcraftWrapper", e);
301 sshJcraftWrapper.closeConnection();
302 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
303 r.message = e.getMessage();
304 sshJcraftWrapper = null;
305 return (setResponseStatus(ctx, r));
308 if (key.equals("xml-download")) {
309 log.debug("key was: xml-download");
310 String User_name = parameters.get("User_name");
311 String Host_ip_address = parameters.get("Host_ip_address");
312 String Password = parameters.get("Password");
313 Password = EncryptionTool.getInstance().decrypt(Password);
314 String Port_number = parameters.get("Port_number");
315 String Contents = parameters.get("Contents");
316 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>";
317 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 ]]>]]>";
318 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
320 log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
321 Host_ip_address, Password, Port_number);
322 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
325 .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
327 String NetconfHelloCmd = netconfHelloCmd;
328 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
329 log.debug("Sending the hello command");
330 sshJcraftWrapper.send(NetconfHelloCmd);
331 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
332 log.debug("Sending xmlCmd cmd");
333 String xmlCmd = Contents;
334 String messageId = "1";
335 messageId = "\"" + messageId + "\"";
336 String loadConfigurationString =
337 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
339 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
340 + xmlCmd + "</config> </edit-config> </rpc>";
341 loadConfigurationString = loadConfigurationString + "]]>]]>";
342 sshJcraftWrapper.send(loadConfigurationString);
343 log.debug("After sending loadConfigurationString");
344 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
345 if (response.indexOf("rpc-error") != -1) {
346 log.debug("Error from device: Response from device had 'rpc-error'");
347 log.debug("response=\n{}\n", response);
348 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
349 r.message = response;
351 log.debug(":LoadConfiguration was a success, sending commit cmd");
352 sshJcraftWrapper.send(commitCmd);
353 log.debug(":After sending commitCmd");
354 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
355 if (response.indexOf("rpc-error") != -1) {
356 log.debug("Error from device: Response from device had 'rpc-error'");
357 log.debug("response=\n{}\n", response);
358 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
359 r.message = response;
361 log.debug(":Looks like a success");
362 log.debug("response=\n{}\n", response);
366 sshJcraftWrapper.send(terminateConnectionCmd);
367 sshJcraftWrapper.closeConnection();
368 sshJcraftWrapper = null;
369 return (setResponseStatus(ctx, r));
370 } catch (Exception e) {
371 log.error("Caught an Exception", e);
372 sshJcraftWrapper.closeConnection();
373 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
374 r.message = e.getMessage();
375 sshJcraftWrapper = null;
376 log.debug("Returning error message");
377 return (setResponseStatus(ctx, r));
380 if (key.equals("xml-getrunningconfig")) {
381 log.debug("key was: : xml-getrunningconfig");
382 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";
383 String Host_ip_address = parameters.get("Host_ip_address");
384 String User_name = parameters.get("User_name");
385 String Password = parameters.get("Password");
386 Password = EncryptionTool.getInstance().decrypt(Password);
387 String Port_number = parameters.get("Port_number");
388 String Protocol = parameters.get("Protocol");
389 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>";
390 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 ]]>]]>";
391 log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
392 Host_ip_address, Password, Port_number);
393 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
395 String NetconfHelloCmd = netconfHelloCmd;
397 .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
399 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
400 log.debug(":Sending the hello command");
401 sshJcraftWrapper.send(NetconfHelloCmd);
402 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
403 log.debug("Sending get running config command");
404 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
405 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
406 log.debug("Response from getRunningconfigCmd={}", response);
407 response = trimResponse(response);
408 ctx.setAttribute("xmlRunningConfigOutput", response);
409 sshJcraftWrapper.send(terminateConnectionCmd);
410 sshJcraftWrapper.closeConnection();
412 sshJcraftWrapper = null;
413 return (setResponseStatus(ctx, r));
414 } catch (Exception e) {
415 log.error("Caught an Exception", e);
416 sshJcraftWrapper.closeConnection();
417 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
418 r.message = e.getMessage();
419 sshJcraftWrapper = null;
420 log.debug("Returning error message");
421 return (setResponseStatus(ctx, r));
424 if (key.equals("DownloadCliConfig")) {
425 log.debug("key was: DownloadCliConfig: ");
426 String User_name = parameters.get("User_name");
427 String Host_ip_address = parameters.get("Host_ip_address");
428 String Password = parameters.get("Password");
429 Password = EncryptionTool.getInstance().decrypt(Password);
430 String Port_number = parameters.get("Port_number");
431 String Download_config_template = parameters.get("Download_config_template");
432 String Config_contents = parameters.get("Config_contents");
433 log.debug("Contents of the 'Config_contents' are: {}", Config_contents);
434 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
435 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
436 int timeout = 4 * 60 * 1000;
438 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
439 + User_name + " Password=" + Password + " Port_number=" + Port_number);
440 StringBuffer sb = new StringBuffer();
441 String response = "";
442 String CliResponse = "";
444 .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
445 log.debug("DownloadCliConfig: On the VNF device");
446 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
447 String command = null;
448 String executeConfigContentsDelemeter = null;
450 while (st.hasMoreTokens()) {
451 String line = st.nextToken();
452 log.debug("line={}", line);
453 if (line.indexOf("Request:") != -1) {
454 log.debug("Found a Request line: line={}", line);
455 command = getStringBetweenQuotes(line);
456 log.debug("Sending command={}", command);
457 sshJcraftWrapper.send(command);
458 log.debug("command has been sent");
459 } else if ((line.indexOf("Response: Ends_With") != -1) && (
460 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
461 log.debug("Found a Response line: line={}", line);
462 String delimiter = getStringBetweenQuotes(line);
463 log.debug("The delimiter={}", delimiter);
464 String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
465 response += tmpResponse;
466 CliResponse += tmpResponse;
467 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
468 log.debug("Found a 'Execute_config_contents Response:' line={}", line);
469 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
470 log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
471 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
472 while (st2.hasMoreTokens()) {
473 String cmd = st2.nextToken();
474 log.debug("Config_contents: cmd={}", cmd);
475 sshJcraftWrapper.send(cmd);
476 String tmpResponse = sshJcraftWrapper
477 .receiveUntil(executeConfigContentsDelemeter, timeout, command);
478 CliResponse += tmpResponse;
482 } catch (NoSuchElementException e) {
483 log.error(e.getMessage(), e);
485 sshJcraftWrapper.closeConnection();
486 sshJcraftWrapper = null;
487 log.debug(":Escaping all the single and double quotes in the response");
488 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
489 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
490 log.debug("CliResponse=\n{}" + CliResponse);
491 ctx.setAttribute("cliOutput", CliResponse);
493 return (setResponseStatus(ctx, r));
494 } catch (IOException e) {
495 log.error(e.getMessage() + e);
496 sshJcraftWrapper.closeConnection();
497 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
498 r.message = e.getMessage();
499 sshJcraftWrapper = null;
500 log.debug("DownloadCliConfig: Returning error message");
501 return (setResponseStatus(ctx, r));
505 log.debug("Unsupported action - {}", action);
506 return ConfigStatus.FAILURE;
509 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
510 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
511 String ndTemplate = readFile(templateName);
512 String nd = buildNetworkData2(ctx, ndTemplate, operation);
514 String reqTemplate = readFile("/config-request.xml");
515 Map<String, String> param = new HashMap<String, String>();
516 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
517 param.put("request-type", requestType);
518 param.put("callback-url", configCallbackUrl);
519 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
520 param.put("action", "GenerateOnly");
522 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
523 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
524 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
525 param.put("network-data", nd);
529 req = buildXmlRequest(param, reqTemplate);
530 } catch (Exception e) {
531 log.error("Error building the XML request: ", e);
533 HttpResponse r = new HttpResponse();
534 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
535 r.message = e.getMessage();
536 return setResponseStatus(ctx, r);
539 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
540 return setResponseStatus(ctx, r);
543 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
544 String reqTemplate = readFile("/config-request.xml");
545 Map<String, String> param = new HashMap<String, String>();
546 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
547 param.put("callback-url", configCallbackUrl);
548 param.put("action", change ? "DownloadChange" : "DownloadBase");
549 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
553 req = buildXmlRequest(param, reqTemplate);
554 } catch (Exception e) {
555 log.error("Error building the XML request: ", e);
557 HttpResponse r = new HttpResponse();
558 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
559 r.message = e.getMessage();
560 return setResponseStatus(ctx, r);
563 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
564 return setResponseStatus(ctx, r);
567 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
568 String reqTemplate = readFile("/audit-request.xml");
569 Map<String, String> param = new HashMap<String, String>();
570 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
571 param.put("callback-url", auditCallbackUrl);
572 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
573 param.put("audit-level", auditLevel);
577 req = buildXmlRequest(param, reqTemplate);
578 } catch (Exception e) {
579 log.error("Error building the XML request: ", e);
581 HttpResponse r = new HttpResponse();
582 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
583 r.message = e.getMessage();
584 return setResponseStatus(ctx, r);
587 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
588 return setResponseStatus(ctx, r);
592 public ConfigStatus activate(String key, SvcLogicContext ctx) {
593 return ConfigStatus.SUCCESS;
597 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
598 return ConfigStatus.SUCCESS;
601 private String escapeMySql(String input) {
606 input = input.replace("\\", "\\\\");
607 input = input.replace("\'", "\\'");
612 private String readFile(String fileName) {
613 InputStream is = getClass().getResourceAsStream(fileName);
614 InputStreamReader isr = new InputStreamReader(is);
615 BufferedReader in = new BufferedReader(isr);
616 StringBuilder ss = new StringBuilder();
618 String s = in.readLine();
620 ss.append(s).append('\n');
623 } catch (IOException e) {
624 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
628 } catch (Exception e) {
629 log.warn("Could not close BufferedReader", e);
633 } catch (Exception e) {
634 log.warn("Could not close InputStreamReader", e);
638 } catch (Exception e) {
639 log.warn("Could not close InputStream", e);
642 return ss.toString();
645 private String buildXmlRequest(Map<String, String> param, String template) {
646 StringBuilder ss = new StringBuilder();
648 while (i < template.length()) {
649 int i1 = template.indexOf("${", i);
651 ss.append(template.substring(i));
655 int i2 = template.indexOf('}', i1 + 2);
657 throw new RuntimeException("Template error: Matching } not found");
660 String var1 = template.substring(i1 + 2, i2);
661 String value1 = param.get(var1);
662 if (value1 == null || value1.trim().length() == 0) {
663 // delete the whole element (line)
664 int i3 = template.lastIndexOf('\n', i1);
668 int i4 = template.indexOf('\n', i1);
670 i4 = template.length();
674 ss.append(template.substring(i, i3));
678 ss.append(template.substring(i, i1)).append(value1);
683 return ss.toString();
686 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
687 log.info("Building XML started");
688 long t1 = System.currentTimeMillis();
690 template = expandRepeats(ctx, template, 1);
692 Map<String, String> mm = new HashMap<>();
693 for (String s : ctx.getAttributeKeySet()) {
694 mm.put(s, ctx.getAttribute(s));
696 mm.put("operation", operation);
698 StringBuilder ss = new StringBuilder();
700 while (i < template.length()) {
701 int i1 = template.indexOf("${", i);
703 ss.append(template.substring(i));
707 int i2 = template.indexOf('}', i1 + 2);
709 throw new RuntimeException("Template error: Matching } not found");
712 String var1 = template.substring(i1 + 2, i2);
713 String value1 = XmlUtil.getXml(mm, var1);
714 if (value1 == null || value1.trim().length() == 0) {
715 int i3 = template.lastIndexOf('\n', i1);
719 int i4 = template.indexOf('\n', i1);
721 i4 = template.length();
725 ss.append(template.substring(i, i3));
729 ss.append(template.substring(i, i1)).append(value1);
734 long t2 = System.currentTimeMillis();
735 log.info("Building XML completed. Time: " + (t2 - t1));
737 return ss.toString();
740 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
741 StringBuilder newTemplate = new StringBuilder();
743 while (k < template.length()) {
744 int i1 = template.indexOf("${repeat:", k);
746 newTemplate.append(template.substring(k));
750 int i2 = template.indexOf(':', i1 + 9);
752 throw new RuntimeException(
753 "Template error: Context variable name followed by : is required after repeat");
756 // Find the closing }, store in i3
760 while (nn > 0 && i < template.length()) {
761 i3 = template.indexOf('}', i);
763 throw new RuntimeException("Template error: Matching } not found");
765 int i32 = template.indexOf('{', i);
766 if (i32 >= 0 && i32 < i3) {
775 String var1 = template.substring(i1 + 9, i2);
776 String value1 = ctx.getAttribute(var1);
777 log.info(" " + var1 + ": " + value1);
780 n = Integer.parseInt(value1);
781 } catch (Exception e) {
785 newTemplate.append(template.substring(k, i1));
787 String rpt = template.substring(i2 + 1, i3);
789 for (int ii = 0; ii < n; ii++) {
790 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
791 newTemplate.append(ss);
798 return newTemplate.toString();
801 return expandRepeats(ctx, newTemplate.toString(), level + 1);
804 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
806 Client client = Client.create();
807 client.setConnectTimeout(5000);
808 WebResource webResource = client.resource(url);
810 log.info("SENDING...............");
811 log.info(xmlRequest);
813 String authString = user + ":" + password;
814 byte[] authEncBytes = Base64.encode(authString);
815 String authStringEnc = new String(authEncBytes);
816 authString = "Basic " + authStringEnc;
818 ClientResponse response =
819 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
820 ClientResponse.class, xmlRequest);
822 int code = response.getStatus();
823 String message = null;
825 log.info("RESPONSE...............");
826 log.info("HTTP response code: " + code);
827 log.info("HTTP response message: " + message);
830 HttpResponse r = new HttpResponse();
835 } catch (Exception e) {
836 log.error("Error sending the request: ", e);
838 HttpResponse r = new HttpResponse();
839 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
840 r.message = e.getMessage();
845 private static class HttpResponse {
848 public String message;
851 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
852 ctx.setAttribute("error-code", String.valueOf(r.code));
853 ctx.setAttribute("error-message", r.message);
855 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
858 private String getStringBetweenQuotes(String string) {
859 log.debug("string=" + string);
861 int start = string.indexOf('\"');
862 int end = string.lastIndexOf('\"');
863 retString = string.substring(start + 1, end);
864 log.debug("retString=" + retString);
868 public static String _readFile(String fileName) {
869 StringBuffer strBuff = new StringBuffer();
872 BufferedReader in = new BufferedReader(new FileReader(fileName));
873 while ((line = in.readLine()) != null) {
874 strBuff.append(line + "\n");
877 } catch (IOException e) {
878 log.error("Caught an IOException in method readFile()", e);
880 return (strBuff.toString());
883 private String trimResponse(String response) {
884 StringTokenizer line = new StringTokenizer(response, "\n");
885 StringBuffer sb = new StringBuffer();
886 boolean captureText = false;
887 while (line.hasMoreTokens()) {
888 String token = line.nextToken();
889 if (token.indexOf("<configuration xmlns=") != -1) {
893 sb.append(token + "\n");
895 if (token.indexOf("</configuration>") != -1) {
899 return (sb.toString());
902 public static void main(String args[]) throws Exception {
903 Properties props = null;
904 System.out.println("*************************Hello*****************************");
905 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
906 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
907 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
908 String key = "GetCliRunningConfig";
909 Map<String, String> parameters = new HashMap();
910 parameters.put("Host_ip_address", "000.00.000.00");
911 parameters.put("User_name", "root");
912 parameters.put("Password", "!bootstrap");
913 parameters.put("Port_number", "22");
914 parameters.put("Get_config_template", Get_config_template);
915 SvcLogicContext ctx = null;
916 System.out.println("*************************TRACE 1*****************************");
917 cca.configure(key, parameters, ctx);