Sho SHIMIZU | 6ec2eca | 2016-05-19 11:37:01 -0700 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.store.resource.impl; |
| 17 | |
| 18 | import org.onlab.packet.MplsLabel; |
| 19 | import org.onlab.packet.VlanId; |
| 20 | import org.onosproject.net.resource.DiscreteResource; |
| 21 | import org.onosproject.net.resource.DiscreteResourceCodec; |
Sho SHIMIZU | 6ec2eca | 2016-05-19 11:37:01 -0700 | [diff] [blame] | 22 | |
| 23 | import java.util.HashMap; |
| 24 | import java.util.Map; |
| 25 | |
| 26 | /** |
| 27 | * A set of {@link DiscreteResourceCodec DiscreteResourceCodecs}. |
| 28 | */ |
| 29 | final class Codecs { |
| 30 | private static final Codecs INSTANCE = new Codecs(); |
| 31 | |
| 32 | private final Map<Class<?>, DiscreteResourceCodec<?>> codecs; |
| 33 | |
| 34 | /** |
| 35 | * Returns an instance of this class. |
| 36 | * |
| 37 | * @return instance |
| 38 | */ |
| 39 | static Codecs getInstance() { |
| 40 | return INSTANCE; |
| 41 | } |
| 42 | |
| 43 | private Codecs() { |
| 44 | this.codecs = new HashMap<>(); |
| 45 | init(); |
| 46 | } |
| 47 | |
| 48 | private void init() { |
Sho SHIMIZU | 59512bf | 2016-06-01 11:30:58 -0700 | [diff] [blame^] | 49 | codecs.put(VlanId.class, new VlanIdCodec()); |
| 50 | codecs.put(MplsLabel.class, new MplsLabelCodec()); |
Sho SHIMIZU | 6ec2eca | 2016-05-19 11:37:01 -0700 | [diff] [blame] | 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Returns if there is a codec available for the specified resource. |
| 55 | * |
| 56 | * @param resource resource to be encoded |
| 57 | * @return true if this class can encode the resource, otherwise false. |
| 58 | */ |
| 59 | boolean isEncodable(DiscreteResource resource) { |
| 60 | return resource.valueAs(Object.class) |
| 61 | .map(Object::getClass) |
| 62 | .map(codecs::containsKey) |
| 63 | .orElse(Boolean.FALSE); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Returns the codec for the specified class. |
| 68 | * |
| 69 | * @param cls class of an instance to be encoded |
| 70 | * @return the codec for the class |
| 71 | */ |
| 72 | DiscreteResourceCodec<?> getCodec(Class<?> cls) { |
| 73 | return codecs.get(cls); |
| 74 | } |
| 75 | } |