Advertisement
tpeierls

JsonDataSerializable

May 10th, 2012
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.79 KB | None | 0 0
  1. import com.hazelcast.nio.DataSerializable;
  2.  
  3. import java.io.DataInput;
  4. import java.io.DataOutput;
  5. import java.io.IOException;
  6.  
  7. import javax.inject.Inject;
  8. import javax.inject.Named;
  9.  
  10. import com.fasterxml.jackson.databind.ObjectMapper;
  11.  
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14.  
  15.  
  16. /**
  17.  * Common serialization/deserialization using Jackson (JSON).
  18.  * Uses binary (Smile) format to implement {@link DataSerializable}.
  19.  * Exposes both JSON- and Smile-oriented ObjectMappers to subclasses.
  20.  */
  21. public class JsonDataSerializable implements DataSerializable {
  22.  
  23.     final static Logger logger = LoggerFactory.getLogger(JsonDataSerializable.class);
  24.  
  25.  
  26.     public void readData(DataInput input) throws IOException {
  27.         int length = input.readInt();
  28.         byte[] bytes = new byte[length];
  29.         input.readFully(bytes);
  30.         try {
  31.             smileObjectMapper.readerForUpdating(this).readValue(bytes);
  32.         } catch (IOException ex) {
  33.             logger.warn("Error reading DataSerializable from this tree: " +
  34.                 objectMapper
  35.                     .writerWithDefaultPrettyPrinter()
  36.                     .writeValueAsString(smileObjectMapper.readTree(bytes))
  37.             );
  38.             throw ex;
  39.         }
  40.     }
  41.  
  42.     public void writeData(DataOutput output) throws IOException {
  43.         byte[] bytes = smileObjectMapper.writeValueAsBytes(this);
  44.         output.writeInt(bytes.length);
  45.         output.write(bytes);
  46.     }
  47.  
  48.  
  49.     protected static ObjectMapper objectMapper() {
  50.         return objectMapper;
  51.     }
  52.  
  53.     protected static ObjectMapper smileObjectMapper() {
  54.         return smileObjectMapper;
  55.     }
  56.  
  57.     @Inject static volatile ObjectMapper objectMapper;
  58.     @Inject @Named(JsonModule.SMILE) static volatile ObjectMapper smileObjectMapper;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement