mrhallak
mrhallak

Reputation: 1178

Retrieving a RabbitMQ message before serialization (Auditing)

I have an object that I'm trying to audit before sending it on Spring Cloud Stream, the problem arises when I send the object as application/json so the interceptor receives the object as a serialized string. Is it possible to run the interceptor before the jackson convertor?

Here's the code for the interceptor:

@Slf4j
public class AuditInterceptor implements ChannelInterceptor {
    private void updateField(Field field, Object payload, String newValue){
        if(field.getType().equals(String.class)){
            try {
                Method readMethod =  BeanUtils.getPropertyDescriptor(payload.getClass(),field.getName()).getReadMethod();

                log.info("Old value {}", readMethod.invoke(payload));

                Method setMethod = BeanUtils.getPropertyDescriptor(payload.getClass(),field.getName()).getWriteMethod();
                setMethod.invoke(payload, newValue);

                log.info("New value {}", readMethod.invoke(payload));
            } catch (IllegalAccessException e) {
                log.error("Error", e);
            } catch (InvocationTargetException e) {
                log.error("Error", e);
            }
        }
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel messageChannel) {
        for(Field field  : message.getPayload().getClass().getDeclaredFields()){

            if (field.isAnnotationPresent(CreatedBy.class)){
                updateField(field, message.getPayload(), "Interceptor");
            }

            if (field.isAnnotationPresent(LastModifiedBy.class)){
                updateField(field, message.getPayload(), "Interceptor");
            }
        }

        return message;
    }
}

Code for the runner:

@Component
public class AuditRunner implements CommandLineRunner {
    @Autowired
    ChannelInterceptor auditInterceptor;

    @Autowired
    MessageChannel output;

    @Override
    public void run(String... strings) throws Exception {
        ((DirectChannel) output).addInterceptor(auditInterceptor);
    }
}

Upvotes: 2

Views: 279

Answers (1)

Gary Russell
Gary Russell

Reputation: 174664

Try...

((DirectChannel) output).addInterceptor(0, auditInterceptor);

...so your interceptor is applied first (the conversion is performed by an interceptor).

Upvotes: 3

Related Questions