Clean up ShortestPathFirst
[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.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 public abstract class AbstractBmpMessageWithTlvParser<T> extends AbstractBmpMessageParser {
21
22     private static final Logger LOG = LoggerFactory.getLogger(AbstractBmpMessageWithTlvParser.class);
23
24     private final BmpTlvRegistry tlvRegistry;
25
26     public AbstractBmpMessageWithTlvParser(final BmpTlvRegistry tlvRegistry) {
27         this.tlvRegistry = tlvRegistry;
28     }
29
30     protected final void parseTlvs(final T builder, final ByteBuf bytes) throws BmpDeserializationException {
31         Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
32         if (!bytes.isReadable()) {
33             return;
34         }
35         while (bytes.isReadable()) {
36             final int type = bytes.readUnsignedShort();
37             final int length = bytes.readUnsignedShort();
38             if (length > bytes.readableBytes()) {
39                 throw new BmpDeserializationException("Wrong length specified. Passed: " + length
40                         + "; Expected: <= " + bytes.readableBytes() + ".");
41             }
42             final ByteBuf tlvBytes = bytes.readSlice(length);
43             LOG.trace("Parsing BMP TLV : {}", ByteBufUtil.hexDump(tlvBytes));
44
45             final Tlv tlv = this.tlvRegistry.parseTlv(type, tlvBytes);
46             if (tlv != null) {
47                 LOG.trace("Parsed BMP TLV {}.", tlv);
48                 addTlv(builder, tlv);
49             }
50         }
51     }
52
53     protected final void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
54         requireNonNull(tlv, "BMP TLV is mandatory.");
55         LOG.trace("Serializing BMP TLV {}", tlv);
56         this.tlvRegistry.serializeTlv(tlv, buffer);
57         LOG.trace("Serialized BMP TLV : {}.", ByteBufUtil.hexDump(buffer));
58     }
59
60     protected void addTlv(final T builder, final Tlv tlv) {
61         //no TLVs by default
62     }
63
64 }