1
|
package eu.dnetlib.services.async;
|
2
|
|
3
|
import java.util.HashMap;
|
4
|
import java.util.Map;
|
5
|
|
6
|
import org.apache.commons.lang3.StringUtils;
|
7
|
import org.apache.commons.logging.Log;
|
8
|
import org.apache.commons.logging.LogFactory;
|
9
|
import org.springframework.stereotype.Component;
|
10
|
import org.springframework.web.client.RestTemplate;
|
11
|
|
12
|
import eu.dnetlib.services.AsyncInvocation;
|
13
|
|
14
|
@Component
|
15
|
public class AsyncClientUtils {
|
16
|
|
17
|
private static final Log log = LogFactory.getLog(AsyncClientUtils.class);
|
18
|
|
19
|
private static final Map<String, AsyncClientCallback> activeRemoteCalls = new HashMap<>();
|
20
|
|
21
|
public Map<String, String> invokeRemoteMethod(final String remoteBaseUrl,
|
22
|
final String remoteMethod,
|
23
|
final String localBaseUrl,
|
24
|
final Object o,
|
25
|
final AsyncClientCallback callback) {
|
26
|
|
27
|
final String url = remoteBaseUrl + "/async/method/" + remoteMethod + ((StringUtils.isNotBlank(localBaseUrl)) ? "?caller=" + localBaseUrl : "");
|
28
|
|
29
|
log.info("invoking async method: " + url);
|
30
|
|
31
|
final AsyncInvocation async = (new RestTemplate()).postForObject(url, o, AsyncInvocation.class);
|
32
|
if (callback != null) {
|
33
|
activeRemoteCalls.put(async.getId(), callback);
|
34
|
}
|
35
|
|
36
|
return async.getInfo();
|
37
|
}
|
38
|
|
39
|
public boolean processResponse(final String id, final AsyncResponse response) {
|
40
|
if (activeRemoteCalls.containsKey(id)) {
|
41
|
final AsyncClientCallback callback = activeRemoteCalls.get(id);
|
42
|
|
43
|
callback.updateLastInvocation();
|
44
|
|
45
|
switch (response.getStatus()) {
|
46
|
case ASSIGNED:
|
47
|
case RUNNING:
|
48
|
callback.onGoing(response);
|
49
|
break;
|
50
|
case SUCCESS:
|
51
|
callback.onDone(response);
|
52
|
activeRemoteCalls.remove(id);
|
53
|
break;
|
54
|
case FAILED:
|
55
|
callback.onFailed(response);
|
56
|
activeRemoteCalls.remove(id);
|
57
|
break;
|
58
|
default:
|
59
|
log.warn("Status " + response.getStatus() + " not managed");
|
60
|
break;
|
61
|
}
|
62
|
return true;
|
63
|
} else {
|
64
|
log.warn("Unexpected message: " + id);
|
65
|
return false;
|
66
|
}
|
67
|
}
|
68
|
|
69
|
public void clearRemoteCalls() {
|
70
|
activeRemoteCalls.clear();
|
71
|
}
|
72
|
|
73
|
public void deleteRemoteCall(final String id) {
|
74
|
activeRemoteCalls.remove(id);
|
75
|
}
|
76
|
|
77
|
public static Map<String, AsyncClientCallback> getActiveremotecalls() {
|
78
|
return activeRemoteCalls;
|
79
|
}
|
80
|
|
81
|
}
|