blob: ac93da860761d3b2d8c39c3c8f2c8c9a841c6a68 [file] [log] [blame]
/**
* Copyright (C) 2015 DataTorrent, Inc.
*
* 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.datatorrent.common.util;
import java.io.IOException;
import java.util.HashMap;
import org.codehaus.jackson.map.ObjectMapper;
import com.datatorrent.common.util.PubSubMessage.PubSubMessageType;
/**
* <p>PubSubMessageCodec class.</p>
*
* @param <T>
* @since 0.3.5
*/
public class PubSubMessageCodec<T>
{
private final ObjectMapper mapper;
public PubSubMessageCodec(ObjectMapper mapper) {
this.mapper = mapper;
}
public String formatMessage(PubSubMessage<T> pubSubMessage) throws IOException {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(PubSubMessage.TYPE_KEY, pubSubMessage.getType().getIdentifier());
map.put(PubSubMessage.TOPIC_KEY, pubSubMessage.getTopic());
T data = pubSubMessage.getData();
if (data != null) {
map.put(PubSubMessage.DATA_KEY, data);
}
return mapper.writeValueAsString(map);
}
/**
*
* @param message
* @return a {@link PubSubMessage} message.
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public PubSubMessage<T> parseMessage(String message) throws IOException {
HashMap<String, Object> map = mapper.readValue(message, HashMap.class);
PubSubMessage<T> pubSubMessage = new PubSubMessage<T>();
pubSubMessage.setType(PubSubMessageType.getPubSubMessageType((String)map.get(PubSubMessage.TYPE_KEY)));
pubSubMessage.setTopic((String)map.get(PubSubMessage.TOPIC_KEY));
pubSubMessage.setData((T)map.get(PubSubMessage.DATA_KEY));
return pubSubMessage;
}
}