001/*
002 * Copyright 2002-2019 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.codec;
018
019import java.util.Arrays;
020import java.util.List;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024
025import org.springframework.core.ResolvableType;
026import org.springframework.lang.Nullable;
027import org.springframework.util.MimeType;
028
029/**
030 * Abstract base class for {@link Decoder} implementations.
031 *
032 * @author Sebastien Deleuze
033 * @author Arjen Poutsma
034 * @since 5.0
035 * @param <T> the element type
036 */
037public abstract class AbstractEncoder<T> implements Encoder<T> {
038
039        private final List<MimeType> encodableMimeTypes;
040
041        protected Log logger = LogFactory.getLog(getClass());
042
043
044        protected AbstractEncoder(MimeType... supportedMimeTypes) {
045                this.encodableMimeTypes = Arrays.asList(supportedMimeTypes);
046        }
047
048
049        /**
050         * Set an alternative logger to use than the one based on the class name.
051         * @param logger the logger to use
052         * @since 5.1
053         */
054        public void setLogger(Log logger) {
055                this.logger = logger;
056        }
057
058        /**
059         * Return the currently configured Logger.
060         * @since 5.1
061         */
062        public Log getLogger() {
063                return logger;
064        }
065
066
067        @Override
068        public List<MimeType> getEncodableMimeTypes() {
069                return this.encodableMimeTypes;
070        }
071
072        @Override
073        public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
074                if (mimeType == null) {
075                        return true;
076                }
077                for (MimeType candidate : this.encodableMimeTypes) {
078                        if (candidate.isCompatibleWith(mimeType)) {
079                                return true;
080                        }
081                }
082                return false;
083        }
084
085}