1

I'm trying to pass a payload to a validate(ValidationPayload) in the Play Framework using Java. I can not access the values stored in payload.getAttrs() which returns a TypedMap.

I tried to access the Cookies by calling in the validate method payload.getAttrs().getOptional(TypedKey.create("Cookies")) but I always get a null back.

When I evaluate expression using IntelliJ I see the attrs contain Cookies, Flash and more. But I can not access theses values. I can see the values in the Expression Evaluator screenshot

public String validate(Constraints.ValidationPayload payload) {
        TypedMap attrs = payload.getAttrs();
        Optional<Object> baseDomain = payload.getAttrs().getOptional(TypedKey.create("baseDomain"));

        Locale value = payload.getAttrs().get(TypedKey.create("selectedLang"));
        return "String";
    }

How can I access these objects stored in a TypedMap?

snjall
  • 23
  • 5

1 Answers1

1

I figured this out a TypedMap map uses TypedKeys. A typed key is unique to each INSTANCE of the key. That means you need to fetch from the typedMap with the same instance of the key that was used to put in the map. Creating a new key will cause an empty or null response.

This should work:

TypedKey<String> baseDomainKey = TypedKey.create("baseDomain")
payload.getAttrs().addAttrs(baseDomainKey, "domain")
String domain = payload.getAttrs().get(baseDomainKey)

This will not work however:

TypedKey<String> baseDomainKey = TypedKey.create("baseDomain")
payload.getAttrs().addAttrs(baseDomainKey, "domain")
String domain = payload.getAttrs().get(TypedKey.create("baseDomain"))
snjall
  • 23
  • 5
  • Have you found a way to retrieve an object from the TypedMap which was already inserted by play? for example the session? – devDomm Apr 01 '21 at 08:40
  • I just wanted to link this answer from a similar post in case anyone else stumbles across this question and wonders how to access existing objects from a TypedMap in play https://stackoverflow.com/questions/66901698/get-value-of-typedmap-from-constraints-validationpayload/67308091#67308091 – devDomm Apr 29 '21 at 11:17