java.util.concurrent.TimeoutException Java Examples

The following examples show how to use java.util.concurrent.TimeoutException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MetricsCollectorTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void metrics_collector_is_invoked_on_basic_get_consumption() throws IOException, TimeoutException {
    MockConnectionFactory mockConnectionFactory = new MockConnectionFactory();
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    mockConnectionFactory.setMetricsCollector(new MicrometerMetricsCollector(registry));

    try (MockConnection connection = mockConnectionFactory.newConnection();
         Channel channel = connection.createChannel(42)) {
        String queueName = channel.queueDeclare().getQueue();
        channel.basicPublish("", queueName, null, "".getBytes());

        assertThat(registry.get("rabbitmq.consumed").counter().count()).isEqualTo(0);
        channel.basicGet(queueName, true);
        assertThat(registry.get("rabbitmq.consumed").counter().count()).isEqualTo(1);
    }
}
 
Example #2
Source File: ConsumerHolderTest.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Test
void activateAndDeactivateWithAutoAck() throws IOException, TimeoutException {
  sut = new ConsumerHolder(eventConsumerMock, "queue", true, PREFETCH_COUNT,
      consumerChannelFactoryMock, declarationsListMock, declarerRepositoryMock);
  Assertions.assertEquals("queue", sut.getQueueName());
  Assertions.assertTrue(sut.isAutoAck());
  when(consumerChannelFactoryMock.createChannel()).thenReturn(channelMock);
  sut.activate();
  verify(channelMock).addRecoveryListener(sut);
  verify(channelMock).basicConsume(eq("queue"), eq(true), isA(DeliverCallback.class),
      isA(ConsumerShutdownSignalCallback.class));
  verify(declarerRepositoryMock).declare(channelMock, declarationsListMock);
  verify(channelMock, never()).close();
  verify(channelMock).basicQos(PREFETCH_COUNT);

  sut.deactivate();
  verify(channelMock).close();
}
 
Example #3
Source File: SignalServiceMessagePipe.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public AttachmentUploadAttributes getAttachmentUploadAttributes() throws IOException {
  try {
    WebSocketRequestMessage requestMessage = WebSocketRequestMessage.newBuilder()
                                                                    .setId(new SecureRandom().nextLong())
                                                                    .setVerb("GET")
                                                                    .setPath("/v2/attachments/form/upload")
                                                                    .build();

    Pair<Integer, String> response = websocket.sendRequest(requestMessage).get(10, TimeUnit.SECONDS);

    if (response.first() < 200 || response.first() >= 300) {
      throw new IOException("Non-successful response: " + response.first());
    }

    return JsonUtil.fromJson(response.second(), AttachmentUploadAttributes.class);
  } catch (InterruptedException | ExecutionException | TimeoutException e) {
    throw new IOException(e);
  }
}
 
Example #4
Source File: Participant.java    From jzab with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for the end of the synchronization and updates last seen config
 * file.
 *
 * @param peerId the id of the peer.
 * @throws TimeoutException in case of timeout.
 * @throws IOException in case of IOException.
 * @throws InterruptedException if it's interrupted.
 */
void waitForSyncEnd(String peerId)
    throws TimeoutException, IOException, InterruptedException {
  MessageTuple tuple = filter.getExpectedMessage(MessageType.SYNC_END,
                                                 peerId,
                                                 getSyncTimeoutMs());
  ClusterConfiguration cnf
    = ClusterConfiguration.fromProto(tuple.getMessage().getConfig(),
                                     this.serverId);
  LOG.debug("Got SYNC_END {} from {}", cnf, peerId);
  this.persistence.setLastSeenConfig(cnf);
  if (persistence.isInStateTransfer()) {
    persistence.endStateTransfer();
  }
  // If the synchronization is performed by truncation, then it's possible
  // the content of cluster_config has been truncated in log, then we'll
  // delete these invalid cluster_config files.
  persistence.cleanupClusterConfigFiles();
}
 
Example #5
Source File: DockerEnvironmentBackupManager.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@VisibleForTesting
void executeCommand(
    String[] commandLine,
    int timeout,
    String address,
    String workspaceId,
    Set<Integer> successResponseCodes)
    throws TimeoutException, IOException, InterruptedException {
  final ListLineConsumer outputConsumer = new ListLineConsumer();
  Process process = ProcessUtil.executeAndWait(commandLine, timeout, SECONDS, outputConsumer);

  if (!successResponseCodes.contains(process.exitValue())) {
    LOG.error(
        "Error occurred during backup/restore of workspace '{}' on node '{}' : {}",
        workspaceId,
        address,
        outputConsumer.getText());
    throw new IOException("Synchronization process failed. Exit code " + process.exitValue());
  }
}
 
Example #6
Source File: PublisherAsBlockingIterableTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void nextWithTimeout() throws Exception {
    BlockingIterator<Integer> iterator = source.toIterable().iterator();
    assertTrue(source.isSubscribed());
    TestSubscription subscription = new TestSubscription();
    source.onSubscribe(subscription);
    source.onNext(1, 2);
    assertThat("hasNext timed out.", iterator.hasNext(-1, MILLISECONDS), is(true));
    assertThat("Unexpected item found.", iterator.next(-1, MILLISECONDS), is(1));
    assertThat("Unexpected item found.", iterator.next(-1, MILLISECONDS), is(2));
    expected.expect(instanceOf(TimeoutException.class));
    try {
        iterator.next(10, MILLISECONDS);
    } catch (TimeoutException e) {
        assertThat("Unexpected item found.", iterator.hasNext(-1, MILLISECONDS), is(false));
        assertTrue(subscription.isCancelled());
        throw e;
    }
}
 
Example #7
Source File: ExecutionSteps.java    From junit5-docker with Apache License 2.0 6 votes vote down vote up
@When("^you run your tests? :$")
public void executeTest() throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<JupiterExecutionListener> future = executor.submit(
        () -> testEngine.executeTestsForClass(compiledClass.getCompiledClass())
    );
    try {
        JupiterExecutionListener listener = future.get(5, TimeUnit.MINUTES);
        assertThat(listener.allTestsPassed())
            .overridingErrorMessage("Tests should be green")
            .isTrue();
    } catch (TimeoutException e) {
        fail("Tests should have finished");
    } finally {
        executor.shutdownNow();
    }
}
 
Example #8
Source File: DaemonTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Test
void get() throws Exception {
    final PowerTenant a = mockTenant(harmlessZonky(), true);
    final ExecutorService e = Executors.newFixedThreadPool(1);
    final Scheduler s = Scheduler.create();
    try (final Daemon d = spy(new Daemon(a, lifecycle, s))) {
        assertThat(d.getSessionInfo()).isSameAs(a.getSessionInfo());
        doNothing().when(d)
            .submitWithTenant(any(), any(), any(), any(), any(), any());
        doNothing().when(d)
            .submitTenantless(any(), any(), any(), any(), any(), any());
        final Future<ReturnCode> f = e.submit(d::get); // will block
        assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS)).isInstanceOf(TimeoutException.class);
        lifecycle.resumeToShutdown(); // unblock
        assertThat(f.get()).isEqualTo(ReturnCode.OK); // should now finish
        // call all the jobs and daemons we know about
        verify(d, times(1)).submitTenantless(any(), any(SimplePayload.class), any(), any(), any(), any());
        verify(d, times(8)).submitWithTenant(any(), any(), any(), any(), any(), any());
    } finally {
        e.shutdownNow();
    }
    verify(a).close();
    assertThat(s.isClosed()).isTrue();
}
 
Example #9
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPriority()
    throws TimeoutException, InterruptedException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ReadFuture readFuture = ReadFuture.untilCountAfterNull(ref, 7);

  ref.setValueAsync("a");
  ref.setValueAsync("b", 5);
  ref.setValueAsync("c", "6");
  ref.setValueAsync("d", 7);
  ref.setValueAsync(new MapBuilder().put(".value", "e").put(".priority", 8).build());
  ref.setValueAsync(new MapBuilder().put(".value", "f").put(".priority", "8").build());
  ref.setValueAsync(new MapBuilder().put(".value", "g").put(".priority", null).build());

  List<EventRecord> events = readFuture.timedGet();
  assertNull(events.get(0).getSnapshot().getPriority());
  assertEquals(5.0, events.get(1).getSnapshot().getPriority());
  assertEquals("6", events.get(2).getSnapshot().getPriority());
  assertEquals(7.0, events.get(3).getSnapshot().getPriority());
  assertEquals(8.0, events.get(4).getSnapshot().getPriority());
  assertEquals("8", events.get(5).getSnapshot().getPriority());
  assertNull(events.get(6).getSnapshot().getPriority());
}
 
Example #10
Source File: InputMonitor.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Waits until JVoiceXml is expecting input.
 * 
 * @throws InterruptedException
 *             waiting interrupted
 * @throws TimeoutException
 *             input closed while waiting for input
 * @throws JVoiceXMLEvent
 *             error while waiting
 */
public void waitUntilExpectingInput() throws InterruptedException,
        TimeoutException, JVoiceXMLEvent {
    synchronized (monitor) {
        try {
            if (expectingInput) {
                return;
            }
            monitor.wait();
            if (event != null) {
                throw event;
            }
            if (!expectingInput) {
                throw new TimeoutException(
                      "input closed while waiting for expected input");
            }
        } finally {
            expectingInput = false;
        }
    }
}
 
Example #11
Source File: ScriptCallableTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testCancelWait() throws Exception {
    List<Runnable> lr = null;
    JexlScript e = JEXL.createScript("wait(10)");
    Callable<Object> c = e.callable(new TestContext());

    ExecutorService executor = Executors.newFixedThreadPool(1);
    try {
        Future<?> future = executor.submit(c);
        Object t = 42;
        try {
            t = future.get(100, TimeUnit.MILLISECONDS);
            Assert.fail("should have timed out");
        } catch (TimeoutException xtimeout) {
            // ok, ignore
            future.cancel(true);
        }
        Assert.assertTrue(future.isCancelled());
        Assert.assertEquals(42, t);
    } finally {
        lr = executor.shutdownNow();
    }
    Assert.assertTrue(lr.isEmpty());
}
 
Example #12
Source File: FutureImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public T get(long timeoutMs, long sleepingIntervalMs) throws TimeoutException {
	long waitingSince = U.time();

	while (!isDone()) {
		if (U.timedOut(waitingSince, timeoutMs)) {
			throw new TimeoutException();
		}

		U.sleep(sleepingIntervalMs);
	}

	if (getError() != null) {
		throw U.rte("Cannot get the result, there was an error!", error);
	}

	return result;
}
 
Example #13
Source File: DifferPublisherTest.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Test
public void negativeDeliveryAck() throws IOException, TimeoutException, InterruptedException {
    //setup
    long deliveryTag = 1L;
    String exchange = "someExchange";
    String routingKey = "someRoutingKey";
    AMQP.BasicProperties properties = new AMQP.BasicProperties();
    byte[] body = new byte[0];
    Delivery delivery = new Delivery(new Envelope(deliveryTag, false, exchange, routingKey), properties, body);

    //test
    differPublisher.negativeDeliveryAck(delivery);

    //assert
    Mockito.verify(channel).basicNack(eq(deliveryTag), eq(false), eq(false));
    Mockito.verify(channel).basicPublish(
            eq(EDDI_EXCHANGE), eq(MESSAGE_CREATED_EDDI_FAILED_ROUTING_KEY), eq(null), eq(body));
    Mockito.verify(channel).waitForConfirmsOrDie(eq(TIMEOUT_CONFIRMS_IN_MILLIS));
}
 
Example #14
Source File: MemcachedItemCacheTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldGetItem() throws InterruptedException, TimeoutException, ExecutionException {
    // Given
    final String key = Randoms.randomString();
    final String item = Randoms.randomString();
    final int timeout = Randoms.randomInt(5) + 1;
    final GetFuture<Object> f = mock(GetFuture.class);
    when(memcachedClient.asyncGet(key)).thenReturn(f);
    when(f.get(timeout, TimeUnit.SECONDS)).thenReturn(item);

    // When
    final Object obj = memcachedItemCache.getItem(key, timeout);

    // Then
    assertEquals(item, obj);
}
 
Example #15
Source File: SyncWrite.java    From lightconf with GNU General Public License v3.0 6 votes vote down vote up
private ReplyMsg doWriteAndSync(final Channel channel, final AskMsg request, final long timeout, final WriteFuture<BaseMsg> writeFuture) throws Exception {

        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                writeFuture.setWriteResult(future.isSuccess());
                writeFuture.setCause(future.cause());
                //失败移除
                if (!writeFuture.isWriteSuccess()) {
                    SyncWriteMap.syncKey.remove(writeFuture.requestId());
                }
            }
        });

        ReplyMsg response = (ReplyMsg)writeFuture.get(timeout, TimeUnit.MILLISECONDS);
        if (response == null) {
            if (writeFuture.isTimeout()) {
                throw new TimeoutException();
            } else {
                // write exception
                throw new Exception(writeFuture.cause());
            }
        }
        return response;
    }
 
Example #16
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUrlEncodingAndDecoding()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {

  DatabaseReference ref = FirebaseDatabase.getInstance(masterApp)
      .getReference("/a%b&c@d/space: /non-ascii:ø");
  String result = ref.toString();
  String expected = IntegrationTestUtils.getDatabaseUrl()
      + "/a%25b%26c%40d/space%3A%20/non-ascii%3A%C3%B8";
  assertEquals(expected, result);

  String child = "" + new Random().nextInt(100000000);
  new WriteFuture(ref.child(child), "testdata").timedGet();
  DataSnapshot snap = TestHelpers.getSnap(ref.child(child));
  assertEquals("testdata", snap.getValue());
}
 
Example #17
Source File: TelegesisFrameHandler.java    From com.zsmartsystems.zigbee with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Wait for the requested {@link TelegesisEvent} to occur
 *
 * @param eventClass the {@link TelegesisEvent} to wait for
 * @return the {@link TelegesisEvent} once received, or null on exception
 */
public TelegesisEvent eventWait(final Class<?> eventClass) {
    Future<TelegesisEvent> future = waitEventAsync(eventClass);
    try {
        return future.get(transactionTimeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        logger.debug("Telegesis interrupted in eventWait {}", eventClass);
        future.cancel(true);
        return null;
    }
}
 
Example #18
Source File: ChaosHttpProxyTest.java    From chaos-http-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpGetTimeout() throws Exception {
    proxy.setFailureSupplier(Suppliers.ofInstance(Failure.TIMEOUT));
    thrown.expect(TimeoutException.class);
    client.newRequest(httpBinEndpoint + "/status/200")
            .timeout(1, TimeUnit.SECONDS)
            .send();
}
 
Example #19
Source File: AbstractGrpcAppTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private void asyncCancelCallWhileProcessing(boolean futureCancel) throws BrokenBarrierException, InterruptedException {
    CyclicBarrier startBarrier = new CyclicBarrier(2);
    CyclicBarrier endBarrier = new CyclicBarrier(2);
    app.getServer().useBarriersForProcessing(startBarrier, endBarrier);

    Future<String> msg = app.sayHelloAsync("bob", 0);

    logger.info("server processing wait for start");
    startBarrier.await();
    logger.info("server processing has started");

    if (futureCancel) {
        msg.cancel(true);
    } else {
        // stop the client in order to make the channel unusable on purpose
        app.getClient().stop();
    }

    if(futureCancel){
        assertThat(msg).isCancelled();
    } else {
        // in case of stopped channel, future is not cancelled but should fail with a timeout
        assertThat(msg).isNotCancelled();

        boolean isThrown = false;
        try {
            msg.get(20, TimeUnit.MILLISECONDS);
        } catch (TimeoutException | ExecutionException e) {
            isThrown = e instanceof TimeoutException;
        }
        assertThat(isThrown).isTrue();
    }

    endBarrier.await();
}
 
Example #20
Source File: ParallelizerTest.java    From mug with Apache License 2.0 5 votes vote down vote up
@Test public void testAwaitTimeoutCancelsInFlightTasks() throws InterruptedException {
  assumeFalse(threading == Threading.DIRECT);
  assumeTrue(mode == Mode.INTERRUPTIBLY);
  maxInFlight = 2;
  timeout = Duration.ofMillis(1);
  assertThrows(
      TimeoutException.class,
      () -> parallelize(serialTasks(
          () -> blockFor(1), // Will be interrupted
          () -> blockFor(2)))); // Might be interrupted
  shutdownAndAssertInterruptedKeys().contains(1);
}
 
Example #21
Source File: EventTypeControllerTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenUpdateEventTypeAndTimelineWaitTimeoutThen503() throws Exception {
    when(timelineSync.workWithEventType(any(), anyLong())).thenThrow(new TimeoutException());
    final EventType eventType = TestUtils.buildDefaultEventType();

    final Problem expectedProblem = Problem.valueOf(SERVICE_UNAVAILABLE,
            "Event type is currently in maintenance, please repeat request");

    putEventType(eventType, eventType.getName(), "org/zalando/nakadi")
            .andExpect(status().isServiceUnavailable())
            .andExpect(content().string(matchesProblem(expectedProblem)));
}
 
Example #22
Source File: OrderTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws TestFailure, TimeoutException, InterruptedException {
  masterApp = IntegrationTestUtils.ensureDefaultApp();
  // Make sure we're connected before any of these tests run
  DatabaseReference ref = FirebaseDatabase.getInstance(masterApp).getReference();
  ReadFuture.untilEquals(ref.child(".info/connected"), true).timedGet();
}
 
Example #23
Source File: TestExceptionDependentRetry.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionDependentRetrySuccess() {
  ExceptionDependentRetry.Builder builder =
      ExceptionDependentRetry.newBuilder();

  int ioExceptionRetries = 1;
  int timeoutExceptionRetries = 2;
  int defaultExceptionRetries = 5;

  long ioExceptionSleepTime = 1;
  long timeoutExceptionSleepTime = 4;
  long defaultExceptionSleepTime = 10;
  int maxAttempts = 3;
  builder.setDefaultPolicy(RetryPolicies.retryUpToMaximumCountWithFixedSleep(defaultExceptionRetries,
      TimeDuration.valueOf(defaultExceptionSleepTime, TimeUnit.SECONDS)));
  builder.setExceptionToPolicy(IOException.class,
      RetryPolicies.retryUpToMaximumCountWithFixedSleep(ioExceptionRetries,
          TimeDuration.valueOf(ioExceptionSleepTime, TimeUnit.SECONDS)));
  builder.setExceptionToPolicy(TimeoutIOException.class,
      RetryPolicies.retryUpToMaximumCountWithFixedSleep(timeoutExceptionRetries,
          TimeDuration.valueOf(timeoutExceptionSleepTime, TimeUnit.SECONDS)));
  builder.setMaxAttempts(maxAttempts);


  ExceptionDependentRetry exceptionDependentRetry = builder.build();

  testException(ioExceptionRetries, maxAttempts,
      exceptionDependentRetry, new IOException(), ioExceptionSleepTime);
  testException(timeoutExceptionRetries, maxAttempts,
      exceptionDependentRetry, new TimeoutIOException("time out"),
      timeoutExceptionSleepTime);

  // now try with an exception which is not there in the map.
  testException(defaultExceptionRetries, maxAttempts,
      exceptionDependentRetry, new TimeoutException(),
      defaultExceptionSleepTime);

}
 
Example #24
Source File: WebSocketClient.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public org.eclipse.jetty.websocket.WebSocket.Connection get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException,
        TimeoutException
{
    _done.await(timeout,unit);
    ByteChannel channel=null;
    org.eclipse.jetty.websocket.WebSocket.Connection connection=null;
    Throwable exception;
    synchronized (this)
    {
        exception=_exception;
        if (_connection==null)
        {
            exception=_exception;
            channel=_channel;
            _channel=null;
        }
        else
            connection=_connection.getConnection();
    }

    if (channel!=null)
        closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_NO_CLOSE,"timeout");
    if (exception!=null)
        throw new ExecutionException(exception);
    if (connection!=null)
        return connection;
    throw new TimeoutException();
}
 
Example #25
Source File: AbstractFuture.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    if (await(timeout, unit)) {
        Throwable cause = cause();
        if (cause == null) {
            return getNow();
        }
        throw new ExecutionException(cause);
    }
    throw new TimeoutException();
}
 
Example #26
Source File: BackEndTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void restApplyNoCompletion() throws InterruptedException, ExecutionException, TimeoutException {
    final ContentResponse response = client
            .GET("http://localhost:12345/rest/?genconfURI=" + genconfURI + "&command=apply&expression=self.na");

    assertEquals(400, response.getStatus());
    assertEquals("text/plain", response.getMediaType());
    assertEquals("completion parameter is mandatory", response.getContentAsString());
}
 
Example #27
Source File: JSR166TestCase.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that future.get times out, with the given millisecond timeout.
 */
void assertFutureTimesOut(Future future, long timeoutMillis) {
    long startTime = System.nanoTime();
    try {
        future.get(timeoutMillis, MILLISECONDS);
        shouldThrow();
    } catch (TimeoutException success) {
    } catch (Exception fail) {
        threadUnexpectedException(fail);
    } finally { future.cancel(true); }
    assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
}
 
Example #28
Source File: QueryTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void listenerCanBeRemovedFromSpecificQuery()
    throws DatabaseException, TestFailure, ExecutionException, TimeoutException,
        InterruptedException {
  DatabaseReference ref = IntegrationTestHelpers.getRandomNode();

  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener listener =
      ref.limitToLast(5)
          .addValueEventListener(
              new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                  semaphore.release();
                }

                @Override
                public void onCancelled(DatabaseError error) {}
              });

  ref.setValue(new MapBuilder().put("a", 5).put("b", 6).build());
  semaphore.acquire();
  ref.limitToLast(5).removeEventListener(listener);
  new WriteFuture(ref, new MapBuilder().put("a", 6).put("b", 5).build()).timedGet();
  IntegrationTestHelpers.waitForQueue(ref);
  assertEquals(0, semaphore.availablePermits());
}
 
Example #29
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumer(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    // create consumer
    consumerService().createConsumer(context, groupId, consumerWithEarliestReset);

    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
    consumerService()
        .deleteConsumer(context, groupId, name);
}
 
Example #30
Source File: FailSafeConsistencyGuard.java    From hudi with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to wait for all files belonging to single directory to appear.
 * 
 * @param dirPath Dir Path
 * @param files Files to appear/disappear
 * @param event Appear/Disappear
 * @throws TimeoutException
 */
public void waitForFilesVisibility(String dirPath, List<String> files, FileVisibility event) throws TimeoutException {
  Path dir = new Path(dirPath);
  List<String> filesWithoutSchemeAndAuthority =
      files.stream().map(f -> Path.getPathWithoutSchemeAndAuthority(new Path(f))).map(Path::toString)
          .collect(Collectors.toList());

  retryTillSuccess((retryNum) -> {
    try {
      LOG.info("Trying " + retryNum);
      FileStatus[] entries = fs.listStatus(dir);
      List<String> gotFiles = Arrays.stream(entries).map(e -> Path.getPathWithoutSchemeAndAuthority(e.getPath()))
          .map(Path::toString).collect(Collectors.toList());
      List<String> candidateFiles = new ArrayList<>(filesWithoutSchemeAndAuthority);
      boolean altered = candidateFiles.removeAll(gotFiles);

      switch (event) {
        case DISAPPEAR:
          LOG.info("Following files are visible" + candidateFiles);
          // If no candidate files gets removed, it means all of them have disappeared
          return !altered;
        case APPEAR:
        default:
          // if all files appear, the list is empty
          return candidateFiles.isEmpty();
      }
    } catch (IOException ioe) {
      LOG.warn("Got IOException waiting for file event. Have tried " + retryNum + " time(s)", ioe);
    }
    return false;
  }, "Timed out waiting for files to become visible");
}