BUG-64 : initial rewrite, MessageRegistry.
[bgpcep.git] / pcep / spi / src / main / java / org / opendaylight / protocol / pcep / spi / pojo / SimpleMessageRegistry.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 io.netty.buffer.ByteBuf;
11
12 import java.util.List;
13
14 import org.opendaylight.protocol.concepts.HandlerRegistry;
15 import org.opendaylight.protocol.pcep.spi.MessageParser;
16 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
17 import org.opendaylight.protocol.pcep.spi.MessageSerializer;
18 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
19 import org.opendaylight.protocol.util.Values;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
21 import org.opendaylight.yangtools.yang.binding.DataContainer;
22
23 import com.google.common.base.Preconditions;
24
25 public final class SimpleMessageRegistry implements MessageRegistry {
26
27         private final HandlerRegistry<DataContainer, MessageParser, MessageSerializer> handlers = new HandlerRegistry<>();
28
29         public AutoCloseable registerMessageParser(final int messageType, final MessageParser parser) {
30                 Preconditions.checkArgument(messageType >= 0 && messageType <= Values.UNSIGNED_BYTE_MAX_VALUE);
31                 return this.handlers.registerParser(messageType, parser);
32         }
33
34         public AutoCloseable registerMessageSerializer(final Class<? extends Message> msgClass, final MessageSerializer serializer) {
35                 return this.handlers.registerSerializer(msgClass, serializer);
36         }
37
38         @Override
39         public Message parseMessage(int messageType, byte[] buffer, List<Message> errors) throws PCEPDeserializerException {
40                 Preconditions.checkArgument(messageType >= 0 && messageType <= Values.UNSIGNED_BYTE_MAX_VALUE);
41                 final MessageParser parser = this.handlers.getParser(messageType);
42                 if (parser == null) {
43                         return null;
44                 }
45                 return parser.parseMessage(buffer, errors);
46         }
47
48         @Override
49         public void serializeMessage(Message message, ByteBuf buffer) {
50                 final MessageSerializer serializer = this.handlers.getSerializer(message.getImplementedInterface());
51                 if (serializer == null) {
52                         return;
53                 }
54                 serializer.serializeMessage(message, buffer);
55         }
56 }