Promote MessageRegistry to pcep-api
[bgpcep.git] / pcep / base-parser / src / main / java / org / opendaylight / protocol / pcep / parser / tlv / OFListTlvParser.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.parser.tlv;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.collect.ImmutableSet;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.buffer.Unpooled;
15 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
16 import org.opendaylight.protocol.pcep.spi.TlvParser;
17 import org.opendaylight.protocol.pcep.spi.TlvSerializer;
18 import org.opendaylight.protocol.pcep.spi.TlvUtil;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.OfId;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Tlv;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.of.list.tlv.OfList;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.of.list.tlv.OfListBuilder;
23 import org.opendaylight.yangtools.yang.common.netty.ByteBufUtils;
24
25 /**
26  * Parser for {@link OfList}.
27  */
28 public class OFListTlvParser implements TlvParser, TlvSerializer {
29     public static final int TYPE = 4;
30
31     private static final int OF_CODE_ELEMENT_LENGTH = 2;
32
33     @Override
34     public OfList parseTlv(final ByteBuf buffer) throws PCEPDeserializerException {
35         if (buffer == null) {
36             return null;
37         }
38         if (buffer.readableBytes() % OF_CODE_ELEMENT_LENGTH != 0) {
39             throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + buffer.readableBytes()
40                 + ".");
41         }
42         final var ofCodes = ImmutableSet.<OfId>builder();
43         while (buffer.isReadable()) {
44             ofCodes.add(new OfId(ByteBufUtils.readUint16(buffer)));
45         }
46         return new OfListBuilder().setCodes(ofCodes.build()).build();
47     }
48
49     @Override
50     public void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
51         checkArgument(tlv instanceof OfList, "OFListTlv is mandatory.");
52         final OfList oft = (OfList) tlv;
53         final ByteBuf body = Unpooled.buffer();
54         for (OfId id : oft.getCodes()) {
55             ByteBufUtils.write(body, id.getValue());
56         }
57         TlvUtil.formatTlv(TYPE, body, buffer);
58     }
59 }