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.tlv;
10 import java.util.Arrays;
11 import java.util.List;
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.util.ByteArray;
17 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OfId;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.of.list.tlv.OfList;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.of.list.tlv.OfListBuilder;
22 import com.google.common.collect.Lists;
25 * Parser for {@link OfList}
27 public class OFListTlvParser implements TlvParser, TlvSerializer {
29 public static final int TYPE = 4;
31 private static final int OF_CODE_ELEMENT_LENGTH = 2;
34 public OfList parseTlv(final byte[] valueBytes) throws PCEPDeserializerException {
35 if (valueBytes == null || valueBytes.length == 0) {
36 throw new IllegalArgumentException("Value bytes array is mandatory. Can't be null or empty.");
38 if (valueBytes.length % OF_CODE_ELEMENT_LENGTH != 0) {
39 throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + valueBytes.length + ".");
41 final List<OfId> ofCodes = Lists.newArrayList();
42 for (int i = 0; i < valueBytes.length; i += OF_CODE_ELEMENT_LENGTH) {
43 ofCodes.add(new OfId(ByteArray.bytesToShort(Arrays.copyOfRange(valueBytes, i, i + OF_CODE_ELEMENT_LENGTH)) & 0xFFFF));
45 return new OfListBuilder().setCodes(ofCodes).build();
49 public byte[] serializeTlv(final Tlv tlv) {
51 throw new IllegalArgumentException("OFListTlv is mandatory.");
53 final OfList oft = (OfList) tlv;
55 final List<OfId> ofCodes = oft.getCodes();
56 final byte[] retBytes = new byte[ofCodes.size() * OF_CODE_ELEMENT_LENGTH];
58 final int size = ofCodes.size();
59 for (int i = 0; i < size; i++) {
60 ByteArray.copyWhole(ByteArray.shortToBytes(ofCodes.get(i).getValue().shortValue()), retBytes, i * OF_CODE_ELEMENT_LENGTH);
62 return TlvUtil.formatTlv(TYPE, retBytes);
66 public int getType() {