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.nio.ByteBuffer; 020import java.util.Map; 021 022import org.springframework.core.ResolvableType; 023import org.springframework.core.io.buffer.DataBuffer; 024import org.springframework.core.io.buffer.DataBufferUtils; 025import org.springframework.lang.Nullable; 026import org.springframework.util.MimeType; 027import org.springframework.util.MimeTypeUtils; 028 029/** 030 * Decoder for {@link ByteBuffer ByteBuffers}. 031 * 032 * @author Sebastien Deleuze 033 * @author Arjen Poutsma 034 * @author Rossen Stoyanchev 035 * @since 5.0 036 */ 037public class ByteBufferDecoder extends AbstractDataBufferDecoder<ByteBuffer> { 038 039 public ByteBufferDecoder() { 040 super(MimeTypeUtils.ALL); 041 } 042 043 044 @Override 045 public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) { 046 return (ByteBuffer.class.isAssignableFrom(elementType.toClass()) && 047 super.canDecode(elementType, mimeType)); 048 } 049 050 @Override 051 public ByteBuffer decode(DataBuffer dataBuffer, ResolvableType elementType, 052 @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { 053 054 int byteCount = dataBuffer.readableByteCount(); 055 ByteBuffer copy = ByteBuffer.allocate(byteCount); 056 copy.put(dataBuffer.asByteBuffer()); 057 copy.flip(); 058 DataBufferUtils.release(dataBuffer); 059 if (logger.isDebugEnabled()) { 060 logger.debug(Hints.getLogPrefix(hints) + "Read " + byteCount + " bytes"); 061 } 062 return copy; 063 } 064 065}