Bad access exception in Poco::Net::HTTPClientSession when network connection is lost - poco-libraries

When I run the following code without a network connection, I get a bad access error on the last line.
Poco::URI uri(sRemoteLoggingURL);
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPathAndQuery());
request.set("User-Agent", "Poco");
string reqBody = "{\"logMessage\":\""+ message + "\", \"application_name\":\""+ sAppName +"\"}";
request.setContentLength( reqBody.length() );
std::ostream& sessionStream = session.sendRequest(request);
Is this expected behavior? Do I need to check for network connectivity before I try to send a request? If so, how do I do that? I've tried session.connected(), but that is returning false even when I do have a network connection.

I think I figured it out. Apparently, you need to be sure to call reset on the session before you destroy it (or before it goes out of scope) if there's an exception. This code works:
Poco::URI uri(sRemoteLoggingURL);
HTTPClientSession session(uri.getHost(), uri.getPort());
try{
HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPathAndQuery());
request.set("User-Agent", "Poco");
string reqBody = "{\"logMessage\":\""+ message + "\", \"application_name\":\""+ sAppName +"\"}";
request.setContentLength( reqBody.length() );
std::ostream& sessionStream = session.sendRequest(request);
if (sessionStream.good()) {
sessionStream << reqBody;
HTTPResponse res;
string text;
istream &is = session.receiveResponse(res);
StreamCopier::copyToString(is, text);
}
}catch(Poco::Exception& e){
// apparently, you MUST call reset before destroying the session, or you'll crash
session.reset();
sdfLog::logFormat("appContent::doIdle Poco::Exception: %s\n", e.what());
}catch(...){
session.reset();
sdfLog::logFormat("appContent::doIdle exception in remote logger %s\n");
}

Related

What does Encountered end-of-stream mid-frame mean when it spits this out on the GRPC server?

I am sending data to grpc service and getting error message in return:
Encountered end-of-stream mid-frame
What does this mean. the connection was interrupted or something else like not enough data sent across. Was it a failure of my client to send enough data of the message over or was it some connection break in the middle of processing. I dont have enough information from this.
If you dont know whats wrong here just tell me if it means the connection closed too early during processing or the datafeed was just not as long as expected but there was no connection problem.
I am using this filter from Envoy proxy (Lyft):
I am using this bridge from Envoy:
https://www.envoyproxy.io/docs/envoy/latest/configuration/http_filters/grpc_http1_bridge_filter
It asks for zero byte up front and 4 bytes with big indian of the length.
For me its a long ugly and meaningless message:
Jul 23, 2019 2:26:06 PM io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$TransportState deframeFailed
WARNING: Exception processing message
io.grpc.StatusRuntimeException: INTERNAL: Encountered end-of-stream mid-frame
at io.grpc.Status.asRuntimeException(Status.java:524)
at io.grpc.internal.AbstractServerStream$TransportState.deframerClosed(AbstractServerStream.java:238)
at io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$TransportState.deframerClosed(NettyServerStream.java:155)
at io.grpc.internal.MessageDeframer.close(MessageDeframer.java:229)
at io.grpc.internal.MessageDeframer.deliver(MessageDeframer.java:296)
at io.grpc.internal.MessageDeframer.request(MessageDeframer.java:161)
at io.grpc.internal.AbstractStream$TransportState.requestMessagesFromDeframer(AbstractStream.java:205)
at io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$Sink$1.run(NettyServerStream.java:100)
at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:333)
at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
14:26:06.445 [grpc-default-worker-ELG-3-2] DEBUG io.grpc.netty.shaded.io.grpc.netty.NettyServerHandler - [id: 0xd01ed34c, L:/127.0.0.1:9009 - R:/127.0.0.1:48042] OUTBOUND RST_STREAM: streamId=45 errorCode=8```
Is there something wrong with the client?
//Define a postRequest request
HttpPost postRequest = new HttpPost("http://10.10.xx.xx:31380/com.test.EchoService/echo");
//Set the API media type in http content-type header
postRequest.addHeader("content-type", "application/grpc");
int messageLength=EchoRequest.newBuilder()
.setMessage("Hello"+ ": " + Thread.currentThread().getName())
.build().getMessageBytes().toByteArray().length;
byte[] lengthBytes = ByteBuffer.allocate(4).putInt(messageLength).array();
byte[] zeroByte = {0};
byte[] messageBytes = EchoRequest.newBuilder()
.setMessage("Hello" + ": " + Thread.currentThread().getName())
.build().getMessageBytes().toByteArray();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(zeroByte);
baos.write(lengthBytes);
baos.write(messageBytes);
byte[] c = baos.toByteArray();
//Set the request post body
StringEntity userEntity = new StringEntity(content);
ByteArrayEntity bae = new ByteArrayEntity(baos.toByteArray());
postRequest.setEntity(userEntity);
//Send the request; It will immediately return the response in HttpResponse object if any
HttpResponse response = httpClient.execute(postRequest);
//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 201)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
the error message means, the server received partial data, and it doesn't expect more data coming since the end of stream is true.
based on the error message, the length is probably larger than actual proto payload.

Sending SMS using Twilio from my website in asp.net

I am trying to send SMS from twilio account. Here is my code.
try
{
string ACCOUNT_SID = ConfigurationManager.AppSettings["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
string AUTH_TOKEN = ConfigurationManager.AppSettings["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"];
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.SendSmsMessage("+1XXXXXXXXXX", "+1XXXXXXXXXXX", "Hi");
Label1.Text = "Sent Successfully";
}
catch (Exception ex)
{
Label1.Text = "Error:"+ex.Message;
}
Running on my server, I am receiving message "Sent Successfully" but not receiving message on my phone.
I have changed the original numbers with "XXXXX".Also I have added packages for Twilio.
Please let me know if can.
Twilio evangelist here.
You might be getting an error back from the Twilio REST API when you make the call to SendSmsMessage. You can check if this is happening by grabbing the value returned from the method and seeing if the RestException property is null or not:
var result = client.SendSmsMessage("+1xxxxxxxxxx", "+1xxxxxxxxxx", "Hi");
if (result.RestException!=null)
{
//An error occured
Console.Writeline(result.RestException.Message);
}
Another option would be to use a tool like Fiddler to watch the actual HTTP request/response as it happens and see if any errors are happening.
Hope that helps.

HTTP Connection Parameters

I am using the HTTP Connection in the following way:
HttpConnection _httpConnection = null;
try {
_httpConnection = (HttpConnection)Connector.open(_url);
} catch(Exception e) { }
byte [] postDataBytes = _postData.getBytes();
_httpConnection.setRequestMethod(HttpConnection.POST);
_httpConnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
_httpConnection.setRequestProperty("Content-Language", "en-US");
_httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
_httpConnection.setRequestProperty("Connection", "close");
_httpConnection.setRequestProperty("Content-Length", Integer.toString(_postData.getBytes().length));
os = _httpConnection.openOutputStream();
os.write(postDataBytes);
os.flush();
This HTTP Connection requires parameters to successfully open. For example on a WIFI network, it requires the ";deviceside=true;interface=wifi" to be added to the URL.
The problem is for the EDGE connection. Each country requires different parameters to be added. For example in lebanon it requires ";deviceside=false" but in KSA if i add this parameter the connection will not open. In USA it needs different types of parametes. The question is how to establish an HTTP connection for all the countries with the same parameters. So that the application will successfully have an internet connection no matter where it is downloaded.
Welcome to the confusing world of network transports on BlackBerry! You will want to start with the article Connecting your BlackBerry - http and socket connections to the world.
Here is a simple example for "just give me a connection" (note, you will need to add appropriate error handling; also, myURL in the code below should have no connection descriptor info appended to it):
ConnectionFactory factory = new ConnectionFactory();
ConnectionDescriptor descriptor = factory.getConnection(myURL);
if (descriptor != null) {
_httpConnection = (HttpConnection) descriptor.getConnection();
...
}
Try using to use the method reffered in this link melick-rajee.blogspot.com and use it like
_url = "http://www.example.com";
_httpConnection = (HttpConnection)Connector.open(_url + getConnectionString());
You will have to sign the application to use this else the application will show exception.
To sign your application just go here Code Signing Keys
To use the connectionFactory, seems you need to set BisBOptions.
Try this:
connFact = new ConnectionFactory();
connFact.setTransportTypeOptions(TransportInfo.TRANSPORT_BIS_B,
new BisBOptions("mds-public"));

500 Internal Server Error when using HttpWebRequest, how can I get to the real error?

I'm trying to improve the information provided in response to an error handled within an app.
This is the code:
Try
httpRequestObj = HttpWebRequest.Create(strRequest)
httpRequestObj.Method = "GET"
httpRequestObj.UseDefaultCredentials = True
* httpResponse = httpRequestObj.GetResponse
Using reader As StreamReader = New StreamReader(httpResponse.GetResponseStream())
strXML = reader.ReadToEnd()
End Using
Catch ex As WebException
'do something with ex
End Try
The webexception is thrown on the * line
Currently all I see in the Exception is "The remote server returned an error: (500) Internal Server Error". I've looked at the exception in debug but the info I need isn't there- I guess the response would need to be read in to see that info but it never gets that far.
If I take the request and paste it into my browser directly I can see the error details in XML format that is returned from the API I'm calling, info like:
<Error>
<description>info I want to get to here</description>
<detail />
<code>info I want to get to here</code>
<source />
<category>info I want to get to here</category>
<file>info I want to get to here</file>
<line>info I want to get to here</line>
<pad />
</Error>
Is there any way I can change this code so that I can get past the 500 error and see the actual response, I'd like to be able to parse this xml to find out the real problem for the failure.
Note: the Exception does have an ex.Response (System.Net.HttpWebResponse), but I can't see the info I need in there, only a load of Header info.
You can get the error response from the exception....
try
{
....
} catch(Exception e) {
if (e is WebException && ((WebException)e).Status==WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)e).Response;
using(Stream respStream = errResp.GetResponseStream())
{
// read the error response
}
}
}
System.Net.WebResponse response = null;
try
{
response = wreq.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
string error = new System.IO.StreamReader(e.Response.GetResponseStream()).ReadToEnd();
}
}
catch (Exception e)
{
}
as simple as this, You will get entire response in the string error.
Try to use Fiddler. It's debuging proxy, which will show you all data sending between client and server. You'll be able to see all headers and context as well.

httpconnection.getResponseCode() giving EOF exception

I am using Httconnection for connecting to webserver , somtimes request fails causing
EOFException when calling httpconnection.getResponseCode().
I am setting the following headers while making the connection
HttpConnection httpconnection = (HttpConnection) Connector.open(url.concat(";interface=wifi"));
httpconnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
httpconnection.setRequestProperty("Content-Language", "en-US");
I am closing all the connections after processing the request properly.Is this exception is due to exceeding max connections.
It's an internal server error, which return status code 500 in response.
This may be caused by incorrect request, but as well server code or overload may be the reason.
If you have access to server, check event logs.
See also
500 EOF when chunk header expected
Why might LWP::UserAgent be failing with '500 EOF'?
500 EOF instead of reponse status line in perl script
Apache 1.3 error - Unexpected EOF reading HTTP status - connectionreset
Error 500!
UPDATE On the other hand, if it's not response message, but a real exception, then it may be simply a bug, just like in old java
And workaround may be putting getResponseCode() inside of try/catch and call second time on exception:
int responseCode = -1;
try {
responseCode = con.getResponseCode();
} catch (IOException ex1) {
//check if it's eof, if yes retrieve code again
if (-1 != ex1.getMessage().indexOf("EOF")) {
try {
responseCode = con.getResponseCode();
} catch (IOException ex2) {
System.out.println(ex2.getMessage());
// handle exception
}
} else {
System.out.println(ex1.getMessage());
// handle exception
}
}
Talking by connections number limit, read
What Is - Maximum number of simultaneous connections
How To - Close connections
Using HTTPTransportSE, write this before invoke the method "call"
ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
transport.call(SOAP_ACTION, envelope, headerPropertyArrayList);

Resources