Changed to unmaintained
[appc.git] / appc-config / appc-config-adaptor / provider / src / main / java / org / onap / appc / ccadaptor / SshJcraftWrapper.java
index 7494f43..8213387 100644 (file)
@@ -2,10 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Copyright (C) 2017 Amdocs
- * =============================================================================
+ * ================================================================================
+ * Modifications Copyright (C) 2018 Ericsson
+ * ================================================================================
+ * Modifications Copyright (c) 2019 IBM
+ * ================================================================================
  * 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
@@ -18,7 +22,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
 
@@ -42,7 +45,6 @@ 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;
@@ -54,19 +56,20 @@ import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.StringTokenizer;
-import javax.annotation.Nonnull;
 import org.apache.commons.lang.StringUtils;
 
 public class SshJcraftWrapper {
 
-    private static final int BUFFER_SIZE = 512000;
-    private InputStream inputStream = null;
+    InputStream inputStream = null;
+    OutputStream outputStream = null;
+    DebugLog debugLog = new DebugLog();
     private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
     private TelnetListener listener = null;
     private String routerLogFileName = null;
     private String host = null;
     private String routerName = null;
-    private char[] charBuffer = new char[BUFFER_SIZE];
+    private int bufferSize = 512000;
+    char[] charBuffer = new char[bufferSize];
     private DataInputStream dis = null;
     private BufferedReader reader = null;
     private BufferedWriter out = null;
@@ -74,6 +77,7 @@ public class SshJcraftWrapper {
     private JSch jsch = null;
     private Session session = null;
     private Channel channel = null;
+    private String tId = "";
     private String aggregatedReceivedString = "";
     private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
     private String routerCmdType = "XML";
@@ -83,22 +87,22 @@ public class SshJcraftWrapper {
     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();
 
-    public void SshJcraftWrapper() {
+    public SshJcraftWrapper() {
         String fn = "SshJcraftWrapper.SshJcraftWrapper";
         DebugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
         routerLogFileName = "/tmp/" + host;
-        this.host = host;
     }
 
     public void connect(String hostname, String username, String password, String prompt, int timeOut)
         throws IOException {
         String fn = "SshJcraftWrapper.connect";
-        jsch = new JSch();
+        jsch = getJSch();
         DebugLog.printRTAriDebug(fn,
-            "Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
+            "Attempting to connect to " + hostname + " username=" + username + " prompt='"
                 + prompt + "' timeOut=" + timeOut);
         DebugLog.printRTAriDebug(fn, "Trace A");
         routerName = hostname;
@@ -117,7 +121,7 @@ public class SshJcraftWrapper {
             ((ChannelShell) channel).setPtyType("vt102");
             inputStream = channel.getInputStream();
             dis = new DataInputStream(inputStream);
-            reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
+            reader = new BufferedReader(new InputStreamReader(dis), bufferSize);
             channel.connect();
             DebugLog.printRTAriDebug(fn, "Successfully connected.");
             DebugLog.printRTAriDebug(fn, "Flushing input buffer");
@@ -128,7 +132,6 @@ public class SshJcraftWrapper {
             }
         } catch (Exception e) {
             DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
-            // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
             throw new IOException(e.toString());
         }
     }
@@ -138,14 +141,14 @@ public class SshJcraftWrapper {
         throws IOException {
         String fn = "SshJcraftWrapper.connect";
         DebugLog.printRTAriDebug(fn,
-            ":Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
+            ":Attempting to connect to " + hostname + " username=" + username + " prompt='"
                 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
         routerName = hostname;
         hostName = hostname;
         userName = username;
         passWord = password;
         routerName = hostname;
-        jsch = new JSch();
+        jsch = getJSch();
         try {
             session = jsch.getSession(username, hostname, portNum);
             UserInfo ui = new MyUserInfo();
@@ -161,7 +164,7 @@ public class SshJcraftWrapper {
             ((ChannelShell) channel).setPtyType("vt102");
             inputStream = channel.getInputStream();
             dis = new DataInputStream(inputStream);
-            reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
+            reader = new BufferedReader(new InputStreamReader(dis), bufferSize);
             channel.connect();
             DebugLog.printRTAriDebug(fn, ":Successfully connected.");
             DebugLog.printRTAriDebug(fn, ":Flushing input buffer");
@@ -178,13 +181,13 @@ public class SshJcraftWrapper {
             DebugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
             dbLog.outputStackTrace(e);
 
-            // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
             throw new IOException(e.toString());
         }
     }
 
 
-    public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent) throws IOException {
+    public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent)
+        throws TimedOutException, IOException {
         String fn = "SshJcraftWrapper.receiveUntil";
         boolean match = false;
         boolean cliPromptCmd = false;
@@ -210,11 +213,11 @@ public class SshJcraftWrapper {
                     throw new TimedOutException("Timeout: time in routine has exceed our deadline");
                 }
                 try {
-                    Thread.sleep(500);
+                    delay(500);
                 } catch (java.lang.InterruptedException ee) {
-                    boolean ignore = true;
+                    Thread.currentThread().interrupt();
                 }
-                int len = reader.read(charBuffer, 0, BUFFER_SIZE);
+                int len = reader.read(charBuffer, 0, bufferSize);
                 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
                 if (len <= 0) {
                     DebugLog.printRTAriDebug(fn,
@@ -238,7 +241,6 @@ public class SshJcraftWrapper {
                             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");
@@ -278,23 +280,6 @@ public class SshJcraftWrapper {
                             break;
                         }
                     }
-                } else {
-                    DebugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
-                    sb2.setLength(0);
-                    for (int i = 0; i < len; i++) {
-                        sbReceive.append((char) charBuffer[i]);
-                        sb2.append((char) charBuffer[i]);
-                    }
-                    appendToRouterFile("/tmp/" + routerName, sb2);
-                    if (listener != null) {
-                        listener.receivedString(sb2.toString());
-                    }
-                    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) {
@@ -310,7 +295,7 @@ public class SshJcraftWrapper {
                 if (fileWriter != null) {
                     fileWriter.close();
                 }
-            } catch (IOException ex) {
+            } catch(IOException ex) {
                 DebugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
             }
         }
@@ -389,10 +374,8 @@ public class SshJcraftWrapper {
             } catch (IOException e) {
                 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
                 dbLog.outputStackTrace(e);
-                e.printStackTrace();
             }
         } else {
-            // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
             // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
             for (x = len - 1; x >= 0; x--) {
                 c = charBuffer[x];
@@ -420,7 +403,6 @@ public class SshJcraftWrapper {
                 } catch (IOException e) {
                     DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
                     dbLog.outputStackTrace(e);
-                    e.printStackTrace();
                 }
             }
         }
@@ -441,6 +423,7 @@ public class SshJcraftWrapper {
         String fn = "SshJcraftWrapper.closeConnection";
         DebugLog.printRTAriDebug(fn, "Executing the closeConnection....");
         inputStream = null;
+        outputStream = null;
         dis = null;
         charBuffer = null;
         session.disconnect();
@@ -449,9 +432,48 @@ public class SshJcraftWrapper {
 
     public void send(String cmd) throws IOException {
         String fn = "SshJcraftWrapper.send";
-
-        try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) {
-            sendSshCommand(cmd, dos);
+        OutputStream out = channel.getOutputStream();
+        DataOutputStream dos = getDataOutputStream(out);
+        if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
+            cmd += "\n";
+        }
+        int length = cmd.length();
+        int i = -1;
+        int nchars = 300000;
+        int ncharsTotalSent = 0;
+        int ncharsSent = 0;
+
+        appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
+        DebugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
+        try {
+            if (length > 600000) {
+                int timeout = 9000;
+                for (i = 0; i < length; i += nchars) {
+                    String Cmd = cmd.substring(i, Math.min(length, i + nchars));
+                    ncharsSent = Cmd.length();
+                    ncharsTotalSent = ncharsTotalSent + Cmd.length();
+                    DebugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
+                    dos.writeBytes(Cmd);
+                    dos.flush();
+                    try {
+                        DebugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
+                        if (ncharsSent < length) {
+                            receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush  i=" + i);
+                        } else {
+                            DebugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
+                            dos.flush();
+                        }
+                    } catch (Exception e) {
+                        DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
+                    }
+                }
+            } else {
+                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);
@@ -463,7 +485,7 @@ public class SshJcraftWrapper {
     public void sendChar(int v) throws IOException {
         String fn = "SshJcraftWrapper.sendChar";
         OutputStream out = channel.getOutputStream();
-        DataOutputStream dos = new DataOutputStream(out);
+        DataOutputStream dos = getDataOutputStream(out);
         try {
             DebugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
             dos.writeChar(v);
@@ -477,7 +499,7 @@ public class SshJcraftWrapper {
     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);
+        DataOutputStream dos = getDataOutputStream(out);
         try {
             dos.write(b, off, len);
             dos.flush();
@@ -533,12 +555,9 @@ public class SshJcraftWrapper {
             // write to it. If it does not exist, don't write to it.
             File tmpFile = new File(fileName);
             if (tmpFile.exists()) {
-                BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
-                // out.write(dataToWrite);
-                // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
-                String tId = "";
-                out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
-                out.close();
+                try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
+                    out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
+                }
             }
         } catch (IOException e) {
             DebugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
@@ -555,9 +574,9 @@ public class SshJcraftWrapper {
             // 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();
+                try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
+                    out.write(dataToWrite);
+                }
             }
         } catch (IOException e) {
             DebugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
@@ -570,7 +589,6 @@ public class SshJcraftWrapper {
     public String getTheDate() {
         Calendar cal = Calendar.getInstance();
         java.util.Date today = cal.getTime();
-        DateFormat df1 = DateFormat.getDateInstance();
         DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss  ");
         return (df3.format(today));
     }
@@ -584,37 +602,30 @@ public class SshJcraftWrapper {
             // write to it. If it does not exist, don't write to it.
             File tmpFile = new File(fileName);
             {
-                // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
                 if (tmpFile.exists()) {
-                    BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
-                    // out.write("<!--  "+getTheDate() +": " +tId +"  -->\n");
-                    out.write(dataToWrite.toString());
-                    out.close();
+                    try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
+                        out.write(dataToWrite.toString());
+                    }
                 }
             }
         } catch (IOException e) {
-            System.err.println("writeToFile() exception: " + e);
-            e.printStackTrace();
+            DebugLog.printAriDebug(fnName, "writeToFile() exception:, e=" + e);
+            dbLog.outputStackTrace(e);
         }
     }
 
     public void appendToRouterFile(String fileName, int len) {
-        String fnName = "SshJcraftWrapper.appendToFile";
-        // DebugLog.printRTAriDebug (fnName, "Entered.... len="+len);
         try {
             // First check to see if a file 'fileName' exist, if it does
             // write to it. If it does not exist, don't write to it.
             File tmpFile = new File(fileName);
-            // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
             if (tmpFile.exists()) {
-                BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
-                // out.write("<!--  "+getTheDate() +": " +tId +"  -->\n");
-                out.write(charBuffer, 0, len);
-                out.close();
+                try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
+                    out.write(charBuffer, 0, len);
+                }
             }
         } catch (IOException e) {
-            System.err.println("writeToFile() exception: " + e);
-            e.printStackTrace();
+            dbLog.outputStackTrace(e);
         }
     }
 
@@ -634,20 +645,15 @@ public class SshJcraftWrapper {
     }
 
     public String stripOffCmdFromRouterResponse(String routerResponse) {
-        String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
-        // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
-
         // The session of SSH will echo the command sent to the router, in the router's response.
         // Since all our commands are terminated by a '\n', strip off the first line
-        // of the response from the router. This first line contains the orginal command.
+        // of the response from the router. This first line contains the original command.
 
         StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
         StringBuffer sb = new StringBuffer();
 
         int numTokens = rr.countTokens();
-        // DebugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
         if (numTokens > 1) {
-            rr.nextToken(); //Skip the first line.
             while (rr.hasMoreTokens()) {
                 sb.append(rr.nextToken() + '\n');
             }
@@ -661,31 +667,30 @@ public class SshJcraftWrapper {
         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 IOException {
         String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
-        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
-        int lines = 0;
-        StringBuilder builder = new StringBuilder();
         String tail = "";
-        long length = file.length();
-        length--;
-        randomAccessFile.seek(length);
-        for (long seek = length; seek >= 0; --seek) {
-            randomAccessFile.seek(seek);
-            char c = (char) randomAccessFile.read();
-            builder.append(c);
-            if (c == '\n') {
-                builder = builder.reverse();
-                // System.out.println(builder.toString());
-                tail = builder.toString() + tail;
-                lines++;
-                builder.setLength(0);
-                if (lines == linesToRead) {
-                    break;
+        try(RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
+            int lines = 0;
+            StringBuilder builder = new StringBuilder();
+            long length = file.length();
+            length--;
+            randomAccessFile.seek(length);
+            for (long seek = length; seek >= 0; --seek) {
+                randomAccessFile.seek(seek);
+                char c = (char) randomAccessFile.read();
+                builder.append(c);
+                if (c == '\n') {
+                    builder = builder.reverse();
+                    tail = builder.toString() + tail;
+                    lines++;
+                    builder.setLength(0);
+                    if (lines == linesToRead) {
+                        break;
+                    }
                 }
             }
         }
-        randomAccessFile.close();
         if (!jcraftReadSwConfigFileFromDisk()) {
             DebugLog.printRTAriDebug(fn, "tail='" + tail + "'");
         }
@@ -718,12 +723,10 @@ public class SshJcraftWrapper {
     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();
@@ -734,16 +737,14 @@ public class SshJcraftWrapper {
                     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);
+                ncharsRead = reader.read(charBuffer, 0, bufferSize);
                 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="
@@ -774,26 +775,8 @@ public class SshJcraftWrapper {
     }
 
     public void sftpPut(String sourcePath, String destDirectory) throws IOException {
-        String fn = "SshJcraftWrapper.sftp";
-        try {
-            Session sftpSession = jsch.getSession(userName, hostName, 22);
-            UserInfo ui = new MyUserInfo();
-            sftpSession.setPassword(passWord);
-            sftpSession.setUserInfo(ui);
-            sftpSession.connect(30 * 1000);
-            DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
-            ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
-            DebugLog.printRTAriDebug(fn, "Connecting....");
-            sftp.connect();
-            DebugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
-            sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
-            DebugLog.printRTAriDebug(fn, "Sent successfully");
-            sftpSession.disconnect();
-        } catch (Exception e) {
-            DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
-            // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
-            throw new IOException(e.toString());
-        }
+        // delegate to duplicate method
+        put(sourcePath, destDirectory);
     }
 
 
@@ -816,7 +799,6 @@ public class SshJcraftWrapper {
             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());
         }
     }
@@ -837,7 +819,6 @@ public class SshJcraftWrapper {
             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) {
@@ -873,16 +854,22 @@ public class SshJcraftWrapper {
                 + 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 {
         String fn = "SshJcraftWrapper.connect";
 
         DebugLog.printRTAriDebug(fn,
-            ":::Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
+            ":::Attempting to connect to " + hostname + " username=" + username + " prompt='"
                 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
         routerName = hostname;
-        jsch = new JSch();
+        jsch = getJSch();
         try {
             session = jsch.getSession(username, hostname, portNum);
             UserInfo ui = new MyUserInfo();
@@ -894,19 +881,18 @@ public class SshJcraftWrapper {
                 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);
 
             inputStream = channel.getInputStream();
             dis = new DataInputStream(inputStream);
-            reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
+            reader = new BufferedReader(new InputStreamReader(dis), bufferSize);
             channel.connect();
             DebugLog.printRTAriDebug(fn, "Successfully connected.");
             DebugLog.printRTAriDebug(fn, "Five second sleep....");
             try {
-                Thread.sleep(5000);
+                delay(5000);
             } catch (java.lang.InterruptedException ee) {
-                boolean ignore = true;
+                Thread.currentThread().interrupt();
             }
         } catch (Exception e) {
             DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
@@ -916,10 +902,9 @@ public class SshJcraftWrapper {
 
     public void connect(String hostName, String username, String password, int portNumber) throws IOException {
         String fn = "SshJcraftWrapper.connect";
-        jsch = new JSch();
+        jsch = getJSch();
         DebugLog.printRTAriDebug(fn,
-            "::Attempting to connect to " + hostName + " username=" + username + " password=" + password
-                + " portNumber=" + portNumber);
+            "::Attempting to connect to " + hostName + " username=" + username + " portNumber=" + portNumber);
         DebugLog.printRTAriDebug(fn, "Trace C");
         routerName = hostName;
         this.hostName = hostName;
@@ -940,7 +925,7 @@ public class SshJcraftWrapper {
             ((ChannelShell) channel).setPtyType("vt102");
             inputStream = channel.getInputStream();
             dis = new DataInputStream(inputStream);
-            reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
+            reader = new BufferedReader(new InputStreamReader(dis), bufferSize);
             channel.connect();
             DebugLog.printRTAriDebug(fn, "::Successfully connected.");
             DebugLog.printRTAriDebug(fn, "::Flushing input buffer");
@@ -952,7 +937,6 @@ public class SshJcraftWrapper {
 
         } 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());
         }
     }
@@ -976,7 +960,6 @@ public class SshJcraftWrapper {
             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());
         }
     }
@@ -986,8 +969,8 @@ public class SshJcraftWrapper {
         String fn = "SshJcraftWrapper.put";
         Session sftpSession = null;
         try {
-            DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
-            jsch = new JSch();
+            DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
+            jsch = getJSch();
             java.util.Properties config = new java.util.Properties();
             config.put("StrictHostKeyChecking", "no");
             sftpSession = jsch.getSession(userName, hostName, 22);
@@ -1011,7 +994,6 @@ public class SshJcraftWrapper {
                     DebugLog.printRTAriDebug(fn, "No files found -- Continue");
                 } else {
                     DebugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
-                    sft.printStackTrace();
                     throw sft;
                 }
             }
@@ -1021,7 +1003,7 @@ public class SshJcraftWrapper {
             DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
             throw new IOException(e.toString());
         } finally {
-            if (sftpSession != null) {
+            if(sftpSession != null) {
                 sftpSession.disconnect();
             }
         }
@@ -1032,8 +1014,8 @@ public class SshJcraftWrapper {
         String fn = "SshJcraftWrapper.get";
         Session sftpSession = null;
         try {
-            DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
-            jsch = new JSch();
+            DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
+            jsch = getJSch();
             sftpSession = jsch.getSession(userName, hostName, 22);
             java.util.Properties config = new java.util.Properties();
             config.put("StrictHostKeyChecking", "no");
@@ -1054,7 +1036,7 @@ public class SshJcraftWrapper {
             DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
             throw new IOException(e.toString());
         } finally {
-            if (sftpSession != null) {
+            if(sftpSession != null) {
                 sftpSession.disconnect();
             }
         }
@@ -1062,68 +1044,65 @@ public class SshJcraftWrapper {
 
     public String send(String cmd, String delimiter) throws IOException {
         String fn = "SshJcraftWrapper.send";
+        OutputStream out = channel.getOutputStream();
+        DataOutputStream dos = getDataOutputStream(out);
 
-        try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) {
-            sendSshCommand(cmd, dos);
+        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
+        try {
+            if (length > 600000) {
+                int timeout = 9000;
+                for (i = 0; i < length; i += nchars) {
+                    String Cmd = cmd.substring(i, Math.min(length, i + nchars));
+                    ncharsSent = Cmd.length();
+                    ncharsTotalSent = ncharsTotalSent + Cmd.length();
+                    DebugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
+                    dos.writeBytes(Cmd);
+                    dos.flush();
+                    try {
+                        DebugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
+                        if (ncharsSent < length) {
+                            receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush  i=" + i);
+                        } else {
+                            DebugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
+                            dos.flush();
+                        }
+                    } catch (Exception e) {
+                        DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
+                    }
+                }
+            } else {
+                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;
+            return (response);
         } catch (IOException e) {
             DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
-            dbLog.outputStackTrace(e);
             throw new IOException(e.toString());
         }
     }
 
-    private void sendSshCommand(@Nonnull String originalCommand, @Nonnull DataOutputStream channelOutputStream)
-        throws IOException {
-        String fn = "SshJcraftWrapper.sendSshCommand";
-        String command = enhanceCommandWithEOL(originalCommand);
-        int length = command.length();
-        int charsChunkSize = 300000;
-        int charsTotalSent = 0;
-
-        appendToFile(debugLogFileName, fn + ": Sending: '" + command);
-        DebugLog.printRTAriDebug(fn, "Length of command is:" + length); // 2,937,706
-        if (isCmdLengthEnoughToSendInChunks(length, charsChunkSize)) {
-            int timeout = 9000;
-            for (int i = 0; i < length; i += charsChunkSize) {
-                String commandChunk = command.substring(i, Math.min(length, i + charsChunkSize));
-                int numCharsSentInChunk = commandChunk.length();
-                charsTotalSent = charsTotalSent + commandChunk.length();
-                DebugLog.printRTAriDebug(fn, "i=" + i + " Sending command: ncharsSent=" + numCharsSentInChunk);
-                channelOutputStream.writeBytes(commandChunk);
-                channelOutputStream.flush();
-                try {
-                    DebugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
-                    if (numCharsSentInChunk < length) {
-                        receiveUntilBufferFlush(numCharsSentInChunk, timeout, "buffer flush  i=" + i);
-                    } else {
-                        DebugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
-                        channelOutputStream.flush();
-                    }
-                } catch (Exception e) {
-                    DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
-                }
-            }
-        } else {
-            DebugLog.printRTAriDebug(fn, "Before executing the channelOutputStream.writeBytes");
-            channelOutputStream.writeBytes(command);
-        }
-        channelOutputStream.flush();
-        DebugLog.printRTAriDebug(fn, "Leaving method");
-        appendToFile(debugLogFileName, fn + ": Leaving method\n");
+    protected JSch getJSch() {
+        return new JSch();
     }
 
-    private boolean isCmdLengthEnoughToSendInChunks(int length, int chunkSize) {
-        return length > 2 * chunkSize;
+    protected DataOutputStream getDataOutputStream(OutputStream out) {
+        return new DataOutputStream(out);
     }
 
-    private String enhanceCommandWithEOL(@Nonnull String originalCommand) {
-        char commandEnding = originalCommand.charAt(originalCommand.length() - 1);
-        if (commandEnding != '\n' && commandEnding != '\r') {
-            return originalCommand + "\n";
-        }
-        return originalCommand;
+    protected void delay(int milliseconds) throws InterruptedException {
+        Thread.sleep(5000);
     }
 }