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.ChannelHandlerContext;
14 import io.netty.handler.codec.ByteToMessageDecoder;
15 import java.util.ArrayList;
16 import java.util.List;
17 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
18 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
19 import org.opendaylight.protocol.pcep.spi.PCEPMessageConstants;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * A PCEP message parser which also does validation.
27 public final class PCEPByteToMessageDecoder extends ByteToMessageDecoder {
28 private static final Logger LOG = LoggerFactory.getLogger(PCEPByteToMessageDecoder.class);
30 private final MessageRegistry registry;
32 public PCEPByteToMessageDecoder(final MessageRegistry registry) {
33 this.registry = Preconditions.checkNotNull(registry);
37 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
38 if (!in.isReadable()) {
39 LOG.debug("No more content in incoming buffer.");
44 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
46 final List<Message> errors = new ArrayList<>();
49 out.add(parse(in, errors));
50 } catch (final PCEPDeserializerException e) {
51 LOG.debug("Failed to decode protocol message", e);
53 in.discardReadBytes();
55 if (!errors.isEmpty()) {
56 // We have a bunch of messages, send them out
57 for (final Object e : errors) {
64 private Message parse(final ByteBuf buffer, final List<Message> errors) throws PCEPDeserializerException {
66 final int type = buffer.readUnsignedByte();
67 final int msgLength = buffer.readUnsignedShort();
68 final int actualLength = buffer.readableBytes();
69 final ByteBuf msgBody = buffer.slice();
70 if (actualLength != msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH) {
71 throw new PCEPDeserializerException("Body size " + actualLength + " does not match header size "
72 + (msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH));
74 buffer.skipBytes(actualLength);
75 return this.registry.parseMessage(type, msgBody, errors);