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, Integer.parseInt(portNumber));
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),
329 String NetconfHelloCmd = netconfHelloCmd;
330 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
331 log.debug("Sending the hello command");
332 sshJcraftWrapper.send(NetconfHelloCmd);
333 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
334 log.debug("Sending xmlCmd cmd");
335 String xmlCmd = Contents;
336 String messageId = "1";
337 messageId = "\"" + messageId + "\"";
338 String loadConfigurationString =
339 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
341 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
342 + xmlCmd + "</config> </edit-config> </rpc>";
343 loadConfigurationString = loadConfigurationString + "]]>]]>";
344 sshJcraftWrapper.send(loadConfigurationString);
345 log.debug("After sending loadConfigurationString");
346 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
347 if (response.indexOf("rpc-error") != -1) {
348 log.debug("Error from device: Response from device had 'rpc-error'");
349 log.debug("response=\n{}\n", response);
350 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
351 r.message = response;
353 log.debug(":LoadConfiguration was a success, sending commit cmd");
354 sshJcraftWrapper.send(commitCmd);
355 log.debug(":After sending commitCmd");
356 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
357 if (response.indexOf("rpc-error") != -1) {
358 log.debug("Error from device: Response from device had 'rpc-error'");
359 log.debug("response=\n{}\n", response);
360 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
361 r.message = response;
363 log.debug(":Looks like a success");
364 log.debug("response=\n{}\n", response);
368 sshJcraftWrapper.send(terminateConnectionCmd);
369 sshJcraftWrapper.closeConnection();
370 sshJcraftWrapper = null;
371 return (setResponseStatus(ctx, r));
372 } catch (Exception e) {
373 log.error("Caught an Exception", e);
374 sshJcraftWrapper.closeConnection();
375 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
376 r.message = e.getMessage();
377 sshJcraftWrapper = null;
378 log.debug("Returning error message");
379 return (setResponseStatus(ctx, r));
382 if (key.equals("xml-getrunningconfig")) {
383 log.debug("key was: : xml-getrunningconfig");
384 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";
385 String Host_ip_address = parameters.get("Host_ip_address");
386 String User_name = parameters.get("User_name");
387 String Password = parameters.get("Password");
388 Password = EncryptionTool.getInstance().decrypt(Password);
389 String Port_number = parameters.get("Port_number");
390 String Protocol = parameters.get("Protocol");
391 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>";
392 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 ]]>]]>";
393 log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", User_name,
394 Host_ip_address, Password, Port_number);
395 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
397 String NetconfHelloCmd = netconfHelloCmd;
399 .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
401 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
402 log.debug(":Sending the hello command");
403 sshJcraftWrapper.send(NetconfHelloCmd);
404 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
405 log.debug("Sending get running config command");
406 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
407 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
408 log.debug("Response from getRunningconfigCmd={}", response);
409 response = trimResponse(response);
410 ctx.setAttribute("xmlRunningConfigOutput", response);
411 sshJcraftWrapper.send(terminateConnectionCmd);
412 sshJcraftWrapper.closeConnection();
414 sshJcraftWrapper = null;
415 return (setResponseStatus(ctx, r));
416 } catch (Exception e) {
417 log.error("Caught an Exception", e);
418 sshJcraftWrapper.closeConnection();
419 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
420 r.message = e.getMessage();
421 sshJcraftWrapper = null;
422 log.debug("Returning error message");
423 return (setResponseStatus(ctx, r));
426 if (key.equals("DownloadCliConfig")) {
427 log.debug("key was: DownloadCliConfig: ");
428 String User_name = parameters.get("User_name");
429 String Host_ip_address = parameters.get("Host_ip_address");
430 String Password = parameters.get("Password");
431 Password = EncryptionTool.getInstance().decrypt(Password);
432 String Port_number = parameters.get("Port_number");
433 String Download_config_template = parameters.get("Download_config_template");
434 String Config_contents = parameters.get("Config_contents");
435 log.debug("Contents of the 'Config_contents' are: {}", Config_contents);
436 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
437 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
438 int timeout = 4 * 60 * 1000;
440 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
441 + User_name + " Password=" + Password + " Port_number=" + Port_number);
442 StringBuffer sb = new StringBuffer();
443 String response = "";
444 String CliResponse = "";
446 .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
447 log.debug("DownloadCliConfig: On the VNF device");
448 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
449 String command = null;
450 String executeConfigContentsDelemeter = null;
452 while (st.hasMoreTokens()) {
453 String line = st.nextToken();
454 log.debug("line={}", line);
455 if (line.indexOf("Request:") != -1) {
456 log.debug("Found a Request line: line={}", line);
457 command = getStringBetweenQuotes(line);
458 log.debug("Sending command={}", command);
459 sshJcraftWrapper.send(command);
460 log.debug("command has been sent");
461 } else if ((line.indexOf("Response: Ends_With") != -1) && (
462 line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
463 log.debug("Found a Response line: line={}", line);
464 String delimiter = getStringBetweenQuotes(line);
465 log.debug("The delimiter={}", delimiter);
466 String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
467 response += tmpResponse;
468 CliResponse += tmpResponse;
469 } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
470 log.debug("Found a 'Execute_config_contents Response:' line={}", line);
471 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
472 log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
473 StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
474 while (st2.hasMoreTokens()) {
475 String cmd = st2.nextToken();
476 log.debug("Config_contents: cmd={}", cmd);
477 sshJcraftWrapper.send(cmd);
478 String tmpResponse = sshJcraftWrapper
479 .receiveUntil(executeConfigContentsDelemeter, timeout, command);
480 CliResponse += tmpResponse;
484 } catch (NoSuchElementException e) {
485 log.error(e.getMessage(), e);
487 sshJcraftWrapper.closeConnection();
488 sshJcraftWrapper = null;
489 log.debug(":Escaping all the single and double quotes in the response");
490 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
491 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
492 log.debug("CliResponse=\n{}" + CliResponse);
493 ctx.setAttribute("cliOutput", CliResponse);
495 return (setResponseStatus(ctx, r));
496 } catch (IOException e) {
497 log.error(e.getMessage() + e);
498 sshJcraftWrapper.closeConnection();
499 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
500 r.message = e.getMessage();
501 sshJcraftWrapper = null;
502 log.debug("DownloadCliConfig: Returning error message");
503 return (setResponseStatus(ctx, r));
507 log.debug("Unsupported action - {}", action);
508 return ConfigStatus.FAILURE;
511 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
512 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
513 String ndTemplate = readFile(templateName);
514 String nd = buildNetworkData2(ctx, ndTemplate, operation);
516 String reqTemplate = readFile("/config-request.xml");
517 Map<String, String> param = new HashMap<String, String>();
518 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
519 param.put("request-type", requestType);
520 param.put("callback-url", configCallbackUrl);
521 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
522 param.put("action", "GenerateOnly");
524 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
525 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
526 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
527 param.put("network-data", nd);
531 req = buildXmlRequest(param, reqTemplate);
532 } catch (Exception e) {
533 log.error("Error building the XML request: ", e);
535 HttpResponse r = new HttpResponse();
536 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
537 r.message = e.getMessage();
538 return setResponseStatus(ctx, r);
541 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
542 return setResponseStatus(ctx, r);
545 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
546 String reqTemplate = readFile("/config-request.xml");
547 Map<String, String> param = new HashMap<String, String>();
548 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
549 param.put("callback-url", configCallbackUrl);
550 param.put("action", change ? "DownloadChange" : "DownloadBase");
551 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
555 req = buildXmlRequest(param, reqTemplate);
556 } catch (Exception e) {
557 log.error("Error building the XML request: ", e);
559 HttpResponse r = new HttpResponse();
560 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
561 r.message = e.getMessage();
562 return setResponseStatus(ctx, r);
565 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
566 return setResponseStatus(ctx, r);
569 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
570 String reqTemplate = readFile("/audit-request.xml");
571 Map<String, String> param = new HashMap<String, String>();
572 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
573 param.put("callback-url", auditCallbackUrl);
574 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
575 param.put("audit-level", auditLevel);
579 req = buildXmlRequest(param, reqTemplate);
580 } catch (Exception e) {
581 log.error("Error building the XML request: ", e);
583 HttpResponse r = new HttpResponse();
584 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
585 r.message = e.getMessage();
586 return setResponseStatus(ctx, r);
589 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
590 return setResponseStatus(ctx, r);
594 public ConfigStatus activate(String key, SvcLogicContext ctx) {
595 return ConfigStatus.SUCCESS;
599 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
600 return ConfigStatus.SUCCESS;
603 private String escapeMySql(String input) {
608 input = input.replace("\\", "\\\\");
609 input = input.replace("\'", "\\'");
614 private String readFile(String fileName) {
615 InputStream is = getClass().getResourceAsStream(fileName);
616 InputStreamReader isr = new InputStreamReader(is);
617 BufferedReader in = new BufferedReader(isr);
618 StringBuilder ss = new StringBuilder();
620 String s = in.readLine();
622 ss.append(s).append('\n');
625 } catch (IOException e) {
626 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
630 } catch (Exception e) {
631 log.warn("Could not close BufferedReader", e);
635 } catch (Exception e) {
636 log.warn("Could not close InputStreamReader", e);
640 } catch (Exception e) {
641 log.warn("Could not close InputStream", e);
644 return ss.toString();
647 private String buildXmlRequest(Map<String, String> param, String template) {
648 StringBuilder ss = new StringBuilder();
650 while (i < template.length()) {
651 int i1 = template.indexOf("${", i);
653 ss.append(template.substring(i));
657 int i2 = template.indexOf('}', i1 + 2);
659 throw new RuntimeException("Template error: Matching } not found");
662 String var1 = template.substring(i1 + 2, i2);
663 String value1 = param.get(var1);
664 if (value1 == null || value1.trim().length() == 0) {
665 // delete the whole element (line)
666 int i3 = template.lastIndexOf('\n', i1);
670 int i4 = template.indexOf('\n', i1);
672 i4 = template.length();
676 ss.append(template.substring(i, i3));
680 ss.append(template.substring(i, i1)).append(value1);
685 return ss.toString();
688 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
689 log.info("Building XML started");
690 long t1 = System.currentTimeMillis();
692 template = expandRepeats(ctx, template, 1);
694 Map<String, String> mm = new HashMap<>();
695 for (String s : ctx.getAttributeKeySet()) {
696 mm.put(s, ctx.getAttribute(s));
698 mm.put("operation", operation);
700 StringBuilder ss = new StringBuilder();
702 while (i < template.length()) {
703 int i1 = template.indexOf("${", i);
705 ss.append(template.substring(i));
709 int i2 = template.indexOf('}', i1 + 2);
711 throw new RuntimeException("Template error: Matching } not found");
714 String var1 = template.substring(i1 + 2, i2);
715 String value1 = XmlUtil.getXml(mm, var1);
716 if (value1 == null || value1.trim().length() == 0) {
717 int i3 = template.lastIndexOf('\n', i1);
721 int i4 = template.indexOf('\n', i1);
723 i4 = template.length();
727 ss.append(template.substring(i, i3));
731 ss.append(template.substring(i, i1)).append(value1);
736 long t2 = System.currentTimeMillis();
737 log.info("Building XML completed. Time: " + (t2 - t1));
739 return ss.toString();
742 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
743 StringBuilder newTemplate = new StringBuilder();
745 while (k < template.length()) {
746 int i1 = template.indexOf("${repeat:", k);
748 newTemplate.append(template.substring(k));
752 int i2 = template.indexOf(':', i1 + 9);
754 throw new RuntimeException(
755 "Template error: Context variable name followed by : is required after repeat");
758 // Find the closing }, store in i3
762 while (nn > 0 && i < template.length()) {
763 i3 = template.indexOf('}', i);
765 throw new RuntimeException("Template error: Matching } not found");
767 int i32 = template.indexOf('{', i);
768 if (i32 >= 0 && i32 < i3) {
777 String var1 = template.substring(i1 + 9, i2);
778 String value1 = ctx.getAttribute(var1);
779 log.info(" " + var1 + ": " + value1);
782 n = Integer.parseInt(value1);
783 } catch (Exception e) {
787 newTemplate.append(template.substring(k, i1));
789 String rpt = template.substring(i2 + 1, i3);
791 for (int ii = 0; ii < n; ii++) {
792 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
793 newTemplate.append(ss);
800 return newTemplate.toString();
803 return expandRepeats(ctx, newTemplate.toString(), level + 1);
806 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
808 Client client = Client.create();
809 client.setConnectTimeout(5000);
810 WebResource webResource = client.resource(url);
812 log.info("SENDING...............");
813 log.info(xmlRequest);
815 String authString = user + ":" + password;
816 byte[] authEncBytes = Base64.encode(authString);
817 String authStringEnc = new String(authEncBytes);
818 authString = "Basic " + authStringEnc;
820 ClientResponse response =
821 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
822 ClientResponse.class, xmlRequest);
824 int code = response.getStatus();
825 String message = null;
827 log.info("RESPONSE...............");
828 log.info("HTTP response code: " + code);
829 log.info("HTTP response message: " + message);
832 HttpResponse r = new HttpResponse();
837 } catch (Exception e) {
838 log.error("Error sending the request: ", e);
840 HttpResponse r = new HttpResponse();
841 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
842 r.message = e.getMessage();
847 private static class HttpResponse {
850 public String message;
853 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
854 ctx.setAttribute("error-code", String.valueOf(r.code));
855 ctx.setAttribute("error-message", r.message);
857 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
860 private String getStringBetweenQuotes(String string) {
861 log.debug("string=" + string);
863 int start = string.indexOf('\"');
864 int end = string.lastIndexOf('\"');
865 retString = string.substring(start + 1, end);
866 log.debug("retString=" + retString);
870 public static String _readFile(String fileName) {
871 StringBuffer strBuff = new StringBuffer();
874 BufferedReader in = new BufferedReader(new FileReader(fileName));
875 while ((line = in.readLine()) != null) {
876 strBuff.append(line + "\n");
879 } catch (IOException e) {
880 log.error("Caught an IOException in method readFile()", e);
882 return (strBuff.toString());
885 private String trimResponse(String response) {
886 StringTokenizer line = new StringTokenizer(response, "\n");
887 StringBuffer sb = new StringBuffer();
888 boolean captureText = false;
889 while (line.hasMoreTokens()) {
890 String token = line.nextToken();
891 if (token.indexOf("<configuration xmlns=") != -1) {
895 sb.append(token + "\n");
897 if (token.indexOf("</configuration>") != -1) {
901 return (sb.toString());
904 public static void main(String args[]) throws Exception {
905 Properties props = null;
906 System.out.println("*************************Hello*****************************");
907 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
908 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
909 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
910 String key = "GetCliRunningConfig";
911 Map<String, String> parameters = new HashMap();
912 parameters.put("Host_ip_address", "000.00.000.00");
913 parameters.put("User_name", "root");
914 parameters.put("Password", "!bootstrap");
915 parameters.put("Port_number", "22");
916 parameters.put("Get_config_template", Get_config_template);
917 SvcLogicContext ctx = null;
918 System.out.println("*************************TRACE 1*****************************");
919 cca.configure(key, parameters, ctx);