summaryrefslogtreecommitdiff
path: root/same/src/main/java/com/orbekk/same/ConnectionManagerImpl.java
blob: ade469e6a12a2f56f4f3eae9327d31834eec814e (plain)
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
package com.orbekk.same;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.jsonrpc4j.ProxyUtil;
import com.orbekk.net.MyJsonRpcHttpClient;
import com.orbekk.paxos.PaxosService;
import com.orbekk.same.discovery.DirectoryService;

public class ConnectionManagerImpl implements ConnectionManager {
    private int connectionTimeout;
    private int readTimeout;
    private Map<String, MyJsonRpcHttpClient> connectionCache =
            new HashMap<String, MyJsonRpcHttpClient>();

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @param connectionTimout Timeout for establishing connection in milliseconds.
     * @param readTimeout Timeout for waiting for answer in milliseconds.
     */
    public ConnectionManagerImpl(int connectionTimout, int readTimeout) {
        this.connectionTimeout = connectionTimout;
        this.readTimeout = readTimeout;
    }

    private MyJsonRpcHttpClient getConnection(String url)
            throws MalformedURLException {
        if (!connectionCache.containsKey(url)) {
            connectionCache.put(url, new MyJsonRpcHttpClient(new URL(url),
                    connectionTimeout, readTimeout));
        }
        return connectionCache.get(url);
    }

    private <T>T getClassProxy(String url, Class<T> clazz) {
        T service = null;
        try {
            MyJsonRpcHttpClient client = getConnection(url);
            service = ProxyUtil.createProxy(
                    this.getClass().getClassLoader(),
                    clazz,
                    client);
        } catch (MalformedURLException e) {
            logger.warn("Unable to create client for {}, {}", url, e);
        }
        return service;
    }

    @Override
    public ClientService getClient(String url) {
        return getClassProxy(url, ClientService.class);
    }

    @Override
    public MasterService getMaster(String url) {
        return getClassProxy(url, MasterService.class);
    }

    @Override
    public PaxosService getPaxos(String url) {
        return getClassProxy(url, PaxosService.class);
    }
    
    @Override
    public DirectoryService getDirectory(String url) {
        return getClassProxy(url, DirectoryService.class);
    }
}