BUG-2794 : refactored code to use BitArray
[bgpcep.git] / pcep / ietf-stateful07 / src / main / java / org / opendaylight / protocol / pcep / ietf / stateful07 / Stateful07StatefulCapabilityTlvParser.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.ietf.stateful07;
9
10 import com.google.common.base.Preconditions;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.Unpooled;
13 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
14 import org.opendaylight.protocol.pcep.spi.TlvParser;
15 import org.opendaylight.protocol.pcep.spi.TlvSerializer;
16 import org.opendaylight.protocol.pcep.spi.TlvUtil;
17 import org.opendaylight.protocol.util.BitArray;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.Stateful;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
21
22 /**
23  * Parser for {@link Stateful}
24  */
25 public class Stateful07StatefulCapabilityTlvParser implements TlvParser, TlvSerializer {
26
27     public static final int TYPE = 16;
28
29     protected static final int FLAGS_F_LENGTH = 32;
30
31     protected static final int U_FLAG_OFFSET = 31;
32
33     @Override
34     public Stateful parseTlv(final ByteBuf buffer) throws PCEPDeserializerException {
35         if (buffer == null) {
36             return null;
37         }
38         if (buffer.readableBytes() < FLAGS_F_LENGTH / Byte.SIZE) {
39             throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + buffer.readableBytes() + "; Expected: >= "
40                     + FLAGS_F_LENGTH / Byte.SIZE + ".");
41         }
42         final BitArray flags = BitArray.valueOf(buffer, FLAGS_F_LENGTH);
43         final StatefulBuilder sb = new StatefulBuilder();
44         sb.setLspUpdateCapability(flags.get(U_FLAG_OFFSET));
45         return sb.build();
46     }
47
48     @Override
49     public void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
50         Preconditions.checkArgument(tlv instanceof Stateful, "StatefulCapabilityTlv is mandatory.");
51         final Stateful sct = (Stateful) tlv;
52         final BitArray flags = new BitArray(FLAGS_F_LENGTH);
53         flags.set(U_FLAG_OFFSET, sct.isLspUpdateCapability());
54         TlvUtil.formatTlv(TYPE, Unpooled.wrappedBuffer(flags.array()), buffer);
55     }
56 }