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.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
@Component
13
public class AsyncClientUtils {
14

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

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

    
19
	public void invokeRemoteMethod(final String remoteBaseUrl,
20
			final String remoteMethod,
21
			final String localBaseUrl,
22
			final Object o,
23
			final AsyncClientCallback callback) {
24

    
25
		final String url = remoteBaseUrl + "/async/method/" + remoteMethod + ((StringUtils.isNotBlank(localBaseUrl)) ? "?caller=" + localBaseUrl : "");
26

    
27
		log.info("invoking async method: " + url);
28

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

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

    
39
			callback.updateLastInvocation();
40

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

    
65
	public void clearRemoteCalls() {
66
		activeRemoteCalls.clear();
67
	}
68

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

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

    
77
}
(2-2/8)