2
2
3
3
import com .variant .server .spi .TargetingLifecycleEvent ;
4
4
import com .variant .server .spi .TargetingLifecycleHook ;
5
+ import com .variant .share .error .VariantException ;
5
6
import com .variant .share .schema .State ;
6
7
import com .variant .share .schema .Variation ;
7
8
import com .variant .share .yaml .YamlMap ;
36
37
*/
37
38
public class WeightedRandomTargetingHook implements TargetingLifecycleHook {
38
39
39
- final private String propName ;
40
+ private String propName = "weight" ;
40
41
41
- public WeightedRandomTargetingHook () {
42
- propName = "weight" ;
43
- }
44
- public WeightedRandomTargetingHook (YamlNode <?> node ) {
45
- var valOpt = Optional .ofNullable (((YamlMap ) node ).value ().get ("key" ));
46
- propName = valOpt
47
- .map (scalar -> ((YamlScalar <String >)scalar ).value ())
48
- .orElseThrow (
49
- () ->
50
- new RuntimeException (
51
- "Unable to value [%s] to a string literal"
52
- .formatted ("foo" ))
42
+ public WeightedRandomTargetingHook (YamlNode <?> init ) {
43
+ Optional .ofNullable (init )
44
+ .ifPresentOrElse (
45
+ node -> {
46
+ if (node instanceof YamlMap mapNode ) {
47
+ propName = Optional .ofNullable (mapNode .value ().get ("key" ))
48
+ .map (
49
+ valueNode -> {
50
+ if (valueNode instanceof YamlScalar <?> scalarNode && scalarNode .value () instanceof String string ) {
51
+ return string ;
52
+ } else {
53
+ throw new VariantException (
54
+ "Unable to value [%s] to a string literal" .formatted (valueNode ));
55
+ }
56
+ }
57
+ )
58
+ .orElseThrow (
59
+ () -> new VariantException (
60
+ "Required key 'key' not found in the initializer map" ));
61
+ }
62
+ else {
63
+ throw new VariantException ("The hook initializer must be a YAML map" );
64
+ }
65
+ },
66
+ // No init key was given
67
+ () -> propName = "weight"
53
68
);
69
+
54
70
}
55
71
private static Random rand = new Random ();
56
72
@@ -67,7 +83,10 @@ public Optional<Variation.Experience> post(TargetingLifecycleEvent event) {
67
83
String .format ("No experiences in variation [%s] are defined on state [%s]" , var .getName (), state .getName ()));
68
84
}
69
85
double weightSum = definedExperiences .stream ()
70
- .map (e -> Double .parseDouble (e .getParameters ().get (propName )))
86
+ .map (e -> {
87
+ var val = e .getParameters ().get (propName );
88
+ return Double .parseDouble (e .getParameters ().get (propName ));
89
+ })
71
90
.reduce (0D , Double ::sum );
72
91
73
92
double randVal = rand .nextDouble () * weightSum ;
0 commit comments