/
AddTypeContract.java
53 lines (43 loc) · 1.84 KB
/
AddTypeContract.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
package com.scalar.am.contract;
import com.scalar.ledger.asset.Asset;
import com.scalar.ledger.contract.Contract;
import com.scalar.ledger.exception.ContractContextException;
import com.scalar.ledger.ledger.Ledger;
import java.util.Optional;
import javax.json.Json;
import javax.json.JsonObject;
public class AddTypeContract extends Contract {
public static final String NAME = "name";
public static final String TYPE = "type";
public static final String HOLDER_ID = "holderId";
private static final String RESULT = "result";
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
private static final String MESSAGE = "message";
@Override
public JsonObject invoke(Ledger ledger, JsonObject argument, Optional<JsonObject> property) {
if (!argument.containsKey(NAME)) {
throw new ContractContextException("wrong argument.");
}
if (!property.isPresent() || !property.get().containsKey(HOLDER_ID)) {
throw new ContractContextException("property: `" + HOLDER_ID + "` is mandatory.");
}
String holderId = property.get().getString(HOLDER_ID);
String name = argument.getString(NAME);
Optional<Asset> type = ledger.get(holderId + "-" + name);
if (type.isPresent()) {
return Json.createObjectBuilder()
.add(RESULT, FAILURE)
.add(MESSAGE, "Type " + name + " is already registered.")
.build();
}
ledger.put(holderId + "-" + name, Json.createObjectBuilder().build());
JsonObject newType = Json.createObjectBuilder().add(NAME, name).build();
ledger.get(holderId + "-" + TYPE);
ledger.put(holderId + "-" + TYPE, newType);
return Json.createObjectBuilder()
.add(RESULT, SUCCESS)
.add(MESSAGE, "type " + name + " put completed.")
.build();
}
}