001/*
002 * Copyright 2002-2015 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.core.serializer.support;
018
019import java.io.ByteArrayOutputStream;
020
021import org.springframework.core.convert.converter.Converter;
022import org.springframework.core.serializer.DefaultSerializer;
023import org.springframework.core.serializer.Serializer;
024import org.springframework.util.Assert;
025
026/**
027 * A {@link Converter} that delegates to a
028 * {@link org.springframework.core.serializer.Serializer}
029 * to convert an object to a byte array.
030 *
031 * @author Gary Russell
032 * @author Mark Fisher
033 * @since 3.0.5
034 */
035public class SerializingConverter implements Converter<Object, byte[]> {
036
037        private final Serializer<Object> serializer;
038
039
040        /**
041         * Create a default {@code SerializingConverter} that uses standard Java serialization.
042         */
043        public SerializingConverter() {
044                this.serializer = new DefaultSerializer();
045        }
046
047        /**
048         * Create a {@code SerializingConverter} that delegates to the provided {@link Serializer}.
049         */
050        public SerializingConverter(Serializer<Object> serializer) {
051                Assert.notNull(serializer, "Serializer must not be null");
052                this.serializer = serializer;
053        }
054
055
056        /**
057         * Serializes the source object and returns the byte array result.
058         */
059        @Override
060        public byte[] convert(Object source) {
061                ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024);
062                try  {
063                        this.serializer.serialize(source, byteStream);
064                        return byteStream.toByteArray();
065                }
066                catch (Throwable ex) {
067                        throw new SerializationFailedException("Failed to serialize object using " +
068                                        this.serializer.getClass().getSimpleName(), ex);
069                }
070        }
071
072}