Java tutorial
/** * This file is part of Trinity. * * Copyright (c) 2014 Agustin L. Alvarez <<wolftein1@gmail.com>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trinity.engine.protocol.detail; import com.trinity.engine.protocol.MessageLookupService; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import java.util.List; /** * Define the {@link ReplayingDecoder} for handling header * <p> * It will convert raw frames to message frames */ public final class ConnectionReplayingDecoder extends ReplayingDecoder<ConnectionReplayingDecoder.DecoderState> { private final MessageLookupService mLookupService; private int mMessageId; private int mMessageLength; /** * Default constructor for {@link ConnectionReplayingDecoder} * * @param service the service of the decoder */ protected ConnectionReplayingDecoder(MessageLookupService service) { super(DecoderState.READ_ID); this.mLookupService = service; } /** * {@inheritDoc} */ @Override protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception { switch (state()) { case READ_ID: mMessageId = input.readUnsignedByte(); checkpoint(DecoderState.READ_LENGTH); break; case READ_LENGTH: mMessageLength = input.readUnsignedShort(); checkpoint(DecoderState.READ_CONTENT); break; case READ_CONTENT: output.add(mLookupService.decode(mMessageId, input.readBytes(mMessageLength))); checkpoint(DecoderState.READ_ID); } } /** * All possible states of {@link ConnectionReplayingDecoder} */ protected static enum DecoderState { READ_ID, READ_LENGTH, READ_CONTENT } }