Project

General

Profile

1
package eu.dnetlib.services.async;
2

    
3
import java.util.HashMap;
4
import java.util.Map;
5

    
6
import org.apache.commons.logging.Log;
7
import org.apache.commons.logging.LogFactory;
8
import org.springframework.stereotype.Component;
9
import org.springframework.web.client.RestTemplate;
10

    
11
@Component
12
public class AsyncClientUtils {
13

    
14
	private static final Log log = LogFactory.getLog(AsyncClientUtils.class);
15

    
16
	private static final Map<String, AsyncClientCallback> activeRemoteCalls = new HashMap<>();
17

    
18
	public void invokeRemoteMethod(final String remoteBaseUrl,
19
			final String remoteMethod,
20
			final String localBaseUrl,
21
			final Object o,
22
			final AsyncClientCallback callback) {
23
		final String url = remoteBaseUrl + "/async/method/" + remoteMethod + "?caller=" + localBaseUrl;
24

    
25
		log.info("invoking async method: " + url);
26

    
27
		final String id = (new RestTemplate()).postForObject(url, o, String.class);
28
		if (callback != null) {
29
			activeRemoteCalls.put(id, callback);
30
		}
31
	}
32

    
33
	public boolean processResponse(final String id, final AsyncResponse response) {
34
		if (activeRemoteCalls.containsKey(id)) {
35
			final AsyncClientCallback callback = activeRemoteCalls.get(id);
36

    
37
			callback.updateLastInvocation();
38

    
39
			switch (response.getStatus()) {
40
			case ASSIGNED:
41
			case RUNNING:
42
				callback.onGoing(response);
43
				break;
44
			case SUCCESS:
45
				callback.onDone(response);
46
				activeRemoteCalls.remove(id);
47
				break;
48
			case FAILED:
49
				callback.onFailed(response);
50
				activeRemoteCalls.remove(id);
51
				break;
52
			default:
53
				log.warn("Status " + response.getStatus() + " not managed");
54
				break;
55
			}
56
			return true;
57
		} else {
58
			log.warn("Unexpected message: " + id);
59
			return false;
60
		}
61
	}
62

    
63
	public void clearRemoteCalls() {
64
		activeRemoteCalls.clear();
65
	}
66

    
67
	public void deleteRemoteCall(final String id) {
68
		activeRemoteCalls.remove(id);
69
	}
70

    
71
	public static Map<String, AsyncClientCallback> getActiveremotecalls() {
72
		return activeRemoteCalls;
73
	}
74

    
75
}
(2-2/8)