Remove duplicate code for test utilities
[bgpcep.git] / testtool-util / src / main / java / org / opendaylight / protocol / util / CheckUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.util;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Stopwatch;
12 import com.google.common.util.concurrent.Uninterruptibles;
13 import io.netty.util.concurrent.Future;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.TimeUnit;
16 import java.util.function.Function;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
21 import org.opendaylight.yangtools.yang.binding.DataObject;
22 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
23
24 public final class CheckUtil {
25     private static final int LATCH_TIMEOUT = 10;
26     private static final int SLEEP_FOR = 200;
27     private static final int TIMEOUT = 60;
28
29     private CheckUtil() {
30         throw new UnsupportedOperationException();
31     }
32
33     @SuppressWarnings("unchecked")
34     public static <T extends Future> void waitFutureSuccess(final T future) {
35         final CountDownLatch latch = new CountDownLatch(1);
36         future.addListener(future1 -> latch.countDown());
37         Uninterruptibles.awaitUninterruptibly(latch, LATCH_TIMEOUT, TimeUnit.SECONDS);
38     }
39
40     public static <R, T extends DataObject> R readData(final DataBroker dataBroker, final InstanceIdentifier<T> iid,
41         final Function<T, R> function) throws ReadFailedException {
42         AssertionError lastError = null;
43         final Stopwatch sw = Stopwatch.createStarted();
44         while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
45             try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
46                 final Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
47                 if (data.isPresent()) {
48                     try {
49                         return function.apply(data.get());
50                     } catch (final AssertionError e) {
51                         lastError = e;
52                         Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
53                     }
54                 }
55             }
56         }
57         throw lastError;
58     }
59 }