tags:

views:

331

answers:

3

I am trying to use the couchdb (continuous) changes API from Java and find that after exhausting the list of current changes the stream seems to be closed, not stay open forever as it is supposed to.

The code I am using is below. I would expect to never drop out of the while loop, but do as soon as the currently existing changes are finished being streamed. I am relatively new to both couchdb and Java so may be missing something obvious. Can anyone show me how to write this correctly?

URL url = new URL("[path to database here]/_changes?feed=continuous";);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true); 
conn.setUseCaches(false); 
conn.setRequestProperty("Connection", "Keep-Alive"); 
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = reader.readLine()) != null){
    // do something with the line here
}
// Should never get here under normal circumstances
reader.close();
A: 

This is just a guess since I dont know enough about the couchdb continuousfeed implementation or the HttpUrlConnection implementation. But it seems barring any bugs in the code of the two that if your java connection client has a timeout set lower than the default heartbeat for couchdb continuous changes then the connection could get terminated by the java client.

Just a thought.

Jeremy Wall
A: 

You can use &heartbeat=1000 to get couchdb sending new lines over the wire every second. That will keep your connection open until you disconnect and/or CouchDB gets shut down.

But you are right, I would also have expected that the connection won't close - seems as if also conn.setReadTimeout(0); doesn't help anything.

Joscha
I opened a defect here: https://issues.apache.org/jira/browse/COUCHDB-580
Joscha
+1  A: 

There's actually a default timeout of 60000ms (60 seconds) unless a different timeout value or a heartbeat is provided. I updated the _changes wiki page back in October and included any defaults I came across in the code.

Setting the heartbeat basically means that you'll be watching for a timeout in the client, i.e. no newline for the heartbeat period means you've definitely lost your connection. I believe CouchDB disables its timeout check if there's a heartbeat.

In any case, you should probably expect the connection to be closed at some point and code for that condition.

Matt Goodall