001/*
002 * Copyright 2002-2020 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 org.springframework.core.convert.converter.Converter;
020import org.springframework.core.serializer.DefaultSerializer;
021import org.springframework.core.serializer.Serializer;
022import org.springframework.util.Assert;
023
024/**
025 * A {@link Converter} that delegates to a
026 * {@link org.springframework.core.serializer.Serializer}
027 * to convert an object to a byte array.
028 *
029 * @author Gary Russell
030 * @author Mark Fisher
031 * @since 3.0.5
032 */
033public class SerializingConverter implements Converter<Object, byte[]> {
034
035        private final Serializer<Object> serializer;
036
037
038        /**
039         * Create a default {@code SerializingConverter} that uses standard Java serialization.
040         */
041        public SerializingConverter() {
042                this.serializer = new DefaultSerializer();
043        }
044
045        /**
046         * Create a {@code SerializingConverter} that delegates to the provided {@link Serializer}.
047         */
048        public SerializingConverter(Serializer<Object> serializer) {
049                Assert.notNull(serializer, "Serializer must not be null");
050                this.serializer = serializer;
051        }
052
053
054        /**
055         * Serializes the source object and returns the byte array result.
056         */
057        @Override
058        public byte[] convert(Object source) {
059                try  {
060                        return this.serializer.serializeToByteArray(source);
061                }
062                catch (Throwable ex) {
063                        throw new SerializationFailedException("Failed to serialize object using " +
064                                        this.serializer.getClass().getSimpleName(), ex);
065                }
066        }
067
068}