001/* 002 * Copyright 2002-2018 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.messaging.tcp.reactor; 018 019import java.nio.ByteBuffer; 020import java.util.Collection; 021import java.util.List; 022 023import io.netty.buffer.ByteBuf; 024 025import org.springframework.messaging.Message; 026 027/** 028 * Convenient base class for {@link ReactorNettyCodec} implementations that need 029 * to work with NIO {@link ByteBuffer ByteBuffers}. 030 * 031 * @author Rossen Stoyanchev 032 * @since 5.0 033 * @param <P> the message payload type 034 */ 035public abstract class AbstractNioBufferReactorNettyCodec<P> implements ReactorNettyCodec<P> { 036 037 @Override 038 public Collection<Message<P>> decode(ByteBuf inputBuffer) { 039 ByteBuffer nioBuffer = inputBuffer.nioBuffer(); 040 int start = nioBuffer.position(); 041 List<Message<P>> messages = decodeInternal(nioBuffer); 042 inputBuffer.skipBytes(nioBuffer.position() - start); 043 return messages; 044 } 045 046 @Override 047 public void encode(Message<P> message, ByteBuf outputBuffer) { 048 outputBuffer.writeBytes(encodeInternal(message)); 049 } 050 051 052 protected abstract List<Message<P>> decodeInternal(ByteBuffer nioBuffer); 053 054 protected abstract ByteBuffer encodeInternal(Message<P> message); 055 056}