forked from open-feature/java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHookData.java
More file actions
76 lines (66 loc) · 2.13 KB
/
Copy pathHookData.java
File metadata and controls
76 lines (66 loc) · 2.13 KB
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
package dev.openfeature.sdk;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Hook data provides a way for hooks to maintain state across their execution stages.
* Each hook instance gets its own isolated data store that persists only for the duration
* of a single flag evaluation.
*/
public interface HookData {
/**
* Sets a value for the given key.
*
* @param key the key to store the value under
* @param value the value to store
*/
void set(String key, Object value);
/**
* Gets the value for the given key.
*
* @param key the key to retrieve the value for
* @return the value, or null if not found
*/
Object get(String key);
/**
* Gets the value for the given key, cast to the specified type.
*
* @param <T> the type to cast to
* @param key the key to retrieve the value for
* @param type the class to cast to
* @return the value cast to the specified type, or null if not found
* @throws ClassCastException if the value cannot be cast to the specified type
*/
<T> T get(String key, Class<T> type);
/**
* Default implementation using ConcurrentHashMap for thread safety.
*/
static HookData create() {
return new DefaultHookData();
}
/**
* Default thread-safe implementation of HookData.
*/
public class DefaultHookData implements HookData {
private final Map<String, Object> data = Collections.synchronizedMap(new HashMap<>());
@Override
public void set(String key, Object value) {
data.put(key, value);
}
@Override
public Object get(String key) {
return data.get(key);
}
@Override
public <T> T get(String key, Class<T> type) {
Object value = data.get(key);
if (value == null) {
return null;
}
if (!type.isInstance(value)) {
throw new ClassCastException("Value for key '" + key + "' is not of type " + type.getName());
}
return type.cast(value);
}
}
}