summaryrefslogtreecommitdiffstats
path: root/appc-config/appc-config-adaptor
diff options
context:
space:
mode:
authorTomek Kaminski <tomasz.kaminski@nokia.com>2018-01-19 15:06:34 +0100
committerPatrick Brady <pb071s@att.com>2018-01-22 18:08:52 +0000
commit9ed1e8d5ba5f08d608d23975479a9abb8ee25548 (patch)
tree36fb5f0f4e53d59ee3c1f0e0d8cfcb85ab59f516 /appc-config/appc-config-adaptor
parent3d619ee65aadb4604bd49a133af9fdf13c11770c (diff)
Move to EELF logging
Changed all logs to use EELF framework without i18n Fixed another several sonar majors Change-Id: I4754a4428bcbb92170de63e34fc5c9c5cb34d9e9 Issue-ID: APPC-428 Signed-off-by: Tomek Kaminski <tomasz.kaminski@nokia.com>
Diffstat (limited to 'appc-config/appc-config-adaptor')
-rw-r--r--appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/SshJcraftWrapper.java666
-rw-r--r--appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java6
2 files changed, 245 insertions, 427 deletions
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 7494f4395..70b762bc7 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,6 +24,8 @@
package org.onap.appc.ccadaptor;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
@@ -42,7 +44,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,17 +55,18 @@ import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
+import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.apache.commons.lang.StringUtils;
public class SshJcraftWrapper {
+ private static final EELFLogger log = EELFManager.getInstance().getLogger(SshJcraftWrapper.class);
+
private static final int BUFFER_SIZE = 512000;
private InputStream inputStream = null;
- 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 DataInputStream dis = null;
@@ -75,7 +77,6 @@ public class SshJcraftWrapper {
private Session session = null;
private Channel channel = null;
private String aggregatedReceivedString = "";
- private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
private String routerCmdType = "XML";
private String routerFileName = null;
private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
@@ -84,23 +85,12 @@ public class SshJcraftWrapper {
private String userName = null;
private String passWord = null;
private Runtime runtime = Runtime.getRuntime();
- private DebugLog dbLog = new DebugLog();
-
- public void SshJcraftWrapper() {
- String fn = "SshJcraftWrapper.SshJcraftWrapper";
- DebugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
- routerLogFileName = "/tmp/" + host;
- this.host = host;
- }
public void connect(String hostname, String username, String password, String prompt, int timeOut)
throws IOException {
- 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");
+ log.debug("Attempting to connect to {0} username={1} prompt='{2}' timeOut={3}",
+ hostname, username, prompt, timeOut);
routerName = hostname;
hostName = hostname;
userName = username;
@@ -119,16 +109,14 @@ public class SshJcraftWrapper {
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");
+ log.info("Successfully connected. 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.");
+ log.warn("Caught an Exception: Nothing to flush out.", e);
}
} catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
- // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
+ log.error("Could not connect to host=" + hostname, e);
throw new IOException(e.toString());
}
}
@@ -136,15 +124,12 @@ public class SshJcraftWrapper {
// User specifies the port number.
public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum)
throws IOException {
- String fn = "SshJcraftWrapper.connect";
- DebugLog.printRTAriDebug(fn,
- ":Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
- + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
+ log.debug("Attempting to connect to {0} username={1} prompt='{2}' timeOut={3} portNum={4}",
+ hostname, username, prompt, timeOut, portNum);
routerName = hostname;
hostName = hostname;
userName = username;
passWord = password;
- routerName = hostname;
jsch = new JSch();
try {
session = jsch.getSession(username, hostname, portNum);
@@ -152,7 +137,7 @@ public class SshJcraftWrapper {
session.setPassword(password);
session.setUserInfo(ui);
session.setConfig("StrictHostKeyChecking", "no");
- DebugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'");
+ log.debug("StrictHostKeyChecking set to 'no'");
session.connect(timeOut);
session.setServerAliveCountMax(
@@ -163,38 +148,29 @@ public class SshJcraftWrapper {
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");
+ log.info("Successfully connected. Flushing input buffer.");
try {
- if (prompt.equals("]]>]]>")) {
+ if ("]]>]]>".equals(prompt)) {
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.");
+ log.warn("Caught an Exception: Nothing to flush out.", e);
}
} catch (Exception e) {
- DebugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
- dbLog.outputStackTrace(e);
-
- // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
+ log.error("Could not connect to host=" + hostname, e);
throw new IOException(e.toString());
}
}
public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent) throws 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");
- String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
+ StringBuilder sb = new StringBuilder();
+ StringBuilder sbReceive = new StringBuilder();
+ log.debug("delimeters='{0}' timeout={1} cmdThatWasSent='{2}'", delimeters, timeout, cmdThatWasSent);
int readCounts = 0;
aggregatedReceivedString = "";
FileWriter fileWriter = null;
@@ -204,21 +180,19 @@ public class SshJcraftWrapper {
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);
- throw new TimedOutException("Timeout: time in routine has exceed our deadline");
+ String formattedCmd = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
+ log.error("Routine has timed out: routerName={0} CmdThatWasSent={1}", routerName, formattedCmd);
+ throw new TimedOutException("Routine has timed out");
}
try {
Thread.sleep(500);
} catch (java.lang.InterruptedException ee) {
- boolean ignore = true;
+ Thread.currentThread().interrupt();
}
int len = reader.read(charBuffer, 0, BUFFER_SIZE);
- appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
+ log.trace("After reader. Read command len={0}", len);
if (len <= 0) {
- DebugLog.printRTAriDebug(fn,
- "Reader read " + len + " bytes. Looks like we timed out, router=" + routerName);
+ log.error("Reader failed to read any bytes. Suspected socket timeout, router={0}", routerName);
throw new TimedOutException("Received a SocketTimeoutException router=" + routerName);
}
if (!cliPromptCmd) {
@@ -227,7 +201,7 @@ public class SshJcraftWrapper {
// This is a IOS XR sw config file. We will write it to the disk.
timeout = timeout * 2;
deadline = new Date().getTime() + timeout;
- DebugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
+ log.debug("IOS XR upload for software config: timeout={0}", timeout);
StringTokenizer st = new StringTokenizer(cmdThatWasSent);
st.nextToken();
routerFileName = st.nextToken();
@@ -235,18 +209,16 @@ public class SshJcraftWrapper {
out = new BufferedWriter(fileWriter);
routerLogFileName = "/tmp/" + routerName;
tmpFile = new File(routerLogFileName);
- DebugLog.printRTAriDebug(fn,
- "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
+ log.debug("Prepared for writing swConfigFile to disk, routerFileName=" + routerFileName);
}
- int c;
out.write(charBuffer, 0, len);
out.flush();
- appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
+ log.debug("{0} bytes has been written to the disk", len);
if (tmpFile.exists()) {
appendToRouterFile(routerLogFileName, len);
}
match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
- if (match == true) {
+ if (match) {
out.flush();
out.close();
out = null;
@@ -254,93 +226,81 @@ public class SshJcraftWrapper {
}
} else {
readCounts++;
- appendToFile(debugLogFileName,
- fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
+ log.debug("Reader read {0} of data within {1} read iteration", len, readCounts);
int c;
- sb2.setLength(0);
+ sb.setLength(0);
for (int i = 0; i < len; i++) {
c = charBuffer[i];
if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
- sbReceive.append((char) charBuffer[i]);
- sb2.append((char) charBuffer[i]);
+ sbReceive.append(charBuffer[i]);
+ sb.append(charBuffer[i]);
}
}
appendToRouterFile("/tmp/" + routerName, len);
if (listener != null) {
- listener.receivedString(sb2.toString());
+ listener.receivedString(sb.toString());
}
-
- appendToFile(debugLogFileName, fn + " Trace 1\n");
- match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
- appendToFile(debugLogFileName, fn + " Trace 2\n");
- if (match == true) {
- appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
+ match = checkIfReceivedStringMatchesDelimeter(delimeters, sb.toString(), cmdThatWasSent);
+ if (match) {
+ log.trace("Match was true, breaking the loop.");
break;
}
}
} else {
- DebugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
- sb2.setLength(0);
+ log.trace("cliPromptCmd");
+ sb.setLength(0);
for (int i = 0; i < len; i++) {
- sbReceive.append((char) charBuffer[i]);
- sb2.append((char) charBuffer[i]);
+ sbReceive.append(charBuffer[i]);
+ sb.append(charBuffer[i]);
}
- appendToRouterFile("/tmp/" + routerName, sb2);
+ appendToRouterFile("/tmp/" + routerName, sb);
if (listener != null) {
- listener.receivedString(sb2.toString());
+ listener.receivedString(sb.toString());
}
- DebugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'");
- if (sb2.toString().indexOf("\nariPrompt>") != -1) {
- DebugLog.printRTAriDebug(fn, "Found our prompt");
- match = true;
+ log.debug("sb2={0} delimiters={1}", sb.toString(), delimeters);
+ if (sb.toString().contains("\nariPrompt>")) {
+ log.debug("Found ari prompt");
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());
+ log.error("JSchException occurred", e);
+ throw new TimedOutException(e.getMessage());
+ } catch (IOException e) {
+ log.error("IOException occurred", e);
+ throw new TimedOutException(e.getMessage());
} finally {
try {
if (fileWriter != null) {
fileWriter.close();
}
} catch (IOException ex) {
- DebugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
+ log.warn("Failed to close fileWriter output stream", ex);
}
}
- String result = stripOffCmdFromRouterResponse(sbReceive.toString());
- DebugLog.printRTAriDebug(fn, "Leaving method successfully");
- return result;
+ return stripOffCmdFromRouterResponse(sbReceive.toString());
}
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");
+ log.debug("Entered checkIfReceivedStringMatchesDelimeter: delimeters={0} cmdThatWasSent={1} receivedString={2}",
+ delimeters, cmdThatWasSent, receivedString);
StringTokenizer st = new StringTokenizer(delimeters, "|");
- if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
+ if ((delimeters.contains("#$")) || ("CLI".equals(routerCmdType))) // This would be an IOS XR, CLI command.
{
- int x = receivedString.lastIndexOf("#");
+ 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");
+ log.debug("IOS XR, CLI command");
+ if (log.isTraceEnabled()) {
+ log.trace("cmdThatWasSent={0}, lastIndexOf hash delimiter={1}, maxIndexNum={2}", cmdThatWasSent, x, y);
}
return (x != -1) && (y == x);
}
- if (cmdThatWasSent.indexOf("show config") != -1) {
- appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
+ if (cmdThatWasSent.contains("show config")) {
+ log.trace("In the block for 'show config'");
while (st.hasMoreTokens()) {
String delimeter = st.nextToken();
// Make sure we don't get faked out by a response of " #".
@@ -349,97 +309,73 @@ public class SshJcraftWrapper {
// 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");
- return (true);
+ log.debug("receivedString={0}", receivedString);
+ log.trace("Found ending for 'show config' command, exiting.");
+ return true;
}
}
} else {
aggregatedReceivedString = aggregatedReceivedString + receivedString;
- _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
+ appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
+ log.debug("receivedString={0}", receivedString);
while (st.hasMoreTokens()) {
String delimeter = st.nextToken();
- appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
- appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
+ log.debug("Looking for an delimiter of:{0}", delimeter);
if (aggregatedReceivedString.indexOf(delimeter) != -1) {
- DebugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
+ log.debug("Found delimiter={0}, exiting", delimeter);
aggregatedReceivedString = "";
- return (true);
+ return true;
}
}
}
- return (false);
+ return false;
}
public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
- String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
int x;
int c;
String str = StringUtils.EMPTY;
if (jcraftReadSwConfigFileFromDisk()) {
- DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
+ log.trace("jcraftReadSwConfigFileFromDisk block");
File fileName = new File(routerFileName);
- appendToFile(debugLogFileName,
- fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
+ log.debug("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);
- e.printStackTrace();
+ log.warn("IOException occurred, while reading file=" + fileName, e);
}
} else {
- // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
// When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
for (x = len - 1; x >= 0; x--) {
c = charBuffer[x];
- if (extraDebugFile.exists()) {
- appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
- }
if ((c != 10) && (c != 32)) // Not a line feed nor a space.
{
break;
}
}
if ((x + 1 - 13) >= 0) {
- str = new String(charBuffer, (x + 1 - 13), 13);
- appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
+ str = new String(charBuffer, x + 1 - 13, 13);
+ log.debug("str:{0}", str);
} 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 + "'");
+ log.debug("Will read the tail end of the file from the disk, x={0} len={1} str={2} routerFileName={3}",
+ x, len, str, routerFileName);
try {
str = getLastFewLinesOfFile(fileName, 3);
} catch (IOException e) {
- DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
- dbLog.outputStackTrace(e);
- e.printStackTrace();
+ log.warn("IOException occurred, while reading file=" + fileName, e);
}
}
}
- 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);
- }
-
+ log.debug("Parsed string was str='{0}', searched delimiter was {1}");
+ return str.contains(delimeter);
}
public void closeConnection() {
- String fn = "SshJcraftWrapper.closeConnection";
- DebugLog.printRTAriDebug(fn, "Executing the closeConnection....");
+ log.info("Closing connection");
inputStream = null;
dis = null;
charBuffer = null;
@@ -448,76 +384,76 @@ 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);
} catch (IOException e) {
- DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
- dbLog.outputStackTrace(e);
- throw new IOException(e.toString());
+ log.error("IOException occurred while sending command=" + cmd, e);
+ throw e;
}
}
-
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 + "'");
+ try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) {
+ if (log.isTraceEnabled()) {
+ log.trace("Sending charCode: {0}", v);
+ }
dos.writeChar(v);
dos.flush();
} catch (IOException e) {
- DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
- throw new IOException(e.toString());
+ log.error("IOException occurred while writing char to channel output stream", e);
+ throw e;
}
}
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 {
+ try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) {
dos.write(b, off, len);
dos.flush();
} catch (IOException e) {
- DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
- throw new IOException(e.toString());
+ log.error("IOException occurred while writing bytes to channel output stream", e);
+ throw e;
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
+ @Override
public String getPassword() {
return null;
}
+ @Override
public boolean promptYesNo(String str) {
return false;
}
+ @Override
public String getPassphrase() {
return null;
}
+ @Override
public boolean promptPassphrase(String message) {
return false;
}
+ @Override
public boolean promptPassword(String message) {
return false;
}
+ @Override
public void showMessage(String message) {
+ //stub
}
+ @Override
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo) {
- return null;
+ return new String[0];
}
}
@@ -525,144 +461,77 @@ public class SshJcraftWrapper {
this.listener = listener;
}
- public void appendToFile(String fileName, String dataToWrite) {
- String fn = "SshJcraftWrapper.appendToFile";
-
- try {
- // First check to see if a file 'fileName' exist, if it does
- // write to it. If it does not exist, don't write to it.
- File tmpFile = new File(fileName);
- if (tmpFile.exists()) {
- BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
- // out.write(dataToWrite);
- // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
- String tId = "";
- out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
- out.close();
- }
- } catch (IOException e) {
- DebugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
- } catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
- }
- }
-
- public void _appendToFile(String fileName, String dataToWrite) {
- String fn = "SshJcraftWrapper.appendToFile";
-
- try {
- // First check to see if a file 'fileName' exist, if it does
- // write to it. If it does not exist, don't write to it.
- File tmpFile = new File(fileName);
- if (tmpFile.exists()) {
- BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
- out.write(dataToWrite);
- out.close();
+ private void appendToFile(String fileName, String dataToWrite) {
+ File outputFile = new File(fileName);
+ if (outputFile.exists()) {
+ try (FileWriter fw = new FileWriter(fileName, true); BufferedWriter ow = new BufferedWriter(fw)) {
+ ow.write(dataToWrite);
+ ow.close();
+ } catch (IOException e) {
+ log.error("IOException occurred while writing to file=" + fileName, 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() {
- 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));
+ DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
+ return dateFormat.format(Calendar.getInstance().getTime());
}
- public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
- String fnName = "SshJcraftWrapper.appendToRouterFile";
- DebugLog.printRTAriDebug(fnName, "Entered.... ");
- try {
- // First check to see if a file 'fileName' exist, if it does
- // write to it. If it does not exist, don't write to it.
- File tmpFile = new File(fileName);
- {
- // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
- if (tmpFile.exists()) {
- BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
- // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
- out.write(dataToWrite.toString());
- out.close();
- }
- }
- } catch (IOException e) {
- System.err.println("writeToFile() exception: " + e);
- e.printStackTrace();
- }
+ public void appendToRouterFile(String fileName, StringBuilder dataToWrite) {
+ appendToFile(fileName, dataToWrite.toString());
}
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();
+ File outputFile = new File(fileName);
+ if (outputFile.exists()) {
+ try (FileWriter fw = new FileWriter(fileName, true); BufferedWriter ow = new BufferedWriter(fw)) {
+ ow.write(charBuffer, 0, len);
+ ow.close();
+ } catch (IOException e) {
+ log.error("IOException occurred while writing to router file=" + fileName, e);
}
- } catch (IOException e) {
- System.err.println("writeToFile() exception: " + e);
- e.printStackTrace();
}
}
public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
- if (str != null) {
+ if (str != null && !StringUtils.EMPTY.equals(str)) {
StringTokenizer strTok = new StringTokenizer(str, "\n");
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
while (strTok.hasMoreTokens()) {
String line = strTok.nextToken();
sb.append(line);
}
- return (sb.toString().trim());
- } else {
- return (str);
+ return sb.toString().trim();
}
+ return StringUtils.EMPTY;
}
public String stripOffCmdFromRouterResponse(String routerResponse) {
- String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
- // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
-
// The session of SSH will echo the command sent to the router, in the router's response.
// Since all our commands are terminated by a '\n', strip off the first line
// of the response from the router. This first line contains the orginal command.
-
StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
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');
+ sb.append(rr.nextToken()).append("\n");
}
}
- return (sb.toString());
+ return sb.toString();
}
public void setRouterCommandType(String type) {
- String fn = "SshJcraftWrapper.setRouterCommandType";
this.routerCmdType = type;
- DebugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
+ log.debug("Router command type is set to: {0}", type);
}
- public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException {
- String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
+ public String getLastFewLinesOfFile(File file, int linesToRead) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
int lines = 0;
StringBuilder builder = new StringBuilder();
@@ -676,7 +545,6 @@ public class SshJcraftWrapper {
builder.append(c);
if (c == '\n') {
builder = builder.reverse();
- // System.out.println(builder.toString());
tail = builder.toString() + tail;
lines++;
builder.setLength(0);
@@ -686,24 +554,18 @@ public class SshJcraftWrapper {
}
}
randomAccessFile.close();
- if (!jcraftReadSwConfigFileFromDisk()) {
- DebugLog.printRTAriDebug(fn, "tail='" + tail + "'");
+ if (log.isDebugEnabled()) {
+ log.debug("Content read from file={0} was tail={1}", file.getName(), tail);
}
- appendToFile(debugLogFileName, "tail='" + tail + "'\n");
return tail;
}
public boolean jcraftReadSwConfigFileFromDisk() {
- if (jcraftReadSwConfigFileFromDisk.exists()) {
- return (true);
- } else {
- return (false);
- }
+ return jcraftReadSwConfigFileFromDisk.exists();
}
public String getEquipNameCode() {
- return (equipNameCode);
-
+ return equipNameCode;
}
public void setEquipNameCode(String equipNameCode) {
@@ -711,19 +573,14 @@ public class SshJcraftWrapper {
}
public String getRouterName() {
- return (routerName);
+ 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 {
- String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
- StringBuffer sb2 = new StringBuffer();
- StringBuffer sbReceive = new StringBuffer();
- DebugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
+ public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message) throws IOException {
+ log.debug("ncharsSent={0}, timeout={1}, message={2}", ncharsSent, timeout, message);
int ncharsTotalReceived = 0;
int ncharsRead = 0;
- boolean flag = false;
long deadline = new Date().getTime() + timeout;
logMemoryUsage();
@@ -731,11 +588,9 @@ public class SshJcraftWrapper {
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;
- throw new TimedOutException("Timeout: time in routine has exceed our deadline");
+ log.error("Routine has timed out: ncharsSent={0}, ncharsTotalReceived={1}", ncharsSent,
+ ncharsTotalReceived);
+ throw new TimedOutException("Routine has timed out");
}
ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
if (listener != null) {
@@ -743,106 +598,97 @@ public class SshJcraftWrapper {
}
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);
+ log.debug("Received the correct number of characters, ncharsSent={0}, ncharsTotalReceived={1}",
+ ncharsSent, ncharsTotalReceived);
logMemoryUsage();
return;
}
}
} catch (JSchException e) {
- DebugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e);
- DebugLog.printRTAriDebug(fn,
- "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
- + ncharsRead);
- throw new TimedOutException(e.toString());
+ log.error("JSchException occurred while command sending", e);
+ log.debug("ncharsSent={0}, ncharsTotalReceived={1}, ncharsRead={2} until error occurred",
+ ncharsSent, ncharsTotalReceived, ncharsRead);
+ throw new TimedOutException(e.getMessage());
}
}
public String getHostName() {
- return (hostName);
+ return hostName;
}
public String getUserName() {
- return (userName);
+ return userName;
}
public String getPassWord() {
- return (passWord);
+ return passWord;
}
- public void sftpPut(String sourcePath, String destDirectory) throws IOException {
- String fn = "SshJcraftWrapper.sftp";
+ public void sftpPutFile(String sourcePath, String destDirectory) throws IOException {
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);
+ log.debug("Sending via sftp from source: {0} to destination: {1}", 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());
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during file transfer", ex);
+ throw new IOException(ex.getMessage());
}
}
-
- public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
- String fn = "SshJcraftWrapper.Sftp";
+ public void sftpPutStringData(String stringOfData, String fullPathDest) throws IOException {
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);
+ log.debug("Sending via sftp stringOfData to destination: {0}", 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());
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during data transfer", ex);
+ throw new IOException(ex.getMessage());
}
}
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);
+ InputStream in = sftp.get(fullFilePathName);
String sftpFileString = readInputStreamAsString(in);
- DebugLog.printRTAriDebug(fn, "Retreived successfully");
- // DebugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
+ log.debug("Received data via sftp connection sftpFileString={0} from fullFilePathName={1}",
+ sftpFileString, fullFilePathName);
sftpSession.disconnect();
- return (sftpFileString);
- } catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
- throw new IOException(e.toString());
+ return sftpFileString;
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during data transfer", ex);
+ throw new IOException(ex.getMessage());
}
}
@@ -860,27 +706,26 @@ public class SshJcraftWrapper {
public void logMemoryUsage() {
- String fn = "SshJcraftWrapper.logMemoryUsage";
int mb = 1024 * 1024;
long usedMemory;
- long maxMemoryAdvailable;
- long memoryLetfOnHeap;
- maxMemoryAdvailable = (runtime.maxMemory() / mb);
- usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
- memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
- DebugLog.printAriDebug(fn,
- "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
- + memoryLetfOnHeap);
+ long maxMemoryAvailable;
+ long memoryLeftOnHeap;
+ maxMemoryAvailable =runtime.maxMemory() / mb;
+ usedMemory = (runtime.totalMemory() / mb) - (runtime.freeMemory() / mb);
+ memoryLeftOnHeap = maxMemoryAvailable - usedMemory;
+ log.info("Memory usage: maxMemoryAvailable={0}, usedMemory={1}, memoryLeftOnHeap={2}",
+ maxMemoryAvailable, usedMemory, memoryLeftOnHeap);
}
// 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);
+ if (log.isDebugEnabled()) {
+ log.debug(
+ "Attempting to connect to {0} username={1} prompt='{2}' timeOut={3} portNum={4} subsystem={5}",
+ hostname, username, prompt, timeOut, portNum, subsystem);
+ }
routerName = hostname;
jsch = new JSch();
try {
@@ -894,33 +739,24 @@ 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);
+ ((ChannelSubsystem) channel).setPty(true); //expected ptyType 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, "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());
+ channel.connect(5000);
+ } catch (JSchException e) {
+ log.error("JschException occurred ", e);
+ throw new IOException(e.getMessage());
+ } catch (TimedOutException e) {
+ log.error("TimedOutException occurred", e);
+ throw new IOException(e.getMessage());
}
}
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");
+ log.debug("Attempting to connect to {0} username={1} portNumber={2}", hostName, username, portNumber);
routerName = hostName;
this.hostName = hostName;
userName = username;
@@ -942,51 +778,46 @@ public class SshJcraftWrapper {
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.");
+ log.warn("Caught an Exception: Nothing to flush out.", 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());
+ } catch (JSchException e) {
+ log.error("JschException occurred ", e);
+ throw new IOException(e.getMessage());
}
}
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);
+ log.debug("Sending via sftp from source: {0} to destination: {1}", 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());
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during file transfer", ex);
+ throw new IOException(ex.getMessage());
}
}
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);
+ log.debug("Sftp put invoked, connection details: username={1} hostname={2}",
+ userName, hostName);
jsch = new JSch();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
@@ -996,30 +827,29 @@ public class SshJcraftWrapper {
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);
+ log.debug("Deleting old files: {0}", oldFiles);
try {
sftp.rm(oldFiles);
- DebugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
- } catch (SftpException sft) {
+ } catch (SftpException ex) {
String exp = "No such file";
- if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
- DebugLog.printRTAriDebug(fn, "No files found -- Continue");
+ if (ex.getMessage() != null && ex.getMessage().contains(exp)) {
+ log.warn("No files found, continue");
} else {
- DebugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
- sft.printStackTrace();
- throw sft;
+ log.error("SftpException while invoking rm command over sftp", ex);
+ throw ex;
}
}
+ log.debug("Sending stringOfData to destination {0}", fullPathDest);
sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
- DebugLog.printRTAriDebug(fn, "Sent successfully");
- } catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
- throw new IOException(e.toString());
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during file transfer", ex);
+ throw new IOException(ex.getMessage());
} finally {
if (sftpSession != null) {
sftpSession.disconnect();
@@ -1029,10 +859,10 @@ public class SshJcraftWrapper {
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);
+ log.debug("Sftp get invoked, connection details: username={1} hostname={2}",
+ userName, hostName);
jsch = new JSch();
sftpSession = jsch.getSession(userName, hostName, 22);
java.util.Properties config = new java.util.Properties();
@@ -1042,17 +872,16 @@ public class SshJcraftWrapper {
sftpSession.setUserInfo(ui);
sftpSession.setConfig(config);
sftpSession.connect(30 * 1000);
- DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
- DebugLog.printRTAriDebug(fn, "Connecting....");
sftp.connect();
InputStream in = sftp.get(fullFilePathName);
- String sftpFileString = readInputStreamAsString(in);
- DebugLog.printRTAriDebug(fn, "Retreived successfully");
- return sftpFileString;
- } catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
- throw new IOException(e.toString());
+ return readInputStreamAsString(in);
+ } catch (JSchException ex) {
+ log.error("JSchException occurred while handling sftp session", ex);
+ throw new IOException(ex.getMessage());
+ } catch (SftpException ex) {
+ log.error("SftpException occurred during file transfer", ex);
+ throw new IOException(ex.getMessage());
} finally {
if (sftpSession != null) {
sftpSession.disconnect();
@@ -1061,58 +890,47 @@ public class SshJcraftWrapper {
}
public String send(String cmd, String delimiter) throws IOException {
- String fn = "SshJcraftWrapper.send";
-
try (OutputStream os = channel.getOutputStream(); DataOutputStream dos = new DataOutputStream(os)) {
sendSshCommand(cmd, dos);
- String response = receiveUntil(delimiter, 300000, cmd);
- DebugLog.printRTAriDebug(fn, "Leaving method");
- return response;
- } catch (IOException e) {
- DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
- dbLog.outputStackTrace(e);
- throw new IOException(e.toString());
+ return receiveUntil(delimiter, 300000, cmd);
+ } catch (IOException ex) {
+ log.error("IOException occurred", ex);
+ throw new IOException(ex.getMessage());
}
}
private void sendSshCommand(@Nonnull String originalCommand, @Nonnull DataOutputStream channelOutputStream)
throws IOException {
- String fn = "SshJcraftWrapper.sendSshCommand";
String command = enhanceCommandWithEOL(originalCommand);
- int length = command.length();
+ int length = command.length(); // 2,937,706
int charsChunkSize = 300000;
int charsTotalSent = 0;
- appendToFile(debugLogFileName, fn + ": Sending: '" + command);
- DebugLog.printRTAriDebug(fn, "Length of command is:" + length); // 2,937,706
+ log.debug("Sending ssh command: length={0}, payload: {1}", length, command);
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);
+ log.debug("Iteration nr:{0}, sending command chunk: {1}", i, 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....");
+ log.trace("i={0}, flush immediately", i);
channelOutputStream.flush();
}
- } catch (Exception e) {
- DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
+ } catch (IOException ex) {
+ log.warn("IOException occurred: nothing to flush out", ex);
}
}
} else {
- DebugLog.printRTAriDebug(fn, "Before executing the channelOutputStream.writeBytes");
channelOutputStream.writeBytes(command);
}
channelOutputStream.flush();
- DebugLog.printRTAriDebug(fn, "Leaving method");
- appendToFile(debugLogFileName, fn + ": Leaving method\n");
}
private boolean isCmdLengthEnoughToSendInChunks(int length, int chunkSize) {
diff --git a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java
index ef1bf7d7f..305017c56 100644
--- a/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java
+++ b/appc-config/appc-config-adaptor/provider/src/test/java/org/onap/appc/ccadaptor/SshJcraftWrapperTest.java
@@ -91,9 +91,9 @@ public class SshJcraftWrapperTest {
public void testSetRouterCommandType2() throws IOException{
SshJcraftWrapper wrapper = new SshJcraftWrapper();
wrapper.appendToRouterFile("test", 2);
- StringBuffer buffer = new StringBuffer();
- buffer.append("test");
- wrapper.appendToRouterFile("Test.txt", buffer);
+ StringBuilder sb = new StringBuilder();
+ sb.append("test");
+ wrapper.appendToRouterFile("Test.txt", sb);
wrapper.receiveUntilBufferFlush(3, 4, "test");
}