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, final String remoteMethod, final Object o, final AsyncClientCallback callback) {
19
		final String url = remoteBaseUrl + "/async/method/" + remoteMethod;
20
		final String id = (new RestTemplate()).postForObject(url, o, String.class);
21
		activeRemoteCalls.put(id, callback);
22
	}
23

    
24
	public boolean processResponse(final String id, final AsyncResponse response) {
25
		if (activeRemoteCalls.containsKey(id)) {
26
			final AsyncClientCallback callback = activeRemoteCalls.get(id);
27

    
28
			callback.updateLastInvocation();
29

    
30
			switch (response.getStatus()) {
31
			case ASSIGNED:
32
			case RUNNING:
33
				callback.onGoing(response);
34
				break;
35
			case SUCCESS:
36
				callback.onDone(response);
37
				activeRemoteCalls.remove(id);
38
				break;
39
			case FAILED:
40
				callback.onFailed(response);
41
				activeRemoteCalls.remove(id);
42
				break;
43
			default:
44
				log.warn("Status " + response.getStatus() + " not managed");
45
				break;
46
			}
47
			return true;
48
		} else {
49
			log.warn("Unexpected message: " + id);
50
			return false;
51
		}
52
	}
53

    
54
	public void clearRemoteCalls() {
55
		activeRemoteCalls.clear();
56
	}
57

    
58
	public void deleteRemoteCall(final String id) {
59
		activeRemoteCalls.remove(id);
60
	}
61

    
62
	public static Map<String, AsyncClientCallback> getActiveremotecalls() {
63
		return activeRemoteCalls;
64
	}
65

    
66
}
(2-2/8)