4ecf8ff913196f1de69228bd3c91b6f8938102db
[honeycomb.git] / vpp-common / vpp-translate-utils / src / main / java / io / fd / honeycomb / translate / v3po / util / TranslateUtils.java
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
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
17 package io.fd.honeycomb.translate.v3po.util;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.google.common.base.Splitter;
22 import com.google.common.net.InetAddresses;
23 import java.net.UnknownHostException;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import java.util.function.BiConsumer;
31 import javax.annotation.Nonnegative;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.openvpp.jvpp.VppBaseCallException;
37 import org.openvpp.jvpp.dto.JVppReply;
38
39 public final class TranslateUtils {
40
41     public static final Splitter COLON_SPLITTER = Splitter.on(':');
42     public static final int DEFAULT_TIMEOUT_IN_SECONDS = 5;
43
44     private TranslateUtils() {
45     }
46
47     public static <REP extends JVppReply<?>> REP getReplyForWrite(@Nonnull Future<REP> future,
48                                                                   @Nonnull final InstanceIdentifier<?> replyType)
49         throws VppBaseCallException, WriteTimeoutException {
50         return getReplyForWrite(future, replyType, DEFAULT_TIMEOUT_IN_SECONDS);
51     }
52
53     public static <REP extends JVppReply<?>> REP getReplyForWrite(@Nonnull Future<REP> future,
54                                                                   @Nonnull final InstanceIdentifier<?> replyType,
55                                                                   @Nonnegative final int timeoutInSeconds)
56         throws VppBaseCallException, WriteTimeoutException {
57         try {
58             return getReply(future, timeoutInSeconds);
59         } catch (TimeoutException e) {
60             throw new WriteTimeoutException(replyType, e);
61         }
62     }
63
64     public static <REP extends JVppReply<?>> REP getReplyForRead(@Nonnull Future<REP> future,
65                                                                  @Nonnull final InstanceIdentifier<?> replyType)
66         throws VppBaseCallException, ReadTimeoutException {
67         return getReplyForRead(future, replyType, DEFAULT_TIMEOUT_IN_SECONDS);
68     }
69
70     public static <REP extends JVppReply<?>> REP getReplyForRead(@Nonnull Future<REP> future,
71                                                                  @Nonnull final InstanceIdentifier<?> replyType,
72                                                                  @Nonnegative final int timeoutInSeconds)
73         throws VppBaseCallException, ReadTimeoutException {
74         try {
75             return getReply(future, timeoutInSeconds);
76         } catch (TimeoutException e) {
77             throw new ReadTimeoutException(replyType, e);
78         }
79     }
80
81     public static <REP extends JVppReply<?>> REP getReply(@Nonnull Future<REP> future)
82         throws TimeoutException, VppBaseCallException {
83         return getReply(future, DEFAULT_TIMEOUT_IN_SECONDS);
84     }
85
86     public static <REP extends JVppReply<?>> REP getReply(@Nonnull Future<REP> future,
87                                                           @Nonnegative final int timeoutInSeconds)
88         throws TimeoutException, VppBaseCallException {
89         try {
90             checkArgument(timeoutInSeconds > 0, "Timeout cannot be < 0");
91             return future.get(timeoutInSeconds, TimeUnit.SECONDS);
92         } catch (InterruptedException e) {
93             Thread.currentThread().interrupt();
94             throw new IllegalStateException("Interrupted", e);
95         } catch (ExecutionException e) {
96             // Execution exception could generally contains any exception
97             // when using exceptions instead of return codes just rethrow it for processing on corresponding place
98             if (e instanceof ExecutionException && (e.getCause() instanceof VppBaseCallException)) {
99                 throw (VppBaseCallException) (e.getCause());
100             }
101             throw new IllegalStateException(e);
102         }
103     }
104
105     /**
106      * Transform Ipv4 address to a byte array acceptable by VPP. VPP expects incoming byte array to be in the same order
107      * as the address.
108      *
109      * @return byte array with address bytes
110      */
111     public static byte[] ipv4AddressNoZoneToArray(final Ipv4AddressNoZone ipv4Addr) {
112         byte[] retval = new byte[4];
113         String[] dots = ipv4Addr.getValue().split("\\.");
114
115         for (int d = 0; d < 4; d++) {
116             retval[d] = (byte) (Short.parseShort(dots[d]) & 0xff);
117         }
118         return retval;
119     }
120
121     /**
122      * Parse byte array returned by VPP representing an Ipv4 address. Vpp returns IP byte arrays in reversed order.
123      *
124      * @return Ipv4AddressNoZone containing string representation of IPv4 address constructed from submitted bytes. No
125      * change in order.
126      */
127     @Nonnull
128     public static Ipv4AddressNoZone arrayToIpv4AddressNoZone(@Nonnull byte[] ip) {
129         // VPP sends ipv4 in a 16 byte array
130         if (ip.length == 16) {
131             ip = Arrays.copyOfRange(ip, 0, 4);
132         }
133         try {
134             // Not reversing the byte array here!! because the IP coming from VPP is in reversed byte order
135             // compared to byte order it was submitted
136             return new Ipv4AddressNoZone(InetAddresses.toAddrString(InetAddresses.fromLittleEndianByteArray(ip)));
137         } catch (UnknownHostException e) {
138             throw new IllegalArgumentException("Unable to parse ipv4", e);
139         }
140     }
141
142     /**
143      * Return (interned) string from byte array while removing \u0000. Strings represented as fixed length byte[] from
144      * vpp contain \u0000.
145      */
146     public static String toString(final byte[] cString) {
147         return new String(cString).replaceAll("\\u0000", "").intern();
148     }
149
150     /**
151      * Parse string represented mac address (using ":" as separator) into a byte array
152      */
153     @Nonnull
154     public static byte[] parseMac(@Nonnull final String macAddress) {
155         final List<String> parts = COLON_SPLITTER.splitToList(macAddress);
156         checkArgument(parts.size() == 6, "Mac address is expected to have 6 parts but was: %s", macAddress);
157         return parseMacLikeString(parts);
158     }
159
160     private static byte[] parseMacLikeString(final List<String> strings) {
161         return strings.stream().limit(6).map(TranslateUtils::parseHexByte).collect(
162             () -> new byte[strings.size()],
163             new BiConsumer<byte[], Byte>() {
164
165                 private int i = -1;
166
167                 @Override
168                 public void accept(final byte[] bytes, final Byte aByte) {
169                     bytes[++i] = aByte;
170                 }
171             },
172             (bytes, bytes2) -> {
173                 throw new UnsupportedOperationException("Parallel collect not supported");
174             });
175     }
176
177     public static byte parseHexByte(final String aByte) {
178         return (byte) Integer.parseInt(aByte, 16);
179     }
180
181     /**
182      * Returns 0 if argument is null or false, 1 otherwise.
183      *
184      * @param value Boolean value to be converted
185      * @return byte value equal to 0 or 1
186      */
187     public static byte booleanToByte(@Nullable final Boolean value) {
188         return value != null && value
189             ? (byte) 1
190             : (byte) 0;
191     }
192
193     /**
194      * Returns Boolean.TRUE if argument is 0, Boolean.FALSE otherwise.
195      *
196      * @param value byte value to be converted
197      * @return Boolean value
198      * @throws IllegalArgumentException if argument is neither 0 nor 1
199      */
200     @Nonnull
201     public static Boolean byteToBoolean(final byte value) {
202         if (value == 0) {
203             return Boolean.FALSE;
204         } else if (value == 1) {
205             return Boolean.TRUE;
206         }
207         throw new IllegalArgumentException(String.format("0 or 1 was expected but was %d", value));
208     }
209
210     /**
211      * Reverses bytes in the byte array
212      *
213      * @param bytes input array
214      * @return reversed array
215      */
216     public static byte[] reverseBytes(final byte[] bytes) {
217         final byte[] reversed = new byte[bytes.length];
218         int i = 1;
219         for (byte aByte : bytes) {
220             reversed[bytes.length - i++] = aByte;
221         }
222
223         return reversed;
224     }
225 }