summaryrefslogtreecommitdiff
path: root/src/main/java/au/id/zancanaro/javacheck/state/CommandValue.java
blob: de0dfc5d2faa4777650f1ed3fa366db21fc0e3a8 (about) (plain)
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
package au.id.zancanaro.javacheck.state;

import java.util.Map;
import java.util.NoSuchElementException;

public class CommandValue<T> {
    public static interface Action<T> {
        T doAction() throws Throwable;
    }

    public static interface VoidAction {
        void doAction() throws Throwable;
    }

    private static Map<Integer, Object> values = null;

    public static <T> T withValues(Map<Integer, Object> newValues, Action<T> action) throws Throwable {
        Map<Integer,Object> oldValues = values;
        try {
            values = newValues;
            return action.doAction();
        } finally {
            values = oldValues;
        }
    }

    public static void withValues(Map<Integer, Object> newValues, VoidAction action) throws Throwable {
        Map<Integer,Object> oldValues = values;
        try {
            values = newValues;
            action.doAction();
        } finally {
            values = oldValues;
        }
    }

    private final int id;

    public CommandValue(int id) {
        this.id = id;
    }

    public boolean isAbstract() {
        return values == null;
    }

    @SuppressWarnings("unchecked")
    public T get() {
        if (values != null && values.containsKey(id)) {
            return (T) values.get(id);
        } else {
            throw new NoSuchElementException("Concrete values cannot be supplied prior to being calculated");
        }
    }

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "#{" + id + "}";
    }
}