YANG revision dates mass-update
[bgpcep.git] / bmp / bmp-spi / src / main / java / org / opendaylight / protocol / bmp / spi / parser / AbstractBmpMessageWithTlvParser.java
1 /*
2  * Copyright (c) 2015 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
9 package org.opendaylight.protocol.bmp.spi.parser;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.Preconditions;
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.ByteBufUtil;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.message.rev200120.Tlv;
17 import org.opendaylight.yangtools.concepts.Builder;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 public abstract class AbstractBmpMessageWithTlvParser<T extends Builder<?>> extends AbstractBmpMessageParser {
22
23     private static final Logger LOG = LoggerFactory.getLogger(AbstractBmpMessageWithTlvParser.class);
24
25     private final BmpTlvRegistry tlvRegistry;
26
27     public AbstractBmpMessageWithTlvParser(final BmpTlvRegistry tlvRegistry) {
28         this.tlvRegistry = tlvRegistry;
29     }
30
31     protected final void parseTlvs(final T builder, final ByteBuf bytes) throws BmpDeserializationException {
32         Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
33         if (!bytes.isReadable()) {
34             return;
35         }
36         while (bytes.isReadable()) {
37             final int type = bytes.readUnsignedShort();
38             final int length = bytes.readUnsignedShort();
39             if (length > bytes.readableBytes()) {
40                 throw new BmpDeserializationException("Wrong length specified. Passed: " + length
41                         + "; Expected: <= " + bytes.readableBytes() + ".");
42             }
43             final ByteBuf tlvBytes = bytes.readSlice(length);
44             LOG.trace("Parsing BMP TLV : {}", ByteBufUtil.hexDump(tlvBytes));
45
46             final Tlv tlv = this.tlvRegistry.parseTlv(type, tlvBytes);
47             if (tlv != null) {
48                 LOG.trace("Parsed BMP TLV {}.", tlv);
49                 addTlv(builder, tlv);
50             }
51         }
52     }
53
54     protected final void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
55         requireNonNull(tlv, "BMP TLV is mandatory.");
56         LOG.trace("Serializing BMP TLV {}", tlv);
57         this.tlvRegistry.serializeTlv(tlv, buffer);
58         LOG.trace("Serialized BMP TLV : {}.", ByteBufUtil.hexDump(buffer));
59     }
60
61     protected void addTlv(final T builder, final Tlv tlv) {
62         //no TLVs by default
63     }
64
65 }