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 java.util.Arrays;
12 import org.opendaylight.protocol.util.ByteArray;
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 import com.google.common.base.Preconditions;
19 public abstract class AbstractObjectWithTlvsParser<T> implements ObjectParser, ObjectSerializer {
21 private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectWithTlvsParser.class);
23 private static final int TLV_TYPE_F_LENGTH = 2;
24 private static final int TLV_LENGTH_F_LENGTH = 2;
25 private static final int TLV_HEADER_LENGTH = TLV_LENGTH_F_LENGTH + TLV_TYPE_F_LENGTH;
27 protected static final int PADDED_TO = 4;
29 private final TlvRegistry tlvReg;
31 protected AbstractObjectWithTlvsParser(final TlvRegistry tlvReg) {
32 this.tlvReg = Preconditions.checkNotNull(tlvReg);
35 protected final void parseTlvs(final T builder, final byte[] bytes) throws PCEPDeserializerException {
37 throw new IllegalArgumentException("Byte array is mandatory.");
39 if (bytes.length == 0) {
47 while (byteOffset < bytes.length) {
48 type = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_TYPE_F_LENGTH));
49 byteOffset += TLV_TYPE_F_LENGTH;
50 length = ByteArray.bytesToInt(ByteArray.subByte(bytes, byteOffset, TLV_LENGTH_F_LENGTH));
51 byteOffset += TLV_LENGTH_F_LENGTH;
53 if (TLV_HEADER_LENGTH + length > bytes.length) {
54 throw new PCEPDeserializerException("Wrong length specified. Passed: " + (TLV_HEADER_LENGTH + length) + "; Expected: <= "
55 + (bytes.length - byteOffset) + ".");
58 final byte[] tlvBytes = ByteArray.subByte(bytes, byteOffset, length);
60 LOG.trace("Attempt to parse tlv from bytes: {}", ByteArray.bytesToHexString(tlvBytes));
61 final Tlv tlv = this.tlvReg.parseTlv(type, tlvBytes);
62 LOG.trace("Tlv was parsed. {}", tlv);
64 byteOffset += length + getPadding(TLV_HEADER_LENGTH + length, PADDED_TO);
68 protected final byte[] serializeTlv(final Tlv tlv) {
69 Preconditions.checkNotNull(tlv, "PCEP TLV is mandatory.");
70 LOG.trace("Serializing PCEP TLV {}", tlv);
71 final byte[] ret = this.tlvReg.serializeTlv(tlv);
73 LOG.warn("TLV serializer for type {} could not be found.", tlv);
75 LOG.trace("Serialized PCEP TLV {}.", Arrays.toString(ret));
79 protected void addTlv(final T builder, final Tlv tlv) {
80 // FIXME: No TLVs by default, fallback to augments
83 public static int getPadding(final int length, final int padding) {
84 return (padding - (length % padding)) % padding;