From 7f6f8a239299407d1bbc07f0e9c1d5d9995acc18 Mon Sep 17 00:00:00 2001 From: Costin Leau Date: Mon, 31 Jan 2011 13:24:37 +0200 Subject: [PATCH] DATAKV-32 + add Jackson serializer support --- .../JacksonJsonRedisSerializer.java | 103 ++++++++++++++++++ .../data/keyvalue/redis/Address.java | 36 ++++++ .../SimpleRedisSerializerTests.java | 9 ++ .../collections/CollectionTestParams.java | 13 ++- 4 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 spring-data-redis/src/main/java/org/springframework/data/keyvalue/redis/serializer/JacksonJsonRedisSerializer.java diff --git a/spring-data-redis/src/main/java/org/springframework/data/keyvalue/redis/serializer/JacksonJsonRedisSerializer.java b/spring-data-redis/src/main/java/org/springframework/data/keyvalue/redis/serializer/JacksonJsonRedisSerializer.java new file mode 100644 index 000000000..bf9adaf64 --- /dev/null +++ b/spring-data-redis/src/main/java/org/springframework/data/keyvalue/redis/serializer/JacksonJsonRedisSerializer.java @@ -0,0 +1,103 @@ +/* + * Copyright 2011 the original author or authors. + * + * 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 org.springframework.data.keyvalue.redis.serializer; + +import java.nio.charset.Charset; + +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.type.TypeFactory; +import org.codehaus.jackson.type.JavaType; +import org.springframework.util.Assert; + +/** + * {@link RedisSerializer} that can read and write JSON using Jackson's {@link ObjectMapper}. + * + *

This converter can be used to bind to typed beans, or untyped {@link java.util.HashMap HashMap} instances. + * + * @author Costin Leau + */ +public class JacksonJsonRedisSerializer implements RedisSerializer { + + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + + private final JavaType javaType; + + private ObjectMapper objectMapper = new ObjectMapper(); + + public JacksonJsonRedisSerializer(Class type) { + this.javaType = TypeFactory.type(type); + } + + @SuppressWarnings("unchecked") + @Override + public T deserialize(byte[] bytes) throws SerializationException { + if (SerializerUtils.isEmpty(bytes)) { + return null; + } + try { + return (T) this.objectMapper.readValue(bytes, 0, bytes.length, javaType); + } catch (Exception ex) { + throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex); + } + } + + @Override + public byte[] serialize(Object t) throws SerializationException { + if (t == null) { + return SerializerUtils.EMPTY_ARRAY; + } + try { + return this.objectMapper.writeValueAsBytes(t); + } catch (Exception ex) { + throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex); + } + } + + /** + * Sets the {@code ObjectMapper} for this view. If not set, a default + * {@link ObjectMapper#ObjectMapper() ObjectMapper} is used. + *

Setting a custom-configured {@code ObjectMapper} is one way to take further control of the JSON serialization + * process. For example, an extended {@link org.codehaus.jackson.map.SerializerFactory} can be configured that provides + * custom serializers for specific types. The other option for refining the serialization process is to use Jackson's + * provided annotations on the types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. + */ + public void setObjectMapper(ObjectMapper objectMapper) { + Assert.notNull(objectMapper, "'objectMapper' must not be null"); + this.objectMapper = objectMapper; + } + + /** + * Returns the Jackson {@link JavaType} for the specific class. + * + *

Default implementation returns {@link TypeFactory#type(java.lang.reflect.Type)}, but this can be overridden + * in subclasses, to allow for custom generic collection handling. For instance: + *

+	 * protected JavaType getJavaType(Class<?> clazz) {
+	 *   if (List.class.isAssignableFrom(clazz)) {
+	 *     return TypeFactory.collectionType(ArrayList.class, MyBean.class);
+	 *   } else {
+	 *     return super.getJavaType(clazz);
+	 *   }
+	 * }
+	 * 
+ * + * @param clazz the class to return the java type for + * @return the java type + */ + protected JavaType getJavaType(Class clazz) { + return TypeFactory.type(clazz); + } +} \ No newline at end of file diff --git a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/Address.java b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/Address.java index 9271fbb91..1967c29c5 100644 --- a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/Address.java +++ b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/Address.java @@ -30,6 +30,9 @@ public class Address implements Serializable { private Integer number; + public Address() { + } + /** * Constructs a new Address instance. * @@ -42,6 +45,39 @@ public class Address implements Serializable { this.number = number; } + + /** + * Returns the street. + * + * @return Returns the street + */ + public String getStreet() { + return street; + } + + /** + * @param street The street to set. + */ + public void setStreet(String street) { + this.street = street; + } + + /** + * Returns the number. + * + * @return Returns the number + */ + public Integer getNumber() { + return number; + } + + /** + * @param number The number to set. + */ + public void setNumber(Integer number) { + this.number = number; + } + @Override public int hashCode() { final int prime = 31; diff --git a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/serializer/SimpleRedisSerializerTests.java b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/serializer/SimpleRedisSerializerTests.java index 3c82b3f6d..01f767ecb 100644 --- a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/serializer/SimpleRedisSerializerTests.java +++ b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/serializer/SimpleRedisSerializerTests.java @@ -151,4 +151,13 @@ public class SimpleRedisSerializerTests { assertEquals(p1, serializer.deserialize(serializer.serialize(p1))); assertEquals(p1, serializer.deserialize(serializer.serialize(p1))); } + + @Test + public void testJsonSerializer() throws Exception { + JacksonJsonRedisSerializer serializer = new JacksonJsonRedisSerializer(Person.class); + String value = UUID.randomUUID().toString(); + Person p1 = new Person(value, value, 1, new Address(value, 2)); + assertEquals(p1, serializer.deserialize(serializer.serialize(p1))); + assertEquals(p1, serializer.deserialize(serializer.serialize(p1))); + } } \ No newline at end of file diff --git a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/support/collections/CollectionTestParams.java b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/support/collections/CollectionTestParams.java index 5ff257fae..e3e5c0d73 100644 --- a/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/support/collections/CollectionTestParams.java +++ b/spring-data-redis/src/test/java/org/springframework/data/keyvalue/redis/support/collections/CollectionTestParams.java @@ -23,6 +23,7 @@ import org.springframework.data.keyvalue.redis.SettingsUtils; import org.springframework.data.keyvalue.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.keyvalue.redis.connection.jredis.JredisConnectionFactory; import org.springframework.data.keyvalue.redis.core.RedisTemplate; +import org.springframework.data.keyvalue.redis.serializer.JacksonJsonRedisSerializer; import org.springframework.data.keyvalue.redis.serializer.OxmSerializer; import org.springframework.oxm.xstream.XStreamMarshaller; @@ -40,6 +41,7 @@ public abstract class CollectionTestParams { throw new RuntimeException("Cannot init XStream", ex); } OxmSerializer serializer = new OxmSerializer(xstream, xstream); + JacksonJsonRedisSerializer jsonSerializer = new JacksonJsonRedisSerializer(Person.class); // create Jedis Factory ObjectFactory stringFactory = new StringObjectFactory(); @@ -64,6 +66,10 @@ public abstract class CollectionTestParams { RedisTemplate xstreamPersonTemplate = new RedisTemplate(jedisConnFactory); xstreamPersonTemplate.setValueSerializer(serializer); + // json + RedisTemplate jsonPersonTemplate = new RedisTemplate(jedisConnFactory); + jsonPersonTemplate.setValueSerializer(jsonSerializer); + JredisConnectionFactory jredisConnFactory = new JredisConnectionFactory(); jredisConnFactory.setUsePool(true); @@ -83,9 +89,14 @@ public abstract class CollectionTestParams { RedisTemplate xstreamPersonTemplateJR = new RedisTemplate(jredisConnFactory); xstreamPersonTemplateJR.setValueSerializer(serializer); + // json JR + RedisTemplate jsonPersonTemplateJR = new RedisTemplate(jredisConnFactory); + jsonPersonTemplate.setValueSerializer(jsonSerializer); + return Arrays.asList(new Object[][] { { stringFactory, stringTemplateJR }, { personFactory, personTemplateJR }, { stringFactory, stringTemplate }, { personFactory, personTemplate }, { stringFactory, xstreamStringTemplate }, { personFactory, xstreamPersonTemplate }, - { stringFactory, xstreamStringTemplateJR }, { personFactory, xstreamPersonTemplateJR } }); + { stringFactory, xstreamStringTemplateJR }, { personFactory, xstreamPersonTemplateJR }, + { personFactory, jsonPersonTemplate }, { personFactory, jsonPersonTemplateJR } }); } }