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.Map; 020 021import reactor.core.publisher.Flux; 022 023import org.springframework.core.ResolvableType; 024import org.springframework.core.io.Resource; 025import org.springframework.core.io.buffer.DataBuffer; 026import org.springframework.core.io.buffer.DataBufferFactory; 027import org.springframework.core.io.buffer.DataBufferUtils; 028import org.springframework.lang.Nullable; 029import org.springframework.util.Assert; 030import org.springframework.util.MimeType; 031import org.springframework.util.MimeTypeUtils; 032import org.springframework.util.StreamUtils; 033 034/** 035 * Encoder for {@link Resource Resources}. 036 * 037 * @author Arjen Poutsma 038 * @since 5.0 039 */ 040public class ResourceEncoder extends AbstractSingleValueEncoder<Resource> { 041 042 /** 043 * The default buffer size used by the encoder. 044 */ 045 public static final int DEFAULT_BUFFER_SIZE = StreamUtils.BUFFER_SIZE; 046 047 private final int bufferSize; 048 049 050 public ResourceEncoder() { 051 this(DEFAULT_BUFFER_SIZE); 052 } 053 054 public ResourceEncoder(int bufferSize) { 055 super(MimeTypeUtils.APPLICATION_OCTET_STREAM, MimeTypeUtils.ALL); 056 Assert.isTrue(bufferSize > 0, "'bufferSize' must be larger than 0"); 057 this.bufferSize = bufferSize; 058 } 059 060 061 @Override 062 public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) { 063 Class<?> clazz = elementType.toClass(); 064 return (super.canEncode(elementType, mimeType) && Resource.class.isAssignableFrom(clazz)); 065 } 066 067 @Override 068 protected Flux<DataBuffer> encode(Resource resource, DataBufferFactory bufferFactory, 069 ResolvableType type, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { 070 071 if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) { 072 String logPrefix = Hints.getLogPrefix(hints); 073 logger.debug(logPrefix + "Writing [" + resource + "]"); 074 } 075 return DataBufferUtils.read(resource, bufferFactory, this.bufferSize); 076 } 077 078}