2 * Copyright (c) 2016 Cisco and/or its affiliates.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package io.fd.hc2vpp.common.translate.util;
19 import static com.google.common.base.Preconditions.checkNotNull;
21 import java.util.Arrays;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6AddressNoZone;
30 * Aggregation trait providing logic for converting address based data
32 public interface AddressTranslator extends Ipv4Translator, Ipv6Translator, MacTranslator {
34 AddressTranslator INSTANCE = new AddressTranslator() {
37 default byte[] ipAddressToArray(IpAddress address) {
38 checkNotNull(address, "Cannot resolve null adddress");
40 if (isIpv6(address)) {
41 return ipv6AddressNoZoneToArray(new Ipv6AddressNoZone(address.getIpv6Address()));
43 return ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(address.getIpv4Address()));
49 * Converts {@link IpAddress} to array representing {@link Ipv4Address} or {@link Ipv6Address}
51 default byte[] ipAddressToArray(boolean isIpv6, @Nonnull IpAddress address) {
52 checkNotNull(address, "Cannot convert null Address");
55 return ipv6AddressNoZoneToArray(new Ipv6AddressNoZone(address.getIpv6Address()));
57 return ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(address.getIpv4Address()));
62 * Converts array bytes to {@link IpAddress}.
65 default IpAddress arrayToIpAddress(boolean isIpv6, byte[] ip) {
67 return new IpAddress(arrayToIpv6AddressNoZone(ip));
69 return new IpAddress(arrayToIpv4AddressNoZone(ip));
73 // safest way to compare addresses - prevents returning false while using different types from hierarchy
74 // Ex. Key for MapResolver contains Ipv4Address as value but we translate addresses from binary data to Ipv4AddressNoZone
75 default boolean addressesEqual(final IpAddress left, final IpAddress right) {
76 return Arrays.equals(left.getValue(), right.getValue());