Merge changes I28a3cc76,I23256575,Id1c370b9
[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.buffer.ByteBufUtil;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14
15 import java.util.List;
16
17 import com.google.common.base.Preconditions;
18
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 public final class ProtocolMessageDecoder<T> extends ByteToMessageDecoder {
23
24         private final static Logger LOG = LoggerFactory.getLogger(ProtocolMessageDecoder.class);
25
26         private final ProtocolMessageFactory<T> factory;
27
28         public ProtocolMessageDecoder(final ProtocolMessageFactory<T> factory) {
29                 this.factory = Preconditions.checkNotNull(factory);
30         }
31
32         @Override
33         protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
34                 if (in.readableBytes() == 0) {
35                         LOG.debug("No more content in incoming buffer.");
36                         return;
37                 }
38                 in.markReaderIndex();
39                 try {
40                         LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
41                         final byte[] bytes = new byte[in.readableBytes()];
42                         in.readBytes(bytes);
43                         out.add(this.factory.parse(bytes));
44                 } catch (DeserializerException | DocumentedException e) {
45                         LOG.debug("Failed to decode protocol message", e);
46                         this.exceptionCaught(ctx, e);
47                 }
48                 in.discardReadBytes();
49         }
50 }