Is it possible to get ContainerRequestContext or HttpHeaders in Jackson serializers/deserializers?

28 Views Asked by At

We have a problem with Jackson deserializers/serializers who dont give me access to the ContainerRequestContext or HttpHeaders. We use Jersey/Jackson framework without Spring.The current solution is now as code below, with ImprovedLocalThread and its not a stable solution.

public class MyValidatorFilter implements ContainerRequestFilter {

    private static final ImprovedThreadLocal<TemporaryKeyMap> thread = new ImprovedThreadLocal<>();

    // We dont want to use ThreadLocal.. 
    public static ImprovedThreadLocal<TemporaryKeyMap> getCurrentRequestTemporaryKeyMap() {
        return thread;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        thread.set(new TemporaryKeyMap());
    }
}
public class MyDeserializer<T> extends StdDeserializer<T> {
    @Override
    public T deserialize(JsonParser pJsonParser, DeserializationContext pDeserializationContext)
    throws IOException {
        
        // How can I get ContainerRequestContext here? 
        TemporaryKeyMap object = MyValidatorFilter.getCurrentRequestTemporaryKeyMap().get();
        
        return null;
    }
}

How can we get rid of ImrovedThreadLocal and get ConteinerRequestContext of HttpHeaders in our deserializer/serializers?

We thried to pass request scoped content through DeserializationContext.

public class MyValidatorFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        ObjectMapper          mapper                = new ObjectMapper();
        DeserializationConfig deserializationConfig = mapper.getDeserializationConfig();
        DeserializationConfig modifiedConfig        = deserializationConfig.withAttribute("datastring", requestContext.getProperty("datastring"));
        mapper.setConfig(modifiedConfig);
        
        ...
    }
}
public class MyDeserializer<T> extends StdDeserializer<T> {
    @Override
    public T deserialize(JsonParser pJsonParser, DeserializationContext pDeserializationContext)
    throws IOException {

        String token = (String) pDeserializationContext.getAttribute("datastring");

        return null;
    }
}

This is not threadsafe?

0

There are 0 best solutions below