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.spi;
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;
17 public abstract class AbstractObjectWithTlvsParser<T> implements ObjectParser, ObjectSerializer {
19 private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectWithTlvsParser.class);
21 private static final int TLV_TYPE_F_LENGTH = 2;
22 private static final int TLV_LENGTH_F_LENGTH = 2;
23 private static final int TLV_HEADER_LENGTH = TLV_LENGTH_F_LENGTH + TLV_TYPE_F_LENGTH;
25 public static final int PADDED_TO = 4;
27 private final TlvRegistry tlvReg;
29 protected AbstractObjectWithTlvsParser(final TlvRegistry tlvReg) {
30 this.tlvReg = Preconditions.checkNotNull(tlvReg);
33 protected final void parseTlvs(final T builder, final ByteBuf bytes) throws PCEPDeserializerException {
34 Preconditions.checkArgument(bytes != null, "Array of bytes is mandatory. Can't be null.");
35 if (!bytes.isReadable()) {
38 while (bytes.isReadable()) {
39 int type = bytes.readUnsignedShort();
40 int length = bytes.readUnsignedShort();
41 if (length > bytes.readableBytes()) {
42 throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= " + bytes.readableBytes()
45 final ByteBuf tlvBytes = bytes.slice(bytes.readerIndex(), length);
46 LOG.trace("Parsing PCEP TLV : {}", ByteBufUtil.hexDump(tlvBytes));
47 final Tlv tlv = this.tlvReg.parseTlv(type, tlvBytes);
48 LOG.trace("Parsed PCEP TLV {}.", tlv);
50 bytes.skipBytes(length + TlvUtil.getPadding(TlvUtil.HEADER_SIZE + length, TlvUtil.PADDED_TO));
54 protected final void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
55 Preconditions.checkNotNull(tlv, "PCEP TLV is mandatory.");
56 LOG.trace("Serializing PCEP TLV {}", tlv);
57 this.tlvReg.serializeTlv(tlv, buffer);
58 LOG.trace("Serialized PCEP TLV : {}.", ByteBufUtil.hexDump(buffer));
61 protected void addTlv(final T builder, final Tlv tlv) {
62 // FIXME: No TLVs by default, fallback to augments