-
Notifications
You must be signed in to change notification settings - Fork 146
/
AbstractBlockSubscriptionStrategy.java
85 lines (70 loc) · 2.65 KB
/
AbstractBlockSubscriptionStrategy.java
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
76
77
78
79
80
81
82
83
84
85
package net.consensys.eventeum.chain.service.strategy;
import lombok.extern.slf4j.Slf4j;
import net.consensys.eventeum.chain.block.BlockListener;
import net.consensys.eventeum.dto.block.BlockDetails;
import net.consensys.eventeum.integration.eventstore.EventStore;
import net.consensys.eventeum.model.LatestBlock;
import net.consensys.eventeum.service.EventStoreService;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlock;
import rx.Subscription;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public abstract class AbstractBlockSubscriptionStrategy<T> implements BlockSubscriptionStrategy {
private Lock lock = new ReentrantLock();
protected Collection<BlockListener> blockListeners = new ConcurrentLinkedQueue<>();
protected Subscription blockSubscription;
protected Web3j web3j;
protected EventStoreService eventStoreService;
protected String nodeName;
public AbstractBlockSubscriptionStrategy(Web3j web3j, String nodeName, EventStoreService eventStoreService) {
this.web3j = web3j;
this.nodeName = nodeName;
this.eventStoreService = eventStoreService;
}
@Override
public void unsubscribe() {
try {
if (blockSubscription != null) {
blockSubscription.unsubscribe();
}
} finally {
blockSubscription = null;
}
}
@Override
public void addBlockListener(BlockListener blockListener) {
blockListeners.add(blockListener);
}
@Override
public void removeBlockListener(BlockListener blockListener) {
blockListeners.remove(blockListener);
}
public boolean isSubscribed() {
return blockSubscription != null && !blockSubscription.isUnsubscribed();
}
protected void triggerListeners(T blockObject) {
lock.lock();
try {
blockListeners.forEach(listener -> triggerListener(listener, convertToBlockDetails(blockObject)));
} finally {
lock.unlock();
}
}
protected void triggerListener(BlockListener listener, BlockDetails block) {
try {
listener.onBlock(block);
} catch(Throwable t) {
log.error(String.format("An error occured when processing block with hash %s", block.getHash()), t);
}
}
protected Optional<LatestBlock> getLatestBlock() {
return eventStoreService.getLatestBlock(nodeName);
}
abstract BlockDetails convertToBlockDetails(T blockObject);
}