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