BUG-54 : switched channel pipeline to be protocol specific.
[bgpcep.git] / framework / src / main / java / org / opendaylight / protocol / framework / ProtocolMessageDecoder.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.framework;
9
10 import io.netty.buffer.ByteBuf;
11 import io.netty.channel.ChannelHandlerContext;
12 import io.netty.handler.codec.ByteToMessageDecoder;
13
14 import java.util.Arrays;
15 import java.util.List;
16
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 public final class ProtocolMessageDecoder<T extends ProtocolMessage> extends ByteToMessageDecoder {
21
22         private final static Logger logger = LoggerFactory.getLogger(ProtocolMessageDecoder.class);
23
24         private final ProtocolMessageFactory<T> factory;
25
26         public ProtocolMessageDecoder(final ProtocolMessageFactory<T> factory) {
27                 this.factory = factory;
28         }
29
30         @Override
31         protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
32                 if (in.readableBytes() == 0) {
33                         logger.debug("No more content in incoming buffer.");
34                         return;
35                 }
36                 in.markReaderIndex();
37                 try {
38                         final byte[] bytes = new byte[in.readableBytes()];
39                         in.readBytes(bytes);
40                         logger.debug("Received to decode: {}", Arrays.toString(bytes));
41                         out.addAll(this.factory.parse(bytes));
42                 } catch (DeserializerException | DocumentedException e) {
43                         logger.debug("Failed to decode protocol message", e);
44                         this.exceptionCaught(ctx, e);
45                 }
46                 in.discardReadBytes();
47         }
48 }