From e7752e8d2dd4e4460bf68a7b36548282cc68d0e9 Mon Sep 17 00:00:00 2001 From: Michal Kabaj Date: Fri, 22 Dec 2017 14:38:01 +0100 Subject: Reformat code according to Java Code Guidelines Align appc-config-adaptor-provider implementation classes with ONAP and Google Java Style guidelines: K&R Style brackets, 120 column limit, indentation fixes, method and property reorder according to visibility. Change-Id: I079e6d9eec5f400db00c5bf41937ca20dd778e72 Issue-ID: APPC-361 Signed-off-by: Michal Kabaj --- .../java/org/onap/appc/ccadaptor/CCAActivator.java | 58 +- .../appc/ccadaptor/ConfigComponentAdaptor.java | 679 ++++----- .../java/org/onap/appc/ccadaptor/DebugLog.java | 125 +- .../org/onap/appc/ccadaptor/EncryptionTool.java | 67 +- .../org/onap/appc/ccadaptor/SshJcraftWrapper.java | 1456 +++++++++----------- .../org/onap/appc/ccadaptor/TelnetListener.java | 9 +- .../org/onap/appc/ccadaptor/TimedOutException.java | 22 +- .../main/java/org/onap/appc/ccadaptor/XmlUtil.java | 239 ++-- 8 files changed, 1217 insertions(+), 1438 deletions(-) (limited to 'appc-config/appc-config-adaptor/provider/src/main/java/org') diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java index ba22753fc..9f94bfabf 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/CCAActivator.java @@ -9,84 +9,74 @@ * 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 com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; - import org.onap.ccsdk.sli.core.sli.ConfigurationException; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class CCAActivator implements BundleActivator -{ - - private static final String CCA_PROP_FILE_VAR = "SDNC_CCA_PROPERTIES"; - private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; - @SuppressWarnings("rawtypes") - private ServiceRegistration registration = null; +public class CCAActivator implements BundleActivator { - //private static final Logger log = LoggerFactory.getLogger(CCAActivator.class); - private static final EELFLogger log = EELFManager.getInstance().getLogger(CCAActivator.class); + private static final String CCA_PROP_FILE_VAR = "SDNC_CCA_PROPERTIES"; + private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR"; + //private static final Logger log = LoggerFactory.getLogger(CCAActivator.class); + private static final EELFLogger log = EELFManager.getInstance().getLogger(CCAActivator.class); + @SuppressWarnings("rawtypes") + private ServiceRegistration registration = null; @Override - public void start(BundleContext ctx) throws Exception - { + public void start(BundleContext ctx) throws Exception { // Read properties Properties props = new Properties(); // Read properties from appc-config-adaptor.properties String propFileName = System.getenv(CCA_PROP_FILE_VAR); - if (propFileName == null) - { + if (propFileName == null) { String propDir = System.getenv(SDNC_CONFIG_DIR_VAR); - if (propDir == null) + if (propDir == null) { throw new ConfigurationException( "Cannot find config file - " + CCA_PROP_FILE_VAR + " and " + SDNC_CONFIG_DIR_VAR + " unset"); + } propFileName = propDir + "/appc-config-adaptor.properties"; log.warn("Environment variable " + CCA_PROP_FILE_VAR + " unset - defaulting to " + propFileName); } File propFile = new File(propFileName); - if (!propFile.exists()) + if (!propFile.exists()) { throw new ConfigurationException("Missing configuration properties file: " + propFile); + } - try(InputStream in = new FileInputStream(propFile)) { + try (InputStream in = new FileInputStream(propFile)) { props.load(in); log.info("Loaded properties: "); - } - catch (Exception e) - { + } catch (Exception e) { throw new ConfigurationException("Could not load properties file " + propFileName, e); } // Advertise adaptor ConfigComponentAdaptor adaptor = new ConfigComponentAdaptor(props); - if (registration == null) - { + if (registration == null) { log.info("Registering service " + ConfigComponentAdaptor.class.getName()); registration = ctx.registerService(ConfigComponentAdaptor.class.getName(), adaptor, null); } @@ -94,10 +84,8 @@ public class CCAActivator implements BundleActivator } @Override - public void stop(BundleContext ctx) throws Exception - { - if (registration != null) - { + public void stop(BundleContext ctx) throws Exception { + if (registration != null) { registration.unregister(); registration = null; } 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 f0bf5c532..fb833cf73 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 @@ -7,9 +7,9 @@ * 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. @@ -20,32 +20,31 @@ package org.onap.appc.ccadaptor; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.core.util.Base64; import java.io.BufferedReader; import java.io.ByteArrayInputStream; +import java.io.FileReader; import java.io.IOException; import java.io.InputStream; -import java.io.FileReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Properties; import java.util.StringTokenizer; -import java.util.NoSuchElementException; import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.Base64; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -public class ConfigComponentAdaptor implements SvcLogicAdaptor -{ +public class ConfigComponentAdaptor implements SvcLogicAdaptor { 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; @@ -54,12 +53,9 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor private String auditPassword = null; private String configCallbackUrl = null; private String auditCallbackUrl = null; - DebugLog debugLog = new DebugLog(); - public ConfigComponentAdaptor(Properties props) - { - if (props != null) - { + public ConfigComponentAdaptor(Properties props) { + if (props != null) { configUrl = props.getProperty("configComponent.url", ""); configUser = props.getProperty("configComponent.user", ""); configPassword = props.getProperty("configComponent.passwd", ""); @@ -68,9 +64,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor auditPassword = props.getProperty("auditComponent.passwd", ""); configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); - } - else - { + } else { configUrl = ""; configUser = ""; configPassword = ""; @@ -83,8 +77,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor } @Override - public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) - { + public ConfigStatus configure(String key, Map parameters, SvcLogicContext ctx) { String fnName = "ConfigComponentAdaptor.configure"; HttpResponse r = new HttpResponse(); r.code = 200; @@ -92,29 +85,25 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor debugLog.printRTAriDebug(fnName, "key = " + key); log.debug("Parameters:"); debugLog.printRTAriDebug(fnName, "Parameters:"); - for (String parmName : parameters.keySet()) - { + for (String parmName : parameters.keySet()) { log.debug(" " + parmName + " = " + parameters.get(parmName)); debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName)); } String parmval = parameters.get("config-component-configUrl"); - if ((parmval != null) && (parmval.length() > 0)) - { + if ((parmval != null) && (parmval.length() > 0)) { log.debug("Overwriting URL with " + parmval); configUrl = parmval; } parmval = parameters.get("config-component-configPassword"); - if ((parmval != null) && (parmval.length() > 0)) - { + if ((parmval != null) && (parmval.length() > 0)) { log.debug("Overwriting configPassword with " + parmval); configPassword = parmval; } parmval = parameters.get("config-component-configUser"); - if ((parmval != null) && (parmval.length() > 0)) - { + if ((parmval != null) && (parmval.length() > 0)) { log.debug("Overwriting configUser id with " + parmval); configUser = parmval; } @@ -122,37 +111,47 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String action = parameters.get("action"); String chg = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); - if (chg != null && "prepare".equalsIgnoreCase(action)) + "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)) + } + if (chg != null && "activate".equalsIgnoreCase(action)) { return activate(ctx, true); + } String scale = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); - if (scale != null && "prepare".equalsIgnoreCase(action)) + "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)) + } + if (scale != null && "activate".equalsIgnoreCase(action)) { return activate(ctx, true); + } - if ("prepare".equalsIgnoreCase(action)) + if ("prepare".equalsIgnoreCase(action)) { return prepare(ctx, "BASE", "create"); - if ("activate".equalsIgnoreCase(action)) + } + if ("activate".equalsIgnoreCase(action)) { return activate(ctx, false); + } - if ("backup".equalsIgnoreCase(action)) + if ("backup".equalsIgnoreCase(action)) { return prepare(ctx, "BACKUP", "backup"); - if ("restorebackup".equalsIgnoreCase(action)) + } + if ("restorebackup".equalsIgnoreCase(action)) { return prepare(ctx, "RESTOREBACKUP", "restorebackup"); - if ("deletebackup".equalsIgnoreCase(action)) + } + if ("deletebackup".equalsIgnoreCase(action)) { return prepare(ctx, "DELETEBACKUP", "deletebackup"); - if ("audit".equalsIgnoreCase(action)) + } + if ("audit".equalsIgnoreCase(action)) { return audit(ctx, "FULL"); - if ("getrunningconfig".equalsIgnoreCase(action)) + } + if ("getrunningconfig".equalsIgnoreCase(action)) { return audit(ctx, "RUNNING"); + } - if ((key.equals("put")) || (key.equals("get"))) - { + if ((key.equals("put")) || (key.equals("get"))) { String loginId = parameters.get("loginId"); String host = parameters.get("host"); String password = parameters.get("password"); @@ -163,10 +162,8 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); log.debug("SCP: SshJcraftWrapper has been instantiated"); debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); - try - { - if (key.equals("put")) - { + 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()); @@ -174,22 +171,18 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); - try - { + try { debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); Thread.sleep(1000 * 180); debugLog.printRTAriDebug(fnName, "Woke up...."); - } - catch (java.lang.InterruptedException ee) - { + } catch (java.lang.InterruptedException ee) { boolean ignore = true; } } else { - r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; log.debug(fnName + " Command is for put: data is null"); - } - } - else // Must be a get + } + } else // Must be a get { log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName); debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); @@ -200,9 +193,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor } sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); - } - catch (IOException e) - { + } 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; @@ -211,8 +202,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return (setResponseStatus(ctx, r)); } } - if (key.equals("cli")) - { + if (key.equals("cli")) { String loginId = parameters.get("loginId"); String host = parameters.get("host"); String password = parameters.get("password"); @@ -220,12 +210,11 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String cliCommand = parameters.get("cli"); String portNumber = parameters.get("portNumber"); SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { + try { log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password + - " portNumber=" + portNumber); + " portNumber=" + portNumber); debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + - " password=" + password + " portNumber=" + portNumber); + " password=" + password + " portNumber=" + portNumber); sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber)); DebugLog.printAriDebug(fnName, "Sending 'sdc'"); @@ -246,9 +235,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor r.code = 200; sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); - } - catch (IOException e) - { + } catch (IOException e) { DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); log.debug(fnName + " : Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); @@ -259,17 +246,15 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return (setResponseStatus(ctx, r)); } } - if (key.equals("escapeSql")) - { + 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: "); + 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"); @@ -279,88 +264,82 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor 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 +" Password="+Password +" Port_number="+Port_number); - log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address="+Host_ip_address + - " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); + debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); + try { + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name + + " Host_ip_address=" + Host_ip_address + " Password=" + Password + " Port_number=" + + Port_number); + log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + + " User_name=" + User_name + " Password=" + Password + " 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)); + 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 - { - while (st.hasMoreTokens()) - { + try { + 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); + 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); + DebugLog.printAriDebug(fnName, "Sending command=" + command); sshJcraftWrapper.send(command); DebugLog.printAriDebug(fnName, "command has been sent"); - if (line.indexOf("show config") != -1) - { + 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.indexOf("Response: Ends_With") != -1) - { - DebugLog.printAriDebug(fnName, "Found a Response line: line="+line); + if (line.indexOf("Response: Ends_With") != -1) { + DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line); String delemeter = getStringBetweenQuotes(line); - DebugLog.printAriDebug(fnName, "The delemeter="+delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30*1000, command); + DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter); + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 30 * 1000, command); response += tmpResponse; - if (showConfigFlag) - { + 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()) - { + while (st2.hasMoreTokens()) { String line2 = st2.nextToken(); - if (line2.indexOf("#") == -1) - CliResponse += line2 +"\n"; + if (line2.indexOf("#") == -1) { + CliResponse += line2 + "\n"; + } } } } } + } catch (NoSuchElementException e) { + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } - catch (NoSuchElementException e) - { - DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); - } - DebugLog.printAriDebug(fnName, "CliResponse=\n"+CliResponse); + 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); + 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)); + return (setResponseStatus(ctx, r)); } } - if(key.equals("xml-download")) - { + 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"); @@ -372,61 +351,64 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; String commitCmd = "\n \n ]]>]]>"; - log(fnName, "xml-download: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + log(fnName, + "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" + Password + + " Port_number=" + Port_number); SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); + try { + sshJcraftWrapper.connect(Host_ip_address, + User_name, + Password, + "]]>]]>", + 30000, + Integer.parseInt(Port_number), + "netconf"); String NetconfHelloCmd = netconfHelloCmd; - NetconfHelloCmd = NetconfHelloCmd +"]]>]]>"; + NetconfHelloCmd = NetconfHelloCmd + "]]>]]>"; log(fnName, "Sending the hello command"); sshJcraftWrapper.send(NetconfHelloCmd); String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, ""); log(fnName, "Sending xmlCmd cmd"); String xmlCmd = Contents; String messageId = "1"; - messageId= "\"" +messageId+"\""; - String loadConfigurationString = " merge "+xmlCmd+" "; - loadConfigurationString = loadConfigurationString +"]]>]]>"; + messageId = "\"" + messageId + "\""; + String loadConfigurationString = + " merge " + + xmlCmd + " "; + loadConfigurationString = loadConfigurationString + "]]>]]>"; sshJcraftWrapper.send(loadConfigurationString); - DebugLog.printAriDebug(fnName,":After sending loadConfigurationString"); + DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString"); response = sshJcraftWrapper.receiveUntil("", 600000, ""); - if (response.indexOf("rpc-error") != -1) - { - DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + 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"); + } else { + DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd"); sshJcraftWrapper.send(commitCmd); - DebugLog.printAriDebug(fnName,":After sending commitCmd"); + DebugLog.printAriDebug(fnName, ":After sending commitCmd"); response = sshJcraftWrapper.receiveUntil("", 180000, ""); - if (response.indexOf("rpc-error") != -1) - { - DebugLog.printAriDebug(fnName,"Error from device: Response from device had 'rpc-error'"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + if (response.indexOf("rpc-error") != -1) { + DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = response; - } - else - { - DebugLog.printAriDebug(fnName,":Looks like a success"); - DebugLog.printAriDebug(fnName,"response=\n"+response +"\n"); + } else { + DebugLog.printAriDebug(fnName, ":Looks like a success"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = 200; } } 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)); + 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(); @@ -435,8 +417,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return (setResponseStatus(ctx, r)); } } - if(key.equals("xml-getrunningconfig")) - { + if (key.equals("xml-getrunningconfig")) { log(fnName, "key was: : xml-getrunningconfig"); String xmlGetRunningConfigCmd = " \n"; String Host_ip_address = parameters.get("Host_ip_address"); @@ -447,32 +428,37 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String Protocol = parameters.get("Protocol"); String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - log(fnName, "xml-getrunningconfig: User_name="+User_name +" Host_ip_address="+Host_ip_address +" Password="+Password +" Port_number="+Port_number); + log(fnName, + "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" + + Password + " Port_number=" + Port_number); SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); - try - { + try { String NetconfHelloCmd = netconfHelloCmd; - sshJcraftWrapper.connect (Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), "netconf"); - 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"); + sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n"); response = sshJcraftWrapper.receiveUntil("", 180000, ""); - DebugLog.printAriDebug(fnName,"Response from getRunningconfigCmd="+response); + 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)); + 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(); @@ -481,9 +467,8 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return (setResponseStatus(ctx, r)); } } - if(key.equals("DownloadCliConfig")) - { - debugLog.printRTAriDebug (fnName, "key was: DownloadCliConfig: "); + 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"); @@ -492,105 +477,100 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor 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); + 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 +" Password="+Password +" Port_number="+Port_number); - log.debug("DownloadCliConfig: Attempting to login: Host_ip_address="+Host_ip_address + - " User_name="+User_name+" Password="+Password+" Port_number="+Port_number); + 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 + " Password=" + Password + " Port_number=" + + Port_number); + log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + + " User_name=" + User_name + " Password=" + Password + " 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)); + 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 - { - while (st.hasMoreTokens()) - { + try { + 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); + 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); + 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); + } 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); + 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); + } 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); + DebugLog.printAriDebug(fnName, + "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter); StringTokenizer st2 = new StringTokenizer(Config_contents, "\n"); - while (st2.hasMoreTokens()) - { + while (st2.hasMoreTokens()) { String cmd = st2.nextToken(); - DebugLog.printAriDebug(fnName, "Config_contents: cmd="+cmd); + DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd); sshJcraftWrapper.send(cmd); - String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, timeout, command); + String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, + timeout, + command); CliResponse += tmpResponse; } } } - } - catch (NoSuchElementException e) - { - DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e="+e); + } 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); + 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); + 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)); + return (setResponseStatus(ctx, r)); } } - debugLog.printRTAriDebug (fnName, "Unsupported action - " + action); + debugLog.printRTAriDebug(fnName, "Unsupported action - " + action); log.error("Unsupported action - " + action); return ConfigStatus.FAILURE; } - private void log (String fileName, String messg) - { - debugLog.printRTAriDebug (fileName, messg); - log.debug(fileName +": "+messg); + private void log(String fileName, String messg) { + debugLog.printRTAriDebug(fileName, messg); + log.debug(fileName + ": " + messg); } - private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) - { + 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); @@ -600,20 +580,18 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor 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")) + 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); String req = null; - try - { + try { req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { + } catch (Exception e) { log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); @@ -626,8 +604,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return setResponseStatus(ctx, r); } - private ConfigStatus activate(SvcLogicContext ctx, boolean change) - { + private ConfigStatus activate(SvcLogicContext ctx, boolean change) { String reqTemplate = readFile("/config-request.xml"); Map param = new HashMap(); param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); @@ -636,12 +613,9 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id")); String req = null; - try - { + try { req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { + } catch (Exception e) { log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); @@ -654,8 +628,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return setResponseStatus(ctx, r); } - private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) - { + private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) { String reqTemplate = readFile("/audit-request.xml"); Map param = new HashMap(); param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id")); @@ -664,12 +637,9 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor param.put("audit-level", auditLevel); String req = null; - try - { + try { req = buildXmlRequest(param, reqTemplate); - } - catch (Exception e) - { + } catch (Exception e) { log.error("Error building the XML request: ", e); HttpResponse r = new HttpResponse(); @@ -683,113 +653,93 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor } @Override - public ConfigStatus activate(String key, SvcLogicContext ctx) - { + public ConfigStatus activate(String key, SvcLogicContext ctx) { return ConfigStatus.SUCCESS; } @Override - public ConfigStatus deactivate(String key, SvcLogicContext ctx) - { + public ConfigStatus deactivate(String key, SvcLogicContext ctx) { return ConfigStatus.SUCCESS; } - private String escapeMySql(String input) - { - if (input == null) + private String escapeMySql(String input) { + if (input == null) { return null; + } - input = input.replace("\\", "\\\\"); + input = input.replace("\\", "\\\\"); input = input.replace("\'", "\\'"); return input; } - private String readFile(String fileName) - { + 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 - { + try { String s = in.readLine(); - while (s != null) - { + while (s != null) { ss.append(s).append('\n'); s = in.readLine(); } - } - catch (IOException e) - { + } catch (IOException e) { System.out.println("Error reading " + fileName + ": " + e.getMessage()); throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e); - } - finally - { - try - { + } finally { + try { in.close(); - } - catch (Exception e) - { + } catch (Exception e) { log.warn("Could not close BufferedReader", e); } - try - { + try { isr.close(); - } - catch (Exception e) - { + } catch (Exception e) { log.warn("Could not close InputStreamReader", e); } - try - { + try { is.close(); - } - catch (Exception e) - { + } catch (Exception e) { log.warn("Could not close InputStream", e); } } return ss.toString(); } - private String buildXmlRequest(Map param, String template) - { + private String buildXmlRequest(Map param, String template) { StringBuilder ss = new StringBuilder(); int i = 0; - while (i < template.length()) - { + while (i < template.length()) { int i1 = template.indexOf("${", i); - if (i1 < 0) - { + if (i1 < 0) { ss.append(template.substring(i)); break; } int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) + if (i2 < 0) { throw new RuntimeException("Template error: Matching } not found"); + } String var1 = template.substring(i1 + 2, i2); String value1 = param.get(var1); - if (value1 == null || value1.trim().length() == 0) - { + if (value1 == null || value1.trim().length() == 0) { // delete the whole element (line) int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) + if (i3 < 0) { i3 = 0; + } int i4 = template.indexOf('\n', i1); - if (i4 < 0) + if (i4 < 0) { i4 = template.length(); + } - if (i < i3) + if (i < i3) { ss.append(template.substring(i, i3)); + } i = i4; - } - else - { + } else { ss.append(template.substring(i, i1)).append(value1); i = i2 + 1; } @@ -798,51 +748,50 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return ss.toString(); } - private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) - { + private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) { log.info("Building XML started"); long t1 = System.currentTimeMillis(); template = expandRepeats(ctx, template, 1); Map mm = new HashMap<>(); - for (String s : ctx.getAttributeKeySet()) + for (String s : ctx.getAttributeKeySet()) { mm.put(s, ctx.getAttribute(s)); + } mm.put("operation", operation); StringBuilder ss = new StringBuilder(); int i = 0; - while (i < template.length()) - { + while (i < template.length()) { int i1 = template.indexOf("${", i); - if (i1 < 0) - { + if (i1 < 0) { ss.append(template.substring(i)); break; } int i2 = template.indexOf('}', i1 + 2); - if (i2 < 0) + if (i2 < 0) { throw new RuntimeException("Template error: Matching } not found"); + } String var1 = template.substring(i1 + 2, i2); String value1 = XmlUtil.getXml(mm, var1); - if (value1 == null || value1.trim().length() == 0) - { + if (value1 == null || value1.trim().length() == 0) { // delete the whole element (line) int i3 = template.lastIndexOf('\n', i1); - if (i3 < 0) + if (i3 < 0) { i3 = 0; + } int i4 = template.indexOf('\n', i1); - if (i4 < 0) + if (i4 < 0) { i4 = template.length(); + } - if (i < i3) + if (i < i3) { ss.append(template.substring(i, i3)); + } i = i4; - } - else - { + } else { ss.append(template.substring(i, i1)).append(value1); i = i2 + 1; } @@ -854,41 +803,36 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor return ss.toString(); } - private String expandRepeats(SvcLogicContext ctx, String template, int level) - { + private String expandRepeats(SvcLogicContext ctx, String template, int level) { StringBuilder newTemplate = new StringBuilder(); int k = 0; - while (k < template.length()) - { + while (k < template.length()) { int i1 = template.indexOf("${repeat:", k); - if (i1 < 0) - { + if (i1 < 0) { newTemplate.append(template.substring(k)); break; } int i2 = template.indexOf(':', i1 + 9); - if (i2 < 0) + if (i2 < 0) { throw new RuntimeException( "Template error: Context variable name followed by : is required after repeat"); + } // Find the closing }, store in i3 int nn = 1; int i3 = -1; int i = i2; - while (nn > 0 && i < template.length()) - { + while (nn > 0 && i < template.length()) { i3 = template.indexOf('}', i); - if (i3 < 0) + if (i3 < 0) { throw new RuntimeException("Template error: Matching } not found"); + } int i32 = template.indexOf('{', i); - if (i32 >= 0 && i32 < i3) - { + if (i32 >= 0 && i32 < i3) { nn++; i = i32 + 1; - } - else - { + } else { nn--; i = i3 + 1; } @@ -898,12 +842,9 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String value1 = ctx.getAttribute(var1); log.info(" " + var1 + ": " + value1); int n = 0; - try - { + try { n = Integer.parseInt(value1); - } - catch (Exception e) - { + } catch (Exception e) { n = 0; } @@ -911,8 +852,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor String rpt = template.substring(i2 + 1, i3); - for (int ii = 0; ii < n; ii++) - { + for (int ii = 0; ii < n; ii++) { String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]"); newTemplate.append(ss); } @@ -920,16 +860,15 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor k = i3 + 1; } - if (k == 0) + if (k == 0) { return newTemplate.toString(); + } return expandRepeats(ctx, newTemplate.toString(), level + 1); } - private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) - { - try - { + private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) { + try { Client client = Client.create(); client.setConnectTimeout(5000); WebResource webResource = client.resource(url); @@ -959,9 +898,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor r.message = message; return r; - } - catch (Exception e) - { + } catch (Exception e) { log.error("Error sending the request: ", e); HttpResponse r = new HttpResponse(); @@ -971,76 +908,69 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor } } - private static class HttpResponse - { + private static class HttpResponse { public int code; + public String message; } - private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) - { + 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) - { + private String getStringBetweenQuotes(String string) { String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes"; - DebugLog.printAriDebug(fnName, "string="+string); + 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); + retString = string.substring(start + 1, end); + DebugLog.printAriDebug(fnName, "retString=" + retString); + return (retString); } - public static String _readFile(String fileName) - { + 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"); + try (BufferedReader in = new BufferedReader(new FileReader(fileName))) { + while ((line = in.readLine()) != null) { + strBuff.append(line + "\n"); } - } - catch (IOException e) - { - System.out.println("Caught an IOException in method readFile(): e="+e.toString()); + } catch (IOException e) { + System.out.println("Caught an IOException in method readFile(): e=" + e.toString()); } return (strBuff.toString()); } - private String trimResponse(String response) - { + private String trimResponse(String response) { StringTokenizer line = new StringTokenizer(response, "\n"); StringBuffer sb = new StringBuffer(); boolean captureText = false; - while (line.hasMoreTokens()) - { + while (line.hasMoreTokens()) { String token = line.nextToken(); - if (token.indexOf("") != -1) + } + if (captureText) { + sb.append(token + "\n"); + } + if (token.indexOf("") != -1) { captureText = false; + } } - return(sb.toString()); + return (sb.toString()); } - public static void main (String args[]) throws Exception - { + 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 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 parameters = new HashMap(); parameters.put("Host_ip_address", "000.00.000.00"); @@ -1053,6 +983,5 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor 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 index 15db56c90..2ed7679f8 100644 --- 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 @@ -7,9 +7,9 @@ * 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. @@ -20,83 +20,78 @@ package org.onap.appc.ccadaptor; -import java.io.*; +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 class DebugLog { - public static void main (String args[]) - { - DebugLog debugLog = new DebugLog(); - debugLog.printAriDebug("DebugLog", "The Message"); - } + private static String fileName = "/tmp/rt.log"; - public static void printAriDebug(String fn, String messg) - { - String logMessg = getDateTime() +" " +fn +" " + messg; - appendToFile(logMessg +"\n"); + 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(); - } + public static void printRTAriDebug(String fn, String messg) { + // System.out.println (getDateTime() +" " +fn +" " + messg); + String logMessg = getDateTime() + " " + fn + " " + messg; + appendToFile(logMessg + "\n"); } - catch (IOException e) - { - DebugLog.printRTAriDebug (fn, "writeToFile() exception: " + e); - //System.err.println("writeToFile() exception: " + e); - e.printStackTrace(); + + 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 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 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 static String getStackTraceString(Exception e) - { - String fn = "DebugLog.outputStackTrace"; - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - String stackTrace = sw.toString(); - return(stackTrace); - } + 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/EncryptionTool.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java index ad09d7faf..a3700ec31 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/EncryptionTool.java @@ -7,9 +7,9 @@ * 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. @@ -23,9 +23,7 @@ package org.onap.appc.ccadaptor; import java.security.Provider; import java.security.Provider.Service; import java.security.Security; - import javax.crypto.Cipher; - import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64; import org.jasypt.util.text.BasicTextEncryptor; import org.slf4j.Logger; @@ -37,40 +35,40 @@ import org.slf4j.LoggerFactory; */ public class EncryptionTool { + /** + * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt + * it + */ + @SuppressWarnings("nls") + public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; /** * This lock object is used ONLY if the singleton has not been set up. */ private static final Object lock = new Object(); - /** * The salt is used to initialize the PBE (password Based Encrpytion) algorithm. */ private static final byte[] DEFAULT_SALT = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; - - /** - * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and therefore decrypt - * it - */ - @SuppressWarnings("nls") - public static final String ENCRYPTED_VALUE_PREFIX = "enc:"; - - /** - * The instance of the encryption utility object - */ - private static EncryptionTool instance = null; - /** * The iteration count used to initialize the PBE algorithm and to generate the key spec */ private static final int ITERATION_COUNT = 20; - /** * The logger for this class. */ private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class); - + /** + * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 + * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. + */ + @SuppressWarnings("nls") + private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; + /** + * The instance of the encryption utility object + */ + private static EncryptionTool instance = null; /** * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we are using is a * symmetrical cipher. @@ -80,14 +78,6 @@ public class EncryptionTool { 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1', 'V', '4', 'l', 'a', '9', 'w', 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q', '{', 'v', 'v', 'K', 'V' }; - - /** - * The algorithm to encrypt and decrpyt data is "Password (or passphrase) Based Encryption with Message Digest #5 - * and the Data Encryption Standard", i.e., PBEWithMD5AndDES. - */ - @SuppressWarnings("nls") - private static final String SECURITY_ALGORITHM = "PBEWITHMD5AND256BITAES";// "PBEWithMD5AndDES"; - /** * The decryption cipher object */ @@ -138,8 +128,8 @@ public class EncryptionTool { /** * Decrypt the provided encrypted text * - * @param cipherText - * THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as is. + * @param cipherText THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is returned as + * is. * @return the clear test of the (possibly) encrypted value. The original value if the string is not encrypted. */ @SuppressWarnings("nls") @@ -159,11 +149,10 @@ public class EncryptionTool { /** * Encrypt the provided clear text * - * @param clearText - * The clear text to be encrypted + * @param clearText The clear text to be encrypted * @return the encrypted text. If the clear text is empty (null or zero length), then an empty string is returned. - * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the - * clear text is encrypted and returned. + * If the clear text is already encrypted, it is not encrypted again and is returned as is. Otherwise, the clear + * text is encrypted and returned. */ @SuppressWarnings("nls") public synchronized String encrypt(String clearText) { @@ -177,11 +166,10 @@ public class EncryptionTool { } /** - * Is a value encrypted? A value is considered to be encrypted if it begins with the - * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. + * Is a value encrypted? A value is considered to be encrypted if it begins with the {@linkplain + * #ENCRYPTED_VALUE_PREFIX encrypted value prefix}. * - * @param value - * the value to check. + * @param value the value to check. * @return true/false; */ private static boolean isEncrypted(final String value) { @@ -192,8 +180,7 @@ public class EncryptionTool { * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the input is longer * and returns a byte array the same size as input * - * @param inp - * The byte array to be XORed with secret + * @param inp The byte array to be XORed with secret * @return A byte array the same size as inp or null if input is null. */ private byte[] xorWithSecret(byte[] inp) { 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 eb9e28fa2..e0e33c456 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 @@ -24,33 +24,52 @@ package org.onap.appc.ccadaptor; +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.ChannelShell; +import com.jcraft.jsch.ChannelSubsystem; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpException; +import com.jcraft.jsch.UIKeyboardInteractive; +import com.jcraft.jsch.UserInfo; +import java.io.BufferedInputStream; import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.*; -import java.util.*; +import java.io.OutputStream; +import java.io.RandomAccessFile; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; -import com.jcraft.jsch.*; +import java.util.Date; +import java.util.StringTokenizer; -public class SshJcraftWrapper -{ +public class SshJcraftWrapper { - private String debugLogFileName = "/tmp/sshJcraftWrapperDebug"; InputStream inputStream = null; OutputStream outputStream = null; + DebugLog debugLog = new DebugLog(); + private String debugLogFileName = "/tmp/sshJcraftWrapperDebug"; private TelnetListener listener = null; private String routerLogFileName = null; - DebugLog debugLog = new DebugLog(); 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; - char[] charBuffer = new char[BUFFER_SIZE]; private BufferedWriter out = null; private File _tmpFile = null; private JSch jsch = null; @@ -61,310 +80,289 @@ public class SshJcraftWrapper 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 hostName = null; - private String userName = null; - private String passWord = null; + private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk"); + private String equipNameCode = null; + private String hostName = null; + private String userName = null; + private String passWord = null; private StringBuffer charactersFromBufferFlush = new StringBuffer(); - private Runtime runtime = Runtime.getRuntime(); - private DebugLog dbLog = new DebugLog(); + private Runtime runtime = Runtime.getRuntime(); + private DebugLog dbLog = new DebugLog(); - public void SshJcraftWrapper() - { + public void SshJcraftWrapper() { String fn = "SshJcraftWrapper.SshJcraftWrapper"; - debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated"); - routerLogFileName = "/tmp/" +host; + 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 - { + public void connect(String hostname, String username, String password, String prompt, int timeOut) + throws IOException { String fn = "SshJcraftWrapper.connect"; jsch = new JSch(); - debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut); - debugLog.printRTAriDebug (fn, "Trace A"); + debugLog.printRTAriDebug(fn, + "Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='" + + prompt + "' timeOut=" + timeOut); + debugLog.printRTAriDebug(fn, "Trace A"); RouterName = hostname; - hostName = hostname; - userName = username; - passWord = password; - try - { + hostName = hostname; + userName = username; + passWord = password; + try { 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"); + 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(prompt, 3000, "No cmd was sent, just waiting"); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out."); - } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e); + debugLog.printRTAriDebug(fn, "Successfully connected."); + debugLog.printRTAriDebug(fn, "Flushing input buffer"); + try { + receiveUntil(prompt, 3000, "No cmd was sent, just waiting"); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out."); + } + } 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()); } } // User specifies the port number. - public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException - { + public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum) + throws IOException { String fn = "SshJcraftWrapper.connect"; - debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum); + debugLog.printRTAriDebug(fn, + ":Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='" + + prompt + "' timeOut=" + timeOut + " portNum=" + portNum); RouterName = hostname; - hostName = hostname; - userName = username; - passWord = password; + hostName = hostname; + userName = username; + passWord = password; RouterName = hostname; jsch = new JSch(); - try - { + try { 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.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!!!! + 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"); + ((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 - { - if (prompt.equals("]]>]]>")) - receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting"); - else - receiveUntil(":~#", 5000, "No cmd was sent, just waiting"); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); - } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e); - dbLog.outputStackTrace(e); + debugLog.printRTAriDebug(fn, ":Successfully connected."); + debugLog.printRTAriDebug(fn, ":Flushing input buffer"); + try { + if (prompt.equals("]]>]]>")) { + receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting"); + } else { + receiveUntil(":~#", 5000, "No cmd was sent, just waiting"); + } + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out."); + } + } catch (Exception e) { + debugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e); + dbLog.outputStackTrace(e); - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+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 TimedOutException, IOException - { + public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent) + throws TimedOutException, IOException { String fn = "SshJcraftWrapper.receiveUntil"; boolean match = false; boolean cliPromptCmd = false; 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"); + 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 = ""; - long deadline = new Date().getTime() + timeout; - try - { + long deadline = new Date().getTime() + timeout; + try { session.setTimeout(timeout); // This is the socket timeout value. - while (!match) - { - if(new Date().getTime() > deadline) - { - debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+RouterName +" CmdThatWasSent="+ CmdThatWasSent); + while (!match) { + if (new Date().getTime() > deadline) { + 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"); } - try - { + try { Thread.sleep(500); - } - catch (java.lang.InterruptedException ee) - { + } 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) - { - debugLog.printRTAriDebug (fn, "Reader read "+len +" bytes. Looks like we timed out, router="+RouterName); - throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName); + int len = reader.read(charBuffer, 0, BUFFER_SIZE); + appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n"); + if (len <= 0) { + 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) - { - if (out == null) - { + if (!cliPromptCmd) { + if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) { + if (out == null) { // This is a IOS XR sw config file. We will write it to the disk. timeout = timeout * 2; deadline = new Date().getTime() + timeout; - debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout); + debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout); StringTokenizer st = new StringTokenizer(cmdThatWasSent); st.nextToken(); routerFileName = st.nextToken(); out = new BufferedWriter(new FileWriter(routerFileName)); - routerLogFileName = "/tmp/"+RouterName; + routerLogFileName = "/tmp/" + RouterName; _tmpFile = new File(routerLogFileName); - debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName); + debugLog.printRTAriDebug(fn, + "Will write the swConfigFile to disk, routerFileName=" + routerFileName); } int c; out.write(charBuffer, 0, len); out.flush(); - appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n"); - 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 == true) - { + if (match == true) { out.flush(); out.close(); - out = null; + out = null; return null; } - } - else - { - readCounts ++; - appendToFile(debugLogFileName, fn +" readCounts="+readCounts +" Reader read "+len +" of data\n"); + } else { + readCounts++; + appendToFile(debugLogFileName, + fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n"); int c; sb2.setLength(0); - for(int i=0; i") != -1) - { - debugLog.printRTAriDebug (fn, "Found our 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 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()); + } 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()); } String result = stripOffCmdFromRouterResponse(sbReceive.toString()); - debugLog.printRTAriDebug (fn, "Leaving method successfully"); + debugLog.printRTAriDebug(fn, "Leaving method successfully"); return (result); } - public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent) - { + public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, + String cmdThatWasSent) { // The delimeters are in a '|' seperated string. Return true on the first match. String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter"; - appendToFile(debugLogFileName, fn +" Entered: delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n"); + appendToFile(debugLogFileName, + fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='" + + receivedString + "'\n"); StringTokenizer st = new StringTokenizer(delimeters, "|"); if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command. { int x = receivedString.lastIndexOf("#"); int y = receivedString.length() - 1; - appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n"); - if (extraDebugFile.exists()) - appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"' x="+x +" y="+y +"\n"); - if ((x != -1) && (y == x)) - return(true); - else - return(false); + appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n"); + if (extraDebugFile.exists()) { + appendToFile(debugLogFileName, + fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n"); + } + if ((x != -1) && (y == x)) { + return (true); + } else { + return (false); + } } - if (cmdThatWasSent.indexOf("show config") != -1) - { - appendToFile(debugLogFileName, fn +"In the block for 'show config'\n"); - while (st.hasMoreTokens()) - { + 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 " #". // Proc #0 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254 // LAAR2# int x = receivedString.lastIndexOf(delimeter); - if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1)) - { - appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n"); - appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n"); + if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) { + 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 - { + } else { aggregatedReceivedString = aggregatedReceivedString + receivedString; - _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); + _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString); - while (st.hasMoreTokens()) - { + while (st.hasMoreTokens()) { String delimeter = st.nextToken(); - appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n"); - appendToFile(debugLogFileName, fn +" receivedString='"+receivedString); - if (aggregatedReceivedString.indexOf(delimeter) != -1) - { - debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'"); + appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n"); + appendToFile(debugLogFileName, fn + " receivedString='" + receivedString); + if (aggregatedReceivedString.indexOf(delimeter) != -1) { + debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'"); aggregatedReceivedString = ""; return (true); } @@ -373,286 +371,242 @@ public class SshJcraftWrapper return (false); } - public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) - { + public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) { String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::"; int x; int c; String str = null; - if (jcraftReadSwConfigFileFromDisk()) - { + if (jcraftReadSwConfigFileFromDisk()) { DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block"); File fileName = new File(routerFileName); - appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); - try - { + appendToFile(debugLogFileName, + fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk"); + try { str = getLastFewLinesOfFile(fileName, 3); - } - catch (IOException e) - { - DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); - dbLog.outputStackTrace(e); + } catch (IOException e) { + DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e); + dbLog.outputStackTrace(e); e.printStackTrace(); } - } - else - { + } 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--) - { + for (x = len - 1; x >= 0; x--) { c = charBuffer[x]; - if (extraDebugFile.exists()) - appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n"); + 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); - appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n"); - } - else - { + if ((x + 1 - 13) >= 0) { + str = new String(charBuffer, (x + 1 - 13), 13); + appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n"); + } else { File fileName = new File(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 - { + 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) - { - DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e); - dbLog.outputStackTrace(e); + } catch (IOException e) { + DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e); + dbLog.outputStackTrace(e); e.printStackTrace(); } } } - 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); + 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); } } - public void closeConnection() - { + public void closeConnection() { String fn = "SshJcraftWrapper.closeConnection"; - debugLog.printRTAriDebug (fn, "Executing the closeConnection...."); + debugLog.printRTAriDebug(fn, "Executing the closeConnection...."); inputStream = null; outputStream = null; dis = null; charBuffer = null; session.disconnect(); - session = null; + session = null; } - public void send (String cmd) throws IOException - { + public void send(String cmd) throws IOException { 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')) + 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; + } + int length = cmd.length(); + int i = -1; + int nchars = 300000; + int ncharsTotalSent = 0; + int ncharsSent = 0; - appendToFile(debugLogFileName, fn+": Sending: '"+cmd ); + 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 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 { + debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes"); + dos.writeBytes(cmd); } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out."); - } - } - } - else - { - 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) - { - debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e); - dbLog.outputStackTrace(e); + dos.flush(); + debugLog.printRTAriDebug(fn, "Leaving method"); + appendToFile(debugLogFileName, fn + ": Leaving method\n"); + } catch (IOException e) { + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); + dbLog.outputStackTrace(e); throw new IOException(e.toString()); } } - public void sendChar (int v) throws IOException - { + public void sendChar(int v) throws IOException { String fn = "SshJcraftWrapper.sendChar"; OutputStream out = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); - try - { - debugLog.printRTAriDebug (fn, "Sending: '" +v +"'"); - dos.writeChar (v); + try { + debugLog.printRTAriDebug(fn, "Sending: '" + v + "'"); + dos.writeChar(v); dos.flush(); - } - catch (IOException e) - { - debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e); + } catch (IOException 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 - { + public void send(byte[] b, int off, int len) throws IOException { String fn = "SshJcraftWrapper.send:byte[]"; OutputStream out = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); - try - { - dos.write (b, off, len); + try { + dos.write(b, off, len); dos.flush(); - } - catch (IOException e) - { - debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e); + } catch (IOException e) { + debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e); throw new IOException(e.toString()); } } - public static class MyUserInfo implements UserInfo, UIKeyboardInteractive - { - public String getPassword() - { + public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { + + public String getPassword() { return null; } - public boolean promptYesNo(String str) - { + + public boolean promptYesNo(String str) { return false; } - public String getPassphrase() - { + + public String getPassphrase() { return null; } - public boolean promptPassphrase(String message) - { + + public boolean promptPassphrase(String message) { return false; } - public boolean promptPassword(String message) - { + + public boolean promptPassword(String message) { return false; } - public void showMessage(String message) - { } + + public void showMessage(String message) { + } + public String[] promptKeyboardInteractive(String destination, - String name, - String instruction, - String[] prompt, - boolean[] echo) - { + String name, + String instruction, + String[] prompt, + boolean[] echo) { return null; } } - public void addListener(TelnetListener listener) - { + public void addListener(TelnetListener listener) { this.listener = listener; } - public void appendToFile (String fileName, String dataToWrite) - { + public void appendToFile(String fileName, String dataToWrite) { String fn = "SshJcraftWrapper.appendToFile"; - try - { + 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()) - { + 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.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); + } 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) - { + public void _appendToFile(String fileName, String dataToWrite) { String fn = "SshJcraftWrapper.appendToFile"; - try - { + 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()) - { + 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); + } 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() - { + public String getTheDate() { Calendar cal = Calendar.getInstance(); java.util.Date today = cal.getTime(); DateFormat df1 = DateFormat.getDateInstance(); @@ -661,78 +615,64 @@ public class SshJcraftWrapper } - public void appendToRouterFile (String fileName, StringBuffer dataToWrite) - { + public void appendToRouterFile(String fileName, StringBuffer dataToWrite) { String fnName = "SshJcraftWrapper.appendToRouterFile"; - debugLog.printRTAriDebug (fnName, "Entered.... "); - try - { + 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()) - { + if (tmpFile.exists()) { BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); - // out.write("\n"); + // out.write("\n"); out.write(dataToWrite.toString()); out.close(); } } - } - catch (IOException e) - { + } catch (IOException e) { System.err.println("writeToFile() exception: " + e); e.printStackTrace(); } } - public void appendToRouterFile (String fileName, int len) - { + public void appendToRouterFile(String fileName, int len) { String fnName = "SshJcraftWrapper.appendToFile"; // debugLog.printRTAriDebug (fnName, "Entered.... len="+len); - try - { + 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("\n"); - out.write(charBuffer, 0, len); - out.close(); - } - } - catch (IOException e) - { + // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true))) + if (tmpFile.exists()) { + BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); + // out.write("\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) - { + public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) { + if (str != null) { StringTokenizer strTok = new StringTokenizer(str, "\n"); StringBuffer sb = new StringBuffer(); - while (strTok.hasMoreTokens()) - { + while (strTok.hasMoreTokens()) { String line = strTok.nextToken(); sb.append(line); } return (sb.toString().trim()); + } else { + return (str); } - else - return(str); } - public String stripOffCmdFromRouterResponse(String routerResponse) - { + public String stripOffCmdFromRouterResponse(String routerResponse) { String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse"; // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n"); @@ -745,26 +685,22 @@ public class SshJcraftWrapper int numTokens = rr.countTokens(); // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens); - if (numTokens > 1) - { + if (numTokens > 1) { rr.nextToken(); //Skip the first line. - while (rr.hasMoreTokens()) - { - sb.append(rr.nextToken()+'\n'); + while (rr.hasMoreTokens()) { + sb.append(rr.nextToken() + '\n'); } } return (sb.toString()); } - public void setRouterCommandType(String type) - { + public void setRouterCommandType(String type) { String fn = "SshJcraftWrapper.setRouterCommandType"; this.routerCmdType = type; - debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'"); + debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'"); } - public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException - { + public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException { String fn = "SshJcraftWrapper.getLastFewLinesOfFile"; RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); int lines = 0; @@ -773,502 +709,458 @@ public class SshJcraftWrapper long length = file.length(); length--; randomAccessFile.seek(length); - for(long seek = length; seek >= 0; --seek) - { + for (long seek = length; seek >= 0; --seek) { randomAccessFile.seek(seek); - char c = (char)randomAccessFile.read(); + char c = (char) randomAccessFile.read(); builder.append(c); - if(c == '\n') - { + if (c == '\n') { builder = builder.reverse(); // System.out.println(builder.toString()); tail = builder.toString() + tail; lines++; builder.setLength(0); - if (lines == linesToRead) - { + if (lines == linesToRead) { break; } } } randomAccessFile.close(); - if(!jcraftReadSwConfigFileFromDisk()) - debugLog.printRTAriDebug (fn, "tail='"+tail +"'"); - appendToFile(debugLogFileName, "tail='"+tail +"'\n"); + if (!jcraftReadSwConfigFileFromDisk()) { + debugLog.printRTAriDebug(fn, "tail='" + tail + "'"); + } + appendToFile(debugLogFileName, "tail='" + tail + "'\n"); return tail; } - public boolean jcraftReadSwConfigFileFromDisk() - { - if (jcraftReadSwConfigFileFromDisk.exists()) - return(true); - else - return(false); + public boolean jcraftReadSwConfigFileFromDisk() { + if (jcraftReadSwConfigFileFromDisk.exists()) { + return (true); + } else { + return (false); + } } - public String getEquipNameCode() - { - return (equipNameCode); + public String getEquipNameCode() { + return (equipNameCode); - } + } - public void setEquipNameCode(String equipNameCode) - { - this.equipNameCode = equipNameCode; - } + public void setEquipNameCode(String equipNameCode) { + this.equipNameCode = equipNameCode; + } - public String getRouterName() - { - return(RouterName); - } + public String getRouterName() { + return (RouterName); + } - // Routine does reads until it has read 'nchars' or times out. - public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException - { + // Routine does reads until it has read 'nchars' or times out. + 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; - boolean flag = false; - charactersFromBufferFlush.setLength(0); - - long deadline = new Date().getTime() + timeout; - logMemoryUsage(); - try - { + debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message); + int ncharsTotalReceived = 0; + int ncharsRead = 0; + boolean flag = false; + charactersFromBufferFlush.setLength(0); + + long deadline = new Date().getTime() + timeout; + logMemoryUsage(); + try { session.setTimeout(timeout); // This is the socket timeout value. - while (true) - { - if(new Date().getTime() > deadline) - { - debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived); - flag = true; + while (true) { + if (new Date().getTime() > deadline) { + 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); - ncharsTotalReceived = ncharsTotalReceived + ncharsRead; - // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); - if (ncharsTotalReceived >= ncharsSent) - { - debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="+ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived); - logMemoryUsage(); - return; - } + ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE); + if (listener != null) { + listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead)); + } + appendToRouterFile("/tmp/" + RouterName, ncharsRead); + ncharsTotalReceived = ncharsTotalReceived + ncharsRead; + // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); + if (ncharsTotalReceived >= ncharsSent) { + debugLog.printRTAriDebug(fn, + "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + + ncharsTotalReceived); + logMemoryUsage(); + return; + } } - } - catch (JSchException e) - { - debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString()); - debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead); - throw new TimedOutException (e.toString()); + } catch (JSchException e) { + debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString()); + debugLog.printRTAriDebug(fn, + "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead=" + + ncharsRead); + throw new TimedOutException(e.toString()); } } - public String getHostName() - { - return(hostName); - } - - public String getUserName() - { - return(userName); - } - - public String getPassWord() - { - return(passWord); - } - - public void sftpPut(String sourcePath, String destDirectory) throws IOException - { - String fn = "SshJcraftWrapper.sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); + public String getHostName() { + return (hostName); + } + + public String getUserName() { + return (userName); + } + + public String getPassWord() { + 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); + 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 SftpPut(String stringOfData, String fullPathDest) throws IOException - { - String fn = "SshJcraftWrapper.Sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); + 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()); - debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest); - sftp.put(is, fullPathDest, 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); + 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()); + debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest); + sftp.put(is, fullPathDest, 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 String sftpGet(String fullFilePathName) throws IOException - { - String fn = "SshJcraftWrapper.Sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); + + public String sftpGet(String fullFilePathName) 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 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); + 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 - { - BufferedInputStream bis = new BufferedInputStream(in); - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - int result = bis.read(); - while(result != -1) - { - byte b = (byte)result; - buf.write(b); - result = bis.read(); + + public static String readInputStreamAsString(InputStream in) throws IOException { + BufferedInputStream bis = new BufferedInputStream(in); + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + int result = bis.read(); + while (result != -1) { + byte b = (byte) result; + buf.write(b); + result = bis.read(); + } + return buf.toString(); } - return buf.toString(); - } - public void logMemoryUsage() - { - String fn = "SshJcraftWrapper.logMemoryUsage"; - int mb = 1024*1024; + public void logMemoryUsage() { + String fn = "SshJcraftWrapper.logMemoryUsage"; + int mb = 1024 * 1024; long usedMemory; long maxMemoryAdvailable; - long memoryLetfOnHeap; + 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); - } + usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb)); + memoryLetfOnHeap = maxMemoryAdvailable - usedMemory; + DebugLog.printAriDebug(fn, + "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap=" + + memoryLetfOnHeap); + } - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- - // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- + // ---------------------------------------------------------------------------- - // 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 - { + // 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"; - debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem); + debugLog.printRTAriDebug(fn, + ":::Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='" + + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem); RouterName = hostname; jsch = new JSch(); - try - { + try { session = jsch.getSession(username, hostname, portNum); UserInfo ui = new MyUserInfo(); session.setPassword(password); session.setUserInfo(ui); - session.setConfig("StrictHostKeyChecking", "no"); + 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!!!! + 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).setPtyType("vt102"); - ((ChannelSubsystem)channel).setPty(true); + ((ChannelSubsystem) channel).setSubsystem(subsystem); + // ((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); + 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, int portNumber) throws IOException - { + 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 +" password="+password +" portNumber="+portNumber); - debugLog.printRTAriDebug (fn, "Trace C"); + debugLog.printRTAriDebug(fn, + "::Attempting to connect to " + hostName + " username=" + username + " password=" + password + + " portNumber=" + portNumber); + debugLog.printRTAriDebug(fn, "Trace C"); RouterName = hostName; - this.hostName = hostName; - userName = username; - passWord = password; - try - { - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); + this.hostName = hostName; + userName = username; + passWord = password; + try { + 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.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"); + 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) - { - debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out."); - } + 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) { + debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out."); + } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e); - // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e); + } 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 - { - String fn = "SshJcraftWrapper.sftp"; - try - { - Session sftpSession = jsch.getSession(userName, hostName, 22); + public void put(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); + 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 put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException - { - String fn = "SshJcraftWrapper.put"; - Session sftpSession = null; - try - { - debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); - jsch = new JSch(); - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); - sftpSession = jsch.getSession(userName, hostName, 22); + + public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) + throws IOException { + String fn = "SshJcraftWrapper.put"; + Session sftpSession = null; + try { + debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord); + 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 +"*"; - 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); - debugLog.printRTAriDebug (fn, "Sent successfully"); - sftpSession.disconnect(); - sftpSession = null; - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - sftpSession.disconnect(); - sftpSession = null; - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + 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 + "*"; + 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); + debugLog.printRTAriDebug(fn, "Sent successfully"); + sftpSession.disconnect(); + sftpSession = null; + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + sftpSession.disconnect(); + sftpSession = null; + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); throw new IOException(e.toString()); + } } - } - - - public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException - { - String fn = "SshJcraftWrapper.get"; - Session sftpSession = null; - try - { - debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord); - jsch = new JSch(); - sftpSession = jsch.getSession(userName, hostName, 22); - java.util.Properties config = new java.util.Properties(); - config.put("StrictHostKeyChecking", "no"); + + + public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException { + String fn = "SshJcraftWrapper.get"; + Session sftpSession = null; + try { + debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord); + 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 = null; - in = sftp.get(fullFilePathName); - String sftpFileString = readInputStreamAsString(in); - debugLog.printRTAriDebug (fn, "Retreived successfully"); - // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); - sftpSession.disconnect(); - sftpSession = null; - return(sftpFileString); - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e); - sftpSession.disconnect(); - sftpSession = null; - // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); + 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 = null; + in = sftp.get(fullFilePathName); + String sftpFileString = readInputStreamAsString(in); + debugLog.printRTAriDebug(fn, "Retreived successfully"); + // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString); + sftpSession.disconnect(); + sftpSession = null; + return (sftpFileString); + } catch (Exception e) { + debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e); + sftpSession.disconnect(); + sftpSession = null; + // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e); throw new IOException(e.toString()); + } } - } - public String send(String cmd, String delimiter) throws IOException - { + public String send(String cmd, String delimiter) throws IOException { 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')) + 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 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 { + debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes"); + dos.writeBytes(cmd); } - } - catch (Exception e) - { - debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out."); - } - } - } - 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); + 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()); } } diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TelnetListener.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TelnetListener.java index 6ae83b238..addb1118f 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TelnetListener.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TelnetListener.java @@ -7,9 +7,9 @@ * 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. @@ -20,9 +20,10 @@ package org.onap.appc.ccadaptor; -public interface TelnetListener -{ +public interface TelnetListener { + public void receivedString(String s); + public void filterStrings(String s1, String s2); } diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TimedOutException.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TimedOutException.java index 3952ffeb9..05969dfdd 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TimedOutException.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/TimedOutException.java @@ -7,9 +7,9 @@ * 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. @@ -20,18 +20,16 @@ package org.onap.appc.ccadaptor; -import java.io.*; +import java.io.IOException; -public class TimedOutException extends IOException -{ - public TimedOutException() - { - } +public class TimedOutException extends IOException { - public TimedOutException(String message) - { - super(message); - } + public TimedOutException() { + } + + public TimedOutException(String message) { + super(message); + } } diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/XmlUtil.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/XmlUtil.java index bc8d968f2..8f9d70252 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/XmlUtil.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/XmlUtil.java @@ -7,9 +7,9 @@ * 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. @@ -24,140 +24,129 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class XmlUtil -{ - - private static final Logger log = LoggerFactory.getLogger(XmlUtil.class); - - public static String getXml(Map varmap, String var) - { - Object o = createStructure(varmap, var); - return generateXml(o, 0); - } - - private static Object createStructure(Map flatmap, String var) - { - if (flatmap.containsKey(var)) - return flatmap.get(var); - - Map mm = new HashMap<>(); - for (String k : flatmap.keySet()) - if (k.startsWith(var + ".")) - { - int i1 = k.indexOf('.', var.length() + 1); - int i2 = k.indexOf('[', var.length() + 1); - int i3 = k.length(); - if (i1 > 0 && i1 < i3) - i3 = i1; - if (i2 > 0 && i2 < i3) - i3 = i2; - String k1 = k.substring(var.length() + 1, i3); - String var1 = k.substring(0, i3); - if (!mm.containsKey(k1)) - { - Object str = createStructure(flatmap, var1); - if (str != null && (!(str instanceof String) || ((String) str).trim().length() > 0)) - mm.put(k1, str); +public class XmlUtil { + + private static final Logger log = LoggerFactory.getLogger(XmlUtil.class); + + public static String getXml(Map varmap, String var) { + Object o = createStructure(varmap, var); + return generateXml(o, 0); + } + + private static Object createStructure(Map flatmap, String var) { + if (flatmap.containsKey(var)) { + return flatmap.get(var); } - } - if (!mm.isEmpty()) - return mm; - - boolean arrayFound = false; - for (String k : flatmap.keySet()) - if (k.startsWith(var + "[")) - { - arrayFound = true; - break; - } - - if (arrayFound) - { - List ll = new ArrayList<>(); - - int length = Integer.MAX_VALUE; - String lengthStr = flatmap.get(var + "_length"); - if (lengthStr != null) - { - try - { - length = Integer.parseInt(lengthStr); + + Map mm = new HashMap<>(); + for (String k : flatmap.keySet()) { + if (k.startsWith(var + ".")) { + int i1 = k.indexOf('.', var.length() + 1); + int i2 = k.indexOf('[', var.length() + 1); + int i3 = k.length(); + if (i1 > 0 && i1 < i3) { + i3 = i1; + } + if (i2 > 0 && i2 < i3) { + i3 = i2; + } + String k1 = k.substring(var.length() + 1, i3); + String var1 = k.substring(0, i3); + if (!mm.containsKey(k1)) { + Object str = createStructure(flatmap, var1); + if (str != null && (!(str instanceof String) || ((String) str).trim().length() > 0)) { + mm.put(k1, str); + } + } + } + } + if (!mm.isEmpty()) { + return mm; } - catch (Exception e) - { - log.warn("Invalid number for " + var + "_length:" + lengthStr); + + boolean arrayFound = false; + for (String k : flatmap.keySet()) { + if (k.startsWith(var + "[")) { + arrayFound = true; + break; + } } - } - - for (int i = 0; i < length; i++) - { - Object v = createStructure(flatmap, var + '[' + i + ']'); - if (v == null) - break; - ll.add(v); - } - - if (!ll.isEmpty()) - return ll; + + if (arrayFound) { + List ll = new ArrayList<>(); + + int length = Integer.MAX_VALUE; + String lengthStr = flatmap.get(var + "_length"); + if (lengthStr != null) { + try { + length = Integer.parseInt(lengthStr); + } catch (Exception e) { + log.warn("Invalid number for " + var + "_length:" + lengthStr); + } + } + + for (int i = 0; i < length; i++) { + Object v = createStructure(flatmap, var + '[' + i + ']'); + if (v == null) { + break; + } + ll.add(v); + } + + if (!ll.isEmpty()) { + return ll; + } + } + + return null; } - return null; - } - - @SuppressWarnings("unchecked") - private static String generateXml(Object o, int indent) - { - if (o == null) - return null; - - if (o instanceof String) - return (String) o; - - if (o instanceof Map) - { - StringBuilder ss = new StringBuilder(); - Map mm = (Map) o; - for (String k : mm.keySet()) - { - Object v = mm.get(k); - if (v instanceof String) - { - ss.append(pad(indent)).append('<').append(k).append('>'); - ss.append(v); - ss.append("').append('\n'); + @SuppressWarnings("unchecked") + private static String generateXml(Object o, int indent) { + if (o == null) { + return null; } - else if (v instanceof Map) - { - ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); - ss.append(generateXml(v, indent + 1)); - ss.append(pad(indent)).append("').append('\n'); + + if (o instanceof String) { + return (String) o; } - else if (v instanceof List) - { - List ll = (List) v; - for (Object o1 : ll) - { - ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); - ss.append(generateXml(o1, indent + 1)); - ss.append(pad(indent)).append("').append('\n'); - } + + if (o instanceof Map) { + StringBuilder ss = new StringBuilder(); + Map mm = (Map) o; + for (String k : mm.keySet()) { + Object v = mm.get(k); + if (v instanceof String) { + ss.append(pad(indent)).append('<').append(k).append('>'); + ss.append(v); + ss.append("').append('\n'); + } else if (v instanceof Map) { + ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); + ss.append(generateXml(v, indent + 1)); + ss.append(pad(indent)).append("').append('\n'); + } else if (v instanceof List) { + List ll = (List) v; + for (Object o1 : ll) { + ss.append(pad(indent)).append('<').append(k).append('>').append('\n'); + ss.append(generateXml(o1, indent + 1)); + ss.append(pad(indent)).append("').append('\n'); + } + } + } + return ss.toString(); } - } - return ss.toString(); - } - return null; - } + return null; + } - private static String pad(int n) - { - String s = ""; - for (int i = 0; i < n; i++) - s += '\t'; - return s; - } + private static String pad(int n) { + String s = ""; + for (int i = 0; i < n; i++) { + s += '\t'; + } + return s; + } } -- cgit 1.2.3-korg