summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java
blob: 97b5f5ae4d1204def9ccb2abf6b56ef88b46febb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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;
	}

}