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);
50 private static final String ACTION_PARAM = "action";
51 private static final String ACTION_PREPARE = "prepare";
52 private static final String ACTION_ACTIVATE = "activate";
53 private static final String PUT_KEY = "put";
54 private static final String GET_KEY = "get";
55 private static final String CLI_KEY = "cli";
56 private static final String SSH_JCRAFT_WRAPPER_EXCEPTION_STR = "Exception occurred while using sshJcraftWrapper";
57 private static final String CLI_OUTPUT_PARAM = "cliOutput";
58 private static final String ESCAPE_SQL_KEY = "escapeSql";
59 private static final String GET_CLI_RUNNING_CONFIG_KEY = "GetCliRunningConfig";
60 private static final String USERNAME_PARAM = "User_name";
61 private static final String HOST_IP_PARAM = "Host_ip_address";
62 private static final String PASSWORD_PARAM = "Password";
63 private static final String PORT_NUMBER = "Port_number";
64 private static final String XML_DOWNLOAD_KEY = "xml-download";
65 private static final String PROMPT_STR = "]]>]]>";
66 private static final String RPC_REPLY_END_TAG = "</rpc-reply>";
67 private static final String RESPONSE_STR = "response=\n{}\n";
68 private static final String XML_GET_RUNNING_CONF_KEY = "xml-getrunningconfig";
69 private static final String DOWNLOAD_CLI_CONFIG_KEY = "DownloadCliConfig";
72 private String configUrl;
73 private String configUser;
74 private String configPassword;
75 private String auditUrl;
76 private String auditUser;
77 private String auditPassword;
78 private String configCallbackUrl;
79 private String auditCallbackUrl;
81 public ConfigComponentAdaptor(Properties props) {
83 configUrl = props.getProperty("configComponent.url", "");
84 configUser = props.getProperty("configComponent.user", "");
85 configPassword = props.getProperty("configComponent.passwd", "");
86 auditUrl = props.getProperty("auditComponent.url", "");
87 auditUser = props.getProperty("auditComponent.user", "");
88 auditPassword = props.getProperty("auditComponent.passwd", "");
89 configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
90 auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
95 public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
96 HttpResponse r = new HttpResponse();
98 log.debug("ConfigComponentAdaptor.configure - key = " + key);
99 log.debug("key = {}", key);
100 log.debug("Parameters:");
101 for (Entry<String, String> paramEntrySet : parameters.entrySet()) {
102 log.debug(" {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue());
105 String parmval = parameters.get("config-component-configUrl");
106 if (!nullOrEmpty(parmval)) {
107 log.debug("Overwriting URL with {}", parmval);
111 parmval = parameters.get("config-component-configPassword");
112 if (!nullOrEmpty(parmval)) {
113 log.debug("Overwriting configPassword with {}", parmval);
114 configPassword = parmval;
117 parmval = parameters.get("config-component-configUser");
118 if (!nullOrEmpty(parmval)) {
119 log.debug("Overwriting configUser id with {}", parmval);
120 configUser = parmval;
123 String action = parameters.get(ACTION_PARAM);
125 String chg = ctx.getAttribute(
126 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
127 if (chg != null && areEqual(action, ACTION_PREPARE)) {
128 return prepare(ctx, "CHANGE", "change");
130 if (chg != null && areEqual(action, ACTION_ACTIVATE)) {
131 return activate(ctx, true);
134 String scale = ctx.getAttribute(
135 "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
136 if (scale != null && areEqual(action, ACTION_PREPARE)) {
137 return prepare(ctx, "CHANGE", "scale");
139 if (scale != null && areEqual(action, ACTION_ACTIVATE)) {
140 return activate(ctx, true);
143 if (areEqual(action, ACTION_PREPARE)) {
144 return prepare(ctx, "BASE", "create");
146 if (areEqual(action, ACTION_ACTIVATE)) {
147 return activate(ctx, false);
150 if ("backup".equalsIgnoreCase(action)) {
151 return prepare(ctx, "BACKUP", "backup");
153 if ("restorebackup".equalsIgnoreCase(action)) {
154 return prepare(ctx, "RESTOREBACKUP", "restorebackup");
156 if ("deletebackup".equalsIgnoreCase(action)) {
157 return prepare(ctx, "DELETEBACKUP", "deletebackup");
159 if ("audit".equalsIgnoreCase(action)) {
160 return audit(ctx, "FULL");
162 if ("getrunningconfig".equalsIgnoreCase(action)) {
163 return audit(ctx, "RUNNING");
166 if ((key.equals(PUT_KEY)) || (key.equals(GET_KEY))) {
167 String loginId = parameters.get("loginId");
168 String host = parameters.get("host");
169 String password = parameters.get("password");
170 password = EncryptionTool.getInstance().decrypt(password);
171 String fullPathFileName = parameters.get("fullPathFileName");
173 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
174 log.debug("SCP: SshJcraftWrapper has been instantiated");
177 if (key.equals(PUT_KEY)) {
178 String data = parameters.get("data");
179 log.debug("Command is for put: Length of data is: {}", data.length());
180 InputStream is = new ByteArrayInputStream(data.getBytes());
181 log.debug("SCP: Doing a put: fullPathFileName={}", fullPathFileName);
182 sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
183 trySleepFor(1000L * 180);
184 } else { // Must be a get
185 log.debug("SCP: Doing a get: fullPathFileName={}", fullPathFileName);
186 String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
187 log.debug("Got the response and putting into the ctx object");
188 ctx.setAttribute("fileContents", response);
189 log.debug("SCP: Closing the SFTP connection");
191 return setResponseStatus(ctx, r);
192 } catch (IOException e) {
193 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
194 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
195 r.message = e.getMessage();
196 return setResponseStatus(ctx, r);
199 if (key.equals(CLI_KEY)) {
200 String loginId = parameters.get("loginId");
201 String host = parameters.get("host");
202 String password = parameters.get("password");
203 password = EncryptionTool.getInstance().decrypt(password);
204 String portNumber = parameters.get("portNumber");
205 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
207 log.debug("CLI: Attempting to login: host={} loginId={} password={} portNumber={}", host, loginId,
208 password, portNumber);
209 sshJcraftWrapper.connect(host, loginId, password); //what about portNum?
211 log.debug("Sending 'sdc'");
212 sshJcraftWrapper.send("sdc", ":");
213 log.debug("Sending 1");
214 sshJcraftWrapper.send("1", ":");
215 log.debug("Sending 1, the second time");
216 sshJcraftWrapper.send("1", "#");
217 log.debug("Sending paging-options disable");
218 sshJcraftWrapper.send("paging-options disable", "#");
219 log.debug("Sending show config");
220 String response = sshJcraftWrapper.send("show config", "#");
222 log.debug("response is now:'{}'", response);
223 log.debug("Populating the ctx object with the response");
224 ctx.setAttribute(CLI_OUTPUT_PARAM, response);
225 sshJcraftWrapper.closeConnection();
227 return setResponseStatus(ctx, r);
228 } catch (IOException e) {
229 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
230 sshJcraftWrapper.closeConnection();
231 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
232 r.message = e.getMessage();
233 return setResponseStatus(ctx, r);
236 if (key.equals(ESCAPE_SQL_KEY)) {
237 String data = parameters.get("artifactContents");
238 log.debug("ConfigComponentAdaptor.configure - escapeSql");
239 data = escapeMySql(data);
240 ctx.setAttribute("escapedData", data);
241 return setResponseStatus(ctx, r);
243 if (key.equals(GET_CLI_RUNNING_CONFIG_KEY)) {
244 log.debug("key was: " + GET_CLI_RUNNING_CONFIG_KEY);
245 String username = parameters.get(USERNAME_PARAM);
246 String hostIpAddress = parameters.get(HOST_IP_PARAM);
247 String password = parameters.get(PASSWORD_PARAM);
248 password = EncryptionTool.getInstance().decrypt(password);
249 String portNumber = parameters.get(PORT_NUMBER);
250 String getConfigTemplate = parameters.get("Get_config_template");
251 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
252 log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
254 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name="
255 + username + " Password=" + password + " Port_number=" + portNumber);
258 boolean showConfigFlag = false;
260 .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber));
261 log.debug("GetCliRunningConfig: On the VNF device");
262 StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n");
263 String command = null;
264 StringBuilder cliResponse = new StringBuilder();
266 // shouldn't this be used somewhere?
267 StringBuilder response = new StringBuilder();
269 while (st.hasMoreTokens()) {
270 String line = st.nextToken();
271 log.debug("line={}", line);
272 if (line.contains("Request:")) {
273 log.debug("Found a Request line: line={}", line);
274 command = getStringBetweenQuotes(line);
275 log.debug("Sending command={}", command);
276 sshJcraftWrapper.send(command);
277 log.debug("command has been sent");
278 if (line.contains("show config")) {
279 showConfigFlag = true;
280 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
283 if (line.contains("Response: Ends_With")) {
284 log.debug("Found a Response line: line={}", line);
285 String delemeter = getStringBetweenQuotes(line);
286 log.debug("The delemeter={}", delemeter);
287 String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command);
288 response.append(tmpResponse);
289 if (showConfigFlag) {
290 showConfigFlag = false;
291 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
292 while (st2.hasMoreTokens()) {
293 String line2 = st2.nextToken();
294 if (!line2.contains("#")) {
295 cliResponse.append(line2).append('\n');
301 } catch (NoSuchElementException e) {
302 log.error(e.getMessage(), e);
304 log.debug("CliResponse=\n{}", cliResponse.toString());
305 ctx.setAttribute(CLI_OUTPUT_PARAM, cliResponse.toString());
306 sshJcraftWrapper.closeConnection();
308 return setResponseStatus(ctx, r);
309 } catch (IOException e) {
310 log.error(SSH_JCRAFT_WRAPPER_EXCEPTION_STR, e);
311 sshJcraftWrapper.closeConnection();
312 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
313 r.message = e.getMessage();
314 return setResponseStatus(ctx, r);
317 if (key.equals(XML_DOWNLOAD_KEY)) {
318 log.debug("key was: " + XML_DOWNLOAD_KEY);
319 String userName = parameters.get(USERNAME_PARAM);
320 String hostIpAddress = parameters.get(HOST_IP_PARAM);
321 String password = parameters.get(PASSWORD_PARAM);
322 password = EncryptionTool.getInstance().decrypt(password);
323 String portNumber = parameters.get(PORT_NUMBER);
324 String contents = parameters.get("Contents");
325 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>";
326 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 ]]>]]>";
327 String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
329 log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", userName,
330 hostIpAddress, password, portNumber);
331 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
333 // what about prompt "]]>]]>"?
335 .connect(hostIpAddress, userName, password, 30000, Integer.parseInt(portNumber), "netconf");
337 netconfHelloCmd += PROMPT_STR;
338 log.debug("Sending the hello command");
339 sshJcraftWrapper.send(netconfHelloCmd);
341 log.debug("Sending xmlCmd cmd");
342 String messageId = "1";
343 messageId = "\"" + messageId + "\"";
344 String loadConfigurationString =
345 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
347 + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
348 + contents + "</config> </edit-config> </rpc>";
349 loadConfigurationString = loadConfigurationString + PROMPT_STR;
350 sshJcraftWrapper.send(loadConfigurationString);
351 log.debug("After sending loadConfigurationString");
352 response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 600000, "");
353 if (response.contains("rpc-error")) {
354 log.debug("Error from device: Response from device had 'rpc-error'");
355 log.debug(RESPONSE_STR, response);
356 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
357 r.message = response;
359 log.debug(":LoadConfiguration was a success, sending commit cmd");
360 sshJcraftWrapper.send(commitCmd);
361 log.debug(":After sending commitCmd");
362 response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, "");
363 handleRpcError(r, response);
365 sshJcraftWrapper.send(terminateConnectionCmd);
366 sshJcraftWrapper.closeConnection();
367 return setResponseStatus(ctx, r);
368 } catch (Exception e) {
369 log.error("Caught an Exception", e);
370 sshJcraftWrapper.closeConnection();
371 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
372 r.message = e.getMessage();
373 log.debug("Returning error message");
374 return setResponseStatus(ctx, r);
377 if (key.equals(XML_GET_RUNNING_CONF_KEY)) {
378 log.debug("key was: : xml-getrunningconfig");
379 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";
380 String hostIpAddress = parameters.get(HOST_IP_PARAM);
381 String username = parameters.get(USERNAME_PARAM);
382 String password = parameters.get(PASSWORD_PARAM);
383 password = EncryptionTool.getInstance().decrypt(password);
384 String portNumber = parameters.get(PORT_NUMBER);
385 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>";
386 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 ]]>]]>";
387 log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", username,
388 hostIpAddress, password, portNumber);
389 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
393 .connect(hostIpAddress, username, password, 30000, Integer.parseInt(portNumber),
394 "netconf"); //What about prompt "]]>]]>" here?
395 netconfHelloCmd += PROMPT_STR;
396 log.debug(":Sending the hello command");
397 sshJcraftWrapper.send(netconfHelloCmd);
399 log.debug("Sending get running config command");
400 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
401 response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, "");
402 log.debug("Response from getRunningconfigCmd={}", response);
403 response = trimResponse(response);
404 ctx.setAttribute("xmlRunningConfigOutput", response);
405 sshJcraftWrapper.send(terminateConnectionCmd);
406 sshJcraftWrapper.closeConnection();
408 return setResponseStatus(ctx, r);
409 } catch (Exception e) {
410 log.error("Caught an Exception", e);
411 sshJcraftWrapper.closeConnection();
412 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
413 r.message = e.getMessage();
414 log.debug("Returning error message");
415 return setResponseStatus(ctx, r);
418 if (key.equals(DOWNLOAD_CLI_CONFIG_KEY)) {
419 log.debug("key was: DownloadCliConfig: ");
420 String username = parameters.get(USERNAME_PARAM);
421 String hostIpAddress = parameters.get(HOST_IP_PARAM);
422 String password = parameters.get(PASSWORD_PARAM);
423 password = EncryptionTool.getInstance().decrypt(password);
424 String portNumber = parameters.get(PORT_NUMBER);
425 String downloadConfigTemplate = parameters.get("Download_config_template");
426 String configContents = parameters.get("Config_contents");
427 log.debug("Contents of the 'Config_contents' are: {}", configContents);
428 SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
429 log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
430 int timeout = 4 * 60 * 1000;
432 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name="
433 + username + " Password=" + password + " Port_number=" + portNumber);
435 StringBuilder cliResponse = new StringBuilder();
437 // shouldn't this be used somewhere?
438 StringBuilder response = new StringBuilder();
441 .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber));
442 log.debug("DownloadCliConfig: On the VNF device");
443 StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n");
444 String command = null;
445 String executeConfigContentsDelemeter;
447 while (st.hasMoreTokens()) {
448 String line = st.nextToken();
449 log.debug("line={}", line);
450 if (line.contains("Request:")) {
451 log.debug("Found a Request line: line={}", line);
452 command = getStringBetweenQuotes(line);
453 log.debug("Sending command={}", command);
454 sshJcraftWrapper.send(command);
455 log.debug("command has been sent");
456 } else if ((line.contains("Response: Ends_With")) && (
457 !line.contains("Execute_config_contents Response: Ends_With"))) {
458 log.debug("Found a Response line: line={}", line);
459 String delimiter = getStringBetweenQuotes(line);
460 log.debug("The delimiter={}", delimiter);
461 String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command);
462 response.append(tmpResponse);
463 cliResponse.append(tmpResponse);
464 } else if (line.contains("Execute_config_contents Response: Ends_With")) {
465 log.debug("Found a 'Execute_config_contents Response:' line={}", line);
466 executeConfigContentsDelemeter = getStringBetweenQuotes(line);
467 log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelemeter);
468 StringTokenizer st2 = new StringTokenizer(configContents, "\n");
469 while (st2.hasMoreTokens()) {
470 String cmd = st2.nextToken();
471 log.debug("Config_contents: cmd={}", cmd);
472 sshJcraftWrapper.send(cmd);
473 String tmpResponse = sshJcraftWrapper
474 .receiveUntil(executeConfigContentsDelemeter, timeout, command);
475 cliResponse.append(tmpResponse);
479 } catch (NoSuchElementException e) {
480 log.error(e.getMessage(), e);
482 sshJcraftWrapper.closeConnection();
483 log.debug(":Escaping all the single and double quotes in the response");
485 String escapedCliResponse = cliResponse
487 .replaceAll("\"", "\\\\\"")
488 .replaceAll("\'", "\\\\'");
490 log.debug("CliResponse=\n{}" + escapedCliResponse);
491 ctx.setAttribute(CLI_OUTPUT_PARAM, escapedCliResponse);
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 log.debug("DownloadCliConfig: Returning error message");
500 return setResponseStatus(ctx, r);
504 log.debug("Unsupported action - {}", action);
505 return ConfigStatus.FAILURE;
508 private boolean areEqual(String action, String actionPrepare) {
509 return action != null && action.equalsIgnoreCase(actionPrepare);
512 private boolean nullOrEmpty(String parmval) {
513 return parmval != null && parmval.length() > 0;
516 private void handleRpcError(HttpResponse r, String response) {
517 if (response.contains("rpc-error")) {
518 log.debug("Error from device: Response from device had 'rpc-error'");
519 log.debug(RESPONSE_STR, response);
520 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
521 r.message = response;
523 log.debug(":Looks like a success");
524 log.debug(RESPONSE_STR, response);
529 private void trySleepFor(long length) {
531 log.debug("Sleeping for 180 seconds....");
532 Thread.sleep(length);
533 log.debug("Woke up....");
534 } catch (InterruptedException ee) {
535 log.error("Sleep interrupted", ee);
536 Thread.currentThread().interrupt();
540 private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
541 String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
542 String ndTemplate = readFile(templateName);
543 String nd = buildNetworkData2(ctx, ndTemplate, operation);
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("request-type", requestType);
549 param.put("callback-url", configCallbackUrl);
550 if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
551 param.put(ACTION_PARAM, "GenerateOnly");
553 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
554 param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
555 param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
556 param.put("network-data", nd);
560 req = buildXmlRequest(param, reqTemplate);
561 } catch (Exception e) {
562 log.error("Error building the XML request: ", e);
564 HttpResponse r = new HttpResponse();
565 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
566 r.message = e.getMessage();
567 return setResponseStatus(ctx, r);
570 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
571 return setResponseStatus(ctx, r);
574 private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
575 String reqTemplate = readFile("/config-request.xml");
576 Map<String, String> param = new HashMap<String, String>();
577 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
578 param.put("callback-url", configCallbackUrl);
579 param.put(ACTION_PARAM, change ? "DownloadChange" : "DownloadBase");
580 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
584 req = buildXmlRequest(param, reqTemplate);
585 } catch (Exception e) {
586 log.error("Error building the XML request: ", e);
588 HttpResponse r = new HttpResponse();
589 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
590 r.message = e.getMessage();
591 return setResponseStatus(ctx, r);
594 HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
595 return setResponseStatus(ctx, r);
598 private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
599 String reqTemplate = readFile("/audit-request.xml");
600 Map<String, String> param = new HashMap<String, String>();
601 param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
602 param.put("callback-url", auditCallbackUrl);
603 param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
604 param.put("audit-level", auditLevel);
608 req = buildXmlRequest(param, reqTemplate);
609 } catch (Exception e) {
610 log.error("Error building the XML request: ", e);
612 HttpResponse r = new HttpResponse();
613 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
614 r.message = e.getMessage();
615 return setResponseStatus(ctx, r);
618 HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
619 return setResponseStatus(ctx, r);
623 public ConfigStatus activate(String key, SvcLogicContext ctx) {
624 return ConfigStatus.SUCCESS;
628 public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
629 return ConfigStatus.SUCCESS;
632 private String escapeMySql(String input) {
637 input = input.replace("\\", "\\\\");
638 input = input.replace("\'", "\\'");
643 private String readFile(String fileName) {
644 InputStream is = getClass().getResourceAsStream(fileName);
645 InputStreamReader isr = new InputStreamReader(is);
646 BufferedReader in = new BufferedReader(isr);
647 StringBuilder ss = new StringBuilder();
649 String s = in.readLine();
651 ss.append(s).append('\n');
654 } catch (IOException e) {
655 throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
659 } catch (Exception e) {
660 log.warn("Could not close BufferedReader", e);
664 } catch (Exception e) {
665 log.warn("Could not close InputStreamReader", e);
669 } catch (Exception e) {
670 log.warn("Could not close InputStream", e);
673 return ss.toString();
676 private String buildXmlRequest(Map<String, String> param, String template) {
677 StringBuilder ss = new StringBuilder();
679 while (i < template.length()) {
680 int i1 = template.indexOf("${", i);
682 ss.append(template.substring(i));
686 int i2 = template.indexOf('}', i1 + 2);
688 throw new RuntimeException("Template error: Matching } not found");
691 String var1 = template.substring(i1 + 2, i2);
692 String value1 = param.get(var1);
693 if (value1 == null || value1.trim().length() == 0) {
694 // delete the whole element (line)
695 int i3 = template.lastIndexOf('\n', i1);
699 int i4 = template.indexOf('\n', i1);
701 i4 = template.length();
705 ss.append(template.substring(i, i3));
709 ss.append(template.substring(i, i1)).append(value1);
714 return ss.toString();
717 private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
718 log.info("Building XML started");
719 long t1 = System.currentTimeMillis();
721 template = expandRepeats(ctx, template, 1);
723 Map<String, String> mm = new HashMap<>();
724 for (String s : ctx.getAttributeKeySet()) {
725 mm.put(s, ctx.getAttribute(s));
727 mm.put("operation", operation);
729 StringBuilder ss = new StringBuilder();
731 while (i < template.length()) {
732 int i1 = template.indexOf("${", i);
734 ss.append(template.substring(i));
738 int i2 = template.indexOf('}', i1 + 2);
740 throw new RuntimeException("Template error: Matching } not found");
743 String var1 = template.substring(i1 + 2, i2);
744 String value1 = XmlUtil.getXml(mm, var1);
745 if (value1 == null || value1.trim().length() == 0) {
746 int i3 = template.lastIndexOf('\n', i1);
750 int i4 = template.indexOf('\n', i1);
752 i4 = template.length();
756 ss.append(template.substring(i, i3));
760 ss.append(template.substring(i, i1)).append(value1);
765 long t2 = System.currentTimeMillis();
766 log.info("Building XML completed. Time: " + (t2 - t1));
768 return ss.toString();
771 private String expandRepeats(SvcLogicContext ctx, String template, int level) {
772 StringBuilder newTemplate = new StringBuilder();
774 while (k < template.length()) {
775 int i1 = template.indexOf("${repeat:", k);
777 newTemplate.append(template.substring(k));
781 int i2 = template.indexOf(':', i1 + 9);
783 throw new RuntimeException(
784 "Template error: Context variable name followed by : is required after repeat");
787 // Find the closing }, store in i3
791 while (nn > 0 && i < template.length()) {
792 i3 = template.indexOf('}', i);
794 throw new RuntimeException("Template error: Matching } not found");
796 int i32 = template.indexOf('{', i);
797 if (i32 >= 0 && i32 < i3) {
806 String var1 = template.substring(i1 + 9, i2);
807 String value1 = ctx.getAttribute(var1);
808 log.info(" " + var1 + ": " + value1);
811 n = Integer.parseInt(value1);
812 } catch (Exception e) {
816 newTemplate.append(template.substring(k, i1));
818 String rpt = template.substring(i2 + 1, i3);
820 for (int ii = 0; ii < n; ii++) {
821 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
822 newTemplate.append(ss);
829 return newTemplate.toString();
832 return expandRepeats(ctx, newTemplate.toString(), level + 1);
835 private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
837 Client client = Client.create();
838 client.setConnectTimeout(5000);
839 WebResource webResource = client.resource(url);
841 log.info("SENDING...............");
842 log.info(xmlRequest);
844 String authString = user + ":" + password;
845 byte[] authEncBytes = Base64.encode(authString);
846 String authStringEnc = new String(authEncBytes);
847 authString = "Basic " + authStringEnc;
849 ClientResponse response =
850 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
851 ClientResponse.class, xmlRequest);
853 int code = response.getStatus();
854 String message = null;
856 log.info("RESPONSE...............");
857 log.info("HTTP response code: " + code);
858 log.info("HTTP response message: " + message);
861 HttpResponse r = new HttpResponse();
866 } catch (Exception e) {
867 log.error("Error sending the request: ", e);
869 HttpResponse r = new HttpResponse();
870 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
871 r.message = e.getMessage();
876 private static class HttpResponse {
879 public String message;
882 private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
883 ctx.setAttribute("error-code", String.valueOf(r.code));
884 ctx.setAttribute("error-message", r.message);
886 return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
889 private String getStringBetweenQuotes(String string) {
890 log.debug("string=" + string);
892 int start = string.indexOf('\"');
893 int end = string.lastIndexOf('\"');
894 retString = string.substring(start + 1, end);
895 log.debug("retString=" + retString);
899 public static String _readFile(String fileName) {
900 StringBuffer strBuff = new StringBuffer();
903 BufferedReader in = new BufferedReader(new FileReader(fileName));
904 while ((line = in.readLine()) != null) {
905 strBuff.append(line + "\n");
908 } catch (IOException e) {
909 log.error("Caught an IOException in method readFile()", e);
911 return (strBuff.toString());
914 private String trimResponse(String response) {
915 StringTokenizer line = new StringTokenizer(response, "\n");
916 StringBuffer sb = new StringBuffer();
917 boolean captureText = false;
918 while (line.hasMoreTokens()) {
919 String token = line.nextToken();
920 if (token.indexOf("<configuration xmlns=") != -1) {
924 sb.append(token + "\n");
926 if (token.indexOf("</configuration>") != -1) {
930 return (sb.toString());
933 public static void main(String args[]) throws Exception {
934 Properties props = null;
935 System.out.println("*************************Hello*****************************");
936 ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
937 String Get_config_template = _readFile("/home/userID/data/Get_config_template");
938 String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
939 String key = "GetCliRunningConfig";
940 Map<String, String> parameters = new HashMap();
941 parameters.put("Host_ip_address", "000.00.000.00");
942 parameters.put("User_name", "root");
943 parameters.put("Password", "!bootstrap");
944 parameters.put("Port_number", "22");
945 parameters.put("Get_config_template", Get_config_template);
946 SvcLogicContext ctx = null;
947 System.out.println("*************************TRACE 1*****************************");
948 cca.configure(key, parameters, ctx);