Armeria: How pass object from a decorator to next decorator ?

Created on 2 Feb 2019  路  6Comments  路  Source: line/armeria

I need get some header value from request and validate that and then pass that value to next decorator.
I can not find a way to do this .
What is the best way for doing this ?

question

All 6 comments

I think find a way. I create a custom ServiceRequestContextWrapper and put a ConcurrentHashMap in it and save all objects that need in this ConcurrentHashMap then i can get this object using RequestContext.current(). i test this solution, this work.
Is this a optimal solution ? I want to use this method in production.

Thank you. :)

For completeness, let me explain the detail here. You can attach one or more attributes to a RequestContext. To attach attributes, you need to define AttributeKeys first:

public final class MyAttributeKeys {
    public static final AttributeKey<Integer> INT_ATTR =
            AttributeKey.valueOf(MyAttributeKeys.class, "INT_ATTR");
    public static final AttributeKey<MyBean> BEAN_ATTR =
            AttributeKey.valueOf(MyAttributeKeys.class, "BEAN_ATTR");
    ...
}

Then, you can access them via RequestContext.attr(AttributeKey):

// Setting:
ctx.attr(INT_ATTR).set(42);
ctx.attr(BEAN_ATTR).set(new MyBean());

// Getting;
Integer i = ctx.attr(INT_ATTR).get();
MyBean bean = ctx.attr(BEAN_ATTR);

You can also iterate over all the attributes in a context using RequestContext.attrs():

for (Attribute<?> a : ctx.attrs()) {
    System.err.println(a.key() + ": " + a.get());
}

If you are only interested in checking whether an attribute exists or not, it would be better using hasAttr(AttributeKey) because it does not perform any allocation for a non-existent attribute unlike attr(AttributeKey):

if (ctx.hasAttr(INT_ATTR)) {
    int i = ctx.attr(INT_ATTR).get();
    ...
}

Please feel free to reopen this issue if your question was not solved.

Was this page helpful?
0 / 5 - 0 ratings