summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/dnbd3/status/poller/ServerPoller.java
blob: bfa70fbdc4c23a0346d5dfeb149a2628f5cda288 (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
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;
	}

}