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;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.ByteBufUtil;
13 import io.netty.channel.ChannelFutureListener;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.ByteToMessageDecoder;
16 import java.util.ArrayList;
17 import java.util.List;
18 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
19 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
20 import org.opendaylight.protocol.pcep.spi.PCEPMessageConstants;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * A PCEP message parser which also does validation.
28 public final class PCEPByteToMessageDecoder extends ByteToMessageDecoder {
29 private static final Logger LOG = LoggerFactory.getLogger(PCEPByteToMessageDecoder.class);
31 private final MessageRegistry registry;
33 public PCEPByteToMessageDecoder(final MessageRegistry registry) {
34 this.registry = Preconditions.checkNotNull(registry);
38 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
39 if (!in.isReadable()) {
40 LOG.debug("No more content in incoming buffer.");
45 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
47 final List<Message> errors = new ArrayList<>();
50 out.add(parse(in, errors));
51 } catch (final PCEPDeserializerException e) {
52 LOG.debug("Failed to decode protocol message", e);
54 in.discardReadBytes();
56 if (!errors.isEmpty()) {
57 // We have a bunch of messages, send them out
58 for (final Object e : errors) {
59 ctx.channel().writeAndFlush(e).addListener((ChannelFutureListener) f -> {
61 LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause());
63 LOG.trace("Message {} sent to socket {}", e, ctx.channel());
70 private Message parse(final ByteBuf buffer, final List<Message> errors) throws PCEPDeserializerException {
72 final int type = buffer.readUnsignedByte();
73 final int msgLength = buffer.readUnsignedShort();
74 final int actualLength = buffer.readableBytes();
75 final ByteBuf msgBody = buffer.slice();
76 if (actualLength != msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH) {
77 throw new PCEPDeserializerException("Body size " + actualLength + " does not match header size "
78 + (msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH));
80 buffer.skipBytes(actualLength);
81 return this.registry.parseMessage(type, msgBody, errors);