blob: c12fd7f5ec31344c0375436dea9192534ea7151b [file] [log] [blame]
Frank Wangcfffbaa2017-05-06 16:11:08 +08001/*
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
17package org.onosproject.incubator.protobuf.models.net;
18
19import org.onlab.packet.IpAddress;
20import org.onlab.packet.MacAddress;
21import org.onlab.packet.VlanId;
22import org.onosproject.grpc.net.models.HostProtoOuterClass.HostProto;
23import org.onosproject.net.DefaultAnnotations;
24import org.onosproject.net.DefaultHost;
25import org.onosproject.net.Host;
26
27import java.util.stream.Collectors;
28
29/**
30 * gRPC HostProto message to equivalent ONOS Host conversion related utilities.
31 */
32public final class HostProtoTranslator {
33
34
35 /**
36 * Translates {@link Host} to gRPC Host message.
37 *
38 * @param host {@link Host}
39 * @return gRPC HostProto message
40 */
41 public static HostProto translate(Host host) {
42
43 if (host != null) {
44 return HostProto.newBuilder()
45 .setHostId(HostIdProtoTranslator.translate(host.id()))
46 .setConfigured(host.configured())
47 .setVlan(host.vlan().toShort())
48 .addAllIpAddresses(host.ipAddresses().stream()
49 .map(IpAddress::toString)
50 .collect(Collectors.toList()))
51 .setLocation(HostLocationProtoTranslator.translate(host.location()))
52 .build();
53 }
54
55 return HostProto.getDefaultInstance();
56 }
57
58 /**
59 * Translates gRPC Host message to {@link Host}.
60 *
61 * @param host gRPC message
62 * @return {@link Host}
63 */
64 public static Host translate(HostProto host) {
65 if (host.equals(HostProto.getDefaultInstance())) {
66 return null;
67 }
68
69 return new DefaultHost(ProviderIdProtoTranslator.translate(host.getProviderId()),
70 HostIdProtoTranslator.translate(host.getHostId()),
71 MacAddress.valueOf(host.getHostId().getMac()),
72 VlanId.vlanId((short) host.getVlan()),
73 HostLocationProtoTranslator.translate(host.getLocation()),
74 host.getIpAddressesList().stream().map(x -> IpAddress.valueOf(x))
75 .collect(Collectors.toSet()),
76 DefaultAnnotations.builder().putAll(host.getAnnotationsMap()).build());
77 }
78
79 // Utility class not intended for instantiation.
80 private HostProtoTranslator() {}
81}