What the situation will make channel.getExitStatus() return 1 - jsch

private String test(String command){
channel = sesConnection.openChannel("exec");
((ChannelExec) channel).setCommand(command);
BufferedReader br =
new BufferedReader(new InputStreamReader(channel.getInputStream()));
InputStream error = ((ChannelExec) channel).getErrStream();
channel.connect();
StringBuffer outputstream = new StringBuffer();
String msg = null;
while ((msg = br.readLine()) != null) {
outputstream.append(msg);
}
System.out.println("Channel exit status:" + channel.getExitStatus());
}

When the command finishes (so the "exec" channel closes) and returns exit code 1.
Or when the channel even fails to open (what is typically when the command is not a valid command).

Related

How to build my own VB.NET mail server on Windows 10

I would like to build my own (simple) mail server on a Windows machine (in VB.NET) in order to receive mails from one sender. My emailadress will be something like "myname#myserver.com".
What do I have to build ? ... an SMTP-server with the SMTPServer class ? ... as f.e. below code.
How can I test that locally on my machine, without having to buy domain myserver.com. I know how to send an email via VB.NET, but what should I use as outgoing smtp-server ?
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace FakeSMTP
{
public class SMTPServer
{
TcpClient client;
NetworkStream stream;
System.IO.StreamReader reader;
System.IO.StreamWriter writer;
public SMTPServer(TcpClient client)
{
this.client = client;
this.client.ReceiveTimeout = 5000;
stream = client.GetStream();
reader = new System.IO.StreamReader(stream);
writer = new System.IO.StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
}
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Loopback,25);
listener.Start();
while (true)
{
SMTPServer handler = new SMTPServer(listener.AcceptTcpClient());
Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
thread.Start();
}
}
public void Run()
{
writer.WriteLine("220 localhost -- Fake proxy server");
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
Console.Error.WriteLine("Read line {0}", line);
switch (line)
{
case "DATA":
writer.WriteLine("354 Start input, end data with <CRLF>.<CRLF>");
StringBuilder data = new StringBuilder();
String subject = "";
line = reader.ReadLine();
if (line != null && line != ".")
{
const string SUBJECT = "Subject: ";
if (line.StartsWith(SUBJECT))
subject = line.Substring(SUBJECT.Length);
else data.AppendLine(line);
for (line = reader.ReadLine();
line != null && line != ".";
line = reader.ReadLine())
{
data.AppendLine(line);
}
}
String message = data.ToString();
Console.Error.WriteLine("Received ­ email with subject: {0} and message: {1}",
subject, message);
writer.WriteLine("250 OK");
client.Close();
return;
default:
writer.WriteLine("250 OK");
break;
}
}
}
}
}

HTTP POST 400 . Bad request. Google Cloud storage XML API call to upload file

I am receiving this error code.
E/camera_classes.callHttpPostToSendFiles: exception message e
java.io.IOException: Server returned non-OK status: 400 message: Bad Request error stream : com.android.okhttp.internal.http.HttpTransport$FixedLengthInputStream#42353798at camera_classes.postMultipartEntity.finish(postMultipartEntity.java:161)
at camera_classes.callHttpPostToSendFiles.postData(callHttpPostToSendFiles.java:193)
at camera_classes.callHttpPostToSendFiles$1.doInBackground(callHttpPostToSendFiles.java:109)
at camera_classes.callHttpPostToSendFiles$1.doInBackground(callHttpPostToSendFiles.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
The error is happening at
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
String server_message = httpConn.getResponseMessage();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status + " message: " + server_message + " error stream : " + httpConn.getErrorStream());
}
1) I am interested in getting more information on the error code (400 Bad Request) listed here, so I can understand what is causing the "400 Bad request" error. Can anyone help. I have tried all the available public methods - httpConn.getResponseMessage(), httpConn.getResponseCode() and httpConn.getErrorStream().
2) What does com.android.okhttp.internal.http.HttpTransport$FixedLengthInputStream#42353798 mean? This is the output of httpConn.getErrorStream().
I'm using an upload method for Google Cloud XML Api like below. About your second question, maybe it's related to use of method setFixedLengthStreamingMode from HttpUrlConnection, as I used in my function, where you have to put the length of file being uploaded:
URL url = new URL("www.urltoupload.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
httpCon.setRequestProperty("Content-Type", Utils.getMimeType(path));
httpCon.setRequestProperty("Connection", "Keep-Alive");
httpCon.setFixedLengthStreamingMode((int) dest.length());
final DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());
float bytesTotal = fileBeingUploaded.length();
int bytesRead;
byte buf[] = new byte[8192];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(dest));
while ((bytesRead = bufInput.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
out.flush();
}
out.close();

JSCH read from input stream hangs from time to time

I'm using jsch-0.1.53.
In order to execute a command and return it's output, I wrote the next block of code:
#Override
public String executeAndGetOutput(CheckPointSSHConnection connection, String command) throws IOException , JSchException{
logger.debug("Executing command \"" + command + "\"");
StringBuilder retVal = new StringBuilder();
ChannelExec channel = null;
InputStream in=null;
InputStream errStream=null;
try {
Session session = connection.getSession();
channel = (ChannelExec) session.openChannel("exec");//only shell
in = channel.getInputStream();
errStream = channel.getErrStream();
channel.setCommand(command);
channel.connect(10000);
String errInStr = StringUtils.toString(errStream);
String inStr = StringUtils.toString(in);
return inStr+errInStr;
} finally {
IOUtils.close(in);
IOUtils.close(errStream);
if (channel != null) {
try {
channel.disconnect();
} catch (Throwable throwable) {
logger.warn("An exception occured while trying to close ssh chanel. Message:",
throwable.getMessage());
}
}
}
}
The problem is that from time to time, reading the errStream just hangs and blocking the thread.
Can someone please tell me what I'm doing wrong?
The command that I'm executing is load_indicators --add -a detect -i /tmp/sample_file.csv , it's Checkpoint CLI

Why am I getting, "Unable to connect to the remote server"?

This err msg is the next one I get after resolving “NotSupportedException” as noted here
I don't even reach the break point in the server code (set on the first line of the method that should be getting called).
This is the relevant server code:
[Route("api/PlatypusItems/PostArgsAndXMLFileAsStr")]
public async void PostArgsAndXMLFileAsStr([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
string beginningInvoiceNum = string.Empty; // <= Breakpoint on this line
string endingInvoiceNum = string.Empty;
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
. . .
And the client (handheld, Compact Framework) code:
private void menuItem4_Click(object sender, EventArgs e)
{
GetAndSendXMLFiles("LocateNLaunch"); // There is a "LocateNLaunch.xml" file
}
private void GetAndSendXMLFiles(string fileType)
{
string serNum = User.getSerialNo();
string siteNum = User.getSiteNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
if (siteNum.Length == 0)
{
siteNum = "03";
}
string uri = string.Format("http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
List<String> XMLFiles = HHSUtils.GetXMLFiles(fileType, #"\");
MessageBox.Show(XMLFiles.Count.ToString());
foreach (string fullXMLFilePath in XMLFiles)
{
MessageBox.Show(fullXMLFilePath);
RESTfulMethods.SendXMLFile(fullXMLFilePath, uri, 500);
}
}
public static string SendXMLFile(string xmlFilepath, string uri, int timeout) // timeout should be 500
{
MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));
MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/xml";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("SendXMLFile exception " + ex.Message);
request.Abort();
return string.Empty;
}
}
}
Running this code, I see from the client the following "debug strings":
0) "1" (from MessageBox.Show(XMLFiles.Count.ToString());)
1) "\Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(fullXMLFilePath);)
2) "In SendXMLFile() - xmlFilePath == \Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));)
3) "In SendXMLFile() - uri == http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum=8675309&siteNum=03" (from MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));)
- and then this one from somewhere:
4) "SendXMLFile exception Unable to connect to the remote server"...
So what could be causing this inability to connect?
UPDATE
The same thing ("Unable to Connect to the Remote Server") happens with this code (different operation, but also from the WindowsCE/Compact Framework/handheld app that tries to connect to the Web API server app):
private void menuItem3_Click(object sender, EventArgs e)
{
string serNum = User.getSerialNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
string clientVer =
HHSUtils.GetFileVersion(#"\Application\sscs\vsd_setup.dll");
if (clientVer.Contains("Win32Exception"))
{
clientVer = "0.0.0.0";
}
MessageBox.Show(string.Format("After call to GetFileVersion(), serial num == {0};
clientVer == {1}", serNum, clientVer));
string uri =
string.Format("http://localhost:28642/api/FileTransfer/GetHHSetupUpdate?
serialNum={0}&clientVersion={1}", serNum, clientVer);
RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
}
public static void DownloadNewerVersionOfHHSetup(string uri)
{
string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff",
CultureInfo.InvariantCulture);
var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
}
}
// I see the "After call to GetFileVersion()" message in menuItem3_Click() handler, but then "DownloadNewerVersionOfHHSetup: Unable to Connect to the Remote Server" in DownloadNewerVersionOfHHSetup()
And yes, the server app is running.
UPDATE 2
Here is the code that I tested prior to "dumbing it down" (retrofitting it, making it as similar as possible to this working test code, yet that may not be saying much) for Compact Framework:
Client code:
DownloadTheFile(textBoxFinalURI.Text); // with textBoxFinalURI.Text being
"http://localhost:28642/api/FileTransfer/GetUpdatedHHSetup?
serialNum=8675309&clientVersion=1.3.3.3" and the file on the server being
version 1.4.0.15
private void DownloadTheFile(string uri)
{
var outputFileName = "Whatever.exe";
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show(webex.Message);
}
}
Server code:
public HttpResponseMessage GetHHSetupUpdate(string serialNum, string clientVersion)
{
HttpResponseMessage result;
string filePath = GetAvailableUpdateForCustomer(serialNum);
FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(filePath);
if (!ServerFileIsNewer(clientVersion, currentVersion))
{
result = new HttpResponseMessage(HttpStatusCode.NoContent);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(filePath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
}
return result;
}
private string GetAvailableUpdateForCustomer(string serialNum)
{
if (serialNum == "8675309")
{
return HostingEnvironment.MapPath(#"~\App_Data\HHSetup.exe");
}
else
{
return HostingEnvironment.MapPath(#"~\App_Data\HDP.exe");
}
}
// clientFileVersion is expected to be something like "1.4.0.15"
private bool ServerFileIsNewer(string clientFileVersion, FileVersionInfo serverFile)
{
Version client = new Version(clientFileVersion);
Version server = new Version(string.Format("{0}.{1}.{2}.{3}",
serverFile.FileMajorPart, serverFile.FileMinorPart,
serverFile.FileBuildPart, serverFile.FilePrivatePart));
return server > client;
}
... This code works fine (server code is the same; the client code has been "retrofied")
I can't use the code as-is because of the limitations of Compact Framework / Windows CE. As the title of this post makes clear, I'm not even able to connect to the server from there yet. Is it possible? If so, what needs to change in my client code (not the client code in Update 2, which works in newer versions of .NET, but the client code shown prior to there)?
It's a similar story with the other method that is also returning "Unable to connect to the remote server" - it works fine in "modern" code running in a test app, but once it's retrofitted (better word than refactored when "dumbing down" to Compact Frameworkerize the code).
UPDATE 3
I tried to get more info from the err msg with the code below (old line commented out), but this "rewards" me instead with a NullReferenceException:
catch (WebException webex)
{
//MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string resp = webex.Response.ToString();
string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
}
UPDATE 4
As I continued to get NREs, I commented out each subsequent line, one-by-one, until I now have this that runs:
//string innerEx = webex.InnerException.ToString();
//string resp = webex.Response.ToString();
//string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
//string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
//string.Format("Message: {0}; Response: {1}; Stack Trace: {2}; Status: {3}", msg, resp, stackTrace, status));
//string.Format("Message: {0}; Stack Trace: {1}; Status: {2}", msg, stackTrace, status));
string.Format("Message: {0}; Status: {1}", msg, status));
...but all I get from it is Status of "ConnectFailure" (I already knew that).
UPDATE 5
This runs without an NRE:
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string status = webex.Status.ToString();
MessageBox.Show(string.Format("Message: {0}; Status: {1}; inner Ex: {2}", msg, status, innerEx));
And this is what I see:
So why would the server actively refuse the connection?
BTW, ASAP I'm going to bountify this question, or will bountify the answerer after the fact*, with a bounty that would make even Long John Silver and Perro-Negro's eyes glimmer and gleam (cared they for geekCoin, that is).
For facts leading to the arrest and eviction of this bug.
PSYCHE! I changed my mind/there's been a mutiny on the bounty => the bountification will happen here instead.
UPDATE 6
This also (using the "raw" IP Address of the server machine) gives me an NRE:
string uri = string.Format("http://192.168.125.50:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);
...as does using the "friendly name" ("Platypus") of the machine in place of the IP Address.
The large problem I see here is the fact that you have localhost as your address. That's absolutely wrong. localhost means, effectively, "on the same machine as I am running" so unless you've somehow managed to get a async .NET 4.0 web service to run on your Windows CE device and your server code is running there, then this is most certainly not what you want.
If you're running on an emulator, it's still wrong. The emulator is, for all intents and purposes, a separate machine.
You must use the address of the server/PC where that web service is running. It must be a routable address, meaning if you're connected over USB then it's probably ppp_peer and not an IP address (well it resolves to a private address, but the name is easier to remember).

Powermock: ProcessBuilder redirectErrorStream giving nullPointerException

I am using powermock to mock some native command invocation using process builder. the strange thing is these test pass sometimes and fail sometimes giving a NPE. Is this a powermock issue or some gotcha in the program.
Here is a snippet of the class I am testing:
public void method1(String jsonString, String filename) {
try {
JSONObject jObj = new JSONObject(jsonString);
JSONArray jArr = jObj.getJSONArray("something");
String cmd = "/home/y/bin/perl <perlscript>.pl<someConstant>" + " -k " + <someConstant> + " -t " + <someConstant>;
cmd += vmArr.getJSONObject(i).getString("jsonKey");
ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
pb.redirectErrorStream(false);
Process shell = pb.start();
shell.waitFor();
if (shell.exitValue() != 0) {
throw new RuntimeException("Error in Collecting the logs. cmd="+cmd);
}
StringBuilder error = new StringBuilder();
InputStream iError = shell.getErrorStream();
BufferedReader bfr =
new BufferedReader(
new InputStreamReader(iError));
String line = null;
while ((line = bfr.readLine()) != null) {
error.append(line + "\n");
}
if (!error.toString().isEmpty()) {
LOGGER.error(error`enter code here`);
}
iError.close();
bfr.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
and the unit test case is:
#PrepareForTest( {<Classtobetested>.class, ProcessBuilder.class,Process.class, InputStream.class,InputStreamReader.class, BufferedReader.class} )
#Test(sequential=true)
public class TestClass {
#Test(groups = {"unit"})
public void testMethod() {
try {
ProcessBuilder prBuilderMock = createMock(ProcessBuilder.class);
Process processMock = createMock(Process.class);
InputStream iStreamMock = createMock(InputStream.class);
InputStreamReader iStrRdrMock = createMock(InputStreamReader.class);
BufferedReader bRdrMock = createMock(BufferedReader.class);
String errorStr =" Error occured";
String json = <jsonStringInput>;
String cmd = "/home/y/bin/perl <perlscript>.pl -k "+<someConstant>+" -t "+<someConstant>+" "+<jsonValue>;
expectNew(ProcessBuilder.class, "bash", "-c", cmd).andReturn(prBuilderMock);
expect(prBuilderMock.redirectErrorStream(false)).andReturn(prBuilderMock);
expect(prBuilderMock.start()).andReturn(processMock);
expect(processMock.waitFor()).andReturn(0);
expect(processMock.exitValue()).andReturn(0);
expect(processMock.getErrorStream()).andReturn(iStreamMock);
expectNew(InputStreamReader.class, iStreamMock)
.andReturn(iStrRdrMock);
expectNew(BufferedReader.class, iStrRdrMock)
.andReturn(bRdrMock);
expect(bRdrMock.readLine()).andReturn(errorStr);
expect(bRdrMock.readLine()).andReturn(null);
iStreamMock.close();
bRdrMock.close();
expectLastCall().once();
replayAll();
<ClassToBeTested> instance = new <ClassToBeTested>();
instance.method1(json, fileName);
verifyAll();
} catch (Exception e) {
Assert.fail("failed while collecting log.", e);
}
}
I get an error on execution and the test case fails..
Caused by: java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:438)
Note: I do not get this error on all executions. Sometimes it passes and sometimes it fails. I am not able to understand this behavior. Also, I have camouflaged some variable names because of the copyright issues.
Since your are mocking the constructor call you have to prepare your code as wall. This is because the constructor invocation is part of your code. Read more in the PowerMock documentation:
http://code.google.com/p/powermock/wiki/MockConstructor