Jian Li | 21fa4fe | 2017-11-21 11:23:19 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.incubator.protobuf.models.net; |
| 17 | |
| 18 | import org.onosproject.net.Annotations; |
| 19 | import org.onosproject.net.DefaultAnnotations; |
| 20 | import org.onosproject.net.SparseAnnotations; |
| 21 | import org.slf4j.Logger; |
| 22 | import org.slf4j.LoggerFactory; |
| 23 | |
| 24 | import java.util.HashMap; |
| 25 | import java.util.Map; |
| 26 | |
| 27 | /** |
| 28 | * gRPC message conversion related utilities for annotations service. |
| 29 | */ |
| 30 | public 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 | } |