blob: c16d94450f87be3421da3042e05a6e28fa3d9c05 [file] [log] [blame]
Sho SHIMIZU6ec2eca2016-05-19 11:37:01 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.resource.impl;
17
18import org.onlab.packet.MplsLabel;
19import org.onlab.packet.VlanId;
Sho SHIMIZU9db6da62016-06-01 12:31:21 -070020import org.onosproject.net.PortNumber;
Sho SHIMIZU6ec2eca2016-05-19 11:37:01 -070021import org.onosproject.net.resource.DiscreteResource;
22import org.onosproject.net.resource.DiscreteResourceCodec;
Sho SHIMIZU6ec2eca2016-05-19 11:37:01 -070023
24import java.util.HashMap;
25import java.util.Map;
26
27/**
28 * A set of {@link DiscreteResourceCodec DiscreteResourceCodecs}.
29 */
30final class Codecs {
31 private static final Codecs INSTANCE = new Codecs();
32
33 private final Map<Class<?>, DiscreteResourceCodec<?>> codecs;
34
35 /**
36 * Returns an instance of this class.
37 *
38 * @return instance
39 */
40 static Codecs getInstance() {
41 return INSTANCE;
42 }
43
44 private Codecs() {
45 this.codecs = new HashMap<>();
46 init();
47 }
48
49 private void init() {
Sho SHIMIZU9db6da62016-06-01 12:31:21 -070050 codecs.put(PortNumber.class, new PortNumberCodec());
Sho SHIMIZU59512bf2016-06-01 11:30:58 -070051 codecs.put(VlanId.class, new VlanIdCodec());
52 codecs.put(MplsLabel.class, new MplsLabelCodec());
Sho SHIMIZU6ec2eca2016-05-19 11:37:01 -070053 }
54
55 /**
56 * Returns if there is a codec available for the specified resource.
57 *
58 * @param resource resource to be encoded
59 * @return true if this class can encode the resource, otherwise false.
60 */
61 boolean isEncodable(DiscreteResource resource) {
62 return resource.valueAs(Object.class)
63 .map(Object::getClass)
64 .map(codecs::containsKey)
65 .orElse(Boolean.FALSE);
66 }
67
68 /**
69 * Returns the codec for the specified class.
70 *
71 * @param cls class of an instance to be encoded
72 * @return the codec for the class
73 */
74 DiscreteResourceCodec<?> getCodec(Class<?> cls) {
75 return codecs.get(cls);
76 }
77}