View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.core.serializer.support;
18  
19  import java.io.ByteArrayOutputStream;
20  
21  import org.springframework.core.convert.converter.Converter;
22  import org.springframework.core.serializer.DefaultSerializer;
23  import org.springframework.core.serializer.Serializer;
24  import org.springframework.util.Assert;
25  
26  /**
27   * A {@link Converter} that delegates to a {@link org.springframework.core.serializer.Serializer}
28   * to convert an object to a byte array.
29   *
30   * @author Gary Russell
31   * @author Mark Fisher
32   * @since 3.0.5
33   */
34  public class SerializingConverter implements Converter<Object, byte[]> {
35  
36  	private final Serializer<Object> serializer;
37  
38  
39  	/**
40  	 * Create a default SerializingConverter that uses standard Java serialization.
41  	 */
42  	public SerializingConverter() {
43  		this.serializer = new DefaultSerializer();
44  	}
45  
46  	/**
47  	 * Create a SerializingConverter that delegates to the provided {@link Serializer}
48  	 */
49  	public SerializingConverter(Serializer<Object> serializer) {
50  		Assert.notNull(serializer, "Serializer must not be null");
51  		this.serializer = serializer;
52  	}
53  
54  
55  	/**
56  	 * Serializes the source object and returns the byte array result.
57  	 */
58  	@Override
59  	public byte[] convert(Object source) {
60  		ByteArrayOutputStream byteStream = new ByteArrayOutputStream(256);
61  		try  {
62  			this.serializer.serialize(source, byteStream);
63  			return byteStream.toByteArray();
64  		}
65  		catch (Throwable ex) {
66  			throw new SerializationFailedException("Failed to serialize object using " +
67  					this.serializer.getClass().getSimpleName(), ex);
68  		}
69  	}
70  
71  }