5d2548ef042b87d39df455c26db6b0b92cf6fc68
[bgpcep.git] / pcep / spi / src / main / java / org / opendaylight / protocol / pcep / spi / AbstractObjectWithTlvsParser.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.protocol.pcep.spi;
9
10 import com.google.common.base.Preconditions;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.ByteBufUtil;
13 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16
17 public abstract class AbstractObjectWithTlvsParser<T> implements ObjectParser, ObjectSerializer {
18
19     private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectWithTlvsParser.class);
20
21     private final TlvRegistry tlvReg;
22
23     protected AbstractObjectWithTlvsParser(final TlvRegistry tlvReg) {
24         this.tlvReg = Preconditions.checkNotNull(tlvReg);
25     }
26
27     protected final void parseTlvs(final T builder, final ByteBuf bytes) throws PCEPDeserializerException {
28         Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
29         if (!bytes.isReadable()) {
30             return;
31         }
32         while (bytes.isReadable()) {
33             int type = bytes.readUnsignedShort();
34             int length = bytes.readUnsignedShort();
35             if (length > bytes.readableBytes()) {
36                 throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= " + bytes.readableBytes()
37                     + ".");
38             }
39             final ByteBuf tlvBytes = bytes.slice(bytes.readerIndex(), length);
40             LOG.trace("Parsing PCEP TLV : {}", ByteBufUtil.hexDump(tlvBytes));
41             final Tlv tlv = this.tlvReg.parseTlv(type, tlvBytes);
42             LOG.trace("Parsed PCEP TLV {}.", tlv);
43             addTlv(builder, tlv);
44             bytes.skipBytes(length + TlvUtil.getPadding(TlvUtil.HEADER_SIZE + length, TlvUtil.PADDED_TO));
45         }
46     }
47
48     protected final void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
49         Preconditions.checkNotNull(tlv, "PCEP TLV is mandatory.");
50         LOG.trace("Serializing PCEP TLV {}", tlv);
51         this.tlvReg.serializeTlv(tlv, buffer);
52         LOG.trace("Serialized PCEP TLV : {}.", ByteBufUtil.hexDump(buffer));
53     }
54
55     protected void addTlv(final T builder, final Tlv tlv) {
56         // FIXME: No TLVs by default, fallback to augments
57     }
58 }