1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
28
29
30
31
32
33
34 public class SerializingConverter implements Converter<Object, byte[]> {
35
36 private final Serializer<Object> serializer;
37
38
39
40
41
42 public SerializingConverter() {
43 this.serializer = new DefaultSerializer();
44 }
45
46
47
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
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 }