blob: 97b5f5ae4d1204def9ccb2abf6b56ef88b46febb (
plain) (
tree)
|
|
package org.openslx.dnbd3.status.poller;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.openslx.dnbd3.status.rpc.Status;
import com.google.gson.Gson;
import fi.iki.elonen.NanoHTTPD;
/**
* Polling a dnbd3 server for its status.
*
*/
public class ServerPoller
{
private final String address;
private final String server;
private final Gson parseGson = new Gson();
private byte[] buffer = new byte[5000];
public ServerPoller( String host, int port )
{
this.address = host;
this.server = "http://" + host + ":" + port + "/query?q=stats&q=clients";
}
public Status update()
{
HttpURLConnection con = null;
InputStream is;
try {
con = (HttpURLConnection)new URL( this.server ).openConnection();
con.setRequestMethod( "GET" );
con.setConnectTimeout( 1000 );
con.setReadTimeout( 2000 );
if ( con.getResponseCode() != HttpURLConnection.HTTP_OK ) {
return null;
}
is = con.getInputStream();
} catch ( java.net.SocketTimeoutException e ) {
return null;
} catch ( java.io.IOException e ) {
return null;
}
// Now read data
Status status;
try {
InputStreamReader isr = new InputStreamReader( is );
status = parseGson.fromJson( isr, Status.class );
while ( is.read( buffer ) > 0 ) {
// Nothing
}
NanoHTTPD.safeClose( isr );
NanoHTTPD.safeClose( is );
NanoHTTPD.safeClose( con.getErrorStream() );
status.setAddress( address );
status.setTimestamp( System.currentTimeMillis() );
} catch ( Exception e ) {
e.printStackTrace();
status = null;
}
// TODO: http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
// once dnbd3 server supports keep-alive connections
return status;
}
public String getAddress()
{
return address;
}
}
|