From 3102d8bce3426d9cf41aeaf201c360d342677770 Mon Sep 17 00:00:00 2001 From: Jesse Morgan Date: Sat, 9 Apr 2016 14:22:20 -0700 Subject: Switching from Ivy+Ant to Maven. --- .../grow/provider/JsonEncodedProvider.java | 83 ++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/main/java/com/p4square/grow/provider/JsonEncodedProvider.java (limited to 'src/main/java/com/p4square/grow/provider/JsonEncodedProvider.java') diff --git a/src/main/java/com/p4square/grow/provider/JsonEncodedProvider.java b/src/main/java/com/p4square/grow/provider/JsonEncodedProvider.java new file mode 100644 index 0000000..500f761 --- /dev/null +++ b/src/main/java/com/p4square/grow/provider/JsonEncodedProvider.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Jesse Morgan + */ + +package com.p4square.grow.provider; + +import java.io.IOException; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +/** + * Provider provides a simple interface for loading and persisting + * objects. + * + * @author Jesse Morgan + */ +public abstract class JsonEncodedProvider { + public static final ObjectMapper MAPPER = new ObjectMapper(); + static { + MAPPER.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); + MAPPER.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); + MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + protected final Class mClazz; + protected final JavaType mType; + + public JsonEncodedProvider(Class clazz) { + mClazz = clazz; + mType = null; + } + + public JsonEncodedProvider(JavaType type) { + mType = type; + mClazz = null; + } + + /** + * Encode the object as JSON. + * + * @param obj The object to encode. + * @return The JSON encoding of obj. + * @throws IOException if the object cannot be encoded. + */ + protected String encode(V obj) throws IOException { + if (mClazz == String.class) { + return (String) obj; + } + + return MAPPER.writeValueAsString(obj); + } + + /** + * Decode the JSON string as an object. + * + * @param blob The JSON data to decode. + * @return The decoded object or null if blob is null. + * @throws IOException If an object cannot be decoded. + */ + protected V decode(String blob) throws IOException { + if (blob == null) { + return null; + } + + if (mClazz == String.class) { + return (V) blob; + } + + V obj; + if (mClazz != null) { + obj = MAPPER.readValue(blob, mClazz); + + } else { + obj = MAPPER.readValue(blob, mType); + } + + return obj; + } +} + -- cgit v1.2.3