* ============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
* 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=========================================================
*/
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.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;
private JSch jsch = null;
private Session session = null;
private Channel channel = null;
+ private String tId = "";
private String aggregatedReceivedString = "";
private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
private String routerCmdType = "XML";
private String 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;
((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");
}
} 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());
}
}
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();
((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");
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;
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,
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");
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) {
if (fileWriter != null) {
fileWriter.close();
}
- } catch (IOException ex) {
+ } catch(IOException ex) {
DebugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
}
}
} 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];
} catch (IOException e) {
DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
dbLog.outputStackTrace(e);
- e.printStackTrace();
}
}
}
String fn = "SshJcraftWrapper.closeConnection";
DebugLog.printRTAriDebug(fn, "Executing the closeConnection....");
inputStream = null;
+ outputStream = null;
dis = null;
charBuffer = null;
session.disconnect();
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);
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);
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();
// 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);
// 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);
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));
}
// 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);
}
}
}
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');
}
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 + "'");
}
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();
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="
}
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);
}
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());
}
}
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) {
+ 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();
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);
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;
((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");
} 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());
}
}
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());
}
}
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);
DebugLog.printRTAriDebug(fn, "No files found -- Continue");
} else {
DebugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
- sft.printStackTrace();
throw sft;
}
}
DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
throw new IOException(e.toString());
} finally {
- if (sftpSession != null) {
+ if(sftpSession != null) {
sftpSession.disconnect();
}
}
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");
DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
throw new IOException(e.toString());
} finally {
- if (sftpSession != null) {
+ if(sftpSession != null) {
sftpSession.disconnect();
}
}
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);
}
}