GsonBuilderUtils for programmatic Base64 serialization setup; common Base64Utils class adapts between Java 8 and Commons Codec

Issue: SPR-9488
This commit is contained in:
Juergen Hoeller
2014-06-04 13:22:11 +02:00
parent 674bad4cfa
commit 64bb308763
5 changed files with 267 additions and 110 deletions

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2002-2014 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.http.converter.json;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.TypeAdapter;
import org.apache.commons.codec.binary.Base64;
/**
* Custom Gson {@link TypeAdapter} for serialization and deserialization
* of {@code byte[]} values to/from Base64-encoded Strings.
*
* <p>By default, Gson converts byte arrays to JSON arrays. This type adapter
* needs to be specifically registered to read/write Base64-encoded byte arrays.
*
* @author Roy Clarkson
* @since 4.1
* @see GsonBuilder#registerTypeHierarchyAdapter(Class, Object)
*/
class GsonBase64ByteArrayJsonTypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private final Base64 base64 = new Base64();
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
String encoded = new String(this.base64.encode(src), DEFAULT_CHARSET);
return new JsonPrimitive(encoded);
}
@Override
public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) {
return this.base64.decode(json.getAsString().getBytes(DEFAULT_CHARSET));
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2002-2014 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.http.converter.json;
import java.lang.reflect.Type;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.springframework.util.Base64Utils;
/**
* A simple utility class for obtaining a Google Gson 2.x {@link GsonBuilder}
* which Base64-encodes {@code byte[]} properties when reading and writing JSON.
*
* @author Juergen Hoeller
* @author Roy Clarkson
* @since 4.1
* @see GsonFactoryBean#setBase64EncodeByteArrays
* @see org.springframework.util.Base64Utils
*/
public abstract class GsonBuilderUtils {
/**
* Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]}
* properties when reading and writing JSON.
* <p>A custom {@link com.google.gson.TypeAdapter} will be registered via
* {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which
* serializes a {@code byte[]} property to and from a Base64-encoded String
* instead of a JSON array.
* <p><strong>NOTE:</strong> Use of this option requires the presence of the
* Apache Commons Codec library on the classpath when running on Java 6 or 7.
* On Java 8, the standard {@link java.util.Base64} facility is used instead.
*/
public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() {
// Assert that Base64 support is available, as long we're not on Java 8+
Base64Utils.encode(null);
// Now, construct a pre-configured GsonBuilder...
GsonBuilder builder = new GsonBuilder();
builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter());
return builder;
}
private static class Base64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64Utils.encodeToString(src));
}
@Override
public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) {
return Base64Utils.decodeFromString(json.getAsString());
}
}
}

View File

@@ -23,7 +23,6 @@ import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.ClassUtils;
/**
@@ -35,32 +34,33 @@ import org.springframework.util.ClassUtils;
*/
public class GsonFactoryBean implements FactoryBean<Gson>, InitializingBean {
/** Apache Commons Codec present on the classpath, for Base64 encoding? */
private static final boolean commonsCodecPresent = ClassUtils.isPresent(
"org.apache.commons.codec.binary.Base64", GsonFactoryBean.class.getClassLoader());
private boolean base64EncodeByteArrays = false;
private boolean serializeNulls = false;
private GsonBuilder gsonBuilder;
private boolean prettyPrinting = false;
private boolean serializeNulls;
private boolean prettyPrinting;
private boolean disableHtmlEscaping;
private boolean disableHtmlEscaping = false;
private String dateFormatPattern;
private boolean base64EncodeByteArrays;
private Gson gson;
/**
* Set the GsonBuilder instance to use.
* If not set, the GsonBuilder will be created using its default constructor.
* Whether to Base64-encode {@code byte[]} properties when reading and
* writing JSON.
* <p>When set to {@code true}, a custom {@link com.google.gson.TypeAdapter} will be
* registered via {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)}
* which serializes a {@code byte[]} property to and from a Base64-encoded String
* instead of a JSON array.
* <p><strong>NOTE:</strong> Use of this option requires the presence of the
* Apache Commons Codec library on the classpath when running on Java 6 or 7.
* On Java 8, the standard {@link java.util.Base64} facility is used instead.
* @see GsonBuilderUtils#gsonBuilderWithBase64EncodedByteArrays()
*/
public void setGsonBuilder(GsonBuilder gsonBuilder) {
this.gsonBuilder = gsonBuilder;
public void setBase64EncodeByteArrays(boolean base64EncodeByteArrays) {
this.base64EncodeByteArrays = base64EncodeByteArrays;
}
/**
@@ -108,49 +108,24 @@ public class GsonFactoryBean implements FactoryBean<Gson>, InitializingBean {
this.dateFormatPattern = dateFormatPattern;
}
/**
* Whether to Base64-encode {@code byte[]} properties when reading and
* writing JSON.
* <p>When set to {@code true} a custom {@link com.google.gson.TypeAdapter} is
* registered via {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)}
* that serializes a {@code byte[]} property to and from a Base64-encoded String
* instead of a JSON array.
* <p><strong>NOTE:</strong> Use of this option requires the presence of the
* Apache Commons Codec library on the classpath.
* @see GsonBase64ByteArrayJsonTypeAdapter
*/
public void setBase64EncodeByteArrays(boolean base64EncodeByteArrays) {
this.base64EncodeByteArrays = base64EncodeByteArrays;
}
@Override
public void afterPropertiesSet() {
if (this.gsonBuilder == null) {
this.gsonBuilder = new GsonBuilder();
}
GsonBuilder builder = (this.base64EncodeByteArrays ?
GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays() : new GsonBuilder());
if (this.serializeNulls) {
this.gsonBuilder.serializeNulls();
builder.serializeNulls();
}
if (this.prettyPrinting) {
this.gsonBuilder.setPrettyPrinting();
builder.setPrettyPrinting();
}
if (this.disableHtmlEscaping) {
this.gsonBuilder.disableHtmlEscaping();
builder.disableHtmlEscaping();
}
if (this.dateFormatPattern != null) {
this.gsonBuilder.setDateFormat(this.dateFormatPattern);
builder.setDateFormat(this.dateFormatPattern);
}
if (this.base64EncodeByteArrays) {
if (commonsCodecPresent) {
this.gsonBuilder.registerTypeHierarchyAdapter(byte[].class, new GsonBase64ByteArrayJsonTypeAdapter());
}
else {
throw new IllegalStateException(
"Apache Commons Codec is not available on the classpath - cannot enable Gson Base64 encoding");
}
}
this.gson = this.gsonBuilder.create();
this.gson = builder.create();
}