org.awaitility.core.ConditionTimeoutException Java Examples

The following examples show how to use org.awaitility.core.ConditionTimeoutException. 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: EthProtocolManagerTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test(expected = ConditionTimeoutException.class)
public void doNotDisconnectOnValidMessage() {
  try (final EthProtocolManager ethManager =
      EthProtocolManagerTestUtil.create(
          blockchain,
          () -> false,
          protocolContext.getWorldStateArchive(),
          transactionPool,
          EthProtocolConfiguration.defaultConfig())) {
    final MessageData messageData =
        GetBlockBodiesMessage.create(Collections.singletonList(gen.hash()));
    final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {});
    ethManager.processMessage(EthProtocol.ETH63, new DefaultMessage(peer, messageData));
    Awaitility.await()
        .catchUncaughtExceptions()
        .atMost(200, TimeUnit.MILLISECONDS)
        .until(peer::isDisconnected);
  }
}
 
Example #2
Source File: ClusterWait.java    From docker-compose-rule with Apache License 2.0 6 votes vote down vote up
public void waitUntilReady(Cluster cluster) {
    final AtomicReference<Optional<SuccessOrFailure>> lastSuccessOrFailure = new AtomicReference<>(
            Optional.empty());

    // semi-intelligent poll interval. If we specify a fast timeout, it will poll more often, otherwise poll
    // at a slower rate
    Duration pollInterval = minDuration(Duration.millis(500), timeout.dividedBy(20));

    try {
        Awaitility.await()
                .pollInterval(pollInterval.getMillis(), TimeUnit.MILLISECONDS)
                .pollDelay(ThreadLocalRandom.current().nextInt(1, 50), TimeUnit.MILLISECONDS)
                .atMost(timeout.getMillis(), TimeUnit.MILLISECONDS)
                .until(weHaveSuccess(cluster, lastSuccessOrFailure));
    } catch (ConditionTimeoutException e) {
        throw new IllegalStateException(serviceDidNotStartupExceptionMessage(lastSuccessOrFailure));
    }
}
 
Example #3
Source File: CachedSupplierTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void testReturnsOldValueIfDelegateFails() throws Throwable {
  // Initial load
  var a = sut.get();
  assertThat(a, is(INITIAL_VALUE));
  verify(delegate, times(1)).get();

  // Make the supplier fail and progress time enough to trigger refresh
  when(delegate.get()).thenThrow(new RuntimeException("Fail!"));
  now = now.plus(TIMEOUT).plusSeconds(1);

  // Trigger refresh
  var b = sut.get();
  assertThat(b, is(INITIAL_VALUE));

  // Ensure that the old value is still returned (never observe another value)
  exception.expect(ConditionTimeoutException.class);
  await().atMost(5, SECONDS).until(() -> sut.get() != INITIAL_VALUE);
}
 
Example #4
Source File: AWSRegionWaiter.java    From testgrid with Apache License 2.0 6 votes vote down vote up
public String waitForAvailableRegion(
        List<AWSResourceRequirement> resourceRequirements, TimeOutBuilder timeOutBuilder)
        throws ConditionTimeoutException, TestGridInfrastructureException, TestGridDAOException {

    AWSResourceLimitUOW awsResourceLimitUOW = new AWSResourceLimitUOW();
    String region = awsResourceLimitUOW.getAvailableRegion(resourceRequirements);
    if (region != null) {
        availableRegion = region;
    } else {
        logger.info("Waiting for an available region on AWS...");
        Awaitility.with().pollInterval(timeOutBuilder.getPollInterval(), timeOutBuilder.getPollUnit()).await().
                atMost(timeOutBuilder.getTimeOut(), timeOutBuilder.getTimeOutUnit())
                .until(new RegionAvailabilityWaiter(resourceRequirements));
    }
    return availableRegion;
}
 
Example #5
Source File: FileWatcherModifyITest.java    From jfilter with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testFileIsModifiedFalse() {
    /*
       Try to modify file, result should be modified
     */
    file.setLastModified(new Date().getTime() + 5000);
    await().atMost(5, SECONDS).until(() -> modified.get());

    assertTrue(modified.get());

    /*
       Try to modify file, result should be NOT modified, because lastModify date lass than the file modify date
     */
    modified.set(false);
    file.setLastModified(new Date().getTime() - 1000);
    try {
        await().atMost(5, SECONDS).until(() -> modified.get());
    } catch (ConditionTimeoutException e) {
        modified.set(false);
    }

    assertFalse(modified.get());
}
 
Example #6
Source File: Transactions.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public void awaitBlockContaining(final String hash) {
  try {
    waitFor(() -> assertThat(eth.getTransactionReceipt(hash).isPresent()).isTrue());
  } catch (final ConditionTimeoutException e) {
    LOG.error("Timed out waiting for a block containing the transaction receipt hash: " + hash);
    throw new RuntimeException("No receipt found for hash: " + hash);
  }
}
 
Example #7
Source File: ElasticsearchArtifactResolverSlave.java    From elasticsearch-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void waitForLockFileCleanup(File lockFile) throws ConditionTimeoutException
{
    config.getLog().info("Waiting for the master process to clean up the lock file");

    try
    {
        Awaitility
                .await("cleanup of the lock file by another plugin execution")
                .atMost(15, TimeUnit.SECONDS)
                .pollDelay(1, TimeUnit.SECONDS)
                .pollInterval(1, TimeUnit.SECONDS)
                .until(() -> {
                    boolean exists = lockFile.exists();
                    config.getLog().debug(
                            "Waiting for the lock file clean up; lock file exist = " + exists);
                    return exists == false;
                });

        config.getLog().info("The master process has finished cleaning up the lock file");
    }
    catch (ConditionTimeoutException ex)
    {
        config.getLog().info(
                "We have timed out waiting for the master process"
                + " to clean up the lock file '" + lockFile.getAbsolutePath() + "'");
    }
}
 
Example #8
Source File: RabbitMQWorkQueueTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void tasksShouldBeConsumedSequentially() {
    AtomicLong counter = new AtomicLong(0L);

    Task task1 = new MemoryReferenceTask(() -> {
        counter.addAndGet(1);
        Thread.sleep(1000);
        return Task.Result.COMPLETED;
    });
    TaskId taskId1 = TaskId.fromString("1111d081-aa30-11e9-bf6c-2d3b9e84aafd");
    TaskWithId taskWithId1 = new TaskWithId(taskId1, task1);

    Task task2 =  new MemoryReferenceTask(() -> {
        counter.addAndGet(2);
        return Task.Result.COMPLETED;
    });

    TaskId taskId2 = TaskId.fromString("2222d082-aa30-22e9-bf6c-2d3b9e84aafd");
    TaskWithId taskWithId2 = new TaskWithId(taskId2, task2);

    testee.submit(taskWithId1);
    testee.submit(taskWithId2);

    assertThatThrownBy(() -> await().atMost(FIVE_HUNDRED_MILLISECONDS).untilAtomic(counter, CoreMatchers.equalTo(3L))).isInstanceOf(ConditionTimeoutException.class);
    assertThatCode(() -> await().atMost(TWO_SECONDS).untilAtomic(counter, CoreMatchers.equalTo(3L))).doesNotThrowAnyException();

}
 
Example #9
Source File: EventVerifier.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private void verifyRightCountOfEvents(final Expect[] expectedEvents) {

        for (final Expect expectedEvent : expectedEvents) {
            try {
                Awaitility.await().atMost(5, TimeUnit.SECONDS)
                        .until(() -> eventCaptor.getCountFor(expectedEvent.type()), equalTo(expectedEvent.count()));

            } catch (final ConditionTimeoutException ex) {
                Assert.fail("Did not receive the expected amount of events form " + expectedEvent.type() + " Expected: "
                        + expectedEvent.count() + " but was: " + eventCaptor.getCountFor(expectedEvent.type()));
            }
        }
    }
 
Example #10
Source File: FFMpegRecorder.java    From video-recorder-java with MIT License 5 votes vote down vote up
private void waitForVideoCompleted(File video) {
    try {
        await().atMost(5, TimeUnit.SECONDS)
                .pollDelay(1, TimeUnit.SECONDS)
                .ignoreExceptions()
                .until(video::exists);
    } catch (ConditionTimeoutException ex) {
        throw new RecordingException(ex.getMessage());
    }
}
 
Example #11
Source File: StackCreationWaiter.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * Periodically checks for the status of stack creation until a defined timeout.
 *
 * @param stackName       Name of the stack
 * @param cloudFormation  AWS cloud formation
 * @param timeOutBuilder  TimeOut object
 */
public void waitForStack(String stackName, AmazonCloudFormation cloudFormation,
                         TimeOutBuilder timeOutBuilder)
        throws ConditionTimeoutException, TestGridInfrastructureException {
    logger.info("AWS CloudFormation stack creation events:");
    Awaitility.with().pollInterval(timeOutBuilder.getPollInterval(), timeOutBuilder.getPollUnit()).await().
            atMost(timeOutBuilder.getTimeOut(), timeOutBuilder.getTimeOutUnit())
            .until(new StackCreationVerifier(stackName, cloudFormation));
}
 
Example #12
Source File: MockUtils.java    From jfilter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
public static boolean sleep(Integer timeout) {
    try {
        await().atMost(timeout, TimeUnit.SECONDS)
                .untilTrue(new AtomicBoolean(false));
        return true;
    } catch (ConditionTimeoutException e) {
        return false;
    }
}
 
Example #13
Source File: BaseRabbitMqTracingItTest.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
void checkNoSpans() {
  try {
    FinishedSpansHelper spans = awaitFinishedSpans();
    Assert.fail("Expected not to receive trace spans when autoconfiguration isn't enabled, but got: " + spans);
  } catch (ConditionTimeoutException e) {
    assertThat(tracer.finishedSpans().size(), equalTo(0));
  }
}
 
Example #14
Source File: SearchTestUtilsTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void waitUntilItemServed_snippetMatchOnlyFails() throws IOException {
  when(searchHelper.search(any()))
      .thenReturn(
          new SearchResponse()
          .setResults(asList(
              new SearchResult().setTitle("other").setSnippet(new Snippet().setSnippet("bar")))));
  thrown.expect(ConditionTimeoutException.class);
  subject.waitUntilItemServed("foo", "bar");
}
 
Example #15
Source File: SearchTestUtilsTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void waitUntilItemServed_titleMatchOnlyFails() throws IOException {
  when(searchHelper.search(any()))
      .thenReturn(
          new SearchResponse()
          .setResults(asList(
              new SearchResult().setTitle("foo").setSnippet(new Snippet().setSnippet("other")))));
  thrown.expect(ConditionTimeoutException.class);
  subject.waitUntilItemServed("foo", "bar");
}
 
Example #16
Source File: TestNodeList.java    From besu with Apache License 2.0 5 votes vote down vote up
public void assertPendingTransactionCounts(final int... expected) {
  checkNotNull(expected);
  checkArgument(
      expected.length == nodes.size(),
      "Expected values for sd nodes, but got %s.",
      expected.length,
      nodes.size());
  int errCnt = 0;
  final StringBuilder sb = new StringBuilder();
  int i = 0;
  for (final TestNode node : nodes) {
    final int expectedCnt = expected[i];
    try {
      Awaitility.await()
          .atMost(MSG_WAIT)
          .until(() -> node.getPendingTransactionCount() == expectedCnt);
    } catch (final ConditionTimeoutException e) {
      /* Ignore ConditionTimeoutException.  We just want a fancy wait here.  The real check will happen
        below and has a proper exception message
      */
    }

    final int actual = node.getPendingTransactionCount();
    if (actual != expected[i]) {
      errCnt++;
      final String msg =
          format(
              "Node %s expected %d pending txs, but has %d.\n",
              node.shortId(), expected[i], actual);
      sb.append(msg);
    }
    i++;
  }
  final String header = "Nodes have " + errCnt + " incorrect Pending Tx pool sizes.\n";
  assertThat(errCnt).describedAs(header + sb).isEqualTo(0);
}
 
Example #17
Source File: BesuNode.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Override
public void awaitStartupCompletion() {
  try {
    LOG.info("Waiting for Besu to become responsive...");
    waitFor(60, () -> assertThat(jsonRpc.ethBlockNumber().send().hasError()).isFalse());
    LOG.info("Besu is now responsive");
    waitFor(
        () ->
            assertThat(jsonRpc.ethBlockNumber().send().getBlockNumber())
                .isGreaterThan(SPURIOUS_DRAGON_HARD_FORK_BLOCK));
  } catch (final ConditionTimeoutException e) {
    showLogFromBesuContainer();
    throw new RuntimeException("Failed to start the Besu node", e);
  }
}
 
Example #18
Source File: Contracts.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public void awaitBlockContaining(final String hash) {
  try {
    waitFor(() -> assertThat(getTransactionReceipt(hash).isPresent()).isTrue());
  } catch (final ConditionTimeoutException e) {
    LOG.error("Timed out waiting for a block containing the transaction receipt hash: " + hash);
  }
}
 
Example #19
Source File: JarRunnerIT.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testThatFastJarFormatWorks() throws Exception {
    File testDir = initProject("projects/classic", "projects/project-classic-console-output-fast-jar");
    RunningInvoker running = new RunningInvoker(testDir, false);

    MavenProcessInvocationResult result = running
            .execute(Arrays.asList("package", "-DskipTests", "-Dquarkus.package.type=fast-jar"), Collections.emptyMap());

    await().atMost(1, TimeUnit.MINUTES).until(() -> result.getProcess() != null && !result.getProcess().isAlive());
    assertThat(running.log()).containsIgnoringCase("BUILD SUCCESS");
    running.stop();

    Path jar = testDir.toPath().toAbsolutePath()
            .resolve(Paths.get("target/acme-1.0-SNAPSHOT-runner.jar"));
    Assertions.assertFalse(Files.exists(jar));

    jar = testDir.toPath().toAbsolutePath()
            .resolve(Paths.get("target/quarkus-app/quarkus-run.jar"));
    Assertions.assertTrue(Files.exists(jar));
    File output = new File(testDir, "target/output.log");
    output.createNewFile();

    Process process = doLaunch(jar, output).start();
    try {
        // Wait until server up
        dumpFileContentOnFailure(() -> {
            await()
                    .pollDelay(1, TimeUnit.SECONDS)
                    .atMost(1, TimeUnit.MINUTES).until(() -> DevModeTestUtils.getHttpResponse("/app/hello/package", 200));
            return null;
        }, output, ConditionTimeoutException.class);

        String logs = FileUtils.readFileToString(output, "UTF-8");

        assertThatOutputWorksCorrectly(logs);

        // test that the application name and version are properly set
        assertApplicationPropertiesSetCorrectly();
        assertResourceReadingFromClassPathWorksCorrectly("");
    } finally {
        process.destroy();
    }

}
 
Example #20
Source File: JarRunnerIT.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
@EnabledForJreRange(min = JRE.JAVA_11)
public void testThatAppCDSAreUsable() throws Exception {
    File testDir = initProject("projects/classic", "projects/project-classic-console-output-appcds");
    RunningInvoker running = new RunningInvoker(testDir, false);

    MavenProcessInvocationResult result = running
            .execute(Arrays.asList("package", "-DskipTests", "-Dquarkus.package.create-appcds=true"),
                    Collections.emptyMap());

    await().atMost(1, TimeUnit.MINUTES).until(() -> result.getProcess() != null && !result.getProcess().isAlive());
    assertThat(running.log()).containsIgnoringCase("BUILD SUCCESS");
    running.stop();

    Path jar = testDir.toPath().toAbsolutePath()
            .resolve(Paths.get("target/acme-1.0-SNAPSHOT-runner.jar"));
    File output = new File(testDir, "target/output.log");
    output.createNewFile();

    // by using '-Xshare:on' we ensure that the JVM will fail if for any reason is cannot use the AppCDS
    // '-Xlog:class+path=info' will print diagnostic information that is useful for debugging if something goes wrong
    Process process = doLaunch(jar.getFileName(), output,
            Arrays.asList("-XX:SharedArchiveFile=app-cds.jsa", "-Xshare:on", "-Xlog:class+path=info"))
                    .directory(jar.getParent().toFile()).start();
    try {
        // Wait until server up
        dumpFileContentOnFailure(() -> {
            await()
                    .pollDelay(1, TimeUnit.SECONDS)
                    .atMost(1, TimeUnit.MINUTES).until(() -> DevModeTestUtils.getHttpResponse("/app/hello/package", 200));
            return null;
        }, output, ConditionTimeoutException.class);

        String logs = FileUtils.readFileToString(output, "UTF-8");

        assertThatOutputWorksCorrectly(logs);
    } finally {
        process.destroy();
    }

}
 
Example #21
Source File: ReactivityTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Test(expected = ConditionTimeoutException.class)
@Override
public void shouldRunReactively() throws JsonProcessingException {
  super.shouldRunReactively();
}
 
Example #22
Source File: CentralDogmaBeanTest.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Test
void test() {
    final int[] called = new int[1];
    final Consumer<TestProperty> listener = testProperty -> called[0] = 1;
    final CentralDogma client = dogma.client();
    final TestProperty property = factory.get(new TestProperty(), TestProperty.class, listener);

    final PushResult res = client.push("a", "b", Revision.HEAD, "Add c.json",
                                       Change.ofJsonUpsert("/c.json",
                                                           '{' +
                                                           "  \"foo\": 20," +
                                                           "  \"bar\": \"Y\"," +
                                                           "  \"qux\": [\"0\", \"1\"]" +
                                                           '}')).join();

    // Wait until the changes are handled.
    await().atMost(5000, TimeUnit.SECONDS).until(() -> property.getFoo() == 20);

    assertThat(property.getBar()).isEqualTo("Y");
    assertThat(property.getQux()).containsExactly("0", "1");
    assertThat(property.getRevision()).isNotNull();
    assertThat(called[0]).isEqualTo(1);

    // test that after close a watcher, it could not receive change anymore
    property.closeWatcher();
    client.push("a", "b", Revision.HEAD, "Modify c.json",
                Change.ofJsonUpsert("/c.json",
                                    '{' +
                                    "  \"foo\": 50," +
                                    "  \"bar\": \"Y2\"," +
                                    "  \"qux\": [\"M\", \"N\"]" +
                                    '}'))
          .join();
    // TODO(huydx): this test may be flaky, is there any better way?
    final Throwable thrown = catchThrowable(() -> await().atMost(2, TimeUnit.SECONDS)
                                                         .until(() -> property.getFoo() == 50));
    assertThat(thrown).isInstanceOf(ConditionTimeoutException.class);

    // test that fail consumer will prevent it from receive change
    // TODO(huydx): this test may be flaky, is there any better way?
    final Consumer<TestProperty> failListener = testProperty -> {
        throw new RuntimeException("test runtime exception");
    };
    final TestProperty failProp = factory.get(new TestProperty(), TestProperty.class, failListener);
    client.push("a", "b", Revision.HEAD, "Add a.json",
                Change.ofJsonUpsert("/c.json",
                                    '{' +
                                    "  \"foo\": 211," +
                                    "  \"bar\": \"Y\"," +
                                    "  \"qux\": [\"11\", \"1\"]" +
                                    '}'))
          .join();
    // await will fail due to exception is thrown before node get serialized
    // and revision will remain null
    final Throwable thrown2 = catchThrowable(() -> await().atMost(2, TimeUnit.SECONDS)
                                                          .until(() -> failProp.getFoo() == 211));
    assertThat(thrown2).isInstanceOf(ConditionTimeoutException.class);
    assertThat(failProp.getRevision()).isNull();
}
 
Example #23
Source File: ReactivityTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Test(expected = ConditionTimeoutException.class)
@Override
public void shouldRunReactively() throws JsonProcessingException {
  super.shouldRunReactively();
}
 
Example #24
Source File: ThrottledMessageBufferTest.java    From storm-dynamic-spout with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Tests that we throttle/block put() calls on "Throttled" spout identifiers.
 */
@Test
public void testThrottling() throws InterruptedException {
    final int bufferSize = 4;
    final int throttledBufferSize = 2;
    final String regexPattern = "^Throttled.*";

    // Create instance & open
    ThrottledMessageBuffer buffer = createDefaultBuffer(bufferSize, throttledBufferSize, regexPattern);

    // Create 3 VSpout Ids
    VirtualSpoutIdentifier virtualSpoutId1 = new DefaultVirtualSpoutIdentifier("Identifier1");
    VirtualSpoutIdentifier virtualSpoutId2 = new DefaultVirtualSpoutIdentifier("Throttled Identifier 1");
    VirtualSpoutIdentifier virtualSpoutId3 = new DefaultVirtualSpoutIdentifier("Throttled Identifier 2");

    // Notify buffer of our Ids
    buffer.addVirtualSpoutId(virtualSpoutId1);
    buffer.addVirtualSpoutId(virtualSpoutId2);
    buffer.addVirtualSpoutId(virtualSpoutId3);

    Message message1 = createMessage(virtualSpoutId1, new Values("A", "B"));
    Message message2 = createMessage(virtualSpoutId1, new Values("C", "D"));
    Message message3 = createMessage(virtualSpoutId1, new Values("E", "F"));
    Message message4 = createMessage(virtualSpoutId1, new Values("G", "H"));
    // We will not be able to add this message to the buffer because we will have reached out max size
    Message message5 = createMessage(virtualSpoutId1, new Values("I", "J"));

    // Add messages, these will not be throttled because the buffer has room
    buffer.put(message1);
    buffer.put(message2);
    buffer.put(message3);
    buffer.put(message4);

    assertEquals(4, buffer.size());

    // Track whether or not we hit the timeout
    boolean timedOut = false;

    // We are going to attempt an await call, but we are actually expecting it to timeout because put() on the
    // buffer is going to block until the buffer has room.
    try {
        await()
            // The timeout here is arbitrary, we just need to prove that putting onto the buffer does not work
            .atMost(2, TimeUnit.SECONDS)
            .untilAsserted(() -> {
                try {
                    buffer.put(message5);
                } catch (InterruptedException e) {
                    // The interruption will occur when the timeout is reached, we are just throwing an unchecked
                    // exception here to end the until.
                    throw new RuntimeException(e);
                }
            });
    } catch (ConditionTimeoutException ex) {
        timedOut = true;
    }

    assertTrue(timedOut, "Timed out trying to put onto the buffer.");

    Message resultMessage1 = buffer.poll();

    assertEquals(3, buffer.size());

    assertNotNull(message1, "First message we put is not null");
    assertEquals(message1, resultMessage1, "First message we put matches the first resulting message");

    // We should be able to put the message that timed out back onto the buffer now
    buffer.put(message5);

    assertEquals(4, buffer.size());

    assertEquals(message2, buffer.poll(), "Second message we put matches the first resulting message");
    assertEquals(message3, buffer.poll(), "Third message we put matches the first resulting message");
    assertEquals(message4, buffer.poll(), "Fourth message we put matches the first resulting message");
    assertEquals(message5, buffer.poll(), "Fifth message (the one that was blocked) we put matches the first resulting message");
}
 
Example #25
Source File: SearchTestUtilsTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void waitUntilItemServed_failOnAllTries() throws IOException {
  when(searchHelper.search(any())).thenReturn(new SearchResponse());
  thrown.expect(ConditionTimeoutException.class);
  subject.waitUntilItemServed("foo", "bar");
}
 
Example #26
Source File: ElasticsearchArtifactResolver.java    From elasticsearch-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Resolve the Elasticsearch reference, downloading and installing it if necessary.
 * @param retry whether to retry on various failures
 *     (eg. time out waiting for the master process to write the server port in the lock file,
 *     time out waiting for the master process to clean up the lock file,
 *     etc)
 * @return the Elasticsearch artifact file in the local filesystem
 * @throws ArtifactException when an artifact exception occurs
 * @throws IOException when an IO exception occurs
 */
private File resolve(boolean retryOnFail) throws ArtifactException, IOException
{
    try
    {
        return resolveMavenArtifact();
    }
    catch (ArtifactException e)
    {
        config.getLog().info("Artifact not found; going the hard way (download and install)");

        File lockFile = buildLockFile();
        boolean lockFileCreated = lockFile.createNewFile();

        if (lockFileCreated)
        {
            config.getLog().info("Running in master mode. Created the lock file.");

            // set it to delete on exit only if we're in master mode
            lockFile.deleteOnExit();

            try
            {
                new ElasticsearchArtifactResolverMaster(config, artifactReference)
                        .resolve(lockFile);
            }
            finally
            {
                lockFile.delete();
            }
        }
        else
        {
            config.getLog().info("Running in slave mode. The lock file already exists.");

            ElasticsearchArtifactResolverSlave resolverSlave =
                    new ElasticsearchArtifactResolverSlave(config);

            // read the port from the lock file
            int serverPort;
            try
            {
                serverPort = resolverSlave.readPort(lockFile);
            }
            catch (ConditionTimeoutException e1)
            {
                return cleanupLockFileAndRetry(lockFile, retryOnFail);
            }

            if (serverPort == -1)
            {
                config.getLog().info(
                        "The master process has finished downloading"
                        + " and installing the artifact");

                return resolveMavenArtifact();
            }

            resolverSlave.waitForMasterResolverServer(serverPort);

            try
            {
                resolverSlave.waitForLockFileCleanup(lockFile);
            }
            catch (ConditionTimeoutException ex)
            {
                return cleanupLockFileAndRetry(lockFile, retryOnFail);
            }
        }

        // if we got this far, it means that the artifact was downloaded and installed
        return resolveMavenArtifact();
    }
}
 
Example #27
Source File: ElasticsearchArtifactResolverSlave.java    From elasticsearch-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Attempt to read the server port from the given lock file.
 * Throws a timeout exception if the port cannot be read.
 * @param lockFile The lock file to monitor
 * @return the server port (greater than 0), or -1 if the lock file has disappeared.
 * @throws ConditionTimeoutException if we time out waiting
 */
public int readPort(File lockFile) throws ConditionTimeoutException
{
    config.getLog().info("Waiting for the master process to start its server");

    MutableInt serverPort = new MutableInt(0);

    try
    {
        Awaitility
                .await("server port in the lock file")
                .atMost(15, TimeUnit.SECONDS)
                .pollDelay(1, TimeUnit.SECONDS)
                .pollInterval(1, TimeUnit.SECONDS)
                .until(() -> {
                    if (lockFile.exists())
                    {
                        String content = null;
                        try
                        {
                            content = FileUtils.readFileToString(
                                    lockFile,
                                    Charset.defaultCharset());
                            if (StringUtils.isNotBlank(content))
                            {
                                serverPort.setValue(Integer.parseInt(content.trim()));
                            }
                        }
                        catch(IOException e1)
                        {
                            config.getLog().debug(
                                    "Failed to read the content of the lock file;"
                                    + " this is unexpected, but lets not error out");
                        }
                        catch(NumberFormatException e2)
                        {
                            config.getLog().debug(
                                    "Failed to parse the file content '"
                                    + content + "' as integer");
                        }
                    }
                    else
                    {
                        config.getLog().debug(
                                "The lock file disappeared;"
                                + " stop trying to read the port");
                        serverPort.setValue(-1);
                    }
                    return serverPort.getValue() != 0;
                });

        config.getLog().info("The master process is running its server on port " + serverPort);

        return serverPort.getValue();
    }
    catch (ConditionTimeoutException ex)
    {
        config.getLog().info(
                "We have timed out waiting for the master process"
                + " to write the server port in the lock file"
                + " '" + lockFile.getAbsolutePath() + "';");
        throw ex;
    }
}