blob: 0b8cb0326905e8fc89939957d6ad9288099ef6b0 [file] [log] [blame]
Jian Li21fa4fe2017-11-21 11:23:19 +09001/*
2 * Copyright 2017-present Open Networking Foundation
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.incubator.protobuf.models.net;
17
18import org.onosproject.net.Annotations;
19import org.onosproject.net.DefaultAnnotations;
20import org.onosproject.net.SparseAnnotations;
21import org.slf4j.Logger;
22import org.slf4j.LoggerFactory;
23
24import java.util.HashMap;
25import java.util.Map;
26
27/**
28 * gRPC message conversion related utilities for annotations service.
29 */
30public final class AnnotationsTranslator {
31
32 private static final Logger log = LoggerFactory.getLogger(AnnotationsTranslator.class);
33
34 /**
35 * Converts Annotations to Map of Strings.
36 *
37 * @param annotations {@link Annotations}
38 * @return Map of annotation key and values
39 */
40 public static Map<String, String> asMap(Annotations annotations) {
41 if (annotations instanceof DefaultAnnotations) {
42 return ((DefaultAnnotations) annotations).asMap();
43 }
44 Map<String, String> map = new HashMap<>();
45 annotations.keys()
46 .forEach(k -> map.put(k, annotations.value(k)));
47
48 return map;
49 }
50
51 /**
52 * Converts Map of Strings to {@link SparseAnnotations}.
53 *
54 * @param annotations Map of annotation key and values
55 * @return {@link SparseAnnotations}
56 */
57 public static SparseAnnotations asAnnotations(Map<String, String> annotations) {
58 DefaultAnnotations.Builder builder = DefaultAnnotations.builder();
59 annotations.entrySet().forEach(e -> {
60 if (e.getValue() != null) {
61 builder.set(e.getKey(), e.getValue());
62 } else {
63 builder.remove(e.getKey());
64 }
65 });
66 return builder.build();
67 }
68
69 // Utility class not intended for instantiation.
70 private AnnotationsTranslator() {}
71}