From 45ada5475192f6afc9645c401de46765be87ee3f Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Thu, 21 May 2015 16:39:25 +0200 Subject: Lean and mean first prototype - to be improved! --- .../openslx/dnbd3/status/poller/ServerPoller.java | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java (limited to 'src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java') diff --git a/src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java b/src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java new file mode 100644 index 0000000..bfa70fb --- /dev/null +++ b/src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java @@ -0,0 +1,70 @@ +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; + +/** + * Polling a dnbd3 server for its status. + * + */ +public class ServerPoller +{ + + private final String address; + private final String server; + private final Gson parseGson = new Gson(); + + public ServerPoller( String host, int port ) + { + this.address = host; + this.server = "http://" + host + ":" + port + "/"; + } + + public Status update() + { + HttpURLConnection con = null; + InputStream is; + try { + con = (HttpURLConnection)new URL( this.server ).openConnection(); + con.setRequestMethod( "GET" ); + + con.setConnectTimeout( 1000 ); + con.setReadTimeout( 3000 ); + + 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 { + status = parseGson.fromJson( new InputStreamReader( is ), Status.class ); + 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; + } + +} -- cgit v1.2.3-55-g7522