get empty notification in production server - java

I develop a google glass app using mirror api. during development I used "Introspected tunnels to localhost" to receive the notification.
Now I uploaded my app on production server. So now I configure my callback URL as my domain name like https://www.mydomain.com:8443/notify. But I get empty notification.
in notify servlet:
BufferedReader notificationReader = new BufferedReader(
new InputStreamReader(request.getInputStream()));
String notificationString = "";
int lines = 0;
while (notificationReader.ready()) {
notificationString += notificationReader.readLine();
lines++;
if (lines > 1000) {
throw new IOException(
"Attempted to parse notification payload that was unexpectedly long.");
}
}
LOG.info("\ngot raw notification : " + notificationString);
in catalina.out
Feb 13, 2014 12:51:48 PM com.google.glassware.NotifyServlet doPost
INFO: got raw notification :
How can I solve it?

StringBuffer stringBuffer = new StringBuffer();
String line = "";
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(request.getInputStream()));
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
notificationString = stringBuffer.toString();
Hope it will works.

I think you should use readLine() method.One of the answer from stack overflow suggest not using ready() for such requirements.
The ready method tells us if the Stream is ready to be read.
Imagine your stream is reading data from a network socket. In this
case, the stream may not have ended, because the socket has not been
closed, yet it may not be ready for the next chunk of data, because
the other end of the socket has not pushed any more data.
In the above scenario, we cannot read any more data until the remote
end pushes it, so we have to wait for the data to become available, or
for the socket to be closed. The ready() method tells us when the data
is available.

I had this same problem and I changed the code to look like this:
StringBuffer jb = new StringBuffer();
String notificationString = "";
String line = "";
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
jb.append(line);
}
notificationString = jb.toString();

Try This One:
while(notificationReader.ready()) {
notificationString = notificationString.concat(notificationReader.readLine());
lines++;
}

Related

ObjectInputStream.readObject skips last line of text file

Fairly simple question, I have a server with some file, lets call it serverFile.txt and I wish to send it line by line to some client. to achieve this, i wrote this simple code on the server side
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null)
{
line = line + System.lineSeparator();
MMULogFileController.getOos().writeObject(line);
line = br.readLine();
System.out.println(line);
}
br.close();
where the MMULogFileController.getOos is the outputstream of the accepted socket.
It does indeed print all the lines of the file serverFile.txt
My problem is on the client side. This is the relevant code -
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = (String)in.readObject();
File newLogFile = new File("newLog.txt");
PrintWriter ptofile = new PrintWriter(newLogFile.getName());
while(line != null)
{
ptofile.write(line);
try
{
line = (String) in.readObject();
}
catch(java.io.EOFException e)
{
line = null;
}
}
ptofile.close();
and it prints all the lines correctly into a new file on the client side, except for the very last line. I know it was sent from the server because it was printed, but on the client side it recieved null because it reaches EOF. Is there any way to deal with this?
Myself, I'd use a PrintStream to send the text out, and then read it in using either a BufferedReader or a Scanner. But having said that, if you insist on using an ObjectOutputStream, you should either flush or close it when done sending your file's text, and certainly close it when you're done using it.
Also, avoid this type of code:
catch(java.io.EOFException e)
{
line = null;
}
since this means that you're completely ignoring your exceptions. At least view the stack trace.

Java, problems with BufferedReader in a while loop

I'm stuck trying to advance. This while loop seems to hang when receiving lines from a socket.
Here's the server side of the code:
out = new PrintWriter(socketcliente.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socketcliente.getInputStream()));
//receive and shows client data
linea = 0;
while ((buffer[linea] = in.readLine()) != null) {
System.out.println(buffer[linea]);
linea = linea+1;
}
//asks for a command and sends it to client
System.out.println("Enter remote command");
while ((input = scanner.nextLine()) != null) {
out.println(input);
}
and here's the client side:
out = new PrintWriter(socketcliente.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socketcliente.getInputStream()));
//sends a limited amount of lines to the server
linea = 0;
while (buffer[linea] != null) {
out.println(buffer[linea]);
linea = linea+1;
}
//receive the command from server, executes and save output for sending to the server
while ((comandor = in.readLine()) != null) {
proceso = Runtime.getRuntime().exec(comandor);
pinput = new BufferedReader(new InputStreamReader(proceso.getInputStream()));
buffer = new String[100];
linea = 0;
while ((psalida = pinput.readLine()) != null) {
buffer[linea] = psalida;
linea = linea+1;
}
}
After the server prints the data it receives, it does nothing, nor exit the while loop. Must send data back to the client. I'm using PrintWriter and BufferedReader.
Edited: More complete code to understand what I'm trying. The command execution and output's save runs fine, the problem is receiving the data in the server, it gets all the data, but stops at end and don't exit the first while loop. How can I allow it to exit the loop? I tried sending a null byte from the client after the message, or a "quit text" that the server can understand like:
while ((buffer[linea] = in.readLine()) != null && (buffer[linea] = in.readLine()) != "quit")
I'm lost and didn't find how to do.
All these are in try statements.
Nothing works. I'm a beginner, thanks for helping.
In your server side code the incrementing line you have written for line is wrong, it must be corrected as line = line+1; so the whole `server side code must look as below
line = 0;
while ((buffer[line] = in.readLine()) != null) {
System.out.println(buffer[line]);
line++;
}
Read string to a StringBuilder instead - less allocations, faster and eaasier:
StringBuilder builder = new StringBuilder();
String aux = "";
BufferedReader pinput = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((aux = pinput.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();

How to reset BufferedReader (or InputStreamReader) to use readline() twice?

I use this code snippet to read text from a webpage aand save it to a string?
I would like the readline() function to start from the beggining. So it would read content of the webpage again. How Can I do that
if (response == httpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
isr = new InputStreamReader(in);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
fullText += line;
}
// I want to go through a webpage source again, but
// I can't because br.readLine() = null. How can I put
// put a marker on the beginning of the page?
while ((line1 = br.readLine()) != null) {
fullText1 += line1;
// It will not go into this loop
}
You can only mark a position for a Reader (and return to it with reset()) if markSupported returns true, and I very much doubt that the stream returned by httpURLConnection.getInputStream() supports marks.
The best option, I think, is to read the response into a buffer and then you can create as many readers as you like over that buffer. You will need to include the line termination characters (which you are currently discarding) to preserve the line structure. (Alternatively, you can read the response into a List<String> rather than into a single String.)
From InputStream will not reset to beginning
your stream inside a BufferedInputStream object like:
with the markSupported() method if your InputStream actually support using mark. According to the API the InputStream class doesn't, but the java.io.BufferedInputStream class does. Maybe you should embed your stream inside a BufferedInputStream object like:
InputStream data = new BufferedInputStream(realResponse.getEntity().getContent());
// data.markSupported() should return "true" now
data.mark(some_size);
// work with "data" now
...
data.reset();

Reading http request from socket with null check java

I'm reading HTTP request from socket input stream
StringBuilder request = new StringBuilder();
String inputLine;
while (!(inputLine = in.readLine()).equals("")) {
request.append(inputLine + "\r\n");
}
It's working but findbugs gives the following bug: Dereference of the result of readLine() without nullcheck. Request ends with "" not eof. So how can I check null value here?
Like that:
while ((inputLine = in.readLine()) != null) {
But I assume that you don't want a blank string, use apache commons:
while(StringUtils.isNotBlank(inputLine = in.readLine())) {
Edit:
Also +1 for sodium's comment. However in my opinion this:
("").equals(in.readLine())
is a bit unreadable.

BufferedReader not stating 'ready' when it should

I am trying to read text from a web document using a BufferedReader over an InputStreamReader on an URL (to the file on some Apache server).
String result = "";
URL url = new URL("http://someserver.domain/somefile");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(), "iso-8859-1"));
result += in.readLine();
Now this works just fine. But Obviously I'd like the reader not to just read one line, but as many as there are in the file.
Looking at the BufferedReader API the following code should do just that:
while (in.ready()) {
result += in.readLine();
}
I.e. read all lines while there are more lines, stop when no more lines are there. This code does not work however - the reader just never reports ready() = true!
I can even print the ready() value right before reading a line (which reads the correct string from the file) but the reader will report 'false'.
Am I doing something wrong? Why does the BufferedReader return 'false' on ready when there is actually stuff to read?
ready() != has more
ready() does not indicate that there is more data to be read. It only shows if a read will could block the thread. It is likely that it will return false before you read all data.
To find out if there is no more data check if readLine() returns null.
String line = in.readLine();
while(line != null){
...
line = in.readLine();
}
Another way you can do this that bypasses the in.ready() is something like:
while ((nextLine = in.readLine()) != null) {
result += nextLine;
}
You will just continue reading until you are done. This way you do not need to worry about the problem with in.ready().
I think the standard way to write this is to just attempt to read the line and verify that it returned sometime. Something like this:
while ((String nextLine = in.readLine()) != null) {
//System.out.println(nextLine);
result += nextLine;
}
So you just continue to go until you get null returned from the stream. See here for extra information:
http://download.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()
The BufferedReader.ready() method is behaving as specified:
The Reader.ready() javadoc says the following:
[Returns] true if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.
Then the BufferedReader.ready() javadoc says the following:
Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
If you put these two together, it is clear that BufferedReader.ready() can return false in situations where are characters available. In short, you shouldn't rely on ready() to test for logical end-of-file or end-of-stream.
This is what we have been using consistently for years - not sure if it is the "standard" method. I'd like to hear comments about the pros and cons of using URL.openURLStream() directly, and if that is causing the OP's problems. This code works for both HTTP and HTTPS connections.
URL getURL = new URL (servletURL.toString() + identifier+"?"+key+"="+value);
URLConnection uConn = getURL.openConnection();
BufferedReader br = new BufferedReader (new
InputStreamReader (uConn.getInputStream()));
for (String s = br.readLine() ; s != null ; s = br.readLine()) {
System.out.println ("[ServletOut] " + s);
// do stuff with s
}
br.close();
Basically the BufferedReader.ready() method can be used for checking whether the underlying stream is ready for providing data to the method caller.... else we can wait the thread for some time till it becomes ready.
But the real problem is that after we completely read the data stream, it will throw false..
so we didn't know whether the stream is fully read OR underlying stream is busy....
If you want to use in.ready(), the following worked for me well:
for (int i = 0; i < 10; i++) {
System.out.println("is InputStreamReader ready: " + in.ready());
if (!in.ready()) {
Thread.sleep(1000);
} else {
break;
}
}

Categories

Resources