-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValidateLedger.java
59 lines (50 loc) · 1.99 KB
/
ValidateLedger.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
package com.scalar.dl.client.contract;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.scalar.dl.ledger.contract.JacksonBasedContract;
import com.scalar.dl.ledger.database.AssetFilter;
import com.scalar.dl.ledger.database.AssetFilter.AgeOrder;
import com.scalar.dl.ledger.exception.ContractContextException;
import com.scalar.dl.ledger.statemachine.Asset;
import com.scalar.dl.ledger.statemachine.Ledger;
import java.util.List;
public class ValidateLedger extends JacksonBasedContract {
static final String ASSET_ID_KEY = "asset_id";
static final String AGE_KEY = "age";
static final String START_AGE_KEY = "start_age";
static final String END_AGE_KEY = "end_age";
static final String DATA_KEY = "data";
@Override
public JsonNode invoke(Ledger<JsonNode> ledger, JsonNode argument, JsonNode properties) {
if (!argument.has(ASSET_ID_KEY)) {
throw new ContractContextException("please set asset_id in the argument");
}
String assetId = argument.get(ASSET_ID_KEY).asText();
int startAge = 0;
int endAge = Integer.MAX_VALUE;
if (argument.has(AGE_KEY)) {
int age = argument.get(AGE_KEY).asInt();
startAge = age;
endAge = age;
} else {
if (argument.has(START_AGE_KEY)) {
startAge = argument.get(START_AGE_KEY).asInt();
}
if (argument.has(END_AGE_KEY)) {
endAge = argument.get(END_AGE_KEY).asInt();
}
}
AssetFilter filter =
new AssetFilter(assetId)
.withStartAge(startAge, true)
.withEndAge(endAge, true)
.withAgeOrder(AgeOrder.ASC);
List<Asset<JsonNode>> assets = ledger.scan(filter);
ObjectMapper mapper = getObjectMapper();
ArrayNode array = mapper.createArrayNode();
assets.forEach(
a -> array.add(mapper.createObjectNode().put(AGE_KEY, a.age()).set(DATA_KEY, a.data())));
return mapper.createObjectNode().set(assetId, array);
}
}