blob: ee81211f4c1b90a595415531baf03a7cc1876cdb [file] [log] [blame]
Sho SHIMIZUc0e010dd2016-05-02 14:46:22 -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.net.resource;
17
18import com.esotericsoftware.kryo.Kryo;
19import com.esotericsoftware.kryo.Serializer;
20import com.esotericsoftware.kryo.io.Input;
21import com.esotericsoftware.kryo.io.Output;
22import com.google.common.annotations.Beta;
23import com.google.common.collect.DiscreteDomain;
24import com.google.common.collect.Range;
25import com.google.common.collect.TreeRangeSet;
26import org.onlab.util.ClosedOpenRange;
27
28import java.util.ArrayList;
29import java.util.List;
30import java.util.Set;
31import java.util.stream.Collectors;
32import java.util.stream.IntStream;
33
34/**
35 * Kryo serializer for {@link DiscreteResourceSet}.
36 */
37@Beta
38public final class DiscreteResourceSetSerializer extends Serializer<DiscreteResourceSet> {
39
40 public DiscreteResourceSetSerializer() {
41 super(false, true);
42 }
43
44 @Override
45 public void write(Kryo kryo, Output output, DiscreteResourceSet object) {
46 TreeRangeSet<Integer> rangeSet = TreeRangeSet.create();
47 object.values().stream()
48 .map(x -> object.codec().encode(x))
49 .map(Range::singleton)
50 .map(x -> x.canonical(DiscreteDomain.integers()))
51 .forEach(rangeSet::add);
52 List<ClosedOpenRange> ranges = rangeSet.asRanges().stream()
53 .map(ClosedOpenRange::of)
54 .collect(Collectors.toList());
55 kryo.writeObject(output, ranges);
56 kryo.writeClassAndObject(output, object.codec());
57 kryo.writeObject(output, object.parent());
58 }
59
60 @Override
61 public DiscreteResourceSet read(Kryo kryo, Input input, Class<DiscreteResourceSet> type) {
62 @SuppressWarnings("unchecked")
63 List<ClosedOpenRange> ranges = kryo.readObject(input, ArrayList.class);
64 DiscreteResourceCodec codec = (DiscreteResourceCodec) kryo.readClassAndObject(input);
65 DiscreteResourceId parent = kryo.readObject(input, DiscreteResourceId.class);
66
67 if (ranges.isEmpty()) {
68 return DiscreteResourceSet.empty();
69 }
70
71 Set<DiscreteResource> resources = ranges.stream()
72 .flatMapToInt(x -> IntStream.range(x.lowerBound(), x.upperBound()))
73 .mapToObj(x -> codec.decode(parent, x))
74 .collect(Collectors.toSet());
75
76 return DiscreteResourceSet.of(resources, codec);
77 }
78}