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 io.netty.buffer.ByteBuf;
11 import io.netty.buffer.ByteBufUtil;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
15 import java.util.ArrayList;
16 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.protocol.util.ByteArray;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
26 import com.google.common.base.Preconditions;
27 import com.google.common.primitives.UnsignedBytes;
30 * A PCEP message parser which also does validation.
32 public final class PCEPByteToMessageDecoder extends ByteToMessageDecoder {
33 private static final Logger LOG = LoggerFactory.getLogger(PCEPByteToMessageDecoder.class);
35 private static final int TYPE_SIZE = 1;
37 private static final int LENGTH_SIZE = 2;
39 private final MessageRegistry registry;
41 public PCEPByteToMessageDecoder(final MessageRegistry registry) {
42 this.registry = Preconditions.checkNotNull(registry);
46 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
47 if (in.readableBytes() == 0) {
48 LOG.debug("No more content in incoming buffer.");
53 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
54 final byte[] bytes = new byte[in.readableBytes()];
57 final List<Message> errors = new ArrayList<>();
60 out.add(parse(bytes, errors));
61 } catch (final PCEPDeserializerException e) {
62 LOG.debug("Failed to decode protocol message", e);
63 this.exceptionCaught(ctx, e);
65 in.discardReadBytes();
67 if (!errors.isEmpty()) {
68 // We have a bunch of messages, send them out
69 for (final Object e : errors) {
70 ctx.channel().write(e);
72 ctx.channel().flush();
76 private Message parse(final byte[] bytes, final List<Message> errors) throws PCEPDeserializerException {
77 final int type = UnsignedBytes.toInt(bytes[1]);
78 final int msgLength = ByteArray.bytesToInt(ByteArray.subByte(bytes, TYPE_SIZE + 1, LENGTH_SIZE));
80 final byte[] msgBody = ByteArray.cutBytes(bytes, TYPE_SIZE + 1 + LENGTH_SIZE);
81 if (msgBody.length != msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH) {
82 throw new PCEPDeserializerException("Body size " + msgBody.length + " does not match header size "
83 + (msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH));
85 return this.registry.parseMessage(type, msgBody, errors);