2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.pcep.impl;
10 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.ByteBufUtil;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.ByteToMessageDecoder;
17 import java.util.ArrayList;
18 import java.util.List;
20 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
21 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
22 import org.opendaylight.protocol.pcep.spi.PCEPMessageConstants;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 * A PCEP message parser which also does validation.
30 public final class PCEPByteToMessageDecoder extends ByteToMessageDecoder {
31 private static final Logger LOG = LoggerFactory.getLogger(PCEPByteToMessageDecoder.class);
33 private final MessageRegistry registry;
35 public PCEPByteToMessageDecoder(final MessageRegistry registry) {
36 this.registry = Preconditions.checkNotNull(registry);
40 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
41 if (!in.isReadable()) {
42 LOG.debug("No more content in incoming buffer.");
47 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
49 final List<Message> errors = new ArrayList<>();
52 out.add(parse(in, errors));
53 } catch (final PCEPDeserializerException e) {
54 LOG.debug("Failed to decode protocol message", e);
55 this.exceptionCaught(ctx, e);
57 in.discardReadBytes();
59 if (!errors.isEmpty()) {
60 // We have a bunch of messages, send them out
61 for (final Object e : errors) {
62 ctx.channel().write(e);
64 ctx.channel().flush();
68 private Message parse(final ByteBuf buffer, final List<Message> errors) throws PCEPDeserializerException {
69 buffer.readerIndex(buffer.readerIndex() + 1);
70 final int type = buffer.readUnsignedByte();
71 final int msgLength = buffer.readUnsignedShort();
72 final int actualLength = buffer.readableBytes();
73 final ByteBuf msgBody = buffer.slice();
74 if (actualLength != msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH) {
75 throw new PCEPDeserializerException("Body size " + actualLength + " does not match header size "
76 + (msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH));
78 buffer.readerIndex(buffer.readerIndex() + actualLength);
79 return this.registry.parseMessage(type, msgBody, errors);