diff options
author | Balaji, Ramya (rb111y) <rb111y@att.com> | 2018-04-03 22:30:22 -0400 |
---|---|---|
committer | Takamune Cho <tc012c@att.com> | 2018-04-04 16:05:53 +0000 |
commit | 12800890db0f5922d6108920036df850d92ed930 (patch) | |
tree | 67bf17fac21f6b04588b042bae1d1d08b6ee0e9a /appc-config | |
parent | 68c95691b62a334e4d98ca32c6fbd1046e3270a6 (diff) |
Restoring to previous known working version
Discovered muliple issues in the refactored code in these files
that has caused failure in existing flow and blocks regression
and new feature testing.Reverted class files and UT case files.
Issue-ID: APPC-827
Change-Id: I2bdd7f54ab919d0e16c79820ebe0ee4e13dbba03
Signed-off-by: Balaji, Ramya (rb111y) <rb111y@att.com>
Diffstat (limited to 'appc-config')
6 files changed, 1753 insertions, 2350 deletions
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..f433fc0b1 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,7 @@ * ============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. * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ * 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========================================================= */ @@ -47,798 +46,790 @@ import org.onap.ccsdk.sli.core.sli.SvcLogicContext; 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 = "</rpc-reply>"; - 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; - - public ConfigComponentAdaptor(Properties props) { - if (props != null) { - configUrl = props.getProperty("configComponent.url", ""); - configUser = props.getProperty("configComponent.user", ""); - configPassword = props.getProperty("configComponent.passwd", ""); - auditUrl = props.getProperty("auditComponent.url", ""); - auditUser = props.getProperty("auditComponent.user", ""); - auditPassword = props.getProperty("auditComponent.passwd", ""); - configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); - auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); - } +private static final 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; +private String configCallbackUrl = null; +private String auditCallbackUrl = null; + +public ConfigComponentAdaptor(Properties props) { + if (props != null) { + configUrl = props.getProperty("configComponent.url", ""); + configUser = props.getProperty("configComponent.user", ""); + configPassword = props.getProperty("configComponent.passwd", ""); + auditUrl = props.getProperty("auditComponent.url", ""); + auditUser = props.getProperty("auditComponent.user", ""); + 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<String, String> parameters, SvcLogicContext ctx) { - HttpResponse r = new HttpResponse(); - r.code = 200; - log.debug("ConfigComponentAdaptor.configure - key = " + key); - log.debug("key = {}", key); - log.debug("Parameters:"); - for (Entry<String, String> paramEntrySet : parameters.entrySet()) { - log.debug(" {} = {}", paramEntrySet.getKey(), paramEntrySet.getValue()); - } - - String parmval = parameters.get("config-component-configUrl"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting URL with {}", parmval); - configUrl = parmval; - } +@Override +public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) { + String fnName = "ConfigComponentAdaptor.configure"; + HttpResponse r = new HttpResponse(); + r.code = 200; + log.debug("ConfigComponentAdaptor.configure - key = " + key); + debugLog.printRTAriDebug(fnName, "key = " + key); + log.debug("Parameters:"); + debugLog.printRTAriDebug(fnName, "Parameters:"); + for (String parmName : parameters.keySet()) { + log.debug(" " + parmName + " = " + parameters.get(parmName)); + debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName)); + } - parmval = parameters.get("config-component-configPassword"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting configPassword with {}", parmval); - configPassword = parmval; - } + String parmval = parameters.get("config-component-configUrl"); + if ((parmval != null) && (parmval.length() > 0)) { + log.debug("Overwriting URL with " + parmval); + configUrl = parmval; + } - parmval = parameters.get("config-component-configUser"); - if (!nullOrEmpty(parmval)) { - log.debug("Overwriting configUser id with {}", parmval); - configUser = parmval; - } + parmval = parameters.get("config-component-configPassword"); + if ((parmval != null) && (parmval.length() > 0)) { + log.debug("Overwriting configPassword with " + parmval); + configPassword = parmval; + } - String action = parameters.get(ACTION_PARAM); + parmval = parameters.get("config-component-configUser"); + if ((parmval != null) && (parmval.length() > 0)) { + log.debug("Overwriting configUser id with " + parmval); + configUser = parmval; + } - 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); - } - if (chg != null && areEqual(action, ACTION_ACTIVATE)) { - return activate(ctx, true); - } + String action = parameters.get("action"); - 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); - } - if (scale != null && areEqual(action, ACTION_ACTIVATE)) { - return activate(ctx, true); - } - - if (areEqual(action, ACTION_PREPARE)) { - return prepare(ctx, BASE_REQUEST, OPERATION_CREATE); - } - if (areEqual(action, ACTION_ACTIVATE)) { - return activate(ctx, false); - } + String chg = ctx.getAttribute( + "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 && "activate".equalsIgnoreCase(action)) { + return activate(ctx, true); + } - if ("backup".equalsIgnoreCase(action)) { - return prepare(ctx, "BACKUP", "backup"); - } - if ("restorebackup".equalsIgnoreCase(action)) { - return prepare(ctx, "RESTOREBACKUP", "restorebackup"); - } - if ("deletebackup".equalsIgnoreCase(action)) { - return prepare(ctx, "DELETEBACKUP", "deletebackup"); - } - if ("audit".equalsIgnoreCase(action)) { - return audit(ctx, "FULL"); - } - if ("getrunningconfig".equalsIgnoreCase(action)) { - return audit(ctx, "RUNNING"); - } + String scale = ctx.getAttribute( + "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 && "activate".equalsIgnoreCase(action)) { + return activate(ctx, true); + } - if ((key.equals(KEY_PUT)) || (key.equals(KEY_GET))) { - 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"); + if ("prepare".equalsIgnoreCase(action)) { + return prepare(ctx, "BASE", "create"); + } + if ("activate".equalsIgnoreCase(action)) { + return activate(ctx, false); + } - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - log.debug("SCP: SshJcraftWrapper has been instantiated"); + if ("backup".equalsIgnoreCase(action)) { + return prepare(ctx, "BACKUP", "backup"); + } + if ("restorebackup".equalsIgnoreCase(action)) { + return prepare(ctx, "RESTOREBACKUP", "restorebackup"); + } + if ("deletebackup".equalsIgnoreCase(action)) { + return prepare(ctx, "DELETEBACKUP", "deletebackup"); + } + if ("audit".equalsIgnoreCase(action)) { + return audit(ctx, "FULL"); + } + if ("getrunningconfig".equalsIgnoreCase(action)) { + return audit(ctx, "RUNNING"); + } - try { - if (key.equals(KEY_PUT)) { - String data = parameters.get("data"); - log.debug("Command is for put: Length of data is: {}", data.length()); + if ((key.equals("put")) || (key.equals("get"))) { + 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(); + log.debug("SCP: SshJcraftWrapper has been instantiated"); + debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); + try { + 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); + log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); + debugLog.printRTAriDebug(fnName, "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); - String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password); - log.debug("Got the response and putting into the ctx object"); - ctx.setAttribute("fileContents", response); - log.debug("SCP: Closing the SFTP connection"); + try { + debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); + Thread.sleep(1000 * 180); + debugLog.printRTAriDebug(fnName, "Woke up...."); + } catch (java.lang.InterruptedException ee) { + boolean ignore = true; + } + } else { + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + log.debug(fnName + " Command is for put: data is null"); } - return setResponseStatus(ctx, r); - } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } - } - if (key.equals(KEY_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(); - 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); - sshJcraftWrapper.closeConnection(); - r.code = 200; - return setResponseStatus(ctx, r); - } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); + } 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); + debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); + ctx.setAttribute("fileContents", response); + log.debug("SCP: Closing the SFTP connection"); } + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } catch (IOException 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(); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); } - if (key.equals(KEY_ESCAPE_SQL)) { - String data = parameters.get("artifactContents"); - log.debug("ConfigComponentAdaptor.configure - escapeSql"); - data = escapeMySql(data); - ctx.setAttribute("escapedData", data); - return setResponseStatus(ctx, r); + } + 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 cliCommand = parameters.get("cli"); + String portNumber = parameters.get("portNumber"); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try { + 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; + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } catch (IOException 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(); + sshJcraftWrapper = null; + DebugLog.printAriDebug(fnName, "Returning error message"); + 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); - password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - String getConfigTemplate = parameters.get(GET_CONFIG_TEMPLATE_PARAM); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); + } + 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)); + } + if (key.equals("GetCliRunningConfig")) { + debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: "); + log.debug("key was: GetCliRunningConfig: "); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Get_config_template = parameters.get("Get_config_template"); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); + debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); + try { + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name + + " Host_ip_address=" + Host_ip_address + " Port_number=" + + Port_number); + log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + + " User_name=" + User_name + " Port_number=" + Port_number); + StringBuffer sb = new StringBuffer(); + String response = ""; + String CliResponse = ""; + boolean showConfigFlag = false; + sshJcraftWrapper.connect(Host_ip_address, + User_name, + Password, + "", + 30000, + Integer.parseInt(Port_number)); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(Get_config_template, "\n"); + String command = null; try { - log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + " User_name=" - + username + " Password=" + password + " Port_number=" + portNumber); - - boolean showConfigFlag = false; - sshJcraftWrapper - .connect(hostIpAddress, username, password, "", 30000, Integer.parseInt(portNumber)); - log.debug("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); - command = getStringBetweenQuotes(line); - log.debug("Sending command={}", command); - sshJcraftWrapper.send(command); - log.debug("command has been sent"); - if (line.contains("show config")) { - showConfigFlag = true; - log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true"); - } + while (st.hasMoreTokens()) { + String line = st.nextToken(); + DebugLog.printAriDebug(fnName, "line=" + line); + if (line.indexOf("Request:") != -1) { + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); + command = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "Sending command=" + command); + sshJcraftWrapper.send(command); + 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); - String delemeter = getStringBetweenQuotes(line); - log.debug("The delemeter={}", delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command); - response.append(tmpResponse); - if (showConfigFlag) { - showConfigFlag = false; - StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n"); - while (st2.hasMoreTokens()) { - String line2 = st2.nextToken(); - if (!line2.contains("#")) { - cliResponse.append(line2).append('\n'); - } + } + if (line.indexOf("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, 30 * 1000, 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.indexOf("#") == -1) { + CliResponse += line2 + "\n"; } } } } - } catch (NoSuchElementException e) { - log.error(e.getMessage(), e); } - log.debug("CliResponse=\n{}", cliResponse.toString()); - ctx.setAttribute(CLI_OUTPUT_PARAM, cliResponse.toString()); - sshJcraftWrapper.closeConnection(); - r.code = 200; - return setResponseStatus(ctx, r); - } catch (IOException e) { - log.error(SSH_JCRAFT_WRAPPER_ERR_STR, e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); + } catch (NoSuchElementException e) { + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } + DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse); + ctx.setAttribute("cliOutput", CliResponse); + sshJcraftWrapper.closeConnection(); + r.code = 200; + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } catch (IOException 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(); + 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); - password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - String contents = parameters.get("Contents"); - 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>"; - 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 ]]>]]>"; - String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>"; - - log.debug("xml-download: User_name={} Host_ip_address={} Password={} Port_number={}", userName, - hostIpAddress, password, portNumber); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - 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"); - String messageId = "1"; - messageId = "\"" + messageId + "\""; - String loadConfigurationString = - "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=" - + messageId - + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" - + contents + "</config> </edit-config> </rpc>"; - loadConfigurationString = loadConfigurationString + PROMPT_STR; - 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); + } + if (key.equals("xml-download")) { + log(fnName, "key was: xml-download"); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Contents = parameters.get("Contents"); + 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>"; + 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 ]]>]]>"; + String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>"; + + log(fnName, + "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + + " Port_number=" + Port_number); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try { + sshJcraftWrapper.connect(Host_ip_address, + User_name, + Password, + "]]>]]>", + 30000, + Integer.parseInt(Port_number), + "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 = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=" + + messageId + + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" + + xmlCmd + "</config> </edit-config> </rpc>"; + loadConfigurationString = loadConfigurationString + "]]>]]>"; + sshJcraftWrapper.send(loadConfigurationString); + DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString"); + response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 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 { + DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd"); + sshJcraftWrapper.send(commitCmd); + DebugLog.printAriDebug(fnName, ":After sending commitCmd"); + response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 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 { - log.debug(":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, ":Looks like a success"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); + r.code = 200; } - sshJcraftWrapper.send(terminateConnectionCmd); - sshJcraftWrapper.closeConnection(); - return setResponseStatus(ctx, r); - } catch (Exception e) { - log.error("Caught an Exception", e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - log.debug("Returning error message"); - return setResponseStatus(ctx, r); } + sshJcraftWrapper.send(terminateConnectionCmd); + sshJcraftWrapper.closeConnection(); + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } catch (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(); + 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 = "<?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"; - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String username = parameters.get(USERNAME_PARAM); - String password = parameters.get(PASSWORD_PARAM); - password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - 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>"; - 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 ]]>]]>"; - log.debug("xml-getrunningconfig: User_name={} Host_ip_address={} Password={} Port_number={}", username, - hostIpAddress, password, portNumber); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - 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"); - sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n"); - response = sshJcraftWrapper.receiveUntil(RPC_REPLY_END_TAG, 180000, ""); - log.debug("Response from getRunningconfigCmd={}", response); - response = trimResponse(response); - ctx.setAttribute("xmlRunningConfigOutput", response); - sshJcraftWrapper.send(terminateConnectionCmd); - sshJcraftWrapper.closeConnection(); - r.code = 200; - return setResponseStatus(ctx, r); - } catch (Exception e) { - log.error("Caught an Exception", e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - log.debug("Returning error message"); - return setResponseStatus(ctx, r); - } + } + if (key.equals("xml-getrunningconfig")) { + log(fnName, "key was: : xml-getrunningconfig"); + 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"; + String Host_ip_address = parameters.get("Host_ip_address"); + String User_name = parameters.get("User_name"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Protocol = parameters.get("Protocol"); + 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>"; + 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 ]]>]]>"; + log(fnName, + "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + + " Port_number=" + Port_number); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + try { + String NetconfHelloCmd = netconfHelloCmd; + sshJcraftWrapper.connect(Host_ip_address, + User_name, + Password, + "]]>]]>", + 30000, + Integer.parseInt(Port_number), + "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>", 180000, ""); + DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response); + response = trimResponse(response); + ctx.setAttribute("xmlRunningConfigOutput", response); + sshJcraftWrapper.send(terminateConnectionCmd); + sshJcraftWrapper.closeConnection(); + r.code = 200; + sshJcraftWrapper = null; + return (setResponseStatus(ctx, r)); + } catch (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(); + sshJcraftWrapper = null; + log(fnName, "Returning error message"); + return (setResponseStatus(ctx, r)); } - if (key.equals(KEY_DOWNLOAD_CLI_CONFIG)) { - log.debug("key was: DownloadCliConfig: "); - String username = parameters.get(USERNAME_PARAM); - String hostIpAddress = parameters.get(HOST_IP_PARAM); - String password = parameters.get(PASSWORD_PARAM); - password = EncryptionTool.getInstance().decrypt(password); - String portNumber = parameters.get(PORT_NUMBER_PARAM); - 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(); - log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); - int timeout = 4 * 60 * 1000; + } + if (key.equals("DownloadCliConfig")) { + debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: "); + log.debug("key was: DownloadCliConfig: "); + String User_name = parameters.get("User_name"); + String Host_ip_address = parameters.get("Host_ip_address"); + String Password = parameters.get("Password"); + Password = EncryptionTool.getInstance().decrypt(Password); + String Port_number = parameters.get("Port_number"); + String Download_config_template = parameters.get("Download_config_template"); + String Config_contents = parameters.get("Config_contents"); + DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents); + SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); + debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); + int timeout = 4 * 60 * 1000; + try { + DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name + + " Host_ip_address=" + Host_ip_address + " Port_number=" + + Port_number); + log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + + " User_name=" + User_name + " Port_number=" + Port_number); + StringBuffer sb = new StringBuffer(); + String response = ""; + String CliResponse = ""; + sshJcraftWrapper.connect(Host_ip_address, + User_name, + Password, + "", + 30000, + Integer.parseInt(Port_number)); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(Download_config_template, "\n"); + String command = null; + String executeConfigContentsDelemeter = null; 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"); - StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n"); - String command = null; - String executeConfigContentsDelimiter; - try { - while (st.hasMoreTokens()) { - String line = st.nextToken(); - log.debug("line={}", line); - if (line.contains("Request:")) { - log.debug("Found a Request line: line={}", line); - command = getStringBetweenQuotes(line); - log.debug("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"); - while (st2.hasMoreTokens()) { - String cmd = st2.nextToken(); - log.debug("Config_contents: cmd={}", cmd); - sshJcraftWrapper.send(cmd); - String tmpResponse = sshJcraftWrapper - .receiveUntil(executeConfigContentsDelimiter, timeout, command); - cliResponse.append(tmpResponse); - } + while (st.hasMoreTokens()) { + String line = st.nextToken(); + DebugLog.printAriDebug(fnName, "line=" + line); + if (line.indexOf("Request:") != -1) { + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); + command = getStringBetweenQuotes(line); + DebugLog.printAriDebug(fnName, "Sending command=" + command); + sshJcraftWrapper.send(command); + 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); + response += tmpResponse; + 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(); + DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd); + sshJcraftWrapper.send(cmd); + String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, + timeout, + command); + CliResponse += tmpResponse; } } - } catch (NoSuchElementException e) { - log.error(e.getMessage(), 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); - r.code = 200; - return setResponseStatus(ctx, r); - } catch (IOException e) { - log.error(e.getMessage() + e); - sshJcraftWrapper.closeConnection(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - log.debug("DownloadCliConfig: Returning error message"); - return setResponseStatus(ctx, r); + } catch (NoSuchElementException e) { + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } + sshJcraftWrapper.closeConnection(); + 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)); + } catch (IOException 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(); + 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); - } + debugLog.printRTAriDebug(fnName, "Unsupported action - " + action); + log.error("Unsupported action - " + action); + return ConfigStatus.FAILURE; +} - private boolean nullOrEmpty(String parmval) { - return parmval != null && parmval.length() > 0; - } +private void log(String fileName, String messg) { + debugLog.printRTAriDebug(fileName, messg); + log.debug(fileName + ": " + messg); +} - 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; - } +private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) { + 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<String, String> param = new HashMap<String, String>(); + param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); + param.put("request-type", requestType); + param.put("callback-url", configCallbackUrl); + if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) { + param.put("action", "GenerateOnly"); } + 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); - 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(); - } - } + String req = null; + try { + req = buildXmlRequest(param, reqTemplate); + } catch (Exception e) { + log.error("Error building the XML request: ", e); - 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 nd = buildNetworkData2(ctx, ndTemplate, operation); + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return setResponseStatus(ctx, r); + } - String reqTemplate = readFile("/config-request.xml"); - Map<String, String> param = new HashMap<>(); - param.put(REQUEST_ID_PARAM, ctx.getAttribute(SVC_REQUEST_ID_ATTR)); - 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(EQUIPMENT_NAME_PARAM, ctx.getAttribute(SERVICE_INSTANCE_ID_ATTR)); - 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); + HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + return setResponseStatus(ctx, r); +} - String req; - try { - req = buildXmlRequest(param, reqTemplate); - } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); +private ConfigStatus activate(SvcLogicContext ctx, boolean change) { + String reqTemplate = readFile("/config-request.xml"); + Map<String, String> param = new HashMap<String, String>(); + 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")); - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } + String req = null; + try { + req = buildXmlRequest(param, reqTemplate); + } catch (Exception e) { + log.error("Error building the XML request: ", e); - HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); return setResponseStatus(ctx, r); } - private ConfigStatus activate(SvcLogicContext ctx, boolean change) { - String reqTemplate = readFile("/config-request.xml"); - Map<String, String> 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)); + HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + return setResponseStatus(ctx, r); +} - String req; - try { - req = buildXmlRequest(param, reqTemplate); - } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); +private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) { + String reqTemplate = readFile("/audit-request.xml"); + Map<String, String> param = new HashMap<String, String>(); + 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); - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } + String req = null; + try { + req = buildXmlRequest(param, reqTemplate); + } catch (Exception e) { + log.error("Error building the XML request: ", e); - HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword); + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); return setResponseStatus(ctx, r); } - private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) { - String reqTemplate = readFile("/audit-request.xml"); - Map<String, String> 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("audit-level", auditLevel); - String req; + HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword); + return setResponseStatus(ctx, r); +} - try { - req = buildXmlRequest(param, reqTemplate); - } catch (Exception e) { - log.error(XML_BUILDING_ERR_STR, e); +@Override +public ConfigStatus activate(String key, SvcLogicContext ctx) { + return ConfigStatus.SUCCESS; +} - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return setResponseStatus(ctx, r); - } +@Override +public ConfigStatus deactivate(String key, SvcLogicContext ctx) { + return ConfigStatus.SUCCESS; +} - HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword); - return setResponseStatus(ctx, r); +private String escapeMySql(String input) { + if (input == null) { + return null; } - @Override - public ConfigStatus activate(String key, SvcLogicContext ctx) { - return ConfigStatus.SUCCESS; - } + input = input.replace("\\", "\\\\"); + input = input.replace("\'", "\\'"); + + return input; +} - @Override - public ConfigStatus deactivate(String key, SvcLogicContext ctx) { - return ConfigStatus.SUCCESS; +private String readFile(String fileName) { + InputStream is = getClass().getResourceAsStream(fileName); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader in = new BufferedReader(isr); + StringBuilder ss = new StringBuilder(); + try { + String s = in.readLine(); + while (s != null) { + ss.append(s).append('\n'); + s = in.readLine(); + } + } catch (IOException e) { + System.out.println("Error reading " + fileName + ": " + e.getMessage()); + throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e); + } finally { + try { + in.close(); + } catch (Exception e) { + log.warn("Could not close BufferedReader", e); + } + try { + isr.close(); + } catch (Exception e) { + log.warn("Could not close InputStreamReader", e); + } + try { + is.close(); + } catch (Exception e) { + log.warn("Could not close InputStream", e); + } } + return ss.toString(); +} - private String escapeMySql(String input) { - if (input == null) { - return null; +private String buildXmlRequest(Map<String, String> param, String template) { + StringBuilder ss = new StringBuilder(); + int i = 0; + while (i < template.length()) { + int i1 = template.indexOf("${", i); + if (i1 < 0) { + ss.append(template.substring(i)); + break; } - return input - .replace("\\", "\\\\") - .replace("\'", "\\'"); - } + int i2 = template.indexOf('}', i1 + 2); + if (i2 < 0) { + throw new RuntimeException("Template error: Matching } not found"); + } - private String readFile(String fileName) { - InputStream is = getClass().getResourceAsStream(fileName); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader in = new BufferedReader(isr); - StringBuilder builder = new StringBuilder(); - try { - String s = in.readLine(); - while (s != null) { - builder.append(s).append('\n'); - s = in.readLine(); - } - } catch (IOException e) { - throw new UncheckedIOException("Error reading " + fileName, e); - } finally { - try { - in.close(); - } catch (Exception e) { - log.warn("Could not close BufferedReader", e); + String var1 = template.substring(i1 + 2, i2); + String value1 = param.get(var1); + if (value1 == null || value1.trim().length() == 0) { + // delete the whole element (line) + int i3 = template.lastIndexOf('\n', i1); + if (i3 < 0) { + i3 = 0; } - try { - isr.close(); - } catch (Exception e) { - log.warn("Could not close InputStreamReader", e); + int i4 = template.indexOf('\n', i1); + if (i4 < 0) { + i4 = template.length(); } - try { - is.close(); - } catch (Exception e) { - log.warn("Could not close InputStream", e); + + if (i < i3) { + ss.append(template.substring(i, i3)); } + i = i4; + } else { + ss.append(template.substring(i, i1)).append(value1); + i = i2 + 1; } - return builder.toString(); } - private String buildXmlRequest(Map<String, String> param, String template) { - StringBuilder ss = new StringBuilder(); - int i = 0; - while (i < template.length()) { - int i1 = template.indexOf("${", i); - if (i1 < 0) { - ss.append(template.substring(i)); - break; - } - - int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) { - throw new TemplateException(TEMPLATE_ERR_STR); - } + return ss.toString(); +} - String var1 = template.substring(i1 + 2, i2); - String value1 = param.get(var1); - if (emptyOrNull(value1)) { - // delete the whole element (line) - int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) { - i3 = 0; - } - int i4 = template.indexOf('\n', i1); - if (i4 < 0) { - i4 = template.length(); - } +private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) { + log.info("Building XML started"); + long t1 = System.currentTimeMillis(); - if (i < i3) { - ss.append(template.substring(i, i3)); - } - i = i4; - } else { - ss.append(template.substring(i, i1)).append(value1); - i = i2 + 1; - } - } + template = expandRepeats(ctx, template, 1); - return ss.toString(); + Map<String, String> mm = new HashMap<>(); + for (String s : ctx.getAttributeKeySet()) { + mm.put(s, ctx.getAttribute(s)); } + mm.put("operation", operation); - private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) { - log.info("Building XML started"); - long t1 = System.currentTimeMillis(); + StringBuilder ss = new StringBuilder(); + int i = 0; + while (i < template.length()) { + int i1 = template.indexOf("${", i); + if (i1 < 0) { + ss.append(template.substring(i)); + break; + } - Map<String, String> mm = new HashMap<>(); - for (String s : ctx.getAttributeKeySet()) { - mm.put(s, ctx.getAttribute(s)); + int i2 = template.indexOf('}', i1 + 2); + if (i2 < 0) { + throw new RuntimeException("Template error: Matching } not found"); } - mm.put("operation", operation); - - StringBuilder ss = new StringBuilder(); - int i = 0; - while (i < template.length()) { - int i1 = template.indexOf("${", i); - if (i1 < 0) { - ss.append(template.substring(i)); - break; - } - int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) { - throw new TemplateException(TEMPLATE_ERR_STR); + String var1 = template.substring(i1 + 2, i2); + String value1 = XmlUtil.getXml(mm, var1); + if (value1 == null || value1.trim().length() == 0) { + // delete the whole element (line) + int i3 = template.lastIndexOf('\n', i1); + if (i3 < 0) { + i3 = 0; + } + int i4 = template.indexOf('\n', i1); + if (i4 < 0) { + i4 = template.length(); } - String var1 = template.substring(i1 + 2, i2); - String value1 = XmlUtil.getXml(mm, var1); - if (emptyOrNull(value1)) { - int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) { - i3 = 0; - } - int i4 = template.indexOf('\n', i1); - if (i4 < 0) { - i4 = template.length(); - } - - if (i < i3) { - ss.append(template.substring(i, i3)); - } - i = i4; - } else { - ss.append(template.substring(i, i1)).append(value1); - i = i2 + 1; + if (i < i3) { + ss.append(template.substring(i, i3)); } + i = i4; + } else { + ss.append(template.substring(i, i1)).append(value1); + i = i2 + 1; } - - long t2 = System.currentTimeMillis(); - log.info("Building XML completed. Time: " + (t2 - t1)); - - return ss.toString(); } - private boolean emptyOrNull(String value1) { - return value1 == null || value1.trim().length() == 0; - } + long t2 = System.currentTimeMillis(); + log.info("Building XML completed. Time: " + (t2 - t1)); - private String expandRepeats(SvcLogicContext ctx, String template, int level) { - StringBuilder newTemplate = new StringBuilder(); - int k = 0; - while (k < template.length()) { - int i1 = template.indexOf("${repeat:", k); - if (i1 < 0) { - newTemplate.append(template.substring(k)); - break; - } - - int i2 = template.indexOf(':', i1 + 9); - if (i2 < 0) { - throw new TemplateException( - "Template error: Context variable name followed by \":\" is required after repeat"); - } - - // Find the closing "}", store in i3 - int i3 = findLastBracketIndex(template, i2); - - String var1 = template.substring(i1 + 9, i2); - String value1 = ctx.getAttribute(var1); - log.info(" " + var1 + ": " + value1); - int n = tryParseValue(value1); - - newTemplate.append(template.substring(k, i1)); - - String rpt = template.substring(i2 + 1, i3); + return ss.toString(); +} - for (int ii = 0; ii < n; ii++) { - String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); - newTemplate.append(ss); - } - k = i3 + 1; +private String expandRepeats(SvcLogicContext ctx, String template, int level) { + StringBuilder newTemplate = new StringBuilder(); + int k = 0; + while (k < template.length()) { + int i1 = template.indexOf("${repeat:", k); + if (i1 < 0) { + newTemplate.append(template.substring(k)); + break; } - if (k == 0) { - return newTemplate.toString(); + int i2 = template.indexOf(':', i1 + 9); + if (i2 < 0) { + throw new RuntimeException( + "Template error: Context variable name followed by : is required after repeat"); } - return expandRepeats(ctx, newTemplate.toString(), level + 1); - } - private int findLastBracketIndex(String template, int i2) { + // Find the closing }, store in i3 + int nn = 1; 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); + throw new RuntimeException("Template error: Matching } not found"); } int i32 = template.indexOf('{', i); if (i32 >= 0 && i32 < i3) { @@ -849,132 +840,150 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { i = i3 + 1; } } - return i3; - } - private int tryParseValue(String value1) { - int n; + String var1 = template.substring(i1 + 9, i2); + String value1 = ctx.getAttribute(var1); + log.info(" " + var1 + ": " + value1); + int n = 0; try { n = Integer.parseInt(value1); } catch (Exception e) { - log.error("Failed to parse value. Using default (0).", e); n = 0; } - return n; + + newTemplate.append(template.substring(k, i1)); + + String rpt = template.substring(i2 + 1, i3); + + for (int ii = 0; ii < n; ii++) { + String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); + newTemplate.append(ss); + } + + k = i3 + 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); + if (k == 0) { + return newTemplate.toString(); + } - log.info("SENDING..............."); - log.info(xmlRequest); + return expandRepeats(ctx, newTemplate.toString(), level + 1); +} - String authString = user + ":" + password; - byte[] authEncBytes = Base64.encode(authString); - String authStringEnc = new String(authEncBytes); - authString = "Basic " + authStringEnc; +private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) { + try { + Client client = Client.create(); + client.setConnectTimeout(5000); + WebResource webResource = client.resource(url); - ClientResponse response = - webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( - ClientResponse.class, xmlRequest); + log.info("SENDING..............."); + log.info(xmlRequest); - int code = response.getStatus(); - String message = null; + String authString = user + ":" + password; + byte[] authEncBytes = Base64.encode(authString); + String authStringEnc = new String(authEncBytes); + authString = "Basic " + authStringEnc; - log.info("RESPONSE..............."); - log.info("HTTP response code: " + code); - log.info("HTTP response message: " + message); - log.info(""); + ClientResponse response = + webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( + ClientResponse.class, xmlRequest); - HttpResponse r = new HttpResponse(); - r.code = code; - r.message = message; - return r; + int code = response.getStatus(); + String message = null; - } catch (Exception e) { - log.error("Error sending the request: ", e); + log.info("RESPONSE..............."); + log.info("HTTP response code: " + code); + log.info("HTTP response message: " + message); + log.info(""); - HttpResponse r = new HttpResponse(); - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; - r.message = e.getMessage(); - return r; - } - } + HttpResponse r = new HttpResponse(); + r.code = code; + r.message = message; + return r; - private static class HttpResponse { + } catch (Exception e) { + log.error("Error sending the request: ", e); - public int code; - public String message; + HttpResponse r = new HttpResponse(); + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.message = e.getMessage(); + return r; } +} - private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) { - ctx.setAttribute("error-code", String.valueOf(r.code)); - ctx.setAttribute("error-message", r.message); +private static class HttpResponse { - return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS; - } + public int code; - private String getStringBetweenQuotes(String string) { - log.debug("string=" + string); - String retString; - int start = string.indexOf('\"'); - int end = string.lastIndexOf('\"'); - retString = string.substring(start + 1, end); - log.debug("retString=" + retString); - return retString; - } + public String message; +} - public static String _readFile(String fileName) { - StringBuilder builder = new StringBuilder(); - String line; - try { - BufferedReader in = new BufferedReader(new FileReader(fileName)); - while ((line = in.readLine()) != null) { - builder.append(line).append('\n'); - } - in.close(); - } catch (IOException e) { - log.error("Caught an IOException in method readFile()", e); +private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) { + ctx.setAttribute("error-code", String.valueOf(r.code)); + ctx.setAttribute("error-message", r.message); + + return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS; +} + +private String getStringBetweenQuotes(String string) { + 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); + DebugLog.printAriDebug(fnName, "retString=" + retString); + return (retString); +} + +public static String _readFile(String fileName) { + StringBuffer strBuff = new StringBuffer(); + String line; + try (BufferedReader in = new BufferedReader(new FileReader(fileName))) { + while ((line = in.readLine()) != null) { + strBuff.append(line + "\n"); } - return builder.toString(); + } catch (IOException e) { + System.out.println("Caught an IOException in method readFile(): e=" + e.toString()); } + return (strBuff.toString()); +} - private String trimResponse(String response) { - StringTokenizer line = new StringTokenizer(response, "\n"); - StringBuilder builder = new StringBuilder(); - boolean captureText = false; - while (line.hasMoreTokens()) { - String token = line.nextToken(); - if (token.contains("<configuration xmlns=")) { - captureText = true; - } - if (captureText) { - builder.append(token).append('\n'); - } - if (token.contains("</configuration>")) { - captureText = false; - } +private String trimResponse(String response) { + StringTokenizer line = new StringTokenizer(response, "\n"); + StringBuffer sb = new StringBuffer(); + boolean captureText = false; + while (line.hasMoreTokens()) { + String token = line.nextToken(); + if (token.indexOf("<configuration xmlns=") != -1) { + captureText = true; + } + if (captureText) { + sb.append(token + "\n"); + } + if (token.indexOf("</configuration>") != -1) { + captureText = false; } - return builder.toString(); - } - - public static void main(String[] args) throws Exception { - Properties props = null; - log.info("*************************Hello*****************************"); - ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String getConfigTemplate = _readFile("/home/userID/data/Get_config_template"); - String key = "GetCliRunningConfig"; - Map<String, String> 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); - SvcLogicContext ctx = null; - log.info("*************************TRACE 1*****************************"); - cca.configure(key, parameters, ctx); } + return (sb.toString()); +} + +public static void main(String args[]) throws Exception { + Properties props = null; + System.out.println("*************************Hello*****************************"); + ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); + String Get_config_template = _readFile("/home/userID/data/Get_config_template"); + String Download_config_template = _readFile("/home/userID/data/Download_config_template_2"); + String key = "GetCliRunningConfig"; + Map<String, String> 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", Get_config_template); + + SvcLogicContext ctx = null; + System.out.println("*************************TRACE 1*****************************"); + cca.configure(key, parameters, ctx); +} } diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java new file mode 100644 index 000000000..fb9d7a392 --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/DebugLog.java @@ -0,0 +1,100 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.ccadaptor;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+
+public class DebugLog {
+
+ private static String fileName = "/tmp/rt.log";
+
+ public static void main(String args[]) {
+ DebugLog debugLog = new DebugLog();
+ debugLog.printAriDebug("DebugLog", "The Message");
+ }
+
+ public static void printAriDebug(String fn, String messg) {
+ String logMessg = getDateTime() + " " + fn + " " + messg;
+ appendToFile(logMessg + "\n");
+
+ }
+
+ public static void printRTAriDebug(String fn, String messg) {
+ // System.out.println (getDateTime() +" " +fn +" " + messg);
+ String logMessg = getDateTime() + " " + fn + " " + messg;
+ appendToFile(logMessg + "\n");
+ }
+
+ public static String getDateTime() {
+ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+ // DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
+ Date date = new Date();
+ return dateFormat.format(date);
+ }
+
+ public static void appendToFile(String dataToWrite) {
+ String fn = "DebugLog.appendToFile";
+ try {
+ // First check to see if a file 'fileName' exist, if it does
+ // write to it. If it does not exist, don't write to it.
+ File tmpFile = new File(fileName);
+ if (tmpFile.exists()) {
+ BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
+ out.write(dataToWrite);
+ out.close();
+ }
+ } catch (IOException e) {
+ DebugLog.printRTAriDebug(fn, "writeToFile() exception: " + e);
+ //System.err.println("writeToFile() exception: " + e);
+ e.printStackTrace();
+ }
+ }
+
+ public void outputStackTrace(Exception e) {
+ String fn = "DebugLog.outputStackTrace";
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ String stackTrace = sw.toString();
+ DebugLog.printRTAriDebug(fn, "Stack trace::: " + stackTrace);
+ }
+
+ public static String getStackTraceString(Exception e) {
+ String fn = "DebugLog.outputStackTrace";
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ String stackTrace = sw.toString();
+ return (stackTrace);
+ }
+
+}
+
diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java index 081f0814f..9aa5f9fbf 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java @@ -2,7 +2,7 @@ * ============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. * ================================================================================ * Copyright (C) 2017 Amdocs * ============================================================================= @@ -18,7 +18,6 @@ * 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========================================================= */ @@ -62,75 +61,81 @@ import org.onap.appc.i18n.Msg; public class SshJcraftWrapper { - private static final EELFLogger log = EELFManager.getInstance().getLogger(SshJcraftWrapper.class); - static final int DEFAULT_PORT = 22; - static final String EOL = "\n"; - static final String CHANNEL_SHELL_TYPE = "shell"; - static final String CHANNEL_SUBSYSTEM_TYPE = "subsystem"; - static final String CHANNEL_SFTP_TYPE = "sftp"; - private static final String TERMINAL_BASIC_MODE = "vt102"; - static final String STRICT_HOST_CHECK_KEY = "StrictHostKeyChecking"; - static final String STRICT_HOST_CHECK_VALUE = "no"; - static final String DELIMITERS_SEPARATOR = "|"; - + InputStream inputStream = null; + OutputStream outputStream = null; + DebugLog debugLog = new DebugLog(); + private String debugLogFileName = "/tmp/sshJcraftWrapperDebug"; private TelnetListener listener = null; private String routerLogFileName = null; + private String host = null; + private String RouterName = null; + private int BUFFER_SIZE = 512000; + char[] charBuffer = new char[BUFFER_SIZE]; + // private int BUFFER_SIZE = 4000000; + private DataInputStream dis = null; private BufferedReader reader = null; private BufferedWriter out = null; - private File tmpFile = null; + private File _tmpFile = null; private JSch jsch = null; private Session session = null; private Channel channel = null; + private String tId = ""; private String aggregatedReceivedString = ""; + private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG"); private String routerCmdType = "XML"; private String routerFileName = null; private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk"); private String equipNameCode = null; - private String routerName = null; private String hostName = null; private String userName = null; private String passWord = null; - private int readIntervalMs = 500; - private int readBufferSizeBytes = 512_000; - private int charsChunkSize = 300_000; - private int sessionTimeoutMs = 9_000; - private char[] charBuffer; + private StringBuffer charactersFromBufferFlush = new StringBuffer(); private Runtime runtime = Runtime.getRuntime(); + private DebugLog dbLog = new DebugLog(); - public SshJcraftWrapper() { - this.jsch = new JSch(); - this.charBuffer = new char[readBufferSizeBytes]; - } - - SshJcraftWrapper(JSch jsch, int readIntervalMs, int readBufferSizeBytes) { - this.readIntervalMs = readIntervalMs; - this.jsch = jsch; - this.readBufferSizeBytes = readBufferSizeBytes; - this.charBuffer = new char[readBufferSizeBytes]; + public void SshJcraftWrapper() { + String fn = "SshJcraftWrapper.SshJcraftWrapper"; + debugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated"); + routerLogFileName = "/tmp/" + host; + this.host = host; } public void connect(String hostname, String username, String password, String prompt, int timeOut) throws IOException { - log.debug("Attempting to connect to {0} username={1} prompt='{2}' timeOut={3}", - hostname, username, prompt, timeOut); - routerName = hostname; + String fn = "SshJcraftWrapper.connect"; + jsch = new JSch(); + debugLog.printRTAriDebug(fn, + "Attempting to connect to " + hostname + " username=" + username + " prompt='" + + prompt + "' timeOut=" + timeOut); + debugLog.printRTAriDebug(fn, "Trace A"); + RouterName = hostname; hostName = hostname; userName = username; passWord = password; try { - channel = provideSessionChannel(CHANNEL_SHELL_TYPE, DEFAULT_PORT, timeOut); - ((ChannelShell) channel).setPtyType(TERMINAL_BASIC_MODE); - reader = new BufferedReader(new InputStreamReader(new DataInputStream(channel.getInputStream())), - readBufferSizeBytes); + session = jsch.getSession(username, hostname, 22); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.connect(timeOut); + channel = session.openChannel("shell"); + session.setServerAliveCountMax( + 0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + ((ChannelShell) channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); channel.connect(); - log.info("Successfully connected. Flushing input buffer."); + debugLog.printRTAriDebug(fn, "Successfully connected."); + debugLog.printRTAriDebug(fn, "Flushing input buffer"); try { receiveUntil(prompt, 3000, "No cmd was sent, just waiting"); - } catch (IOException e) { - log.warn("Caught an Exception: Nothing to flush out.", e); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out."); } - } catch (JSchException e) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostname, String.valueOf(DEFAULT_PORT), username); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e); + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); throw new IOException(e.toString()); } } @@ -138,42 +143,66 @@ public class SshJcraftWrapper { // User specifies the port number. public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException { - log.debug("Attempting to connect to {0} username={1} prompt='{2}' timeOut={3} portNum={4}", - hostname, username, prompt, timeOut, portNum); - routerName = hostname; + String fn = "SshJcraftWrapper.connect"; + debugLog.printRTAriDebug(fn, + ":Attempting to connect to " + hostname + " username=" + username + " prompt='" + + prompt + "' timeOut=" + timeOut + " portNum=" + portNum); + RouterName = hostname; hostName = hostname; userName = username; passWord = password; + RouterName = hostname; + jsch = new JSch(); try { - channel = provideSessionChannel(CHANNEL_SHELL_TYPE, portNum, timeOut); - ((ChannelShell) channel).setPtyType(TERMINAL_BASIC_MODE); - reader = new BufferedReader(new InputStreamReader(new DataInputStream(channel.getInputStream())), - readBufferSizeBytes); + session = jsch.getSession(username, hostname, portNum); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.setConfig("StrictHostKeyChecking", "no"); + debugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'"); + + session.connect(timeOut); + session.setServerAliveCountMax( + 0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + channel = session.openChannel("shell"); + ((ChannelShell) channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); channel.connect(); - log.info("Successfully connected. Flushing input buffer."); + debugLog.printRTAriDebug(fn, ":Successfully connected."); + debugLog.printRTAriDebug(fn, ":Flushing input buffer"); try { - if ("]]>]]>".equals(prompt)) { + if (prompt.equals("]]>]]>")) { receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting"); } else { receiveUntil(":~#", 5000, "No cmd was sent, just waiting"); } - } catch (IOException e) { - log.warn("Caught an Exception: Nothing to flush out.", e); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out."); } - } catch (JSchException e) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostname, String.valueOf(portNum), username); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e); + dbLog.outputStackTrace(e); + + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); throw new IOException(e.toString()); } } - public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent) throws IOException { - checkConnection(); + public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent) + throws TimedOutException, IOException { + String fn = "SshJcraftWrapper.receiveUntil"; boolean match = false; boolean cliPromptCmd = false; - StringBuilder sb = new StringBuilder(); - StringBuilder sbReceive = new StringBuilder(); - log.debug("delimeters='{0}' timeout={1} cmdThatWasSent='{2}'", delimeters, timeout, cmdThatWasSent); + StringBuffer sb2 = new StringBuffer(); + StringBuffer sbReceive = new StringBuffer(); + debugLog.printRTAriDebug(fn, + "delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'"); + appendToFile(debugLogFileName, + fn + " delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'\n"); + String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent); int readCounts = 0; aggregatedReceivedString = ""; FileWriter fileWriter = null; @@ -183,16 +212,22 @@ public class SshJcraftWrapper { session.setTimeout(timeout); // This is the socket timeout value. while (!match) { if (new Date().getTime() > deadline) { - String formattedCmd = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent); - log.error(Msg.SSH_CONNECTION_TIMEOUT, routerName, formattedCmd); - throw new TimedOutException("Routine has timed out"); + debugLog.printRTAriDebug(fn, + "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:" + + RouterName + " CmdThatWasSent=" + CmdThatWasSent); + throw new TimedOutException("Timeout: time in routine has exceed our deadline"); } - sleep(readIntervalMs); - int len = reader.read(charBuffer, 0, readBufferSizeBytes); - log.trace("After reader. Read command len={0}", len); + try { + Thread.sleep(500); + } catch (java.lang.InterruptedException ee) { + boolean ignore = true; + } + int len = reader.read(charBuffer, 0, BUFFER_SIZE); + appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n"); if (len <= 0) { - log.error(Msg.SSH_CONNECTION_TIMEOUT, routerName, cmdThatWasSent); - throw new TimedOutException("Received a SocketTimeoutException router=" + routerName); + debugLog.printRTAriDebug(fn, + "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName); + throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName); } if (!cliPromptCmd) { if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) { @@ -200,24 +235,26 @@ public class SshJcraftWrapper { // This is a IOS XR sw config file. We will write it to the disk. timeout = timeout * 2; deadline = new Date().getTime() + timeout; - log.debug("IOS XR upload for software config: timeout={0}", timeout); + debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout); StringTokenizer st = new StringTokenizer(cmdThatWasSent); st.nextToken(); routerFileName = st.nextToken(); fileWriter = new FileWriter(routerFileName); out = new BufferedWriter(fileWriter); - routerLogFileName = "/tmp/" + routerName; - tmpFile = new File(routerLogFileName); - log.debug("Prepared for writing swConfigFile to disk, routerFileName=" + routerFileName); + routerLogFileName = "/tmp/" + RouterName; + _tmpFile = new File(routerLogFileName); + debugLog.printRTAriDebug(fn, + "Will write the swConfigFile to disk, routerFileName=" + routerFileName); } + int c; out.write(charBuffer, 0, len); out.flush(); - log.debug("{0} bytes has been written to the disk", len); - if (tmpFile.exists()) { + appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n"); + if (_tmpFile.exists()) { appendToRouterFile(routerLogFileName, len); } match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>"); - if (match) { + if (match == true) { out.flush(); out.close(); out = null; @@ -225,96 +262,93 @@ public class SshJcraftWrapper { } } else { readCounts++; - log.debug("Reader read {0} of data within {1} read iteration", len, readCounts); + appendToFile(debugLogFileName, + fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n"); int c; - sb.setLength(0); + sb2.setLength(0); for (int i = 0; i < len; i++) { c = charBuffer[i]; if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) { - sbReceive.append(charBuffer[i]); - sb.append(charBuffer[i]); + sbReceive.append((char) charBuffer[i]); + sb2.append((char) charBuffer[i]); } } - appendToRouterFile("/tmp/" + routerName, len); + appendToRouterFile("/tmp/" + RouterName, len); if (listener != null) { - listener.receivedString(sb.toString()); + listener.receivedString(sb2.toString()); } - match = checkIfReceivedStringMatchesDelimeter(delimeters, sb.toString(), cmdThatWasSent); - if (match) { - log.trace("Match was true, breaking the loop."); + + appendToFile(debugLogFileName, fn + " Trace 1\n"); + match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent); + appendToFile(debugLogFileName, fn + " Trace 2\n"); + if (match == true) { + appendToFile(debugLogFileName, fn + " Match was true, breaking...\n"); break; } } } else { - log.trace("cliPromptCmd"); - sb.setLength(0); + debugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2"); + sb2.setLength(0); for (int i = 0; i < len; i++) { - sbReceive.append(charBuffer[i]); - sb.append(charBuffer[i]); + sbReceive.append((char) charBuffer[i]); + sb2.append((char) charBuffer[i]); } - appendToRouterFile("/tmp/" + routerName, sb); + appendToRouterFile("/tmp/" + RouterName, sb2); if (listener != null) { - listener.receivedString(sb.toString()); + listener.receivedString(sb2.toString()); } - log.debug("sb2={0} delimiters={1}", sb.toString(), delimeters); - if (sb.toString().contains("\nariPrompt>")) { - log.debug("Found ari prompt"); + debugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'"); + if (sb2.toString().indexOf("\nariPrompt>") != -1) { + debugLog.printRTAriDebug(fn, "Found our prompt"); + match = true; break; } } } - } catch (JSchException | IOException e) { - log.error(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - throw new TimedOutException(e.getMessage()); + } catch (JSchException e) { + debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString()); + dbLog.outputStackTrace(e); + throw new TimedOutException(e.toString()); + } catch (IOException ee) { + debugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString()); + dbLog.outputStackTrace(ee); + throw new TimedOutException(ee.toString()); } finally { try { if (fileWriter != null) { fileWriter.close(); } - } catch (IOException ex) { - log.warn("Failed to close fileWriter output stream", ex); - } - } - return stripOffCmdFromRouterResponse(sbReceive.toString()); - } - - private void sleep(long timeoutMs) { - try { - TimeUnit.MILLISECONDS.sleep(timeoutMs); - } catch (java.lang.InterruptedException ee) { - Thread.currentThread().interrupt(); - } - } - - private void checkConnection() { - try { - if (!isConnected() || !reader.ready()) { - throw new IllegalStateException("Connection not established. Cannot perform action."); + } catch(IOException ex) { + debugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex); } - } catch (IOException e) { - throw new IllegalStateException("Reader stream is closed. Cannot perform action.", e); } + String result = stripOffCmdFromRouterResponse(sbReceive.toString()); + debugLog.printRTAriDebug(fn, "Leaving method successfully"); + return result; } public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent) { // The delimeters are in a '|' seperated string. Return true on the first match. - log.debug("Entered checkIfReceivedStringMatchesDelimeter: delimeters={0} cmdThatWasSent={1} receivedString={2}", - delimeters, cmdThatWasSent, receivedString); - StringTokenizer st = new StringTokenizer(delimeters, DELIMITERS_SEPARATOR); + String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter"; + appendToFile(debugLogFileName, + fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='" + + receivedString + "'\n"); + StringTokenizer st = new StringTokenizer(delimeters, "|"); - if ((delimeters.contains("#$")) || ("CLI".equals(routerCmdType))) // This would be an IOS XR, CLI command. + if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command. { - int x = receivedString.lastIndexOf('#'); + int x = receivedString.lastIndexOf("#"); int y = receivedString.length() - 1; - log.debug("IOS XR, CLI command"); - if (log.isTraceEnabled()) { - log.trace("cmdThatWasSent={0}, lastIndexOf hash delimiter={1}, maxIndexNum={2}", cmdThatWasSent, x, y); + appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n"); + if (extraDebugFile.exists()) { + appendToFile(debugLogFileName, + fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n"); } return (x != -1) && (y == x); } - if (cmdThatWasSent.contains("show config")) { - log.trace("In the block for 'show config'"); + if (cmdThatWasSent.indexOf("show config") != -1) { + appendToFile(debugLogFileName, fn + "In the block for 'show config'\n"); while (st.hasMoreTokens()) { String delimeter = st.nextToken(); // Make sure we don't get faked out by a response of " #". @@ -323,172 +357,217 @@ public class SshJcraftWrapper { // LAAR2# int x = receivedString.lastIndexOf(delimeter); if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) { - log.debug("receivedString={0}", receivedString); - log.trace("Found ending for 'show config' command, exiting."); - return true; + appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n"); + appendToFile(debugLogFileName, + fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n"); + return (true); } } } else { aggregatedReceivedString = aggregatedReceivedString + receivedString; - appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); + _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); - log.debug("receivedString={0}", receivedString); while (st.hasMoreTokens()) { String delimeter = st.nextToken(); - log.debug("Looking for an delimiter of:{0}", delimeter); + appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n"); + appendToFile(debugLogFileName, fn + " receivedString='" + receivedString); if (aggregatedReceivedString.indexOf(delimeter) != -1) { - log.debug("Found delimiter={0}, exiting", delimeter); + debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'"); aggregatedReceivedString = ""; - return true; + return (true); } } } - return false; + return (false); } public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) { + String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::"; int x; int c; String str = StringUtils.EMPTY; if (jcraftReadSwConfigFileFromDisk()) { - log.trace("jcraftReadSwConfigFileFromDisk block"); + DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block"); File fileName = new File(routerFileName); - log.debug("jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); + appendToFile(debugLogFileName, + fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); try { str = getLastFewLinesOfFile(fileName, 3); } catch (IOException e) { - log.warn("IOException occurred, while reading file=" + fileName, e); + DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e); + dbLog.outputStackTrace(e); + e.printStackTrace(); } } else { + // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************"); // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible. for (x = len - 1; x >= 0; x--) { c = charBuffer[x]; + if (extraDebugFile.exists()) { + appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n"); + } if ((c != 10) && (c != 32)) // Not a line feed nor a space. { break; } } if ((x + 1 - 13) >= 0) { - str = new String(charBuffer, x + 1 - 13, 13); - log.debug("str:{0}", str); + str = new String(charBuffer, (x + 1 - 13), 13); + appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n"); } else { File fileName = new File(routerFileName); - log.debug("Will read the tail end of the file from the disk, x={0} len={1} str={2} routerFileName={3}", - x, len, str, routerFileName); + appendToFile(debugLogFileName, + fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + + str + "' routerFileName='" + routerFileName + "'\n"); + DebugLog.printAriDebug(fnName, + "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str + + "' routerFileName='" + routerFileName + "'"); try { str = getLastFewLinesOfFile(fileName, 3); } catch (IOException e) { - log.warn("IOException occurred, while reading file=" + fileName, e); + DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e); + dbLog.outputStackTrace(e); + e.printStackTrace(); } } } - log.debug("Parsed string was str='{0}', searched delimiter was {1}"); - return str.contains(delimeter); - } - - public void closeConnection() { - log.info("Closing connection"); - try { - if (reader != null) { - reader.close(); - } - } catch (IOException ex) { - log.warn("Could not close reader instance", ex); - } finally { - if (isConnected()) { - channel.disconnect(); - session.disconnect(); - channel = null; - session = null; - } - reader = null; + if (str.indexOf(delimeter) != -1) { + DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'"); + appendToFile(debugLogFileName, + fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n"); + return (true); + } else { + appendToFile(debugLogFileName, fnName + " Returning false"); + return (false); } + } - boolean isConnected() { - return channel != null && session != null; + public void closeConnection() { + String fn = "SshJcraftWrapper.closeConnection"; + debugLog.printRTAriDebug(fn, "Executing the closeConnection...."); + inputStream = null; + outputStream = null; + dis = null; + charBuffer = null; + session.disconnect(); + session = null; } public void send(String cmd) throws IOException { - try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) { - String command = enhanceCommandWithEOL(cmd); - int length = command.length(); - log.debug("Sending ssh command: length={0}, payload: {1}", command.length(), command); - if(isCmdLengthEnoughToSendInChunks(length, charsChunkSize)) { - sendSshCommandInChunks(command, dos); + String fn = "SshJcraftWrapper.send"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + + if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) { + cmd += "\n"; + } + int length = cmd.length(); + int i = -1; + int nchars = 300000; + int ncharsTotalSent = 0; + int ncharsSent = 0; + + appendToFile(debugLogFileName, fn + ": Sending: '" + cmd); + // debugLog.printRTAriDebug (fn, "cmd = "+cmd); + debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706 + try { + if (length > 600000) { + int timeout = 9000; + for (i = 0; i < length; i += nchars) { + String Cmd = cmd.substring(i, Math.min(length, i + nchars)); + ncharsSent = Cmd.length(); + ncharsTotalSent = ncharsTotalSent + Cmd.length(); + debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent); + dos.writeBytes(Cmd); + dos.flush(); + try { + debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length); + if (ncharsSent < length) { + receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i); + } else { + debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time...."); + dos.flush(); + } + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out."); + } + } } else { - sendSshCommand(command, dos); + debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes"); + dos.writeBytes(cmd); } + dos.flush(); + debugLog.printRTAriDebug(fn, "Leaving method"); + appendToFile(debugLogFileName, fn + ": Leaving method\n"); } catch (IOException e) { - log.error(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - throw e; + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); + dbLog.outputStackTrace(e); + throw new IOException(e.toString()); } } + public void sendChar(int v) throws IOException { - try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) { - if (log.isTraceEnabled()) { - log.trace("Sending charCode: {0}", v); - } + String fn = "SshJcraftWrapper.sendChar"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + try { + debugLog.printRTAriDebug(fn, "Sending: '" + v + "'"); dos.writeChar(v); dos.flush(); } catch (IOException e) { - log.error(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - throw e; + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); + throw new IOException(e.toString()); } } public void send(byte[] b, int off, int len) throws IOException { - try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) { + String fn = "SshJcraftWrapper.send:byte[]"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); + try { dos.write(b, off, len); dos.flush(); } catch (IOException e) { - log.error(Msg.SSH_DATA_EXCEPTION, e.getMessage()); - throw e; + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); + throw new IOException(e.toString()); } } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { - @Override public String getPassword() { return null; } - @Override public boolean promptYesNo(String str) { return false; } - @Override public String getPassphrase() { return null; } - @Override public boolean promptPassphrase(String message) { return false; } - @Override public boolean promptPassword(String message) { return false; } - @Override public void showMessage(String message) { - //stub } - @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { - return new String[0]; + return null; } } @@ -496,103 +575,184 @@ public class SshJcraftWrapper { this.listener = listener; } - private void appendToFile(String fileName, String dataToWrite) { - File outputFile = new File(fileName); - if (outputFile.exists()) { - try (FileWriter fw = new FileWriter(fileName, true); BufferedWriter ow = new BufferedWriter(fw)) { - ow.write(dataToWrite); - ow.close(); - } catch (IOException e) { - log.warn("IOException occurred while writing to file=" + fileName, e); + public void appendToFile(String fileName, String dataToWrite) { + String fn = "SshJcraftWrapper.appendToFile"; + + try { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + if (tmpFile.exists()) { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + // out.write(dataToWrite); + // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite); + out.write(getTheDate() + ": " + tId + ": " + dataToWrite); + out.close(); + } + } catch (IOException e) { + debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e); + } + } + + public void _appendToFile(String fileName, String dataToWrite) { + String fn = "SshJcraftWrapper.appendToFile"; + + try { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + if (tmpFile.exists()) { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + out.write(dataToWrite); + out.close(); } + } catch (IOException e) { + debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e); } } + public String getTheDate() { - DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy H:mm:ss "); - return dateFormat.format(Calendar.getInstance().getTime()); + Calendar cal = Calendar.getInstance(); + java.util.Date today = cal.getTime(); + DateFormat df1 = DateFormat.getDateInstance(); + DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss "); + return (df3.format(today)); } - public void appendToRouterFile(String fileName, StringBuilder dataToWrite) { - appendToFile(fileName, dataToWrite.toString()); + public void appendToRouterFile(String fileName, StringBuffer dataToWrite) { + String fnName = "SshJcraftWrapper.appendToRouterFile"; + debugLog.printRTAriDebug(fnName, "Entered.... "); + try { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + { + // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true))) + if (tmpFile.exists()) { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + // out.write("<!-- "+getTheDate() +": " +tId +" -->\n"); + out.write(dataToWrite.toString()); + out.close(); + } + } + } catch (IOException e) { + System.err.println("writeToFile() exception: " + e); + e.printStackTrace(); + } } public void appendToRouterFile(String fileName, int len) { - File outputFile = new File(fileName); - if (outputFile.exists()) { - try (FileWriter fw = new FileWriter(fileName, true); BufferedWriter ow = new BufferedWriter(fw)) { - ow.write(charBuffer, 0, len); - ow.close(); - } catch (IOException e) { - log.warn("Could not write data to router file:" + fileName, e); + String fnName = "SshJcraftWrapper.appendToFile"; + // debugLog.printRTAriDebug (fnName, "Entered.... len="+len); + try { + // First check to see if a file 'fileName' exist, if it does + // write to it. If it does not exist, don't write to it. + File tmpFile = new File(fileName); + // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true))) + if (tmpFile.exists()) { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + // out.write("<!-- "+getTheDate() +": " +tId +" -->\n"); + out.write(charBuffer, 0, len); + out.close(); } + } catch (IOException e) { + System.err.println("writeToFile() exception: " + e); + e.printStackTrace(); } } public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) { - if (str != null && !StringUtils.EMPTY.equals(str)) { - StringTokenizer strTok = new StringTokenizer(str, EOL); - StringBuilder sb = new StringBuilder(); + if (str != null) { + StringTokenizer strTok = new StringTokenizer(str, "\n"); + StringBuffer sb = new StringBuffer(); while (strTok.hasMoreTokens()) { String line = strTok.nextToken(); sb.append(line); } - return sb.toString().trim(); + return (sb.toString().trim()); + } else { + return (str); } - return StringUtils.EMPTY; } public String stripOffCmdFromRouterResponse(String routerResponse) { + String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse"; + // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n"); + // The session of SSH will echo the command sent to the router, in the router's response. // Since all our commands are terminated by a '\n', strip off the first line // of the response from the router. This first line contains the orginal command. - String[] responseTokens = routerResponse.split(EOL, 2); - return responseTokens[responseTokens.length - 1]; + StringTokenizer rr = new StringTokenizer(routerResponse, "\n"); + StringBuffer sb = new StringBuffer(); + + int numTokens = rr.countTokens(); + // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens); + if (numTokens > 1) { + rr.nextToken(); //Skip the first line. + while (rr.hasMoreTokens()) { + sb.append(rr.nextToken() + '\n'); + } + } + return (sb.toString()); } public void setRouterCommandType(String type) { + String fn = "SshJcraftWrapper.setRouterCommandType"; this.routerCmdType = type; - log.debug("Router command type is set to: {0}", type); + debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'"); } - public String getLastFewLinesOfFile(File file, int linesToRead) throws IOException { + public String getLastFewLinesOfFile(File file, int linesToRead) throws IOException { + String fn = "SshJcraftWrapper.getLastFewLinesOfFile"; + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); + int lines = 0; + StringBuilder builder = new StringBuilder(); String tail = ""; - try(RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) { - int lines = 0; - StringBuilder builder = new StringBuilder(); - long length = file.length(); - length--; - randomAccessFile.seek(length); - for (long seek = length; seek >= 0; --seek) { - randomAccessFile.seek(seek); - char c = (char) randomAccessFile.read(); - builder.append(c); - if (c == '\n') { - builder = builder.reverse(); - tail = builder.append(tail).toString(); - lines++; - builder.setLength(0); - if (lines == linesToRead) { - break; - } + long length = file.length(); + length--; + randomAccessFile.seek(length); + for (long seek = length; seek >= 0; --seek) { + randomAccessFile.seek(seek); + char c = (char) randomAccessFile.read(); + builder.append(c); + if (c == '\n') { + builder = builder.reverse(); + // System.out.println(builder.toString()); + tail = builder.toString() + tail; + lines++; + builder.setLength(0); + if (lines == linesToRead) { + break; } } } - if (log.isDebugEnabled()) { - log.debug("Content read from file={0} was tail={1}", file.getName(), tail); + randomAccessFile.close(); + if (!jcraftReadSwConfigFileFromDisk()) { + debugLog.printRTAriDebug(fn, "tail='" + tail + "'"); } + appendToFile(debugLogFileName, "tail='" + tail + "'\n"); return tail; } public boolean jcraftReadSwConfigFileFromDisk() { - return jcraftReadSwConfigFileFromDisk.exists(); + if (jcraftReadSwConfigFileFromDisk.exists()) { + return (true); + } else { + return (false); + } } public String getEquipNameCode() { - return equipNameCode; + return (equipNameCode); + } public void setEquipNameCode(String equipNameCode) { @@ -600,15 +760,20 @@ public class SshJcraftWrapper { } public String getRouterName() { - return routerName; + return (RouterName); } // Routine does reads until it has read 'nchars' or times out. - public String receiveUntilBufferFlush(int ncharsSent, int timeout, String command) throws IOException { - log.debug("ncharsSent={0}, timeout={1}, message={2}", ncharsSent, timeout, command); + public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message) + throws TimedOutException, IOException { + String fn = "SshJcraftWrapper.receiveUntilBufferFlush"; + StringBuffer sb2 = new StringBuffer(); + StringBuffer sbReceive = new StringBuffer(); + debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message); int ncharsTotalReceived = 0; int ncharsRead = 0; - StringBuilder received = new StringBuilder(); + boolean flag = false; + charactersFromBufferFlush.setLength(0); long deadline = new Date().getTime() + timeout; logMemoryUsage(); @@ -616,65 +781,120 @@ public class SshJcraftWrapper { session.setTimeout(timeout); // This is the socket timeout value. while (true) { if (new Date().getTime() > deadline) { - log.error(Msg.SSH_CONNECTION_TIMEOUT, routerName, command); - throw new TimedOutException("Routine has timed out"); - } - ncharsRead = reader.read(charBuffer, 0, readBufferSizeBytes); - if(ncharsRead >=0) { - received.append(charBuffer, 0, ncharsRead); + debugLog.printRTAriDebug(fn, + "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent=" + + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived); + flag = true; + throw new TimedOutException("Timeout: time in routine has exceed our deadline"); } + ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE); if (listener != null) { listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead)); } - appendToRouterFile("/tmp/" + routerName, ncharsRead); + appendToRouterFile("/tmp/" + RouterName, ncharsRead); ncharsTotalReceived = ncharsTotalReceived + ncharsRead; + // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); if (ncharsTotalReceived >= ncharsSent) { - log.debug("Received the correct number of characters, ncharsSent={0}, ncharsTotalReceived={1}", - ncharsSent, ncharsTotalReceived); + debugLog.printRTAriDebug(fn, + "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + + ncharsTotalReceived); logMemoryUsage(); - return received.toString(); + return; } } } catch (JSchException e) { - log.error(Msg.SSH_SESSION_CONFIG_ERROR, e.getMessage()); - log.debug("ncharsSent={0}, ncharsTotalReceived={1}, ncharsRead={2} until error occurred", - ncharsSent, ncharsTotalReceived, ncharsRead); - throw new TimedOutException(e.getMessage()); + debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e); + debugLog.printRTAriDebug(fn, + "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead=" + + ncharsRead); + throw new TimedOutException(e.toString()); } } public String getHostName() { - return hostName; + return (hostName); } public String getUserName() { - return userName; + return (userName); } public String getPassWord() { - return passWord; + return (passWord); + } + + public void sftpPut(String sourcePath, String destDirectory) throws IOException { + String fn = "SshJcraftWrapper.sftp"; + try { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); + debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory); + sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); + debugLog.printRTAriDebug(fn, "Sent successfully"); + sftpSession.disconnect(); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } } - public void sftpPutStringData(String stringOfData, String fullPathDest) throws IOException { - ChannelSftp sftp = null; + + public void SftpPut(String stringOfData, String fullPathDest) throws IOException { + String fn = "SshJcraftWrapper.Sftp"; try { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); InputStream is = new ByteArrayInputStream(stringOfData.getBytes()); - sftp = getSftpConnection(hostName, userName, passWord); - log.debug("Sending via sftp stringOfData to destination: {0}", fullPathDest); + debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest); sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); - } catch (JSchException ex) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostName, String.valueOf(DEFAULT_PORT), userName); - throw new IOException(ex.getMessage()); - } catch (SftpException ex) { - log.error(Msg.SFTP_TRANSFER_FAILED, hostName, userName, "PUT", ex.getMessage()); - throw new IOException(ex.getMessage()); - } finally { - disconnectSftp(sftp); + debugLog.printRTAriDebug(fn, "Sent successfully"); + sftpSession.disconnect(); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); } } public String sftpGet(String fullFilePathName) throws IOException { - return get(fullFilePathName, hostName, userName, passWord); + String fn = "SshJcraftWrapper.Sftp"; + try { + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); + InputStream in = null; + in = sftp.get(fullFilePathName); + String sftpFileString = readInputStreamAsString(in); + debugLog.printRTAriDebug(fn, "Retreived successfully"); + // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); + sftpSession.disconnect(); + return (sftpFileString); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); + } } public static String readInputStreamAsString(InputStream in) throws IOException { @@ -689,238 +909,266 @@ public class SshJcraftWrapper { return buf.toString(); } + public void logMemoryUsage() { + String fn = "SshJcraftWrapper.logMemoryUsage"; int mb = 1024 * 1024; long usedMemory; - long maxMemoryAvailable; - long memoryLeftOnHeap; - maxMemoryAvailable = runtime.maxMemory() / mb; - usedMemory = (runtime.totalMemory() / mb) - (runtime.freeMemory() / mb); - memoryLeftOnHeap = maxMemoryAvailable - usedMemory; - log.info("Memory usage: maxMemoryAvailable={0}, usedMemory={1}, memoryLeftOnHeap={2}", - maxMemoryAvailable, usedMemory, memoryLeftOnHeap); + long maxMemoryAdvailable; + long memoryLetfOnHeap; + maxMemoryAdvailable = (runtime.maxMemory() / mb); + usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb)); + memoryLetfOnHeap = maxMemoryAdvailable - usedMemory; + DebugLog.printAriDebug(fn, + "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap=" + + memoryLetfOnHeap); } - public void connect(String hostname, String username, String password, int timeOut, int portNum, + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + + + // User specifies the port number, and the subsystem + public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException { + String fn = "SshJcraftWrapper.connect"; - if (log.isDebugEnabled()) { - log.debug( - "Attempting to connect to {0} username={1} timeOut={2} portNum={3} subsystem={4}", - hostname, username, timeOut, portNum, subsystem); - } - this.routerName = hostname; - this.hostName = hostname; - this.userName = username; - this.passWord = password; + debugLog.printRTAriDebug(fn, + ":::Attempting to connect to " + hostname + " username=" + username + " prompt='" + + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem); + RouterName = hostname; + jsch = new JSch(); try { - channel = provideSessionChannel(CHANNEL_SUBSYSTEM_TYPE, portNum, timeOut); + session = jsch.getSession(username, hostname, portNum); + UserInfo ui = new MyUserInfo(); + session.setPassword(password); + session.setUserInfo(ui); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(timeOut); + session.setServerAliveCountMax( + 0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + channel = session.openChannel("subsystem"); ((ChannelSubsystem) channel).setSubsystem(subsystem); - ((ChannelSubsystem) channel).setPty(true); //expected ptyType vt102 - reader = new BufferedReader(new InputStreamReader(new DataInputStream(channel.getInputStream())), - readBufferSizeBytes); - channel.connect(5000); - } catch (JSchException e) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostname, String.valueOf(portNum), username); - throw new IOException(e.getMessage()); + // ((ChannelSubsystem)channel).setPtyType("vt102"); + ((ChannelSubsystem) channel).setPty(true); + + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); + channel.connect(); + debugLog.printRTAriDebug(fn, "Successfully connected."); + debugLog.printRTAriDebug(fn, "Five second sleep...."); + try { + Thread.sleep(5000); + } catch (java.lang.InterruptedException ee) { + boolean ignore = true; + } + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e); + throw new IOException(e.toString()); } } - public void connect(String hostName, String username, String password) throws IOException { - log.debug("Attempting to connect to {0} username={1} portNumber={2}", hostName, username, DEFAULT_PORT); - this.routerName = hostName; + public void connect(String hostName, String username, String password, int portNumber) throws IOException { + String fn = "SshJcraftWrapper.connect"; + jsch = new JSch(); + debugLog.printRTAriDebug(fn, + "::Attempting to connect to " + hostName + " username=" + username + " portNumber=" + portNumber); + debugLog.printRTAriDebug(fn, "Trace C"); + RouterName = hostName; this.hostName = hostName; - this.userName = username; - this.passWord = password; + userName = username; + passWord = password; try { - channel = provideSessionChannel(CHANNEL_SHELL_TYPE, DEFAULT_PORT, 30000); - ((ChannelShell) channel).setPtyType(TERMINAL_BASIC_MODE); - reader = new BufferedReader(new InputStreamReader(new DataInputStream(channel.getInputStream())), - readBufferSizeBytes); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + session = jsch.getSession(username, hostName, 22); + // session = jsch.getSession(username, hostName, portNumber); + UserInfo ui = new MyUserInfo(); + session.setConfig(config); + session.setPassword(password); + session.setUserInfo(ui); + session.connect(30000); + channel = session.openChannel("shell"); + session.setServerAliveCountMax( + 0); // If this is not set to '0', then socket timeout on all reads will not work!!!! + ((ChannelShell) channel).setPtyType("vt102"); + inputStream = channel.getInputStream(); + dis = new DataInputStream(inputStream); + reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE); channel.connect(); + debugLog.printRTAriDebug(fn, "::Successfully connected."); + debugLog.printRTAriDebug(fn, "::Flushing input buffer"); try { receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'"); } catch (Exception e) { - log.warn("Caught an Exception: Nothing to flush out.", e); + debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out."); } - } catch (JSchException e) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostName, String.valueOf(DEFAULT_PORT), username); - throw new IOException(e.getMessage()); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e); + // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e); + throw new IOException(e.toString()); } } public void put(String sourcePath, String destDirectory) throws IOException { - ChannelSftp sftp = null; + String fn = "SshJcraftWrapper.sftp"; try { - sftp = getSftpConnection(hostName, userName, passWord); - log.debug("Sending via sftp from source: {0} to destination: {1}", sourcePath, destDirectory); + Session sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); + debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory); sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE); - } catch (JSchException ex) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostName, String.valueOf(DEFAULT_PORT), userName); - throw new IOException(ex.getMessage()); - } catch (SftpException ex) { - log.error(Msg.SFTP_TRANSFER_FAILED, hostName, userName, "PUT", ex.getMessage()); - throw new IOException(ex.getMessage()); - } finally { - disconnectSftp(sftp); + debugLog.printRTAriDebug(fn, "Sent successfully"); + sftpSession.disconnect(); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + throw new IOException(e.toString()); } } public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException { - ChannelSftp sftp = null; + String fn = "SshJcraftWrapper.put"; + Session sftpSession = null; try { - log.debug("Sftp put invoked, connection details: username={1} hostname={2}", userName, hostName); - sftp = getSftpConnection(hostName, userName, passWord); + debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName); + jsch = new JSch(); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + sftpSession = jsch.getSession(userName, hostName, 22); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.setConfig(config); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); String oldFiles = fullPathDest + "*"; - log.debug("Deleting old files: {0}", oldFiles); - removeOldFiles(sftp, oldFiles, hostName, userName); - log.debug("Sending stringOfData to destination {0}", fullPathDest); + debugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles); + try { + sftp.rm(oldFiles); + debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest); + } catch (SftpException sft) { + String exp = "No such file"; + if (sft.getMessage() != null && sft.getMessage().contains(exp)) { + debugLog.printRTAriDebug(fn, "No files found -- Continue"); + } else { + debugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage()); + sft.printStackTrace(); + throw sft; + } + } sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE); - } catch (JSchException ex) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostName, String.valueOf(DEFAULT_PORT), userName); - throw new IOException(ex.getMessage()); - } catch (SftpException ex) { - log.error(Msg.SFTP_TRANSFER_FAILED, hostName, userName, "PUT", ex.getMessage()); - throw new IOException(ex.getMessage()); + debugLog.printRTAriDebug(fn, "Sent successfully"); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + throw new IOException(e.toString()); } finally { - disconnectSftp(sftp); - } - } - - private void removeOldFiles(ChannelSftp sftp, String oldFiles, String hostname, String username) throws SftpException { - try { - sftp.rm(oldFiles); - } catch (SftpException ex) { - if (ChannelSftp.SSH_FX_NO_SUCH_FILE == ex.id) { - log.warn("No files found, continue"); - } else { - log.error(Msg.SFTP_TRANSFER_FAILED, hostname, username, "RM", ex.getMessage()); - throw ex; + if(sftpSession != null) { + sftpSession.disconnect(); } } } + public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException { - ChannelSftp sftp = null; + String fn = "SshJcraftWrapper.get"; + Session sftpSession = null; try { - log.debug("Sftp get invoked, connection details: username={1} hostname={2}", - userName, hostName); - sftp = getSftpConnection(hostName, userName, passWord); + debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName); + jsch = new JSch(); + sftpSession = jsch.getSession(userName, hostName, 22); + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + UserInfo ui = new MyUserInfo(); + sftpSession.setPassword(passWord); + sftpSession.setUserInfo(ui); + sftpSession.setConfig(config); + sftpSession.connect(30 * 1000); + debugLog.printRTAriDebug(fn, "Opening up an sftp channel...."); + ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp"); + debugLog.printRTAriDebug(fn, "Connecting...."); + sftp.connect(); InputStream in = sftp.get(fullFilePathName); - return readInputStreamAsString(in); - } catch (JSchException ex) { - log.error(Msg.CANNOT_ESTABLISH_CONNECTION, hostName, String.valueOf(DEFAULT_PORT), userName); - throw new IOException(ex.getMessage()); - } catch (SftpException ex) { - log.error(Msg.SFTP_TRANSFER_FAILED, hostName, userName, "GET", ex.getMessage()); - throw new IOException(ex.getMessage()); + String sftpFileString = readInputStreamAsString(in); + debugLog.printRTAriDebug(fn, "Retreived successfully"); + return sftpFileString; + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + throw new IOException(e.toString()); } finally { - disconnectSftp(sftp); - } - } - - private void disconnectSftp (ChannelSftp sftp) { - if (sftp != null) { - sftp.disconnect(); - } - if (session != null) { - session.disconnect(); - session = null; + if(sftpSession != null) { + sftpSession.disconnect(); + } } } - ChannelSftp getSftpConnection(String hostname, String username, String password) throws JSchException { - connectSession(hostname, username, password, DEFAULT_PORT, 30_000); - ChannelSftp sftp = openSftpChannel(session); - sftp.connect(); - return sftp; - } - - ChannelSftp openSftpChannel(Session sftpSession) throws JSchException { - return (ChannelSftp) sftpSession.openChannel(CHANNEL_SFTP_TYPE); - } - public String send(String cmd, String delimiter) throws IOException { - try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) { - String command = enhanceCommandWithEOL(cmd); - int length = command.length(); - log.debug("Sending ssh command: length={0}, payload: {1}", command.length(), command); - if(isCmdLengthEnoughToSendInChunks(length, charsChunkSize)) { - return sendSshCommandInChunks(command, dos); - } else { - sendSshCommand(command, dos); - return receiveUntil(delimiter, 300000, cmd); - } - } - } + String fn = "SshJcraftWrapper.send"; + OutputStream out = channel.getOutputStream(); + DataOutputStream dos = new DataOutputStream(out); - private void sendSshCommand(@Nonnull String command, @Nonnull DataOutputStream channelOutputStream) - throws IOException { - channelOutputStream.writeBytes(command); - channelOutputStream.flush(); - } - - private String sendSshCommandInChunks(@Nonnull String command, @Nonnull DataOutputStream channelOutputStream) throws IOException { - StringBuilder received = new StringBuilder(); - int charsTotalSent = 0; - int length = command.length(); - for (int i = 0; i < length; i += charsChunkSize) { - String commandChunk = command.substring(i, Math.min(length, i + charsChunkSize)); - int numCharsSentInChunk = commandChunk.length(); - charsTotalSent = charsTotalSent + commandChunk.length(); - log.debug("Iteration nr:{0}, sending command chunk: {1}", i, numCharsSentInChunk); - channelOutputStream.writeBytes(commandChunk); - channelOutputStream.flush(); - try { - if (numCharsSentInChunk < length) { - received.append(receiveUntilBufferFlush(numCharsSentInChunk, sessionTimeoutMs, command)); - } else { - log.trace("i={0}, flush immediately", i); - channelOutputStream.flush(); + if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) { + cmd += "\n"; + } + int length = cmd.length(); + int i = -1; + int nchars = 300000; + int ncharsTotalSent = 0; + int ncharsSent = 0; + + debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706 + debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706 + try { + if (length > 600000) { + int timeout = 9000; + for (i = 0; i < length; i += nchars) { + String Cmd = cmd.substring(i, Math.min(length, i + nchars)); + ncharsSent = Cmd.length(); + ncharsTotalSent = ncharsTotalSent + Cmd.length(); + debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent); + dos.writeBytes(Cmd); + dos.flush(); + try { + debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length); + if (ncharsSent < length) { + receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i); + } else { + debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time...."); + dos.flush(); + } + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out."); + } } - } catch (IOException ex) { - log.warn("IOException occurred: nothing to flush out", ex); + } else { + debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes"); + dos.writeBytes(cmd); } + dos.flush(); + // Now lets get the response. + String response = receiveUntil(delimiter, 300000, cmd); + debugLog.printRTAriDebug(fn, "Leaving method"); + return (response); + } catch (IOException e) { + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); + throw new IOException(e.toString()); } - return received.toString(); - } - - public void setSessionTimeoutMs(int sessionTimeoutMs) { - this.sessionTimeoutMs = sessionTimeoutMs; - } - - void setCharsChunkSize(int charsChunkSize) { - this.charsChunkSize = charsChunkSize; - } - - private boolean isCmdLengthEnoughToSendInChunks(int length, int chunkSize) { - return length > 2 * chunkSize; - } - - private String enhanceCommandWithEOL(@Nonnull String originalCommand) { - char commandEnding = originalCommand.charAt(originalCommand.length() - 1); - if (commandEnding != '\n' && commandEnding != '\r') { - return originalCommand + EOL; - } - return originalCommand; - } - - private Channel provideSessionChannel(String channelType, int port, int timeout) throws JSchException { - connectSession(this.hostName, this.userName, this.passWord, port, timeout); - session.setServerAliveCountMax( - 0); // If this is not set to '0', then socket timeout on all reads will not work!!!! - return session.openChannel(channelType); } - private void connectSession(String hostname, String username, String password, int port, int timeout) throws JSchException { - session = jsch.getSession(username, hostname, port); - session.setPassword(password); - session.setUserInfo(new MyUserInfo()); //needed? - session.setConfig(STRICT_HOST_CHECK_KEY, STRICT_HOST_CHECK_VALUE); - session.connect(timeout); - } } diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java index 3e41664da..534606670 100644 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/ConfigComponentAdaptorTest.java @@ -2,34 +2,27 @@ * ============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. * ================================================================================ * Copyright (C) 2017 Amdocs * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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 static org.onap.appc.ccadaptor.ConfigComponentAdaptor.GET_CONFIG_TEMPLATE_PARAM; -import static org.onap.appc.ccadaptor.ConfigComponentAdaptor.HOST_IP_PARAM; -import static org.onap.appc.ccadaptor.ConfigComponentAdaptor.PASSWORD_PARAM; -import static org.onap.appc.ccadaptor.ConfigComponentAdaptor.PORT_NUMBER_PARAM; -import static org.onap.appc.ccadaptor.ConfigComponentAdaptor.USERNAME_PARAM; - import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -48,11 +41,11 @@ public class ConfigComponentAdaptorTest { String Get_config_template = ("get_config_template"); String key = "GetCliRunningConfig"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); SvcLogicContext ctx = new SvcLogicContext(); ctx.setAttribute( @@ -68,11 +61,11 @@ public class ConfigComponentAdaptorTest { String Get_config_template = ("get_config_template"); String key = "DownloadCliConfig"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); SvcLogicContext ctx = new SvcLogicContext(); ctx.setAttribute( @@ -88,11 +81,11 @@ public class ConfigComponentAdaptorTest { String Get_config_template = ("get_config_template"); String key = "xml-download"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); SvcLogicContext ctx = new SvcLogicContext(); ctx.setAttribute( @@ -108,11 +101,11 @@ public class ConfigComponentAdaptorTest { String Get_config_template = ("get_config_template"); String key = "xml-getrunningconfig"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); SvcLogicContext ctx = new SvcLogicContext(); ctx.setAttribute( @@ -128,11 +121,11 @@ public class ConfigComponentAdaptorTest { String Get_config_template = ("get_config_template"); String key = "escapeSql"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); SvcLogicContext ctx = new SvcLogicContext(); ctx.setAttribute( @@ -149,13 +142,13 @@ public class ConfigComponentAdaptorTest { String Download_config_template = ("test"); String key = "GetCliRunningConfig"; Map<String, String> parameters = new HashMap<>(); - parameters.put(HOST_IP_PARAM, "test"); - parameters.put(USERNAME_PARAM, "test"); - parameters.put(PASSWORD_PARAM, "password"); - parameters.put(PORT_NUMBER_PARAM, "22"); + parameters.put("Host_ip_address", "test"); + parameters.put("User_name", "test"); + parameters.put("Password", "password"); + parameters.put("Port_number", "22"); + parameters.put("Get_config_template", Get_config_template); parameters.put("Protocol", "netconf"); parameters.put("Contents", "Contents"); - parameters.put(GET_CONFIG_TEMPLATE_PARAM, Get_config_template); parameters.put("Download_config_template", Download_config_template); parameters.put("Config_contents", "test"); @@ -180,7 +173,7 @@ public class ConfigComponentAdaptorTest { cca.configure(key, parameters, ctx); } - @Test + //@Test public void testAll2() { Properties props = null; ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); @@ -269,4 +262,5 @@ public class ConfigComponentAdaptorTest { String result = Whitebox.invokeMethod(cca, "prepare", ctx, "test", "test"); Assert.assertEquals("template", result); } + } diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java new file mode 100644 index 000000000..2c86cbb9a --- /dev/null +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/DebugLogTest.java @@ -0,0 +1,91 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.ccadaptor;
+
+import static junit.framework.TestCase.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class DebugLogTest {
+
+ @BeforeClass
+ public static void createEmptyLogFile() throws IOException {
+ Path logPath = Paths.get(buildTestResourcePath("rt.log"));
+ Files.createFile(logPath);
+ }
+
+ @AfterClass
+ public static void removeLog() throws IOException {
+ Path existingLogPath = Paths.get(buildTestResourcePath("rt.log"));
+ Files.delete(existingLogPath);
+ }
+
+ //@Test
+ public void printRTAriDebug_shouldNotDoAnything_whenLogFileDoesNotExist() {
+ // GIVEN
+ Path nonExistingLogPath = Paths.get(buildTestResourcePath("nonExisting.log"));
+
+ // WHEN
+ // DebugLog debugLog = new DebugLog(nonExistingLogPath);
+ DebugLog debugLog = new DebugLog();
+ debugLog.printRTAriDebug("testMethod", "Custom Debug Message");
+
+ // THEN
+ assertTrue(Files.notExists(nonExistingLogPath));
+ }
+
+ //@Test
+ public void printRTAriDebug_shouldWriteMessageToLogWithDate_whenLogFileExists() throws IOException {
+ // GIVEN
+ Path existingLogPath = Paths.get(buildTestResourcePath("rt.log"));
+
+ // WHEN
+ //DebugLog debugLog = new DebugLog(existingLogPath);
+ DebugLog debugLog = new DebugLog();
+ debugLog.printRTAriDebug("testMethod", "Custom Debug Message");
+
+ // THEN
+ String logEntry = readLogEntry(existingLogPath);
+ assertTrue(logEntry.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2} testMethod Custom Debug Message"));
+ }
+
+ private static String buildTestResourcePath(String resourceName) {
+ String path = DebugLogTest.class.getClassLoader().getResource("./").getPath();
+ return path + resourceName;
+ }
+
+ private String readLogEntry(Path path) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) {
+ return br.readLine();
+ }
+ }
+}
diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java index 305f7f5a9..ce2b385b2 100644 --- a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java +++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java @@ -2,23 +2,22 @@ * ============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. * ================================================================================ * Copyright (C) 2017 Amdocs * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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========================================================= */ @@ -71,98 +70,50 @@ import org.apache.commons.io.IOUtils; @RunWith(MockitoJUnitRunner.class) public class SshJcraftWrapperTest { - - private static final String USER = "username"; - private static final String PASS = "pass"; - private static final String HOST = "hostname"; - private static final String SUBSYSTEM = "netconf"; - private static final String PROMPT = "]]>]]>"; - private static final String SEARCH_STR = "</rpc-reply>"; - private static final String REMOTE_PATH = "/var/tmp/path/"; - private static final String SOURCE_PATH = "/tmp/local/path/"; - private static final String IO_EXCEPTION_MSG = "IOException should be thrown"; - private static final int READ_TIMEOUT = 180_000; - private static final int PORT_NUM = 23; - private static final int SESSION_TIMEOUT = 30_000; - private static final int READ_INTERVAL_MS = 1; - private static final int READ_BUFFER_SIZE = 10; - - private SshJcraftWrapper cut; - @Mock - private JSch jSchMock; - @Mock - private Session session; - @Mock - private ChannelShell channelShell; - @Mock - private ChannelSubsystem channelSubsystem; - @Mock - private InputStream channelIs; - @Mock - private OutputStream channelOs; - @Mock - private ChannelSftp channelSftp; - - @Before - public void setUpTest() throws Exception { - InputStream is = IOUtils.toInputStream("test input stream:~#", "UTF-8"); - given(channelShell.getInputStream()).willReturn(is); - given(channelSubsystem.getInputStream()).willReturn(is); - given(session.openChannel(SshJcraftWrapper.CHANNEL_SHELL_TYPE)).willReturn(channelShell); - given(session.openChannel(SshJcraftWrapper.CHANNEL_SUBSYSTEM_TYPE)).willReturn(channelSubsystem); - given(jSchMock.getSession(anyString(), anyString(), anyInt())).willReturn(session); - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, READ_BUFFER_SIZE); - } - - @Ignore @Test - public void TestCheckIfReceivedStringMatchesDelimeter() { + public void TestCheckIfReceivedStringMatchesDelimeter(){ SshJcraftWrapper wrapper = new SshJcraftWrapper(); wrapper.getTheDate(); boolean result = wrapper.checkIfReceivedStringMatchesDelimeter("#", "test#", "test#"); Assert.assertEquals(true, result); } - @Ignore @Test - public void testRemoveWhiteSpaceAndNewLineCharactersAroundString() { + public void testRemoveWhiteSpaceAndNewLineCharactersAroundString(){ SshJcraftWrapper wrapper = new SshJcraftWrapper(); String nameSpace = wrapper.removeWhiteSpaceAndNewLineCharactersAroundString("namespace "); Assert.assertEquals("namespace", nameSpace); } - @Ignore @Test - public void testStripOffCmdFromRouterResponse() { + public void testStripOffCmdFromRouterResponse(){ SshJcraftWrapper wrapper = new SshJcraftWrapper(); String result = wrapper.stripOffCmdFromRouterResponse("test\nsuccess"); Assert.assertEquals("success\n", result); } //@Test - public void testGetLastFewLinesOfFile() throws FileNotFoundException, IOException { + public void testGetLastFewLinesOfFile() throws FileNotFoundException, IOException{ SshJcraftWrapper wrapper = new SshJcraftWrapper(); URL path = SshJcraftWrapperTest.class.getResource("Test"); File file = new File(path.getFile()); - String value = wrapper.getLastFewLinesOfFile(file, 1); + String value = wrapper.getLastFewLinesOfFile(file,1); Assert.assertEquals("\nTest data 3", value); } - @Ignore - @Test(expected = Exception.class) - public void testSetRouterCommandType() throws IOException { + @Test(expected=Exception.class) + public void testSetRouterCommandType() throws IOException{ SshJcraftWrapper wrapper = new SshJcraftWrapper(); wrapper.setRouterCommandType("test"); wrapper.receiveUntil("test", 2, "test"); } - @Ignore @Test - public void testValues() throws IOException { + public void testValues() throws IOException{ SshJcraftWrapper wrapper = new SshJcraftWrapper(); wrapper.setEquipNameCode("testcode"); wrapper.setRouterCommandType("testcommand"); - String equipName = wrapper.getEquipNameCode(); + String equipName =wrapper.getEquipNameCode(); wrapper.getHostName(); wrapper.getPassWord(); wrapper.getRouterName(); @@ -171,1009 +122,19 @@ public class SshJcraftWrapperTest { Assert.assertEquals("testcode", equipName); } - @Ignore - @Test(expected = Exception.class) - public void testSetRouterCommandType2() throws IOException { + @Test(expected=Exception.class) + public void testSetRouterCommandType2() throws IOException{ SshJcraftWrapper wrapper = new SshJcraftWrapper(); wrapper.appendToRouterFile("test", 2); - StringBuilder sb = new StringBuilder(); - sb.append("test"); - wrapper.appendToRouterFile("Test.txt", sb); + StringBuffer buffer = new StringBuffer(); + buffer.append("test"); + wrapper.appendToRouterFile("Test.txt", buffer); wrapper.receiveUntilBufferFlush(3, 4, "test"); } - @Ignore - @Test(expected = Exception.class) - public void testSetRouterCommandType3() throws IOException { + @Test(expected=Exception.class) + public void testSetRouterCommandType3() throws IOException{ SshJcraftWrapper wrapper = new SshJcraftWrapper(); wrapper.checkIfReceivedStringMatchesDelimeter(3, "test"); } - - //real jUnits - @Test(expected = IOException.class) - public void connect_shouldThrowIOException_whenJSchFails() throws Exception { - //given - given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException()); - - //when - cut.connect(HOST, USER, PASS); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void connect_shouldSetVariables() throws Exception { - //when - cut.connect(HOST, USER, PASS); - - //then - assertEquals(HOST, cut.getHostName()); - assertEquals(HOST, cut.getRouterName()); - assertEquals(USER, cut.getUserName()); - assertEquals(PASS, cut.getPassWord()); - } - - @Test - public void connect_shouldSetUpSessionWithProperInvocationOrder() throws Exception { - //given - InOrder inOrder = inOrder(session, channelShell); - - //when - cut.connect(HOST, USER, PASS); - - //then - verifySessionConfigurationOrderForChannelShellOpening( - inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT); - } - - @Test - public void connect_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception { - //given - doThrow(new JSchException()).when(session).setTimeout(anyInt()); - - //when - cut.connect(HOST, USER, PASS); - - //then - verify(session).setTimeout(anyInt()); - } - - @Test(expected = IOException.class) - public void connect_withSubsystem_shouldThrowIOException_whenJSchFails() throws Exception { - //given - given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException()); - - //when - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void connect_withSubsystem_shouldSetRouterName() throws Exception { - //when - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - - //then - assertEquals(HOST, cut.getRouterName()); - } - - @Test - public void connect_withSubsystem_shouldSetUpSessionWithProperInvocationOrder() throws Exception { - //given - InOrder inOrder = inOrder(session, channelSubsystem); - - //when - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - - //then - verify(jSchMock).getSession(USER, HOST, PORT_NUM); - inOrder.verify(session).setPassword(PASS); - inOrder.verify(session).setUserInfo(any(UserInfo.class)); - inOrder.verify(session) - .setConfig(SshJcraftWrapper.STRICT_HOST_CHECK_KEY, SshJcraftWrapper.STRICT_HOST_CHECK_VALUE); - inOrder.verify(session).connect(SESSION_TIMEOUT); - inOrder.verify(session).setServerAliveCountMax(0); - inOrder.verify(session).openChannel(SshJcraftWrapper.CHANNEL_SUBSYSTEM_TYPE); - inOrder.verify(channelSubsystem).getInputStream(); - inOrder.verify(channelSubsystem).connect(anyInt()); - inOrder.verifyNoMoreInteractions(); - verifyNoMoreInteractions(jSchMock); - } - - @Test(expected = IOException.class) - public void connect_withPrompt_shouldThrowIOException_whenJSchFails() throws Exception { - //given - given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException()); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void connect_withPrompt_shouldSetVariables() throws Exception { - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT); - - //then - assertEquals(HOST, cut.getHostName()); - assertEquals(HOST, cut.getRouterName()); - assertEquals(USER, cut.getUserName()); - assertEquals(PASS, cut.getPassWord()); - } - - @Test - public void connect_withPrompt_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception { - //given - doThrow(new JSchException()).when(session).setTimeout(anyInt()); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT); - - //then - verify(session).setTimeout(anyInt()); - } - - @Test - public void connect_withPrompt_shouldSetUpSessionWithProperInvocationOrder() throws Exception { - //given - InOrder inOrder = inOrder(session, channelShell); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT); - - //then - verifySessionConfigurationOrderForChannelShellOpening( - inOrder, USER, HOST, PASS, SshJcraftWrapper.DEFAULT_PORT, SESSION_TIMEOUT); - } - - @Test(expected = IOException.class) - public void connect_withPort_shouldThrowIOException_whenJSchFails() throws Exception { - //given - given(jSchMock.getSession(anyString(), anyString(), anyInt())).willThrow(new JSchException()); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void connect_withPort_shouldSetVariables() throws Exception { - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM); - - //then - assertEquals(HOST, cut.getHostName()); - assertEquals(HOST, cut.getRouterName()); - assertEquals(USER, cut.getUserName()); - assertEquals(PASS, cut.getPassWord()); - } - - @Test - public void connect_withPort_shouldFinishSuccessfully_whenExceptionThrownDuringReceivingPhase() throws Exception { - //given - doThrow(new JSchException()).when(session).setTimeout(anyInt()); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM); - - //then - verify(session).setTimeout(anyInt()); - } - - @Test - public void connect_withPort_shouldSetUpSessionWithProperInvocationOrder() throws Exception { - //given - InOrder inOrder = inOrder(session, channelShell); - - //when - cut.connect(HOST, USER, PASS, PROMPT, SESSION_TIMEOUT, PORT_NUM); - - //then - verifySessionConfigurationOrderForChannelShellOpening(inOrder, USER, HOST, PASS, PORT_NUM, SESSION_TIMEOUT); - } - - private void verifySessionConfigurationOrderForChannelShellOpening(InOrder inOrder, String user, String host, - String pass, int port, int sessionTimeout) throws Exception { - verify(jSchMock).getSession(user, host, port); - inOrder.verify(session).setPassword(pass); - inOrder.verify(session).setUserInfo(any(UserInfo.class)); - inOrder.verify(session) - .setConfig(SshJcraftWrapper.STRICT_HOST_CHECK_KEY, SshJcraftWrapper.STRICT_HOST_CHECK_VALUE); - inOrder.verify(session).connect(sessionTimeout); - inOrder.verify(session).setServerAliveCountMax(0); - inOrder.verify(session).openChannel(SshJcraftWrapper.CHANNEL_SHELL_TYPE); - inOrder.verify(channelShell).getInputStream(); - inOrder.verify(channelShell).connect(); - inOrder.verify(session).setTimeout(anyInt()); - inOrder.verifyNoMoreInteractions(); - verifyNoMoreInteractions(jSchMock); - } - - @Test - public void closeConnection_shouldCloseReaderChannelAndSession_inAGivenOrder() throws Exception { - //given - provideConnectedSubsystemInstance(); - InOrder inOrder = inOrder(channelIs, channelSubsystem, session); - - //when - cut.closeConnection(); - - //then - inOrder.verify(channelIs).close(); - inOrder.verify(channelSubsystem).disconnect(); - inOrder.verify(session).disconnect(); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void closeConnection_shouldCloseChannelAndSession_whenClosingReaderFails() throws Exception { - //given - doThrow(new IOException("failed to close reader")).when(channelIs).close(); - provideConnectedSubsystemInstance(); - - //when - cut.closeConnection(); - - //then - verify(channelIs).close(); - verify(channelSubsystem).disconnect(); - verify(session).disconnect(); - } - - @Test - public void closeConnection_shouldBeIdempotent_whenRunOnNewInstance() throws Exception { - //given - assertFalse(cut.isConnected()); - - //when - cut.closeConnection(); - - //then - assertFalse(cut.isConnected()); - } - - @Test - public void closeConnection_shouldBeIdempotent_whenRunTwiceOnConnectedInstance() throws Exception { - //given - provideConnectedSubsystemInstance(); - - //when - cut.closeConnection(); - cut.closeConnection(); - - //then - assertFalse(cut.isConnected()); - } - - @Test - public void closeConnection_shouldCloseResourcesOnce_whenRunTwiceOnConnectedInstance() throws Exception { - //given - provideConnectedSubsystemInstance(); - - //when - cut.closeConnection(); - cut.closeConnection(); - - //then - verify(channelIs, times(1)).close(); - verify(channelSubsystem, times(1)).disconnect(); - verify(session, times(1)).disconnect(); - } - - private void provideConnectedSubsystemInstance() throws Exception { - given(channelSubsystem.getInputStream()).willReturn(channelIs); - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - assertTrue(cut.isConnected()); - } - - //receiveUntil tests begin - @Test(expected = IllegalStateException.class) - public void receiveUntil_shouldThrowIllegalStateException_whenInstanceIsNotConnected() throws Exception { - //given - assertFalse(cut.isConnected()); - - //when - cut.receiveUntil(SEARCH_STR, READ_TIMEOUT, ""); - - //then - fail("IllegalStateException should be thrown"); - } - - @Test(expected = IllegalStateException.class) - public void receiveUntil_shouldThrowIllegalStateException_whenJschReaderStreamIsNotAvailable() throws Exception { - //given - provideConnectedSubsystemInstance(); - given(channelIs.available()).willReturn(0); - - //when - cut.receiveUntil(SEARCH_STR, READ_TIMEOUT, ""); - - //then - fail("IllegalStateException should be thrown"); - } - - @Test(expected = TimedOutException.class) - public void receiveUntil_shouldThrowTimedOutException_whenSessionFails() throws Exception { - //given - given(channelSubsystem.getInputStream()).willReturn(IOUtils.toInputStream("test input stream:~#", "UTF-8")); - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - assertTrue(cut.isConnected()); - doThrow(new JSchException("Session is not available")).when(session).setTimeout(anyInt()); - - //when - cut.receiveUntil(SEARCH_STR, READ_TIMEOUT, ""); - - //then - fail("TimedOutException should be thrown"); - } - - @Test(expected = TimedOutException.class) - public void receiveUntil_shouldThrowTimedOutException_whenReadFails() throws Exception { - //given - provideConnectedSubsystemInstance(); - given(channelIs.available()).willReturn(1); - given(channelIs.read(any(), anyInt(), anyInt())).willThrow(new IOException("Could not read stream")); - - //when - cut.receiveUntil(SEARCH_STR, READ_TIMEOUT, ""); - - //then - fail("TimedOutException should be thrown"); - } - - @Test(expected = TimedOutException.class) - public void receiveUntil_shouldThrowException_whenTimeoutIsReached() throws Exception { - //given - String streamContent = "test input stream:~#"; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - cut.receiveUntil(SEARCH_STR, -1000, " Some fake command\n"); - - //then - fail("TimedOutException should be thrown"); - } - - @Test(expected = TimedOutException.class) - public void receiveUntil_shouldThrowException_whenReachedEndOfStream_andCouldNotReadMoreBytes() throws Exception { - //given - provideConnectedSubsystemInstance(); - given(channelIs.available()).willReturn(1); - given(channelIs.read(any(), anyInt(), anyInt())).willReturn(-1); - - //when - cut.receiveUntil(SEARCH_STR, READ_TIMEOUT, ""); - - //then - fail("TimedOutException should be thrown"); - } - - @Test - public void receiveUntil_shouldReadUnderlyingStream_andStripOffFirstLine() throws Exception { - //given - String command = "Command" + SshJcraftWrapper.EOL; - String reply = "Reply" + SshJcraftWrapper.EOL; - String streamContent = command + reply + PROMPT; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - String result = cut.receiveUntil(PROMPT, SESSION_TIMEOUT, command); - - //then - assertEquals(reply + PROMPT, result); - } - - @Test - public void receiveUntil_shouldReadUnderlyingStream_andReturnWholeReadString() throws Exception { - //given - String streamContent = "Command and Reply in just one line" + PROMPT; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - String result = cut.receiveUntil(PROMPT, SESSION_TIMEOUT, streamContent); - - //then - assertEquals(streamContent, result); - } - - @Test - public void receiveUntil_shouldCutOffSpecialCharactersFromStream() throws Exception { - //given - char special1 = Character.UNASSIGNED; - char special2 = Character.ENCLOSING_MARK; - char special3 = Character.LINE_SEPARATOR; - char special4 = Character.MODIFIER_SYMBOL; - StringBuilder sb = new StringBuilder("Command"); - sb.append(special1).append("With").append(special2).append("Special") - .append(special3).append("Characters").append(special4).append("Set").append(PROMPT); - - provideConnectedSubsystemInstanceWithStreamContent(sb.toString()); - - //when - String result = cut.receiveUntil(PROMPT, SESSION_TIMEOUT, ""); - - //then - assertEquals("CommandWithSpecialCharactersSet" + PROMPT, result); - } - - @Test - public void receiveUntil_shouldReadUnderlyingStream_untilCLIDelimiterFound_whenProperDelimiterSet() - throws Exception { - //given - String cliDelimiter = "#$"; - String delimiters = PROMPT + SshJcraftWrapper.DELIMITERS_SEPARATOR + cliDelimiter; - String streamContent = "Command for CLI invocation #"; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - String result = cut.receiveUntil(delimiters, SESSION_TIMEOUT, streamContent); - - //then - assertEquals(streamContent, result); - } - - @Test - public void receiveUntil_shouldReadUnderlyingStream_untilCLIDelimiterFound_whenCLICommandSet() throws Exception { - //given - String streamContent = "Command for CLI invocation #"; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - cut.setRouterCommandType("CLI"); - - //when - String result = cut.receiveUntil("", SESSION_TIMEOUT, streamContent); - - //then - assertEquals(streamContent, result); - } - - @Test - public void receiveUntil_shouldReadUnderlyingStream_untilCLIDelimiterFound_forShowConfigCommand() throws Exception { - //given - String streamContent = "show config\nconfig content#"; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - String result = cut.receiveUntil("#", SESSION_TIMEOUT, streamContent); - - //then - assertEquals("config content#", result); - } - - @Test - public void receiveUntil_shouldWriteOutputToRouterFile_whenReadingIOSXRswConfigFile_confirmFromFile() - throws Exception { - receiveUntil_shouldWriteOutputToRouterFile_whenReadingIOSXRswConfigFile(); - } - - @Test - public void receiveUntil_shouldWriteOutputToRouterFile_whenReadingIOSXRswConfigFile_confirmFromBuffer() - throws Exception { - //given - int biggerBufferSize = 32; - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, biggerBufferSize); - - receiveUntil_shouldWriteOutputToRouterFile_whenReadingIOSXRswConfigFile(); - } - - private void receiveUntil_shouldWriteOutputToRouterFile_whenReadingIOSXRswConfigFile() throws Exception { - //given - String routerName = "router"; - String command = "RP/0/RP0/CPU0: " + routerName + " #IOS_XR_uploadedSwConfigCmd"; - String configFileEnding = "\nXML>"; - String streamContent = "Config file\ncontent" + configFileEnding; - provideConnectedSubsystemInstanceWithStreamContent(streamContent); - - //when - String result = cut.receiveUntil("", SESSION_TIMEOUT, command); - - //then - assertNull(result); //TO-DO: it would be better to return empty string in this situation - assertFileExist(routerName); - - //after - teardownFile(routerName); - } - - private void provideConnectedSubsystemInstanceWithStreamContent(String streamContent) throws Exception { - given(channelSubsystem.getInputStream()).willReturn(IOUtils.toInputStream(streamContent, "UTF-8")); - cut.connect(HOST, USER, PASS, SESSION_TIMEOUT, PORT_NUM, SUBSYSTEM); - assertTrue(cut.isConnected()); - } - - private void teardownFile(String routerName) { - File file = new File(routerName); - if (file.exists() && file.isFile()) { - file.delete(); - } - } - - private void assertFileExist(String fileName) { - File file = new File(fileName); - assertTrue(file.exists()); - assertTrue(file.isFile()); - } - - @Test - public void send_withReceive_shouldWriteCommandToChannelOutputStream_andReturnReceivedCommand() throws Exception { - //given - String command = "sdc"; - String delimiter = ":"; - InOrder inOrder = inOrder(channelOs); - provideConnectedSubsystemInstanceWithStreamContent(command + delimiter); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - - //when - String result = cut.send(command, delimiter); - - //then - verifySdcCommandSent(inOrder); - assertEquals(command + delimiter, result); - } - - @Test - public void send_shouldWriteCommandToChannelOutputStream() throws Exception { - //given - String command = "sdc"; - InOrder inOrder = inOrder(channelOs); - provideConnectedSubsystemInstance(); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - - //when - cut.send(command); - - //then - verifySdcCommandSent(inOrder); - } - - private void verifySdcCommandSent(InOrder inOrder) throws IOException { - inOrder.verify(channelOs).write('s'); - inOrder.verify(channelOs).write('d'); - inOrder.verify(channelOs).write('c'); - inOrder.verify(channelOs, atLeastOnce()).flush(); - inOrder.verify(channelOs, atLeastOnce()).close(); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void send_withReceive_shouldWriteCommandInChunksToChannelOutputStream_andReturnReceivedCommand() - throws Exception { - //given - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, 1); - cut.setCharsChunkSize(1); - String command = "sdc"; - String delimiter = ":"; - int timeout = 9000; - provideConnectedSubsystemInstanceWithStreamContent(command + delimiter + SshJcraftWrapper.EOL); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - InOrder inOrder = inOrder(channelOs, session); - - //when - String result = cut.send(command, delimiter); - - //then - verifySdcCommandSentInChunk(inOrder, timeout); - assertEquals(command + delimiter, result); - } - - @Test - public void send_shouldWriteCommandInChunksToChannelOutputStream() throws Exception { - //given - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, 1); - cut.setCharsChunkSize(1); - String command = "sdc"; - int timeout = 9000; - provideConnectedSubsystemInstanceWithStreamContent(command + SshJcraftWrapper.EOL); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - InOrder inOrder = inOrder(channelOs, session); - - //when - cut.send(command); - - //then - verifySdcCommandSentInChunk(inOrder, timeout); - } - - private void verifySdcCommandSentInChunk(InOrder inOrder, int timeout) throws Exception { - inOrder.verify(channelOs).write('s'); - inOrder.verify(channelOs).flush(); - inOrder.verify(session).setTimeout(timeout); - inOrder.verify(channelOs).write('d'); - inOrder.verify(channelOs).flush(); - inOrder.verify(session).setTimeout(timeout); - inOrder.verify(channelOs).write('c'); - inOrder.verify(channelOs).flush(); - inOrder.verify(session).setTimeout(timeout); - inOrder.verify(channelOs, atLeastOnce()).flush(); - inOrder.verify(channelOs, atLeastOnce()).close(); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void send_withReceive_shouldReturnActualResult_whenTimeoutReached() throws Exception { - //given - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, 1); - cut.setCharsChunkSize(1); - cut.setSessionTimeoutMs(-1); - String command = "sdc"; - String delimiter = ":"; - provideConnectedSubsystemInstanceWithStreamContent(command + SshJcraftWrapper.EOL); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - - //when - String result = cut.send(command, delimiter); - - //then - assertEquals(StringUtils.EMPTY, result); - } - - @Test - public void send_withReceive_shouldReturnActualResult_whenCouldNotSetSessionTimeout() throws Exception { - //given - cut = new SshJcraftWrapper(jSchMock, READ_INTERVAL_MS, 1); - cut.setCharsChunkSize(1); - String command = "sdc"; - String delimiter = ":"; - provideConnectedSubsystemInstanceWithStreamContent(command + SshJcraftWrapper.EOL); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - doThrow(new JSchException("failed to set session timeout")).when(session).setTimeout(anyInt()); - - //when - String result = cut.send(command, delimiter); - - //then - assertEquals(StringUtils.EMPTY, result); - } - - @Test - public void sendChar_shouldWriteCharacterToChannelOutputStream() throws Exception { - //given - int charNum = 100; - provideConnectedSubsystemInstance(); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - InOrder inOrder = inOrder(channelOs); - - //when - cut.sendChar(charNum); - - //then - inOrder.verify(channelOs).write(charNum); - inOrder.verify(channelOs, atLeastOnce()).flush(); - inOrder.verify(channelOs, atLeastOnce()).close(); - inOrder.verifyNoMoreInteractions(); - } - - @Test(expected = IOException.class) - public void sendChar_shouldRethrowIOException_whenOccurs() throws Exception { - //given - int charNum = 100; - provideConnectedSubsystemInstance(); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - doThrow(new IOException()).when(channelOs).write(charNum); - - //when - cut.sendChar(charNum); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void send_withByteBuffer_shouldWriteBufferToChannelOutputStream() throws Exception { - //given - byte[] buffer = "Command".getBytes(); - int offset = 5; - provideConnectedSubsystemInstance(); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - InOrder inOrder = inOrder(channelOs); - - //when - cut.send(buffer, offset, buffer.length); - - //then - inOrder.verify(channelOs).write(buffer, offset, buffer.length); - inOrder.verify(channelOs, atLeastOnce()).flush(); - inOrder.verify(channelOs, atLeastOnce()).close(); - inOrder.verifyNoMoreInteractions(); - } - - @Test(expected = IOException.class) - public void send_withByteBuffer_shouldRethrowIOException_whenOccurs() throws Exception { - //given - byte[] buffer = "Command".getBytes(); - int offset = 5; - provideConnectedSubsystemInstance(); - given(channelSubsystem.getOutputStream()).willReturn(channelOs); - doThrow(new IOException()).when(channelOs).write(buffer, offset, buffer.length); - - //when - cut.send(buffer, offset, buffer.length); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void getSftpConnection_shouldSetupSessionWithProperInvocationOrder() throws Exception { - //given - SshJcraftWrapper instance = spy(cut); - given(instance.openSftpChannel(session)).willReturn(channelSftp); - InOrder inOrder = inOrder(session, channelSftp, instance); - - //when - ChannelSftp result = instance.getSftpConnection(HOST, USER, PASS); - - //then - verify(jSchMock).getSession(USER, HOST, SshJcraftWrapper.DEFAULT_PORT); - inOrder.verify(session).setPassword(PASS); - inOrder.verify(session).setUserInfo(any(UserInfo.class)); - inOrder.verify(session) - .setConfig(SshJcraftWrapper.STRICT_HOST_CHECK_KEY, SshJcraftWrapper.STRICT_HOST_CHECK_VALUE); - inOrder.verify(session).connect(SESSION_TIMEOUT); - inOrder.verify(instance).openSftpChannel(session); - inOrder.verify(channelSftp).connect(); - inOrder.verifyNoMoreInteractions(); - assertEquals(channelSftp, result); - } - - @Test - public void sftp_get_shouldReadFromChannelInputStream_andCloseConnection() throws Exception { - //given - String streamContent = "test input stream content"; - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - given(channelSftp.get(REMOTE_PATH)).willReturn(IOUtils.toInputStream(streamContent, "UTF-8")); - - //when - String result = spyInstance.get(REMOTE_PATH, HOST, USER, PASS); - - //then - assertEquals(streamContent, result); - verify(channelSftp).disconnect(); - verify(session).disconnect(); - } - - @Test(expected = IOException.class) - public void sftp_get_shouldThrowIOException_whenJschFails() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - doThrow(new JSchException()).when(spyInstance).openSftpChannel(session); - - //when - spyInstance.get(REMOTE_PATH, HOST, USER, PASS); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test(expected = IOException.class) - public void sftp_get_shouldThrowIOException_whenSftpOperationFails() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(0, "sftp error")).when(channelSftp).get(REMOTE_PATH); - - //when - spyInstance.get(REMOTE_PATH, HOST, USER, PASS); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void sftp_get_shouldCloseSessionAndChannel_whenExceptionOccursOnConnectedInstance() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(0, "sftp error")).when(channelSftp).get(REMOTE_PATH); - boolean ioException = false; - - //when - try { - spyInstance.get(REMOTE_PATH, HOST, USER, PASS); - } catch (IOException e) { - ioException = true; - } - - //then - assertTrue(ioException); - verify(channelSftp).disconnect(); - verify(session).disconnect(); - } - - @Test - public void sftp_get_shouldSkipClosingSessionAndChannel_whenExceptionOccursOnNotConnectedInstance() throws Exception { - //given - doThrow(new JSchException()).when(jSchMock).getSession(anyString(), anyString(), anyInt()); - boolean ioException = false; - - //when - try { - cut.get(REMOTE_PATH, HOST, USER, PASS); - } catch (IOException e) { - ioException = true; - } - - //then - assertTrue(ioException); - verify(channelSftp, never()).disconnect(); - verify(session, never()).disconnect(); - } - - @Test - public void sftp_put_withIs_shouldRemoveOldFilesFromDestinationPath_andPutNewData() throws Exception { - //given - InputStream is = IOUtils.toInputStream("test input stream content", "UTF-8"); - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - InOrder inOrder = inOrder(channelSftp, session); - - //when - spyInstance.put(is, REMOTE_PATH, HOST, USER, PASS); - - //then - inOrder.verify(channelSftp).rm(REMOTE_PATH + "*"); - inOrder.verify(channelSftp).put(is, REMOTE_PATH, ChannelSftp.OVERWRITE); - inOrder.verify(channelSftp).disconnect(); - inOrder.verify(session).disconnect(); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void sftp_put_withIs_shouldContinueInsertingNewData_whenFileNotFoundDuringRemoval() throws Exception { - //given - InputStream is = IOUtils.toInputStream("test input stream content", "UTF-8"); - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "No such file/dir")) - .when(channelSftp).rm(REMOTE_PATH + "*"); - - //when - spyInstance.put(is, REMOTE_PATH, HOST, USER, PASS); - - //then - verify(channelSftp).rm(REMOTE_PATH + "*"); - verify(channelSftp).put(is, REMOTE_PATH, ChannelSftp.OVERWRITE); - } - - @Test(expected = IOException.class) - public void sftp_put_withIs_shouldThrowIOException_whenSftpFails() throws Exception { - //given - InputStream is = IOUtils.toInputStream("test input stream content", "UTF-8"); - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(ChannelSftp.SSH_FX_FAILURE, "general error")) - .when(channelSftp).rm(anyString()); - - //when - spyInstance.put(is, REMOTE_PATH, HOST, USER, PASS); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test(expected = IOException.class) - public void sftp_put_withIs_shouldThrowIOException_whenJschFails() throws Exception { - //given - InputStream is = IOUtils.toInputStream("test input stream content", "UTF-8"); - SshJcraftWrapper spyInstance = spy(cut); - doThrow(new JSchException()).when(spyInstance).openSftpChannel(session); - - //when - spyInstance.put(is, REMOTE_PATH, HOST, USER, PASS); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void sftp_put_withSourcePath_shouldPutSrcPathToDestinationPath_andDisconnectAfterwards() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - - //when - spyInstance.put(SOURCE_PATH, REMOTE_PATH); - - //then - verify(channelSftp).put(SOURCE_PATH, REMOTE_PATH, ChannelSftp.OVERWRITE); - verify(channelSftp).disconnect(); - verify(session).disconnect(); - } - - @Test(expected = IOException.class) - public void sftp_put_withSourcePath_shouldThrowIOException_whenSftpFails() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(ChannelSftp.SSH_FX_FAILURE, "general error")) - .when(channelSftp).put(anyString(), anyString(), anyInt()); - - //when - spyInstance.put(SOURCE_PATH, REMOTE_PATH); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test(expected = IOException.class) - public void sftp_put_withSourcePath_shouldThrowIOException_whenJschFails() throws Exception { - //given - SshJcraftWrapper spyInstance = spy(cut); - doThrow(new JSchException()).when(spyInstance).openSftpChannel(session); - - //when - spyInstance.put(SOURCE_PATH, REMOTE_PATH); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void sftpPutStringData_shouldPutInputStreamToRemotePath() throws Exception { - //given - String inputData = "Test data"; - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - - //when - spyInstance.sftpPutStringData(inputData, REMOTE_PATH); - - //then - verify(channelSftp).put(any(InputStream.class), eq(REMOTE_PATH), eq(ChannelSftp.OVERWRITE)); - verify(channelSftp).disconnect(); - verify(session).disconnect(); - } - - @Test(expected = IOException.class) - public void sftpPutStringData_shouldThrowIOException_whenJschFails() throws Exception { - //given - String inputData = "Test data"; - SshJcraftWrapper spyInstance = spy(cut); - doThrow(new JSchException()).when(spyInstance).openSftpChannel(session); - - //when - spyInstance.sftpPutStringData(inputData, REMOTE_PATH); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test(expected = IOException.class) - public void sftpPutStringData_shouldThrowIOException_whenSftpFails() throws Exception { - //given - String inputData = "Test data"; - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - doThrow(new SftpException(ChannelSftp.SSH_FX_FAILURE, "general error")) - .when(channelSftp).put(any(InputStream.class), anyString(), anyInt()); - - //when - spyInstance.sftpPutStringData(inputData, REMOTE_PATH); - - //then - fail(IO_EXCEPTION_MSG); - } - - @Test - public void sftpGet_shouldReadFromChannelInputStream_withInstanceCredentials() throws Exception { - //given - String remoteStreamContent = "test input stream content"; - SshJcraftWrapper spyInstance = spy(cut); - given(spyInstance.openSftpChannel(session)).willReturn(channelSftp); - given(channelSftp.get(REMOTE_PATH)).willReturn(IOUtils.toInputStream(remoteStreamContent, "UTF-8")); - - //when - String result = spyInstance.sftpGet(REMOTE_PATH); - - //then - assertEquals(remoteStreamContent, result); - } } |