X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=appc-config%2Fappc-config-adaptor%2Fprovider%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fappc%2Fccadaptor%2FConfigComponentAdaptor.java;h=1928687971eaa44a7373953fd978015d1f7de42a;hb=refs%2Fheads%2Fmaster;hp=415642521133fbb602adc49cb19767f3d2bee597;hpb=f78405fa2d752fe29b1f86e527d741b75b388fcb;p=appc.git diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java index 415642521..192868797 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java @@ -2,7 +2,11 @@ * ============LICENSE_START======================================================= * ONAP : APPC * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ============================================================================= + * Modifications Copyright (C) 2018-2019 IBM. + * ============================================================================= + * Modifications Copyright (C) 2018-2019 Ericsson * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,87 +20,103 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. * ============LICENSE_END========================================================= */ package org.onap.appc.ccadaptor; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.Base64; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.UncheckedIOException; +import java.io.StringReader; +import java.io.StringWriter; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.Map; -import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.StringTokenizer; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import org.onap.appc.exceptions.APPCException; import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.glassfish.jersey.oauth1.signature.Base64; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; public class ConfigComponentAdaptor implements SvcLogicAdaptor { - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); - - private static final String ACTION_PARAM = "action"; - private static final String ACTION_PREPARE = "prepare"; - private static final String ACTION_ACTIVATE = "activate"; - - private static final String KEY_PUT = "put"; - private static final String KEY_GET = "get"; - private static final String KEY_CLI = "cli"; - private static final String KEY_ESCAPE_SQL = "escapeSql"; - private static final String KEY_XML_DOWNLOAD = "xml-download"; - private static final String KEY_XML_GET_RUNNING_CONF = "xml-getrunningconfig"; - private static final String KEY_DOWNLOAD_CLI_CONFIG = "DownloadCliConfig"; - private static final String KEY_GET_CLI_RUNNING_CONFIG = "GetCliRunningConfig"; - - private static final String OPERATION_CREATE = "create"; - private static final String OPERATION_CHANGE = "change"; - private static final String OPERATION_SCALE = "scale"; - - static final String USERNAME_PARAM = "User_name"; - static final String PASSWORD_PARAM = "Password"; - static final String HOST_IP_PARAM = "Host_ip_address"; - static final String PORT_NUMBER_PARAM = "Port_number"; - static final String GET_CONFIG_TEMPLATE_PARAM = "Get_config_template"; - - private static final String CLI_OUTPUT_PARAM = "cliOutput"; - private static final String REQUEST_ID_PARAM = "request-id"; - private static final String CALLBACK_URL_PARAM = "callback-url"; - private static final String EQUIPMENT_NAME_PARAM = "equipment-name"; - - private static final String XML_BUILDING_ERR_STR = "Error building the XML request: "; - private static final String TEMPLATE_ERR_STR = "Template error: Matching \"}\" not found"; - private static final String SSH_JCRAFT_WRAPPER_ERR_STR = "Exception occurred while using sshJcraftWrapper"; - private static final String PROMPT_STR = "]]>]]>"; - private static final String RESPONSE_STR = "response=\n{}\n"; - - private static final String SERVICE_INSTANCE_ID_ATTR = "service-data.service-information.service-instance-id"; - private static final String SVC_REQUEST_ID_ATTR = "service-data.appc-request-header.svc-request-id"; - - private static final String RPC_REPLY_END_TAG = ""; - private static final String BASE_REQUEST = "BASE"; - - private String configUrl; - private String configUser; - private String configPassword; - private String auditUrl; - private String auditUser; - private String auditPassword; - private String configCallbackUrl; - private String auditCallbackUrl; + private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); + DebugLog debugLog = new DebugLog(); + private String configUrl = null; + private String configUser = null; + private String configPassword = null; + private String auditUrl = null; + private String auditUser = null; + private String auditPassword = null; + + public String getConfigUrl() { + return configUrl; + } + + public String getConfigUser() { + return configUser; + } + + public String getConfigPassword() { + return configPassword; + } + + public String getAuditUrl() { + return auditUrl; + } + + public String getAuditUser() { + return auditUser; + } + + public String getAuditPassword() { + return auditPassword; + } + + public String getConfigCallbackUrl() { + return configCallbackUrl; + } + + public String getAuditCallbackUrl() { + return auditCallbackUrl; + } + + private String configCallbackUrl = null; + private String auditCallbackUrl = null; + private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ; public ConfigComponentAdaptor(Properties props) { if (props != null) { @@ -108,62 +128,74 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { auditPassword = props.getProperty("auditComponent.passwd", ""); configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); + } else { + configUrl = ""; + configUser = ""; + configPassword = ""; + auditUrl = ""; + auditUser = ""; + auditPassword = ""; + configCallbackUrl = ""; + auditCallbackUrl = ""; } } @Override public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) { + String fnName = "ConfigComponentAdaptor.configure"; HttpResponse r = new HttpResponse(); r.code = 200; log.debug("ConfigComponentAdaptor.configure - key = " + key); - log.debug("key = {}", key); + DebugLog.printRTAriDebug(fnName, "key = " + key); log.debug("Parameters:"); - for (Entry paramEntrySet : parameters.entrySet()) { - log.debug(" {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue()); + DebugLog.printRTAriDebug(fnName, "Parameters:"); + for (Map.Entry entry : parameters.entrySet()) { + log.debug(" " + entry.getKey() + " = " + entry.getValue()); + DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue()); } String parmval = parameters.get("config-component-configUrl"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting URL with {}", parmval); + if ((parmval != null) && (parmval.length() > 0)) { + log.debug("Overwriting URL with " + parmval); configUrl = parmval; } parmval = parameters.get("config-component-configPassword"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting configPassword with {}", parmval); + if ((parmval != null) && (parmval.length() > 0)) { + //log.debug("Overwriting configPassword with " + parmval); configPassword = parmval; } parmval = parameters.get("config-component-configUser"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting configUser id with {}", parmval); + if ((parmval != null) && (parmval.length() > 0)) { + log.debug("Overwriting configUser id with " + parmval); configUser = parmval; } - String action = parameters.get(ACTION_PARAM); + String action = parameters.get("action"); String chg = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); - if (chg != null && areEqual(action, ACTION_PREPARE)) { - return prepare(ctx, "CHANGE", OPERATION_CHANGE); + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); + if (chg != null && "prepare".equalsIgnoreCase(action)) { + return prepare(ctx, "CHANGE", "change"); } - if (chg != null && areEqual(action, ACTION_ACTIVATE)) { + if (chg != null && "activate".equalsIgnoreCase(action)) { return activate(ctx, true); } String scale = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); - if (scale != null && areEqual(action, ACTION_PREPARE)) { - return prepare(ctx, "CHANGE", OPERATION_SCALE); + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); + if (scale != null && "prepare".equalsIgnoreCase(action)) { + return prepare(ctx, "CHANGE", "scale"); } - if (scale != null && areEqual(action, ACTION_ACTIVATE)) { + if (scale != null && "activate".equalsIgnoreCase(action)) { return activate(ctx, true); } - if (areEqual(action, ACTION_PREPARE)) { - return prepare(ctx, BASE_REQUEST, OPERATION_CREATE); + if ("prepare".equalsIgnoreCase(action)) { + return prepare(ctx, "BASE", "create"); } - if (areEqual(action, ACTION_ACTIVATE)) { + if ("activate".equalsIgnoreCase(action)) { return activate(ctx, false); } @@ -183,404 +215,444 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return audit(ctx, "RUNNING"); } - if ((key.equals(KEY_PUT)) || (key.equals(KEY_GET))) { + if (("put".equals(key)) || ("get".equals(key))) { String loginId = parameters.get("loginId"); String host = parameters.get("host"); String password = parameters.get("password"); password = EncryptionTool.getInstance().decrypt(password); String fullPathFileName = parameters.get("fullPathFileName"); + String data = null; - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("SCP: SshJcraftWrapper has been instantiated"); - + DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); try { - if (key.equals(KEY_PUT)) { - String data = parameters.get("data"); - log.debug("Command is for put: Length of data is: {}", data.length()); - InputStream is = new ByteArrayInputStream(data.getBytes()); - log.debug("SCP: Doing a put: fullPathFileName={}", fullPathFileName); - sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); - trySleepFor(1000L * 180); - } else { // Must be a get - log.debug("SCP: Doing a get: fullPathFileName={}", fullPathFileName); + if (key.equals("put")) { + data = parameters.get("data"); + if (data != null) { + DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length()); + InputStream is = new ByteArrayInputStream(data.getBytes()); + log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); + DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); + sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); + try { + DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); + Thread.sleep(1000l * 180); + DebugLog.printRTAriDebug(fnName, "Woke up...."); + } catch (java.lang.InterruptedException ee) { + boolean ignore = true; + Thread.currentThread().interrupt(); + } + } else { + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + log.debug(fnName + " Command is for put: data is null"); + } + } else // Must be a get + { + log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName); + DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password); - log.debug("Got the response and putting into the ctx object"); + DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); ctx.setAttribute("fileContents", response); log.debug("SCP: Closing the SFTP connection"); } - return setResponseStatus(ctx, r); + return (setResponseStatus(ctx, r)); } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); + log.debug(fnName + " : Caught a IOException e=" + e); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - return setResponseStatus(ctx, r); + return (setResponseStatus(ctx, r)); } } - if (key.equals(KEY_CLI)) { + if (key.equals("cli")) { String loginId = parameters.get("loginId"); String host = parameters.get("host"); String password = parameters.get("password"); password = EncryptionTool.getInstance().decrypt(password); String portNumber = parameters.get("portNumber"); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { - log.debug("CLI: Attempting to login: host={} loginId={} password={} portNumber={}", host, loginId, - password, portNumber); - sshJcraftWrapper.connect(host, loginId, password); //what about portNum? - - log.debug("Sending 'sdc'"); - sshJcraftWrapper.send("sdc", ":"); - log.debug("Sending 1"); - sshJcraftWrapper.send("1", ":"); - log.debug("Sending 1, the second time"); - sshJcraftWrapper.send("1", "#"); - log.debug("Sending paging-options disable"); - sshJcraftWrapper.send("paging-options disable", "#"); - log.debug("Sending show config"); - String response = sshJcraftWrapper.send("show config", "#"); - - log.debug("response is now:'{}'", response); - log.debug("Populating the ctx object with the response"); - ctx.setAttribute(CLI_OUTPUT_PARAM, response); + log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + + " portNumber=" + portNumber); + DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + + " portNumber=" + portNumber); + sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber)); + + DebugLog.printAriDebug(fnName, "Sending 'sdc'"); + String response = sshJcraftWrapper.send("sdc", ":"); + DebugLog.printAriDebug(fnName, "Sending 1"); + response = sshJcraftWrapper.send("1", ":"); + DebugLog.printAriDebug(fnName, "Sending 1, the second time"); + response = sshJcraftWrapper.send("1", "#"); + DebugLog.printAriDebug(fnName, "Sending paging-options disable"); + response = sshJcraftWrapper.send("paging-options disable", "#"); + DebugLog.printAriDebug(fnName, "Sending show config"); + response = sshJcraftWrapper.send("show config", "#"); + + DebugLog.printAriDebug(fnName, "response is now:'" + response + "'"); + DebugLog.printAriDebug(fnName, "Populating the ctx object with the response"); + ctx.setAttribute("cliOutput", response); sshJcraftWrapper.closeConnection(); r.code = 200; - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); + log.debug(fnName + " : Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); } } - if (key.equals(KEY_ESCAPE_SQL)) { + if (key.equals("escapeSql")) { String data = parameters.get("artifactContents"); log.debug("ConfigComponentAdaptor.configure - escapeSql"); data = escapeMySql(data); ctx.setAttribute("escapedData", data); - return setResponseStatus(ctx, r); + return (setResponseStatus(ctx, r)); } - if (key.equals(KEY_GET_CLI_RUNNING_CONFIG)) { - log.debug("key was: " + KEY_GET_CLI_RUNNING_CONFIG); - String username = parameters.get(USERNAME_PARAM); - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String password = parameters.get(PASSWORD_PARAM); + if (key.equals("GetCliRunningConfig")) { + DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: "); + log.debug("key was: GetCliRunningConfig: "); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - String getConfigTemplate = parameters.get(GET_CONFIG_TEMPLATE_PARAM); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + String portNumber = parameters.get("Port_number"); + String getConfigTemplate = parameters.get("Get_config_template"); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); + DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); try { - log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name=" - + username + " Password=" + password + " Port_number=" + portNumber); - + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + userName + + " Host_ip_address=" + hostIpAddress + " Port_number=" + + portNumber); + log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + + " User_name=" + userName + " Port_number=" + portNumber); + String response = ""; + String CliResponse = ""; boolean showConfigFlag = false; - sshJcraftWrapper - .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber)); - log.debug("GetCliRunningConfig: On the VNF device"); + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "", + 30000, + Integer.parseInt(portNumber)); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n"); String command = null; - - StringBuilder cliResponse = new StringBuilder(); - - // shouldn't this be used somewhere? - StringBuilder response = new StringBuilder(); - try { while (st.hasMoreTokens()) { String line = st.nextToken(); - log.debug("line={}", line); - if (line.contains("Request:")) { - log.debug("Found a Request line: line={}", line); + DebugLog.printAriDebug(fnName, "line=" + line); + if (line.indexOf("Request:") != -1) { + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); command = getStringBetweenQuotes(line); - log.debug("Sending command={}", command); + DebugLog.printAriDebug(fnName, "Sending command=" + command); sshJcraftWrapper.send(command); - log.debug("command has been sent"); - if (line.contains("show config")) { + DebugLog.printAriDebug(fnName, "command has been sent"); + if (line.indexOf("show config") != -1) { showConfigFlag = true; + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true"); log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true"); } } - if (line.contains("Response: Ends_With")) { - log.debug("Found a Response line: line={}", line); + if (line.indexOf("Response: Ends_With") != -1) { + DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line); String delemeter = getStringBetweenQuotes(line); - log.debug("The delemeter={}", delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command); - response.append(tmpResponse); + DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter); + //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806 + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, + DEFAULT_TIMEOUT_GETRUNNING_CLI, command); + response += tmpResponse; if (showConfigFlag) { showConfigFlag = false; StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n"); + // Strip off the last line which is the command prompt from the VNF device. while (st2.hasMoreTokens()) { String line2 = st2.nextToken(); - if (!line2.contains("#")) { - cliResponse.append(line2).append('\n'); + if (line2.indexOf('#') == -1) { + CliResponse += line2 + "\n"; } } } } } } catch (NoSuchElementException e) { - log.error(e.getMessage(), e); + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } - log.debug("CliResponse=\n{}", cliResponse.toString()); - ctx.setAttribute(CLI_OUTPUT_PARAM, cliResponse.toString()); + DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse); + ctx.setAttribute("cliOutput", CliResponse); sshJcraftWrapper.closeConnection(); r.code = 200; - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e); + log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message"); + return (setResponseStatus(ctx, r)); } } - if (key.equals(KEY_XML_DOWNLOAD)) { - log.debug("key was: " + KEY_XML_DOWNLOAD); - String userName = parameters.get(USERNAME_PARAM); - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String password = parameters.get(PASSWORD_PARAM); + if (key.equals("xml-download")) { + log(fnName, "key was: xml-download"); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - String contents = parameters.get("Contents"); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - String commitCmd = "\n \n ]]>]]>"; - - log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", userName, - hostIpAddress, password, portNumber); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + String portNumber = parameters.get("Port_number"); + String Contents = parameters.get("Contents"); + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + String commitCmd = "\n \n ]]>]]>"; + + log(fnName, + "xml-download: User_name=" + userName + " Host_ip_address=" + hostIpAddress + + " Port_number=" + portNumber); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { - // what about prompt "]]>]]>"? - sshJcraftWrapper - .connect(hostIpAddress, userName, password, 30000, Integer.parseInt(portNumber), "netconf"); - - netconfHelloCmd += PROMPT_STR; - log.debug("Sending the hello command"); - sshJcraftWrapper.send(netconfHelloCmd); - String response; - log.debug("Sending xmlCmd cmd"); + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "]]>]]>", + 30000, + Integer.parseInt(portNumber), + "netconf"); + String NetconfHelloCmd = netconfHelloCmd; + NetconfHelloCmd = NetconfHelloCmd + "]]>]]>"; + log(fnName, "Sending the hello command"); + sshJcraftWrapper.send(NetconfHelloCmd); + String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); + log(fnName, "Sending xmlCmd cmd"); + String xmlCmd = Contents; String messageId = "1"; messageId = "\"" + messageId + "\""; String loadConfigurationString = - " merge " - + contents + " "; - loadConfigurationString = loadConfigurationString + PROMPT_STR; + " merge " + + xmlCmd + " "; + loadConfigurationString = loadConfigurationString + "]]>]]>"; sshJcraftWrapper.send(loadConfigurationString); - log.debug("After sending loadConfigurationString"); - response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 600000, ""); - if (response.contains("rpc-error")) { - log.debug("Error from device: Response from device had 'rpc-error'"); - log.debug(RESPONSE_STR, response); + DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString"); + response = sshJcraftWrapper.receiveUntil("", 600000, ""); + if (response.indexOf("rpc-error") != -1) { + DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = response; } else { - log.debug(":LoadConfiguration was a success, sending commit cmd"); + DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd"); sshJcraftWrapper.send(commitCmd); - log.debug(":After sending commitCmd"); - response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, ""); - handleRpcError(r, response); + DebugLog.printAriDebug(fnName, ":After sending commitCmd"); + response = sshJcraftWrapper.receiveUntil("", 180000, ""); + if (response.indexOf("rpc-error") != -1) { + DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = response; + } else { + DebugLog.printAriDebug(fnName, ":Looks like a success"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); + r.code = 200; + } } sshJcraftWrapper.send(terminateConnectionCmd); sshJcraftWrapper.closeConnection(); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); } catch (Exception e) { - log.error("Caught an Exception", e); + log(fnName, "Caught an Exception, e=" + e); + log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e)); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - log.debug("Returning error message"); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + log(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); } } - if (key.equals(KEY_XML_GET_RUNNING_CONF)) { - log.debug("key was: : xml-getrunningconfig"); - String xmlGetRunningConfigCmd = " \n"; - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String username = parameters.get(USERNAME_PARAM); - String password = parameters.get(PASSWORD_PARAM); + if (key.equals("xml-getrunningconfig")) { + log(fnName, "key was: : xml-getrunningconfig"); + String xmlGetRunningConfigCmd = " \n"; + String hostIpAddress = parameters.get("Host_ip_address"); + String userName = parameters.get("User_name"); + String password = parameters.get("Password"); password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", username, - hostIpAddress, password, portNumber); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + String portNumber = parameters.get("Port_number"); + String Protocol = parameters.get("Protocol"); + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + log(fnName, + "xml-getrunningconfig: User_name=" + userName + " Host_ip_address=" + hostIpAddress + + " Port_number=" + portNumber); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { - - sshJcraftWrapper - .connect(hostIpAddress, username, password, 30000, Integer.parseInt(portNumber), - "netconf"); //What about prompt "]]>]]>" here? - netconfHelloCmd += PROMPT_STR; - log.debug(":Sending the hello command"); - sshJcraftWrapper.send(netconfHelloCmd); - String response; - log.debug("Sending get running config command"); + String NetconfHelloCmd = netconfHelloCmd; + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "]]>]]>", + 30000, + Integer.parseInt(portNumber), + "netconf"); + NetconfHelloCmd = NetconfHelloCmd + "]]>]]>"; + log(fnName, ":Sending the hello command"); + sshJcraftWrapper.send(NetconfHelloCmd); + String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); + log(fnName, "Sending get running config command"); sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n"); - response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, ""); - log.debug("Response from getRunningconfigCmd={}", response); + response = sshJcraftWrapper.receiveUntil("", 180000, ""); + DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response); response = trimResponse(response); ctx.setAttribute("xmlRunningConfigOutput", response); sshJcraftWrapper.send(terminateConnectionCmd); sshJcraftWrapper.closeConnection(); r.code = 200; - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); } catch (Exception e) { - log.error("Caught an Exception", e); + log(fnName, "Caught an Exception, e=" + e); + log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e)); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - log.debug("Returning error message"); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + log(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); } } - if (key.equals(KEY_DOWNLOAD_CLI_CONFIG)) { + if (key.equals("DownloadCliConfig")) { + DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: "); log.debug("key was: DownloadCliConfig: "); - String username = parameters.get(USERNAME_PARAM); - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String password = parameters.get(PASSWORD_PARAM); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); + String portNumber = parameters.get("Port_number"); String downloadConfigTemplate = parameters.get("Download_config_template"); - String configContents = parameters.get("Config_contents"); - log.debug("Contents of the 'Config_contents' are: {}", configContents); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + String Config_contents = parameters.get("Config_contents"); + DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); + DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); int timeout = 4 * 60 * 1000; try { - log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name=" - + username + " Password=" + password + " Port_number=" + portNumber); - - StringBuilder cliResponse = new StringBuilder(); - - // shouldn't this be used somewhere? - StringBuilder response = new StringBuilder(); - - sshJcraftWrapper - .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber)); - log.debug("DownloadCliConfig: On the VNF device"); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + userName + + " Host_ip_address=" + hostIpAddress + " Port_number=" + + portNumber); + log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress + + " User_name=" + userName + " Port_number=" + portNumber); + String CliResponse = ""; + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "", + 30000, + Integer.parseInt(portNumber)); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device"); StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n"); String command = null; - String executeConfigContentsDelimiter; + String executeConfigContentsDelemeter = null; try { while (st.hasMoreTokens()) { String line = st.nextToken(); - log.debug("line={}", line); - if (line.contains("Request:")) { - log.debug("Found a Request line: line={}", line); + DebugLog.printAriDebug(fnName, "line=" + line); + if (line.indexOf("Request:") != -1) { + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); command = getStringBetweenQuotes(line); - log.debug("Sending command={}", command); + DebugLog.printAriDebug(fnName, "Sending command=" + command); sshJcraftWrapper.send(command); - log.debug("command has been sent"); - } else if ((line.contains("Response: Ends_With")) && ( - !line.contains("Execute_config_contents Response: Ends_With"))) { - log.debug("Found a Response line: line={}", line); - String delimiter = getStringBetweenQuotes(line); - log.debug("The delimiter={}", delimiter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delimiter, timeout, command); - response.append(tmpResponse); - cliResponse.append(tmpResponse); - } else if (line.contains("Execute_config_contents Response: Ends_With")) { - log.debug("Found a 'Execute_config_contents Response:' line={}", line); - executeConfigContentsDelimiter = getStringBetweenQuotes(line); - log.debug("executeConfigContentsDelemeter={}", executeConfigContentsDelimiter); - StringTokenizer st2 = new StringTokenizer(configContents, "\n"); + DebugLog.printAriDebug(fnName, "command has been sent"); + } else if ((line.indexOf("Response: Ends_With") != -1) && ( + line.indexOf("Execute_config_contents Response: Ends_With") == -1)) { + DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line); + String delemeter = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter); + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command); + CliResponse += tmpResponse; + } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) { + DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line); + executeConfigContentsDelemeter = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, + "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter); + StringTokenizer st2 = new StringTokenizer(Config_contents, "\n"); while (st2.hasMoreTokens()) { String cmd = st2.nextToken(); - log.debug("Config_contents: cmd={}", cmd); + DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd); sshJcraftWrapper.send(cmd); - String tmpResponse = sshJcraftWrapper - .receiveUntil(executeConfigContentsDelimiter, timeout, command); - cliResponse.append(tmpResponse); + String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, + timeout, + command); + CliResponse += tmpResponse; } } } } catch (NoSuchElementException e) { - log.error(e.getMessage(), e); + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } sshJcraftWrapper.closeConnection(); - log.debug(":Escaping all the single and double quotes in the response"); - - String escapedCliResponse = cliResponse - .toString() - .replaceAll("\"", "\\\\\"") - .replaceAll("\'", "\\\\'"); - - log.debug("CliResponse=\n{}" + escapedCliResponse); - ctx.setAttribute(CLI_OUTPUT_PARAM, escapedCliResponse); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response"); + CliResponse = CliResponse.replaceAll("\"", "\\\\\""); + CliResponse = CliResponse.replaceAll("\'", "\\\\'"); + DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse); + ctx.setAttribute("cliOutput", CliResponse); r.code = 200; - return setResponseStatus(ctx, r); + return (setResponseStatus(ctx, r)); } catch (IOException e) { - log.error(e.getMessage() + e); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e); + log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - log.debug("DownloadCliConfig: Returning error message"); - return setResponseStatus(ctx, r); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message"); + return (setResponseStatus(ctx, r)); } } - log.debug("Unsupported action - {}", action); - return ConfigStatus.FAILURE; - } - - private boolean areEqual(String action, String actionPrepare) { - return action != null && action.equalsIgnoreCase(actionPrepare); - } - private boolean nullOrEmpty(String parmval) { - return parmval != null && parmval.length() > 0; - } - - private void handleRpcError(HttpResponse r, String response) { - if (response.contains("rpc-error")) { - log.debug("Error from device: Response from device had 'rpc-error'"); - log.debug(RESPONSE_STR, response); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = response; - } else { - log.debug(":Looks like a success"); - log.debug(RESPONSE_STR, response); - r.code = 200; - } + DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action); + log.error("Unsupported action - " + action); + return ConfigStatus.FAILURE; } - private void trySleepFor(long length) { - try { - log.debug("Sleeping for 180 seconds...."); - Thread.sleep(length); - log.debug("Woke up...."); - } catch (InterruptedException ee) { - log.error("Sleep interrupted", ee); - Thread.currentThread().interrupt(); - } + private void log(String fileName, String messg) { + DebugLog.printRTAriDebug(fileName, messg); + log.debug(fileName + ": " + messg); } private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) { - String templateName = requestType.equals(BASE_REQUEST) ? "/config-base.xml" : "/config-data.xml"; - String ndTemplate = expandRepeats(ctx, readFile(templateName), 1); + String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml"; + String ndTemplate = readFile(templateName); String nd = buildNetworkData2(ctx, ndTemplate, operation); String reqTemplate = readFile("/config-request.xml"); Map param = new HashMap<>(); - param.put(REQUEST_ID_PARAM, ctx.getAttribute(SVC_REQUEST_ID_ATTR)); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); param.put("request-type", requestType); - param.put(CALLBACK_URL_PARAM, configCallbackUrl); - if (operation.equals(OPERATION_CREATE) || operation.equals(OPERATION_CHANGE) - || operation.equals(OPERATION_SCALE)) { - param.put(ACTION_PARAM, "GenerateOnly"); + param.put("callback-url", configCallbackUrl); + if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) { + param.put("action", "GenerateOnly"); } - param.put(EQUIPMENT_NAME_PARAM, ctx.getAttribute(SERVICE_INSTANCE_ID_ATTR)); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address")); param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor")); param.put("network-data", nd); - String req; + String req = null; try { req = buildXmlRequest(param, reqTemplate); } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); + log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; @@ -595,16 +667,16 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private ConfigStatus activate(SvcLogicContext ctx, boolean change) { String reqTemplate = readFile("/config-request.xml"); Map param = new HashMap<>(); - param.put(REQUEST_ID_PARAM, ctx.getAttribute(SVC_REQUEST_ID_ATTR)); - param.put(CALLBACK_URL_PARAM, configCallbackUrl); - param.put(ACTION_PARAM, change ? "DownloadChange" : "DownloadBase"); - param.put(EQUIPMENT_NAME_PARAM, ctx.getAttribute(SERVICE_INSTANCE_ID_ATTR)); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("callback-url", configCallbackUrl); + param.put("action", change ? "DownloadChange" : "DownloadBase"); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); - String req; + String req = null; try { req = buildXmlRequest(param, reqTemplate); } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); + log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; @@ -619,16 +691,16 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) { String reqTemplate = readFile("/audit-request.xml"); Map param = new HashMap<>(); - param.put(REQUEST_ID_PARAM, ctx.getAttribute(SVC_REQUEST_ID_ATTR)); - param.put(CALLBACK_URL_PARAM, auditCallbackUrl); - param.put(EQUIPMENT_NAME_PARAM, ctx.getAttribute(SERVICE_INSTANCE_ID_ATTR)); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("callback-url", auditCallbackUrl); + param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); param.put("audit-level", auditLevel); - String req; + String req = null; try { req = buildXmlRequest(param, reqTemplate); } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); + log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; @@ -655,24 +727,26 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return null; } - return input - .replace("\\", "\\\\") - .replace("\'", "\\'"); + input = input.replace("\\", "\\\\"); + input = input.replace("\'", "\\'"); + + return input; } - private String readFile(String fileName) { + protected String readFile(String fileName) { InputStream is = getClass().getResourceAsStream(fileName); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); - StringBuilder builder = new StringBuilder(); + StringBuilder ss = new StringBuilder(); try { String s = in.readLine(); while (s != null) { - builder.append(s).append('\n'); + ss.append(s).append('\n'); s = in.readLine(); } } catch (IOException e) { - throw new UncheckedIOException("Error reading " + fileName, e); + System.out.println("Error reading " + fileName + ": " + e.getMessage()); + throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e); } finally { try { in.close(); @@ -690,7 +764,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { log.warn("Could not close InputStream", e); } } - return builder.toString(); + return ss.toString(); } private String buildXmlRequest(Map param, String template) { @@ -705,12 +779,12 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { int i2 = template.indexOf('}', i1 + 2); if (i2 < 0) { - throw new TemplateException(TEMPLATE_ERR_STR); + throw new RuntimeException("Template error: Matching } not found"); } String var1 = template.substring(i1 + 2, i2); String value1 = param.get(var1); - if (emptyOrNull(value1)) { + if (value1 == null || value1.trim().length() == 0) { // delete the whole element (line) int i3 = template.lastIndexOf('\n', i1); if (i3 < 0) { @@ -738,6 +812,8 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { log.info("Building XML started"); long t1 = System.currentTimeMillis(); + template = expandRepeats(ctx, template, 1); + Map mm = new HashMap<>(); for (String s : ctx.getAttributeKeySet()) { mm.put(s, ctx.getAttribute(s)); @@ -755,12 +831,13 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { int i2 = template.indexOf('}', i1 + 2); if (i2 < 0) { - throw new TemplateException(TEMPLATE_ERR_STR); + throw new RuntimeException("Template error: Matching } not found"); } String var1 = template.substring(i1 + 2, i2); String value1 = XmlUtil.getXml(mm, var1); - if (emptyOrNull(value1)) { + if (value1 == null || value1.trim().length() == 0) { + // delete the whole element (line) int i3 = template.lastIndexOf('\n', i1); if (i3 < 0) { i3 = 0; @@ -786,10 +863,6 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return ss.toString(); } - private boolean emptyOrNull(String value1) { - return value1 == null || value1.trim().length() == 0; - } - private String expandRepeats(SvcLogicContext ctx, String template, int level) { StringBuilder newTemplate = new StringBuilder(); int k = 0; @@ -802,17 +875,38 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { int i2 = template.indexOf(':', i1 + 9); if (i2 < 0) { - throw new TemplateException( - "Template error: Context variable name followed by \":\" is required after repeat"); + throw new RuntimeException( + "Template error: Context variable name followed by : is required after repeat"); } - // Find the closing "}", store in i3 - int i3 = findLastBracketIndex(template, i2); + // Find the closing }, store in i3 + int nn = 1; + int i3 = -1; + int i = i2; + while (nn > 0 && i < template.length()) { + i3 = template.indexOf('}', i); + if (i3 < 0) { + throw new RuntimeException("Template error: Matching } not found"); + } + int i32 = template.indexOf('{', i); + if (i32 >= 0 && i32 < i3) { + nn++; + i = i32 + 1; + } else { + nn--; + i = i3 + 1; + } + } String var1 = template.substring(i1 + 9, i2); String value1 = ctx.getAttribute(var1); - log.info(" " + var1 + ": " + value1); - int n = tryParseValue(value1); + log.info(" " + var1 + ": " + value1); + int n = 0; + try { + n = Integer.parseInt(value1); + } catch (Exception e) { + n = 0; + } newTemplate.append(template.substring(k, i1)); @@ -822,68 +916,44 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); newTemplate.append(ss); } + k = i3 + 1; } if (k == 0) { return newTemplate.toString(); } - return expandRepeats(ctx, newTemplate.toString(), level + 1); - } - private int findLastBracketIndex(String template, int i2) { - int i3 = -1; - int i = i2; - int nn = 1; - while (nn > 0 && i < template.length()) { - i3 = template.indexOf('}', i); - if (i3 < 0) { - throw new TemplateException(TEMPLATE_ERR_STR); - } - int i32 = template.indexOf('{', i); - if (i32 >= 0 && i32 < i3) { - nn++; - i = i32 + 1; - } else { - nn--; - i = i3 + 1; - } - } - return i3; - } - - private int tryParseValue(String value1) { - int n; - try { - n = Integer.parseInt(value1); - } catch (Exception e) { - log.error("Failed to parse value. Using default (0).", e); - n = 0; - } - return n; + return expandRepeats(ctx, newTemplate.toString(), level + 1); } private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) { try { - Client client = Client.create(); - client.setConnectTimeout(5000); - WebResource webResource = client.resource(url); + Client client = getClient(); + WebTarget webResource = client.target(url); log.info("SENDING..............."); - log.info(xmlRequest); - + if (log.isTraceEnabled()) { + log.trace(xmlRequest); + } + else { + if(xmlRequest.length() > 255 ) { + log.info(xmlRequest.substring(0, 255)); + log.info("\n...\n" + xmlRequest.length() + + " characters in request, turn on TRACE logging to log entire request"); + } + else { + log.info(xmlRequest); + } + } String authString = user + ":" + password; - byte[] authEncBytes = Base64.encode(authString); - String authStringEnc = new String(authEncBytes); + String authStringEnc = Base64.encode(authString.getBytes()); authString = "Basic " + authStringEnc; - ClientResponse response = - webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( - ClientResponse.class, xmlRequest); + Response response = getClientResponse(webResource, authString, xmlRequest); int code = response.getStatus(); - String message = null; - + String message = response.getStatusInfo().getReasonPhrase(); log.info("RESPONSE..............."); log.info("HTTP response code: " + code); log.info("HTTP response message: " + message); @@ -907,6 +977,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private static class HttpResponse { public int code; + public String message; } @@ -918,63 +989,146 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { } private String getStringBetweenQuotes(String string) { - log.debug("string=" + string); - String retString; + String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes"; + DebugLog.printAriDebug(fnName, "string=" + string); + String retString = null; int start = string.indexOf('\"'); int end = string.lastIndexOf('\"'); retString = string.substring(start + 1, end); - log.debug("retString=" + retString); - return retString; + DebugLog.printAriDebug(fnName, "retString=" + retString); + return (retString); } public static String _readFile(String fileName) { - StringBuilder builder = new StringBuilder(); + StringBuffer strBuff = new StringBuffer(); String line; - try { - BufferedReader in = new BufferedReader(new FileReader(fileName)); + try (BufferedReader in = new BufferedReader(new FileReader(fileName))) { while ((line = in.readLine()) != null) { - builder.append(line).append('\n'); + strBuff.append(line + "\n"); } - in.close(); } catch (IOException e) { - log.error("Caught an IOException in method readFile()", e); + System.out.println("Caught an IOException in method readFile(): e=" + e.toString()); } - return builder.toString(); + return (strBuff.toString()); } - private String trimResponse(String response) { + /** + * A supporting method to extract the data and configuration element from the NETCONF-XML response + * from the node and create well formatted xml. + * + * @param requestData The unformatted NETCONF-XML + * @return responseBuilder the extracted data + * @throws APPCException Exception during parsing xml data + */ + private String extractFromNetconfXml(String requestData) throws APPCException { + log.debug("extractFromNetconfXml -- Start"); + StringBuilder responseBuilder = new StringBuilder(); + StringWriter stringBuffer = new StringWriter(); + try { + requestData = requestData.replaceAll("]]>]]>", ""); + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document document = documentBuilder.parse(new InputSource(new StringReader(requestData))); + document.getDocumentElement().normalize(); + XPath xPath = XPathFactory.newInstance().newXPath(); + Node dataNode = (Node) xPath.evaluate("//data", document, XPathConstants.NODE); + Transformer xform = TransformerFactory.newInstance().newTransformer(); + xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + xform.setOutputProperty(OutputKeys.INDENT, "yes"); + xform.transform(new DOMSource(dataNode), new StreamResult(stringBuffer)); + responseBuilder.append(stringBuffer.toString()); + if (log.isTraceEnabled()) { + log.trace("ConfigComponentAdaptor:extractFromNetconfXml after Extract: " + + responseBuilder.toString()); + } + } catch (SAXException | IOException | ParserConfigurationException | TransformerException + | XPathExpressionException exception) { + throw new APPCException("Error Occured during parsing Netconf-XML", exception); + + } + log.debug("extractFromNetconfXml -- End"); + return responseBuilder.toString(); + } + + private String trimResponse(String response) throws APPCException { + response = extractFromNetconfXml(response); + log.debug("runningConfig before trimResponse : " + response); StringTokenizer line = new StringTokenizer(response, "\n"); - StringBuilder builder = new StringBuilder(); + StringBuffer sb = new StringBuffer(); + String runningConfig = "" ; boolean captureText = false; while (line.hasMoreTokens()) { String token = line.nextToken(); - if (token.contains("") != -1) { + log.debug("token-line:with in "+token); + captureText = false; } if (captureText) { - builder.append(token).append('\n'); + sb.append(token + "\n"); } - if (token.contains("")) { + if (token.indexOf("") != -1) { captureText = false; } } - return builder.toString(); + runningConfig = sb.toString(); + + if (log.isTraceEnabled()) { + log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig); + } + else { + if (runningConfig.length() > 255) { + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + + runningConfig.substring(0, 255)); + log.info("\n...\n" + runningConfig.length() + + " characters in config, turn on TRACE logging to log entire config"); + } + else { + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + + runningConfig); + } + } + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig); + return runningConfig; } - public static void main(String[] args) throws Exception { + public static void main(String args[]) throws Exception { Properties props = null; - log.info("*************************Hello*****************************"); + System.out.println("*************************Hello*****************************"); ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); String getConfigTemplate = _readFile("/home/userID/data/Get_config_template"); + String downloadConfigTemplate = _readFile("/home/userID/data/Download_config_template_2"); String key = "GetCliRunningConfig"; - Map parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "000.00.000.00"); - parameters.put(USERNAME_PARAM, "root"); - parameters.put(PASSWORD_PARAM, "!bootstrap"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, getConfigTemplate); + Map parameters = new HashMap(); + parameters.put("Host_ip_address", "000.00.000.00"); + parameters.put("User_name", "root"); + parameters.put("Password", "!bootstrap"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", getConfigTemplate); + SvcLogicContext ctx = null; - log.info("*************************TRACE 1*****************************"); + System.out.println("*************************TRACE 1*****************************"); cca.configure(key, parameters, ctx); } + + protected SshJcraftWrapper getSshJcraftWrapper() { + return new SshJcraftWrapper(); + } + + protected Client getClient() { + ClientConfig clientConfig = new ClientConfig(); + clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000); + return ClientBuilder.newClient(clientConfig); + } + + protected Response getClientResponse(WebTarget webResource, String authString, String xmlRequest) { + return webResource.request("UTF-8").header("Authorization", authString).header("Content-Type", "application/xml").post( + Entity.xml(xmlRequest),Response.class); + } }