Rework PCEPDeserializerException and move it into SPI
[bgpcep.git] / pcep / impl / src / main / java / org / opendaylight / protocol / pcep / impl / subobject / Type1LabelParser.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.impl.subobject;
9
10 import org.opendaylight.protocol.pcep.spi.LabelParser;
11 import org.opendaylight.protocol.pcep.spi.LabelSerializer;
12 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
13 import org.opendaylight.protocol.util.ByteArray;
14 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.label.subobject.LabelType;
15 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.label.subobject.label.type.Type1Label;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev130820.label.subobject.label.type.Type1LabelBuilder;
17
18 import com.google.common.primitives.UnsignedInts;
19
20 public class Type1LabelParser implements LabelParser, LabelSerializer {
21
22         public static final int CTYPE = 1;
23
24         public static final int LABEL_LENGTH = 4;
25
26         @Override
27         public LabelType parseLabel(final byte[] buffer) throws PCEPDeserializerException {
28                 if (buffer == null || buffer.length == 0) {
29                         throw new IllegalArgumentException("Array of bytes is mandatory. Can't be null or empty.");
30                 }
31                 if (buffer.length != LABEL_LENGTH) {
32                         throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + buffer.length + "; Expected: " + LABEL_LENGTH
33                                         + ".");
34                 }
35                 return new Type1LabelBuilder().setType1Label(UnsignedInts.toLong(ByteArray.bytesToInt(buffer))).build();
36         }
37
38         @Override
39         public byte[] serializeLabel(final LabelType subobject) {
40                 if (!(subobject instanceof Type1Label)) {
41                         throw new IllegalArgumentException("Unknown Label Subobject instance. Passed " + subobject.getClass() + ". Needed Type1Label.");
42                 }
43                 return ByteArray.subByte(ByteArray.longToBytes(((Type1Label) subobject).getType1Label().longValue()), 4, LABEL_LENGTH);
44         }
45
46         @Override
47         public int getType() {
48                 return CTYPE;
49         }
50 }