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 org.reactivestreams.Publisher; 022import reactor.core.publisher.Flux; 023 024import org.springframework.core.ResolvableType; 025import org.springframework.core.io.buffer.DataBuffer; 026import org.springframework.core.io.buffer.DataBufferFactory; 027import org.springframework.lang.Nullable; 028import org.springframework.util.MimeType; 029import org.springframework.util.MimeTypeUtils; 030 031/** 032 * Simple pass-through encoder for {@link DataBuffer DataBuffers}. 033 * 034 * @author Arjen Poutsma 035 * @since 5.0 036 */ 037public class DataBufferEncoder extends AbstractEncoder<DataBuffer> { 038 039 public DataBufferEncoder() { 040 super(MimeTypeUtils.ALL); 041 } 042 043 044 @Override 045 public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) { 046 Class<?> clazz = elementType.toClass(); 047 return super.canEncode(elementType, mimeType) && DataBuffer.class.isAssignableFrom(clazz); 048 } 049 050 @Override 051 public Flux<DataBuffer> encode(Publisher<? extends DataBuffer> inputStream, 052 DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType, 053 @Nullable Map<String, Object> hints) { 054 055 Flux<DataBuffer> flux = Flux.from(inputStream); 056 if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) { 057 flux = flux.doOnNext(buffer -> logValue(buffer, hints)); 058 } 059 return flux; 060 } 061 062 @Override 063 public DataBuffer encodeValue(DataBuffer buffer, DataBufferFactory bufferFactory, 064 ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { 065 066 if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) { 067 logValue(buffer, hints); 068 } 069 return buffer; 070 } 071 072 private void logValue(DataBuffer buffer, @Nullable Map<String, Object> hints) { 073 String logPrefix = Hints.getLogPrefix(hints); 074 logger.debug(logPrefix + "Writing " + buffer.readableByteCount() + " bytes"); 075 } 076 077}