Netty 5.0 object send and receive - object

I am attempting to get to grips with netty and i confess i am having a hard time doing the simplest of thing with it, i cant really find much in the way of tutorials or any as of yet published material.
So on to the problem:
I have downloaded the example ObjectEcho example from http://netty.io/5.0/xref/io/netty/example/objectecho/package-summary.html
I have it set up on localhost and when i start it all up and run the client i get the following:
Jul 11, 2015 11:21:34 PM io.netty.handler.logging.LoggingHandler channelRead
INFO: [id: 0x3b3ab260, /0:0:0:0:0:0:0:0:8007] RECEIVED: [id: 0x1f7374e8, /127.0.0.1:49196 => /127.0.0.1:8007]
Excellent, next i tried to send a String from the client like so:
// Start the connection attempt.
b.connect(HOST, PORT).sync().channel().closeFuture().sync();
b.connect().channel().write("Hello");
On the server side in the serverhandler class i add within channelRead method the following:
if(msg instanceof String){
ctx.write((String)msg);
System.out.println((String)msg);
}
I was hoping i would thus see on console the word "Hello".
Instead i get nothing at all, so i am going to assume i am missing out a step, doing something terribly wrong or a mix of the two, any out there got the answer ?

In your channelRead, the msg should be ByteBuffer, not a String. You should do as below:
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");

Related

Raven DB 4.1.2 hangs on streaming query in Java

I have a jax-rs-based REST service that I run on Tomcat 8.5 on 64bit Linux, using Java 11; this service connects to a RavenDB 4.1.2 instance, also on the same Linux machine. I make use of the streaming query to return the request result. I use Postman to submit the same request, and everything works well: the results are returned, and rather quickly.
However - it only works 10 times. When I submit the same request as previously an 11th time, the results = currentSession.advanced().stream(query); line hangs and doesn't return.
At first I thought I could have something to do with the StreamingOutput or OutputStreamWriter not being closed appropriately. or perhaps something do to with the Response - but as I stepped through the deployed code in Eclipse in debug mode, I noticed that execution hangs on that streaming line.
(I find exactly 10 times to be a peculiarly "human choice" kind of number...)
The relevant parts of my code:
#GET
#Path("/abcntr/{ccode}/{st}/{zm}")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
public Response retrieveInfo(#PathParam("ccode") String ccode, #PathParam("st") String st, #PathParam("zm") String zm)
{
(...)
StreamingOutput adminAreaStream = new StreamingOutput()
{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
#Override
public void write(OutputStream output) throws IOException, WebApplicationException
{
try(IDocumentSession currentSession = ServiceListener.ravenDBStore.openSession())
{
Writer writer = new BufferedWriter(new OutputStreamWriter(output));
(...)
if(indexToBeQueried.startsWith("Level0"))
{
IDocumentQuery<AdministrativeArea> query = currentSession.query(area.class, Query.index(indexToBeQueried))
.whereEquals("i", ccode);
results = currentSession.advanced().stream(query);
}
else
{
IDocumentQuery<AdministrativeArea> query = currentSession.query(area.class, Query.index(indexToBeQueried))
.whereEquals("i", ccode)
.andAlso()
.whereEquals("N1", sName);
results = currentSession.advanced().stream(query); // THIS IS WHERE IT DOESNT COME BACK
}
while(results.hasNext())
{
StreamResult<AdministrativeArea> adma = results.next();
adma.getDocument().properties = retrievePropertiesForArea(adma.getDocument(), currentSession);
writer.write(ow.writeValueAsString(adma.getDocument()));
writer.write(",");
}
(...)
currentSession.advanced().clear();
currentSession.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage() + e.getStackTrace());
}
}
};
if(!requestIsValid)
return Response.status(400).build();
else
return Response.ok(adminAreaStream).build();
}
The RavenDB error logs come up empty, as do the Tomcat error logs. The only thing that remotely resembles an error message relevant to this is something that shows up from "Gather debug info":
System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at Raven.Server.Documents.Handlers.Debugging.QueriesDebugHandler.QueriesCacheList() in C:\Builds\RavenDB-Stable-4.1\src\Raven.Server\Documents\Handlers\Debugging\QueriesDebugHandler.cs:line 181
at Raven.Server.ServerWide.LocalEndpointClient.InvokeAsync(RouteInformation route, Dictionary`2 parameters) in C:\Builds\RavenDB-Stable-4.1\src\Raven.Server\ServerWide\LocalEndpointClient.cs:line 61
at Raven.Server.ServerWide.LocalEndpointClient.InvokeAndReadObjectAsync(RouteInformation route, JsonOperationContext context, Dictionary`2 parameters) in C:\Builds\RavenDB-Stable-4.1\src\Raven.Server\ServerWide\LocalEndpointClient.cs:line 91
at Raven.Server.Documents.Handlers.Debugging.ServerWideDebugInfoPackageHandler.WriteForDatabase(ZipArchive archive, JsonOperationContext jsonOperationContext, LocalEndpointClient localEndpointClient, String databaseName, String path) in C:\Builds\RavenDB-Stable-4.1\src\Raven.Server\Documents\Handlers\Debugging\ServerWideDebugInfoPackageHandler.cs:line 311
Thank you for any kinds of investigation hints you can give me.
UPDATE:
Same thing when moving the compiler and Tomcat JVM back to Java 1.8.
It appears that it has nothing to do with Java 11 (or 1.8), but simply that it had slipped my attention to close CloseableIterator<StreamResult<AdministrativeArea>> results; After adding a simple results.close(); everything appears to work as it should. If this wasn't the solution, I'll come back and update.

How do a get the data from Haxe's http.customRequest without crashing?

Forewarning: I’m very new to Haxe.
I’m trying to use http.customRequest (with the intention of later making PUT and DELETE requests). But when I try to access the result bytes I get a segmentation fault with C++ and a NullPointerException with Java.
I’ve googled for some other uses of customRequest, and what I’m doing doesn’t seem wrong, but clearly it is.
class Main {
static function main() {
var req = new haxe.Http("https://httpbin.org/put");
var responseBytes = new haxe.io.BytesOutput();
req.onError = function(err) {
trace("onError");
trace(err); // Java says NullPointerException
};
req.onStatus = function(status) {
trace("About to get bytes");
// Removing these lines prevents the errors
var b = responseBytes.getBytes();
trace("Got the bytes");
trace(b.length); // Shouldn't be empty, but is
};
req.customRequest(false, responseBytes, null, "PUT");
}
}
I’ve tried this with the current release and with HEAD (via Brew).
I think my command lines are pretty basic:
$ haxe -cp src -main Main -java bin/java
$ java -jar bin/java/Main.jar
src/Main.hx:12: About to get bytes
src/Main.hx:16: Got the bytes
src/Main.hx:17: 0
src/Main.hx:7: onError
src/Main.hx:8: java.lang.NullPointerException
$ haxe -cp src -main Main -cpp bin/cpp
$ ./bin/cpp/Main
src/Main.hx:12: About to get bytes
src/Main.hx:16: Got the bytes
src/Main.hx:17: 0
[1] 54544 segmentation fault ./bin/cpp/Main
In case it’s useful, here’s the differently broken output for Python:
$ haxe -cp src -main Main -python bin/Main.py
$ python3 bin/Main.py
onError
True
About to trace err
SSLError(1, '[SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1045)')
I’d really appreciate any guidance. TIA
(Reposted from the Haxe forum, where I haven't had a response.)
That's quite an interesting interaction there, here's what happens in order:
sys.Http receives the response and calls onStatus().
You call responseBytes.getBytes(), which ends up invalidating the internal buffer in haxe.io.BytesBuffer.getBytes(). The docs of that method state "Once called, the buffer can no longer be used", as it sets the internal buffer b to null.
The Http class then attempts to write to that same buffer, which is no longer valid.
Since there's a catch-all around the entire logic, the onError() callback is called due to the null reference.
The status code passed to onStatus() is 200 (OK), so apart from the getBytes() call, the request seems to work as expected. And according to apitester.com, data is empty for this particular request.

How to properly identify an exception type in node.js

I'm getting an SSL error thrown by node. This is the exact line of code triggering it:
https://github.com/nodejs/node/blob/master/lib/tls.js#L201
I'm a novice to node and honestly I don't know how to correctly identify this SSL-specific error. In my code, I might look for the Hostname/IP doesn't match certificate's altnames string, but that looks very ugly.
Is there a better way to identify this error, other than looking for text in the error message?
Thanks!
You can handle the known error in a better way by create array of errors and that can also attached with the action need to be taken.
When you handle the exception / error, map them against the array you created using js prototypes and take necessary action.
Hope this will help. Thanks.
Updating...
var arrayOfErros = [
{error:"IP Error",action:"FunctionCall",Message:"You are getting IP Error"},
{error:"IP Error1",action:"FunctionCall1",Message:"You are getting IP Error1"}
]
try {
} catch(exp) {
arrayOfErros.findError(exp,function(msg,action) {
// do eval or show msg or any actions
});
}
Array.findError(err, callback) {
//run through array and return msg and action wn matches.
}

[SmartIrc4Net]: UI Freezing

So I've run into an issue while creating a 'Bot' to watch over one of my IRC Channels, and once the Listen() command is sent the UI is prone to freezing... Now I'm aware that this may be caused by SmartIrc4Net constantly checking for data and what not...
So I've been trying to implement it into another thread by using three of the following ways... But once I start to debug the program no 'debug' message is sent to the server, I know for a fact that the 'Bot' is connecting successfully and this is only when a new 'Thread' is not introduced to the application.
All my 'Bot' programming is separated into Class Library's, and I have tried putting it all into a 'DEBUG' application, and it yields that same annoying result.
My mind is beyong boggled and hopefully someone here has assist me with my situation, as fast as humanly possible....
(Notice: Expect responses from 13:00 / 15:30 to 24:00 GMT)
new Thread(() =>
{
while(BotConnection._IsBotConnected)
{
BotConnection.IRCBOT.Listen();
}
});
-- AND --
ThreadStart IRCThread = new ThreadStart(_IRCListen);
private static void _IRCListen()
{
BotConnection.IRCBOT.Listen();
}
-- AND --
ThreadStart ListenThread = delegate
{
BotConnection.IRCBOT.Listen();
}; new Thread(ListenThread).Start();
I ended up fixing the problem by doing the following.
ThreadStart ListenThread = delegate
{
while(BotConnection._IsBotConnected)
{
BotConnection.IRCBOT.Listen();
BotConnection.IRCBOT.RfcPing("IRC_URL_CON");
}
}; new Thread(ListenThread).Start();

as3 Air 2.5 Linux PrintJob Addpage trowh error nº 2057

I heve the next lines of code:
_printJob = new PrintJob();
if (_printJob.start2(null, _printWorkSettings.usePageSetupDialog)) {
MonsterDebugger.trace(this, new Date());
try {
_printJob.addPage(objectoToPrint, null, _printWorkSettings.jobOptions);
} catch (error:Error) {
MonsterDebugger.trace(this, error + "/n" + error.getStackTrace() + "/n" + error.toString());
}
_printJob.send();
MonsterDebugger.trace(this, 'job sended to printer');
MonsterDebugger.trace(this, new Date());
}
When it is executed on a Linux machine running AIR 2.5 I get the error 2057, the I check the time between the start2 method and the send and is on the same second. I also checked that the property objectToPrint is a MovieClip.
This works on a windows PC, and I'm unable to do a better debugging than the one is possible using the trace of MonsterDebugger, so any ideas on how can I get more information about why addPage is returning this error or any information about the printJob on Linux?
By the way, I also tryed:
_printJob.addPage(objectoToPrint);
And I get the same result.
The property _printWorkSettings.usePageSetupDialog is always true so I now showing the print menu for the user.
Thansk in advance folks :)
I found the problem, there is only one printer on the linux system and was not setted a default so addpage trowh errors.
I get a inspiration on this forum

Resources