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.impl.object;
10 import com.google.common.base.Preconditions;
11 import com.google.common.primitives.UnsignedBytes;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.buffer.ByteBufUtil;
16 import java.util.ArrayList;
17 import java.util.List;
19 import org.opendaylight.protocol.pcep.spi.ObjectParser;
20 import org.opendaylight.protocol.pcep.spi.ObjectSerializer;
21 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
22 import org.opendaylight.protocol.pcep.spi.RROSubobjectRegistry;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.reported.route.object.rro.Subobject;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
27 public abstract class AbstractRROWithSubobjectsParser implements ObjectParser, ObjectSerializer {
29 private static final Logger LOG = LoggerFactory.getLogger(AbstractRROWithSubobjectsParser.class);
31 private final RROSubobjectRegistry subobjReg;
33 private static final int HEADER_LENGTH = 2;
35 protected AbstractRROWithSubobjectsParser(final RROSubobjectRegistry subobjReg) {
36 this.subobjReg = Preconditions.checkNotNull(subobjReg);
39 protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
40 Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
41 final List<Subobject> subs = new ArrayList<>();
42 while (buffer.isReadable()) {
43 int type = UnsignedBytes.toInt(buffer.readByte());
44 int length = UnsignedBytes.toInt(buffer.readByte()) - HEADER_LENGTH;
45 if (length > buffer.readableBytes()) {
46 throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
47 + buffer.readableBytes());
49 LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
50 final Subobject sub = this.subobjReg.parseSubobject(type, buffer.slice(buffer.readerIndex(), length));
52 LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
54 LOG.debug("Subobject was parsed. {}", sub);
57 buffer.readerIndex(buffer.readerIndex() + length);
62 protected final void serializeSubobject(final List<Subobject> subobjects, final ByteBuf buffer) {
63 for (final Subobject subobject : subobjects) {
64 this.subobjReg.serializeSubobject(subobject, buffer);