0902064eb16a0cd8c397658de1ac2360e6475277
[hc2vpp.git] /
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         return ipv4AddressNoZoneToArray(ipv4Addr.getValue());
113     }
114
115     public static byte[] ipv4AddressNoZoneToArray(final String ipv4Addr) {
116         byte[] retval = new byte[4];
117         String[] dots = ipv4Addr.split("\\.");
118
119         for (int d = 0; d < 4; d++) {
120             retval[d] = (byte) (Short.parseShort(dots[d]) & 0xff);
121         }
122         return retval;
123     }
124
125     /**
126      * Parse byte array returned by VPP representing an Ipv4 address. Vpp returns IP byte arrays in reversed order.
127      *
128      * @return Ipv4AddressNoZone containing string representation of IPv4 address constructed from submitted bytes. No
129      * change in order.
130      */
131     @Nonnull
132     public static Ipv4AddressNoZone arrayToIpv4AddressNoZone(@Nonnull byte[] ip) {
133         // VPP sends ipv4 in a 16 byte array
134         if (ip.length == 16) {
135             ip = Arrays.copyOfRange(ip, 0, 4);
136         }
137         try {
138             // Not reversing the byte array here!! because the IP coming from VPP is in reversed byte order
139             // compared to byte order it was submitted
140             return new Ipv4AddressNoZone(InetAddresses.toAddrString(InetAddresses.fromLittleEndianByteArray(ip)));
141         } catch (UnknownHostException e) {
142             throw new IllegalArgumentException("Unable to parse ipv4", e);
143         }
144     }
145
146     /**
147      * Return (interned) string from byte array while removing \u0000. Strings represented as fixed length byte[] from
148      * vpp contain \u0000.
149      */
150     public static String toString(final byte[] cString) {
151         return new String(cString).replaceAll("\\u0000", "").intern();
152     }
153
154     /**
155      * Parse string represented mac address (using ":" as separator) into a byte array
156      */
157     @Nonnull
158     public static byte[] parseMac(@Nonnull final String macAddress) {
159         final List<String> parts = COLON_SPLITTER.splitToList(macAddress);
160         checkArgument(parts.size() == 6, "Mac address is expected to have 6 parts but was: %s", macAddress);
161         return parseMacLikeString(parts);
162     }
163
164     private static byte[] parseMacLikeString(final List<String> strings) {
165         return strings.stream().limit(6).map(TranslateUtils::parseHexByte).collect(
166             () -> new byte[strings.size()],
167             new BiConsumer<byte[], Byte>() {
168
169                 private int i = -1;
170
171                 @Override
172                 public void accept(final byte[] bytes, final Byte aByte) {
173                     bytes[++i] = aByte;
174                 }
175             },
176             (bytes, bytes2) -> {
177                 throw new UnsupportedOperationException("Parallel collect not supported");
178             });
179     }
180
181     public static byte parseHexByte(final String aByte) {
182         return (byte) Integer.parseInt(aByte, 16);
183     }
184
185     /**
186      * Returns 0 if argument is null or false, 1 otherwise.
187      *
188      * @param value Boolean value to be converted
189      * @return byte value equal to 0 or 1
190      */
191     public static byte booleanToByte(@Nullable final Boolean value) {
192         return value != null && value
193             ? (byte) 1
194             : (byte) 0;
195     }
196
197     /**
198      * Returns Boolean.TRUE if argument is 0, Boolean.FALSE otherwise.
199      *
200      * @param value byte value to be converted
201      * @return Boolean value
202      * @throws IllegalArgumentException if argument is neither 0 nor 1
203      */
204     @Nonnull
205     public static Boolean byteToBoolean(final byte value) {
206         if (value == 0) {
207             return Boolean.FALSE;
208         } else if (value == 1) {
209             return Boolean.TRUE;
210         }
211         throw new IllegalArgumentException(String.format("0 or 1 was expected but was %d", value));
212     }
213
214     /**
215      * Reverses bytes in the byte array
216      *
217      * @param bytes input array
218      * @return reversed array
219      */
220     public static byte[] reverseBytes(final byte[] bytes) {
221         final byte[] reversed = new byte[bytes.length];
222         int i = 1;
223         for (byte aByte : bytes) {
224             reversed[bytes.length - i++] = aByte;
225         }
226
227         return reversed;
228     }
229 }