Search code examples
springbase64spring-integrationmqttspring-integration-mqtt

Spring Integration transform Base64 to JsonObject


My project consist of three main block: MQTT protocol, RabbitMQ as a broker and Spring Integration.

MQTT protocol send encoded string eyJrZXkiOiJIZWxsbyBXb3JsZCJ9 to broker and Spring Integration consume and process data.

How can I decode/encode the data IntegrationFlow from Base64 eyJrZXkiOiJIZWxsbyBXb3JsZCJ9 to JsonObject {"key":"Hello World"} ?

What function should i use from IntegrationFlow: convert(), transform() or handle() ? What logical difference between this three? Can you please show me the example of code how to encode and decode data.

    @Bean
    IntegrationFlow inboundFlow(MqttPahoMessageDrivenChannelAdapter inboundAdapter){
        return IntegrationFlow
                .from(inboundAdapter)
                .transform( ... )  // How to implement decoder
                .handle((payload, headers) -> {
                    System.out.println(payload);
                    return null;
                })
                .get();
    }

Solution

  • Most of the EIP are just variations of the Service Activator which is a handle() in Java DSL. All those are for specific use-case and convenience for narrowed scope. Therefore you can just implement your own Service Activator to do the job. In your case it is indeed enough to use a transform() since this one plays the role to transform a payload of the message.

    The convert is not going to help you since you do not do conversion from one type to another. You just have a string as input and probably you want to have a string on the output. Therefore there is no type conversion involved.

    As Martin commented you can use that simple transformer:

    transform(String.class, (in) -> Base64.getDecoder().decode(in))
    

    This will give you a byte[] as an output. It is up to you to do anything else with that afterwards.