Merge "BUG-730 : added tests for Encoders/Decoders in PCEP."
[bgpcep.git] / pcep / spi / src / main / java / org / opendaylight / protocol / pcep / spi / pojo / SimpleTlvRegistry.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.spi.pojo;
9
10 import org.opendaylight.protocol.concepts.HandlerRegistry;
11 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
12 import org.opendaylight.protocol.pcep.spi.TlvParser;
13 import org.opendaylight.protocol.pcep.spi.TlvRegistry;
14 import org.opendaylight.protocol.pcep.spi.TlvSerializer;
15 import org.opendaylight.protocol.util.Values;
16 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
17 import org.opendaylight.yangtools.yang.binding.DataContainer;
18
19 import com.google.common.base.Preconditions;
20
21 /**
22  *
23  */
24 public final class SimpleTlvRegistry implements TlvRegistry {
25
26         private final HandlerRegistry<DataContainer, TlvParser, TlvSerializer> handlers = new HandlerRegistry<>();
27
28         public AutoCloseable registerTlvParser(final int tlvType, final TlvParser parser) {
29                 Preconditions.checkArgument(tlvType >= 0 && tlvType < Values.UNSIGNED_SHORT_MAX_VALUE);
30                 return this.handlers.registerParser(tlvType, parser);
31         }
32
33         public AutoCloseable registerTlvSerializer(final Class<? extends Tlv> tlvClass, final TlvSerializer serializer) {
34                 return this.handlers.registerSerializer(tlvClass, serializer);
35         }
36
37         @Override
38         public Tlv parseTlv(final int type, final byte[] buffer) throws PCEPDeserializerException {
39                 Preconditions.checkArgument(type >= 0 && type <= Values.UNSIGNED_SHORT_MAX_VALUE);
40                 final TlvParser parser = this.handlers.getParser(type);
41                 if (parser == null) {
42                         return null;
43                 }
44                 return parser.parseTlv(buffer);
45         }
46
47         @Override
48         public byte[] serializeTlv(final Tlv tlv) {
49                 final TlvSerializer serializer = this.handlers.getSerializer(tlv.getImplementedInterface());
50                 if (serializer == null) {
51                         return null;
52                 }
53                 return serializer.serializeTlv(tlv);
54         }
55 }