blob: c79b23a7c43d90561306d7ceb0a6a745fe7d72c5 [file] [log] [blame]
Sho SHIMIZU2795d632016-05-25 14:10:13 -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.util.Tools;
19import org.onosproject.net.resource.DiscreteResource;
20import org.onosproject.net.resource.DiscreteResourceCodec;
21import org.onosproject.net.resource.DiscreteResourceId;
22import org.onosproject.net.resource.Resources;
23
24import java.util.LinkedHashSet;
25import java.util.Set;
26import java.util.stream.Collectors;
27
28/**
29 * Represents discrete resources encoded by a codec.
30 */
31final class EncodedDiscreteResources {
32 private final Set<Integer> rawValues;
33 private final DiscreteResourceCodec codec;
34
35 EncodedDiscreteResources(Set<Integer> rawValues, DiscreteResourceCodec codec) {
36 this.rawValues = rawValues;
37 this.codec = codec;
38 }
39
40 static EncodedDiscreteResources of(Set<DiscreteResource> resources, DiscreteResourceCodec codec) {
41 Set<Integer> rawValues = resources.stream()
42 .map(x -> x.valueAs(Object.class))
43 .flatMap(Tools::stream)
44 .map(x -> codec.encode(x))
45 .collect(Collectors.toCollection(LinkedHashSet::new));
46
47 return new EncodedDiscreteResources(rawValues, codec);
48 }
49
50 Set<Integer> rawValues() {
51 return rawValues;
52 }
53
54 DiscreteResourceCodec codec() {
55 return codec;
56 }
57
58 Set<DiscreteResource> resources(DiscreteResourceId parent) {
59 return rawValues.stream()
60 .map(x -> codec.decode(x))
61 .map(x -> Resources.discrete(parent, x).resource())
62 .collect(Collectors.toCollection(LinkedHashSet::new));
63 }
64
65 @SuppressWarnings("unchecked")
66 boolean contains(DiscreteResource resource) {
67 return rawValues.contains(codec.encode(resource));
68 }
69
70 boolean isEmpty() {
71 return rawValues.isEmpty();
72 }
73}