com.codeveo.lago.bot.stomp.client.LagoJsonMessageConverter.java Source code

Java tutorial

Introduction

Here is the source code for com.codeveo.lago.bot.stomp.client.LagoJsonMessageConverter.java

Source

/*
 * Copyright 2014 Ladislav Klenovic <klenovic@nerdrobot.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codeveo.lago.bot.stomp.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import com.codeveo.lago.common.shared.RObjectType;
import com.codeveo.lago.communication.rest.api.RClientMessage;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

@Component("jsonMessageConverterBean")
public class LagoJsonMessageConverter implements MessageConverter {
    private static final Logger LOG = LoggerFactory.getLogger(LagoJsonMessageConverter.class);

    private final ObjectMapper mapper;

    public LagoJsonMessageConverter() {
        mapper = new ObjectMapper();

        /* make serializer use JAXB annotations (only) */
        JaxbAnnotationModule module = new JaxbAnnotationModule();
        mapper.registerModule(module);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(Include.NON_NULL);
    }

    @Override
    public Object fromMessage(Message<?> message, Class<?> targetClass) {
        try {
            /* NOTE: Message that came from STOMP broker */
            /* class discovery */
            RObjectType rObjectType = mapper.readValue((byte[]) message.getPayload(), RObjectType.class);

            if (rObjectType == null) {
                LOG.warn("Could not get R-object type from message '{}'", message);
                throw new Exception("Could not get R-Object type");
            }

            Class<?> clazz = ClientCommunicationHelperService.getClassFromClassId(rObjectType.getClassId());

            if (clazz == null) {
                LOG.warn("Could not identify class of R-object with class ID '{}' in message '{}'",
                        rObjectType.getClassId(), message);
                throw new Exception("Could not identify class of R-object");
            }

            Object obj = mapper.readValue((byte[]) message.getPayload(), clazz);

            if (clazz.equals(RClientMessage.class)) {
                JsonNode rootNode = mapper.readValue((byte[]) message.getPayload(), JsonNode.class);
                JsonNode dataJsonObject = rootNode.get("data");

                RObjectType data = null;
                RClientMessage clientMessage = (RClientMessage) obj;

                if (clientMessage.getData() != null) {
                    Class<?> dataClass = ClientCommunicationHelperService
                            .getClassFromClassId(clientMessage.getData().getClassId());

                    data = (RObjectType) mapper.readValue(dataJsonObject.toString(), dataClass);
                }

                clientMessage.setData(data);
            }

            return obj;
        } catch (Exception e) {
            LOG.error("Error occured during message deserialization", e);
        }

        return null;
    }

    @Override
    public Message<?> toMessage(Object payload, MessageHeaders header) {
        try {
            if (payload == null) {
                throw new Exception("Message must not be null");
            }

            if (!(payload instanceof RClientMessage)) {
                throw new Exception("Payload is not type of '" + RClientMessage.class.getName() + "' but '"
                        + payload.getClass().getName() + "'");
            }

            String json = mapper.writeValueAsString((RClientMessage) payload);
            /* NOTE: Message that goes to STOMP broker */
            Message<?> message = MessageBuilder.withPayload(json.getBytes()).build();

            return message;
        } catch (Exception e) {
            LOG.error("Error occured during message serialization", e);
        }

        return null;
    }
}