Java Code Examples for org.awaitility.Awaitility

The following examples show how to use org.awaitility.Awaitility. These examples are extracted from open source projects. 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 Project: java-spring-web   Source File: AbstractBaseITests.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testAsyncDeferred() throws Exception {
    {
        getRestTemplate().getForEntity("/asyncDeferred", String.class);
        Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1));
    }
    List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());
    assertOnErrors(mockSpans);

    MockSpan span = mockSpans.get(0);
    Assert.assertEquals("test", span.operationName());

    Assert.assertEquals(5, span.tags().size());
    Assert.assertEquals(Tags.SPAN_KIND_SERVER, span.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", span.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(getUrl("/asyncDeferred"), span.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(202, span.tags().get(Tags.HTTP_STATUS.getKey()));
    Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));

    assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterConcurrentHandlingStarted",
            "preHandle", "afterCompletion"));
}
 
Example 2
Source Project: quarkus   Source File: ReadTimeoutTestCase.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testReadSuccess() throws Exception {
    PostEndpoint.invoked = false;

    //make sure incomplete writes do not block threads
    //and that incoplete data is not delivered to the endpoint
    Socket socket = new Socket(url.getHost(), url.getPort());
    socket.getOutputStream().write(
            "POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:9\r\n\r\n12345".getBytes(StandardCharsets.UTF_8));
    socket.getOutputStream().flush();
    Thread.sleep(1);
    socket.getOutputStream().write(
            "6789".getBytes(StandardCharsets.UTF_8));
    socket.getOutputStream().flush();
    Awaitility.await().atMost(20, TimeUnit.SECONDS).pollInterval(50, TimeUnit.MILLISECONDS)
            .untilAsserted(new ThrowingRunnable() {
                @Override
                public void run() throws Throwable {
                    //make sure the read timed out and the endpoint was invoked
                    Assertions.assertTrue(PostEndpoint.invoked);
                }
            });
    socket.close();
}
 
Example 3
Source Project: jaeger-analytics-java   Source File: WaitUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void untilQueryHasTag(QueryServiceBlockingStub queryService, String service, String tagKey, String tagValue) {
  TraceQueryParameters queryParameters = TraceQueryParameters.newBuilder().setServiceName(service).build();

  Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> {
    Iterator<SpansResponseChunk> traces = queryService
        .findTraces(FindTracesRequest.newBuilder().setQuery(queryParameters).build());

    while (traces.hasNext()) {
      SpansResponseChunk trace = traces.next();
      for (Span span: trace.getSpansList()) {
        for (KeyValue tag: span.getTagsList()) {
          if (tagKey.equals(tag.getKey()) && tagValue.equals(tag.getVStr())) {
            return true;
          }
        }
      }
    }
    return false;
  });
}
 
Example 4
Source Project: elexis-3-core   Source File: TaskServiceTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Use-Case: manual execution, db check, repair, import
 * 
 * @throws Exception
 */
@Ignore("TODO fix test case")
@Test
public void triggerManual_HelloWorld() throws Exception{
	taskDescriptor = taskService.createTaskDescriptor(rwcLogContext);
	taskDescriptor.setOwner(owner);
	taskDescriptor.setReferenceId("manual_helloWorld");
	taskDescriptor.setRunContextParameter("testKey", "testValue");
	taskService.setActive(taskDescriptor, true);
	
	Optional<ITask> findExecutions = taskService.findLatestExecution(taskDescriptor);
	assertTrue(findExecutions.isPresent());
	
	ITask task =
		taskService.trigger(taskDescriptor, progressMonitor, TaskTriggerType.MANUAL, null);
	
	Awaitility.await().atMost(2, TimeUnit.SECONDS).until(taskDone(task));
	assertEquals(TaskState.COMPLETED, task.getState());
	
	findExecutions = taskService.findLatestExecution(taskDescriptor);
	assertTrue(findExecutions.isPresent());
	assertEquals(TaskState.COMPLETED, findExecutions.get().getState());
	assertTrue(findExecutions.get().getResult().containsKey("runnableExecDuration"));
}
 
Example 5
Source Project: caffeine   Source File: WriteBehindCacheWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void givenCacheUpdateOnMultipleKeys_writeBehindIsCalled() {
  AtomicBoolean writerCalled = new AtomicBoolean(false);
  AtomicInteger numberOfEntries = new AtomicInteger(0);

  // Given this cache...
  Cache<Long, ZonedDateTime> cache = Caffeine.newBuilder()
      .writer(new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>()
          .bufferTime(1, TimeUnit.SECONDS)
          .coalesce(BinaryOperator.maxBy(ZonedDateTime::compareTo))
          .writeAction(entries -> {
            numberOfEntries.set(entries.size());
            writerCalled.set(true);
          }).build())
      .build();

  // When these cache updates happen ...
  cache.put(1L, ZonedDateTime.now());
  cache.put(2L, ZonedDateTime.now());
  cache.put(3L, ZonedDateTime.now());

  // Then the write behind action gets 3 entries to write
  Awaitility.await().untilTrue(writerCalled);
  Assert.assertEquals(3, numberOfEntries.intValue());
}
 
Example 6
Source Project: redisson   Source File: RedissonSubscribeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    
}
 
Example 7
Source Project: weld-vertx   Source File: AsyncReferenceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncReferenceCompletionStage(TestContext context) throws InterruptedException {
    BlockingFoo.reset();
    Async async = context.async(2);

    Hello hello = weld.select(Hello.class).get();
    hello.hello().thenAccept((m) -> {
        context.assertEquals("Foo", m);
        async.complete();
    });
    BlockingFoo.complete("Foo");
    Awaitility.await().atMost(Timeouts.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> hello.foo.isDone());
    hello.hello().thenAccept((m) -> {
        context.assertEquals("Foo", m);
        async.complete();
    });
}
 
Example 8
Source Project: elasticsearch-maven-plugin   Source File: Monitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Wait until the cluster has fully started (ie. all nodes have joined).
 * @param clusterName the ES cluster name
 * @param nodesCount the number of nodes in the cluster
 * @param timeout how many seconds to wait
 */
public void waitToStartCluster(final String clusterName, int nodesCount, int timeout)
{
    log.debug(String.format(
            "Waiting up to %ds for the Elasticsearch cluster to start ...",
            timeout));
    Awaitility.await()
            .atMost(timeout, TimeUnit.SECONDS)
            .pollDelay(1, TimeUnit.SECONDS)
            .pollInterval(1,  TimeUnit.SECONDS)
            .until(new Callable<Boolean>()
                    {
                        @Override
                        public Boolean call() throws Exception
                        {
                            return isClusterRunning(clusterName, nodesCount, client);
                        }
                    }
            );
    log.info("The Elasticsearch cluster has started");
}
 
Example 9
Source Project: micro-integrator   Source File: ESBIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private String retrieveArtifactUsingManagementApi(String artifactType) throws IOException {

        if (!isManagementApiAvailable) {
            Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(DEFAULT_TIMEOUT, TimeUnit.SECONDS).
                    until(isManagementApiAvailable());
        }

        SimpleHttpClient client = new SimpleHttpClient();
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        String endpoint = "https://" + hostName + ":" + (DEFAULT_INTERNAL_API_HTTPS_PORT + portOffset) + "/management/"
                + artifactType;

        HttpResponse response = client.doGet(endpoint, headers);
        return client.getResponsePayload(response);
    }
 
Example 10
Source Project: micro-integrator   Source File: VFSTransportTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = Linux Path, " + "transport.vfs.ContentType = text/xml, "
        + "transport.vfs.FileNamePattern = - *\\.xml")
public void testVFSProxyFileURI_LinuxPath_ContentType_XML() throws Exception {

    //Related proxy : VFSProxy1
    File sourceFile = new File(pathToVfsDir + File.separator + "test.xml");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy1") + File.separator + "in" + File.separator + "test.xml");
    File outfile = new File(proxyVFSRoots.get("VFSProxy1") + File.separator + "out" + File.separator + "out.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS).until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "WSO2 Company"));
}
 
Example 11
Source Project: product-ei   Source File: BpelVersioningTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.bps", "wso2.bps.deployment"}, description = "Tests uploading Bpel Service with In memory", singleThreaded = true)
public void getVersion() throws RemoteException, XMLStreamException, InterruptedException,
        ProcessManagementException {

    Awaitility.await()
            .pollInterval(50, TimeUnit.MILLISECONDS)
            .atMost(MAX_TIME, TimeUnit.SECONDS)
            .until(isInforListAvailable("HelloWorld2"));
    List<String> processBefore = bpelProcessManagementClient.getProcessInfoList("HelloWorld2");
    activeStatus = new LinkedList<String>();
    for (String processid : processBefore) {
        if (bpelProcessManagementClient.getStatus(processid).equals("ACTIVE")) {
            activeStatus.add(processid);
        }
    }
    sendRequest();
}
 
Example 12
Source Project: micro-integrator   Source File: VFSTransportTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = /home/someuser/somedir " + "transport.vfs.ContentType = text/plain, "
        + "transport.vfs.FileNamePattern = - *\\.txt, " + "transport.PollInterval=1,"
        + " transport.vfs.ReplyFileName = out.txt ")
public void testVFSProxyReplyFileName_Normal() throws Exception {

    //Related proxy : VFSProxy9
    File sourceFile = new File(pathToVfsDir + File.separator + "test.txt");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "in" + File.separator + "test.txt");
    File outfile = new File(proxyVFSRoots.get("VFSProxy9") + File.separator + "out" + File.separator + "out.txt");

    FileUtils.copyFile(sourceFile, targetFile);

    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "[email protected]"));
}
 
Example 13
Source Project: micro-integrator   Source File: VFSTransportTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport : "
        + "transport.vfs.FileURI = /home/someuser/somedir " + "transport.vfs.ContentType = text/plain, "
        + "transport.vfs.FileNamePattern = - *\\.txt, " + "transport.PollInterval=1, "
        + "transport.vfs.ReplyFileName = not specified ")
public void testVFSProxyReplyFileName_NotSpecified() throws Exception {

    //Related proxy : VFSProxy11
    File sourceFile = new File(pathToVfsDir + File.separator + "test.txt");
    File targetFile = new File(proxyVFSRoots.get("VFSProxy11") + File.separator + "in" + File.separator + "test" +
            ".txt");
    File outfile = new File(proxyVFSRoots.get("VFSProxy11") + File.separator + "out" + File.separator + "response.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileExist(outfile));
    Assert.assertTrue(outfile.exists());
    Assert.assertTrue(doesFileContain(outfile, "[email protected]"));
}
 
Example 14
Source Project: AILibs   Source File: InterruptTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Two timed computations are nested. The outer is canceled significantly (1s) earlier than the inner.
 *
 * @throws ExecutionException
 * @throws InterruptedException
 */
@Test
public void testNestedInterruptDuringExecutionWithOuterSignifiantlyEarlier() throws ExecutionException, InterruptedException {

	for (int i = 0; i < NUMBER_ITERATIONS_SHIFTED; i++) {

		/* test that InterruptException is thrown and that no interrupts are open */
		try {
			TimedComputation.compute(() -> TimedComputation.compute(new BusyBeaver(Long.MAX_VALUE), 2000, "inner interrupt"), 1000, "outer interrupt");
		} catch (AlgorithmTimeoutedException e) {

			/* this is expected behavior */
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			Awaitility.await().atLeast(2, TimeUnit.SECONDS);
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			continue;
		}
		fail("No exception was thrown, but an AlgorithmTimedoutedException should have been thrown!");
	}
}
 
Example 15
Source Project: micro-integrator   Source File: VFSTransportTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Sending a file through VFS Transport :"
        + " transport.vfs.FileURI = Linux Path, " + "transport.vfs.ContentType = text/xml, "
        + "transport.vfs.FileNamePattern = - *\\.xml " + "transport.vfs.ActionAfterFailure=NotSpecified")
public void testVFSProxyActionAfterFailure_NotSpecified() throws Exception {

    String proxyName = "VFSProxy14";
    File sourceFile = new File(pathToVfsDir + File.separator + "fail.xml");
    File targetFile = new File(proxyVFSRoots.get(proxyName) + File.separator + "in" + File.separator + "fail.xml");
    File outfile = new File(proxyVFSRoots.get(proxyName) + File.separator + "out" + File.separator + "out.xml");
    File originalFile = new File(proxyVFSRoots.get(proxyName) + File.separator + "failure" + File.separator + "fail.xml");

    FileUtils.copyFile(sourceFile, targetFile);
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileNotExist(targetFile));
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
            .until(isFileNotExist(outfile));
    Assert.assertFalse(outfile.exists());
    Assert.assertFalse(originalFile.exists());
    Assert.assertFalse(
            new File(proxyVFSRoots.get(proxyName) + File.separator + "in" + File.separator + "fail.xml.lock").exists(),
            "lock file exists even after moving the failed file");
}
 
Example 16
Source Project: redisson   Source File: RedissonSubscribeReactiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplate() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    AtomicLong counter = new AtomicLong();

    ReactiveStringRedisTemplate template = new ReactiveStringRedisTemplate(factory);
    template.listenTo(ChannelTopic.of("test")).flatMap(message -> {
        counter.incrementAndGet();
        return Mono.empty();
    }).subscribe();

    template.listenTo(ChannelTopic.of("test2")).flatMap(message -> {
        counter.incrementAndGet();
        return Mono.empty();
    }).subscribe();

    ReactiveRedisConnection connection = factory.getReactiveConnection();
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();

    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> counter.get() == 1);
}
 
Example 17
Source Project: spring-cloud-sleuth   Source File: Issue410Tests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Related to issue #1232
 */
@Test
public void should_pass_tracing_info_for_submitted_tasks_with_threadPoolTaskScheduler() {
	Span span = this.tracer.nextSpan().name("foo");
	log.info("Starting test");
	try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
		String response = this.restTemplate.getForObject(
				"http://localhost:" + port() + "/threadPoolTaskScheduler_submit",
				String.class);

		then(response).isEqualTo(span.context().traceIdString());
		Awaitility.await().untilAsserted(() -> {
			then(this.asyncTask.getSpan().get()).isNotNull();
			then(this.asyncTask.getSpan().get().context().traceId())
					.isEqualTo(span.context().traceId());
		});
	}
	finally {
		span.finish();
	}

	then(this.tracer.currentSpan()).isNull();
}
 
Example 18
Source Project: redisson   Source File: RedissonSubscribeReactiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    ReactiveRedisConnection connection = factory.getReactiveConnection();
    Mono<ReactiveSubscription> s = connection.pubSubCommands().createSubscription();
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    ReactiveSubscription ss = s.block();

    ss.subscribe(ByteBuffer.wrap("test".getBytes())).block();
    ss.receive().doOnEach(message -> {
        msg.set(message.get().getMessage().array());
    }).subscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();

    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    ss.unsubscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
}
 
Example 19
@Test
public void resolvePolicyIdFromThingReturnsPolicyId() {

    final ReferencePlaceholder referencePlaceholder =
            ReferencePlaceholder.fromCharSequence("{{ ref:things/" + THING_ID + "/policyId }}")
                    .orElseThrow(IllegalStateException::new);

    final CompletionStage<String> policyIdCS = sut.resolve(referencePlaceholder, DittoHeaders.empty());

    final RetrieveThing retrieveThing = conciergeForwarderActorProbe.expectMsgClass(RetrieveThing.class);
    assertThat((CharSequence) retrieveThing.getThingEntityId()).isEqualTo(THING_ID);
    assertThat(retrieveThing.getSelectedFields()).contains(JsonFieldSelector.newInstance("policyId"));

    conciergeForwarderActorProbe.reply(RetrieveThingResponse.of(THING_ID,
            Thing.newBuilder().setPolicyId("namespace:myPolicy").build(), DittoHeaders.empty()));

    Awaitility.await()
            .atMost(org.awaitility.Duration.ONE_SECOND)
            .until(() -> policyIdCS.toCompletableFuture().isDone());
    assertThat(policyIdCS.toCompletableFuture())
            .isCompletedWithValue("namespace:myPolicy");
}
 
Example 20
private void waitForLogMessage(BufferedReader reader, String message) {
	Awaitility.await(message)
		.atMost(60, TimeUnit.SECONDS)
		.until(() -> {
			// drain all lines up to the one requested, or until no more lines in reader.
			while (reader.ready()) {
				String line = reader.readLine();

				if (line == null) {
					return false;
				}

				if (line.contains(message)) {
					return true;
				}
			}
			return false;
		});
}
 
Example 21
Source Project: cloudinary_android   Source File: ResponsiveTest.java    License: MIT License 6 votes vote down vote up
private void onlyWidthTest(String gravity, String cropMode, int stepSize, int minDimension, int maxDimension, int viewWidth, int viewHeight, final String expectedUrlSuffix) {
    final StatefulCallback callback = new StatefulCallback();

    new ResponsiveUrl(cloudinary, true, false, cropMode, gravity)
            .stepSize(stepSize)
            .minDimension(minDimension)
            .maxDimension(maxDimension)
            .generate("publicId", getImageView(viewWidth, viewHeight), callback);

    Awaitility.await().atMost(Duration.ONE_SECOND).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return callback.url.endsWith(expectedUrlSuffix);
        }
    });
}
 
Example 22
@Test
public void testFilePropagatedToLocalDirectory() {
	BlobId blobId = BlobId.of(this.cloudInputBucket, TEST_FILE_NAME);
	BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
	this.storage.create(blobInfo, "Hello World!".getBytes(StandardCharsets.UTF_8));

	Awaitility.await().atMost(15, TimeUnit.SECONDS)
			.untilAsserted(() -> {
				Path outputFile = Paths.get(this.outputFolder + "/" + TEST_FILE_NAME);
				assertThat(Files.exists(outputFile)).isTrue();
				assertThat(Files.isRegularFile(outputFile)).isTrue();

				String firstLine = Files.lines(outputFile).findFirst().get();
				assertThat(firstLine).isEqualTo("Hello World!");

				List<String> blobNamesInOutputBucket = new ArrayList<>();
				this.storage.list(this.cloudOutputBucket).iterateAll()
						.forEach((b) -> blobNamesInOutputBucket.add(b.getName()));

				assertThat(blobNamesInOutputBucket).contains(TEST_FILE_NAME);
			});
}
 
Example 23
Source Project: product-ei   Source File: MSMPCronForwarderCase.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true)
protected void init() throws Exception {
    // START THE ESB
    super.init();
    // START THE SERVER
    tomcatServerManager =
            new TomcatServerManager(CustomerConfig.class.getName(), TomcatServerType.jaxrs.name(), 8080);

    tomcatServerManager.startServer();  // staring tomcat server instance
    Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS)
              .until(isServerStarted());
    logAdmin = new LoggingAdminClient(contextUrls.getBackEndUrl(), getSessionCookie());
    serverConfigurationManager =
            new ServerConfigurationManager(new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN));
    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    File log4jProperties = new File(carbonHome + File.separator + "conf" +
            File.separator + "log4j2.properties");
    applyProperty(log4jProperties, "logger.org-apache-synapse.level", "DEBUG");
    serverConfigurationManager.restartGracefully();
    super.init();
}
 
Example 24
Source Project: AILibs   Source File: InterruptTest.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Two timed computations are nested. The outer is canceled significantly (1s) later than the inner.
 *
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws AlgorithmTimeoutedException
 */
@Test
public void testNestedInterruptDuringExecutionWithOuterSignifiantlyLater() throws InterruptedException, AlgorithmTimeoutedException, ExecutionException {
	this.checkPreconditions();
	for (int i = 0; i < NUMBER_ITERATIONS_SHIFTED; i++) {

		/* test that InterruptException is thrown and that no interrupts are open */
		try {
			TimedComputation.compute(() -> TimedComputation.compute(new BusyBeaver(Long.MAX_VALUE), 1000, "inner interrupt"), 2000, "outer interrupt");
		} catch (ExecutionException e) {

			if (!(e.getCause() instanceof AlgorithmTimeoutedException)) {
				throw e;
			}

			/* this is expected behavior */
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			Awaitility.await().atLeast(2, TimeUnit.SECONDS);
			assertTrue(GlobalTimer.getInstance().getActiveTasks().isEmpty());
			assertFalse(Interrupter.get().hasCurrentThreadOpenInterrupts());
			continue;
		}
		fail("No exception was thrown, but an AlgorithmTimedoutedException should have been thrown!");
	}
}
 
Example 25
Source Project: redisson   Source File: RedissonSubscribeReactiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    ReactiveRedisConnection connection = factory.getReactiveConnection();
    Mono<ReactiveSubscription> s = connection.pubSubCommands().createSubscription();
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    ReactiveSubscription ss = s.block();

    ss.subscribe(ByteBuffer.wrap("test".getBytes())).block();
    ss.receive().doOnEach(message -> {
        msg.set(message.get().getMessage().array());
    }).subscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    ss.unsubscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
    
    
}
 
Example 26
Source Project: james-project   Source File: MockSMTPServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void serverShouldActLikeDefaultAfterGettingEnoughMatches() {
    int numberOfAnswer = 4;
    MockSMTPBehavior behavior = new MockSMTPBehavior(
        MAIL_FROM,
        Condition.MATCH_ALL,
        new Response(SERVICE_NOT_AVAILABLE_421, "mock response"),
        MockSMTPBehavior.NumberOfAnswersPolicy.times(numberOfAnswer));

    behaviorRepository.setBehaviors(behavior);

    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);
    sendMessageIgnoreError(mail1);

    sendMessageIgnoreError(mail1);
    Awaitility.await().atMost(Duration.TEN_SECONDS)
        .untilAsserted(() -> assertThat(mailRepository.list()).hasSize(1));
}
 
Example 27
@Test
void givenTwoTerminationSubscribersWhenAnEventIsSentItShouldBeReceivedByBoth() {
    TerminationSubscriber subscriber1 = subscriber();
    TerminationSubscriber subscriber2 = subscriber();

    Flux<Event> firstListener = Flux.from(subscriber1.listenEvents());
    Flux<Event> secondListener = Flux.from(subscriber2.listenEvents());

    sendEvents(subscriber1, COMPLETED_EVENT);

    List<Event> receivedEventsFirst = new ArrayList<>();
    firstListener.subscribe(receivedEventsFirst::add);
    List<Event> receivedEventsSecond = new ArrayList<>();
    secondListener.subscribe(receivedEventsSecond::add);

    Awaitility.await().atMost(ONE_MINUTE).until(() -> receivedEventsFirst.size() == 1 && receivedEventsSecond.size() == 1);

    assertThat(receivedEventsFirst).containsExactly(COMPLETED_EVENT);
    assertThat(receivedEventsSecond).containsExactly(COMPLETED_EVENT);
}
 
Example 28
@Test
public void shouldAddErrorTagWhenExceptionOccurredInNewSpan() {
	try {
		Mono<String> mono = this.testBean.testMethod12("test");

		then(this.spans).isEmpty();

		mono.block();
	}
	catch (RuntimeException ignored) {
	}

	Awaitility.await().untilAsserted(() -> {
		then(this.spans).hasSize(1);
		then(this.spans.get(0).name()).isEqualTo("test-method12");
		then(this.spans.get(0).tags()).containsEntry("testTag12", "test");
		then(this.spans.get(0).error()).hasMessageContaining("test exception 12");
		then(this.spans.get(0).finishTimestamp()).isNotZero();
		then(this.tracer.currentSpan()).isNull();
	});
}
 
Example 29
Source Project: data-highway   Source File: RoadEndpointsIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createRoadAndSchemas() throws Exception {
  // create Road
  String roadName = "a1";
  BasicRoadModel basicRoadModel = new BasicRoadModel(roadName, "a1 road", "a1 team", "[email protected]", true, "", null,
      Maps.newHashMap());
  ResponseEntity<StandardResponse> createRoadResult = rest.exchange(post(uri("/paver/v1/roads"))
      .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8)))
      .contentType(APPLICATION_JSON_UTF8)
      .body(basicRoadModel), StandardResponse.class);
  assertThat(createRoadResult.getStatusCode(), is(HttpStatus.OK));
  assertThat(createRoadResult.getBody().getMessage(), is("Request to create road \"a1\" received"));

  Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> {
    String expected = "{\"documentId\":\"a1\",\"operations\":[{\"op\":\"add\",\"path\":\"\",\"value\":{\"name\":\"a1\",\"topicName\":null,\"description\":\"a1 road\",\"teamName\":\"a1 team\",\"contactEmail\":\"[email protected]\",\"enabled\":true,\"partitionPath\":\"\",\"metadata\":{},\"schemas\":{},\"destinations\":{},\"status\":null,\"compatibilityMode\":\"CAN_READ_ALL\"}}]}";
    String actual = readRecords(patchConsumer, 1).get(0);
    assertJsonEquals(expected, actual);
  });

  // Emulate TollBooth to process the above patch and create road for us.
  Map<String, Road> kafkaStore = kafkaStore();
  Road road = new Road();
  road.setName(roadName);
  kafkaStore.put(roadName, road);

  // Add schema to road.
  ResponseEntity<StandardResponse> schemaResult = rest.exchange(post(uri("/paver/v1/roads/a1/schemas"))
      .header(AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString("user:pass".getBytes(UTF_8)))
      .contentType(APPLICATION_JSON_UTF8)
      .body(schema1.toString()), StandardResponse.class);
  assertThat(schemaResult.getStatusCode(), is(HttpStatus.OK));
  assertThat(schemaResult.getBody().getMessage(), is("Request to add a new schema received."));

  Awaitility.await().atMost(Duration.FIVE_SECONDS).until(() -> {
    List<String> records = readRecords(patchConsumer, 1);
    String expectedPatch = "{\"documentId\":\"a1\",\"operations\":[{\"op\":\"add\",\"path\":\"/schemas/1\",\"value\":{\"schema\":{\"type\":\"record\",\"name\":\"record\",\"fields\":[{\"name\":\"field\",\"type\":\"boolean\"}]},\"version\":1,\"deleted\":false}}]}";
    assertJsonEquals(expectedPatch, records.get(0));
  });
}
 
Example 30
Source Project: helios   Source File: HeliosSoloIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceDiscovery() throws Exception {
  // start a container that runs nginx and registers with SkyDNS
  final TemporaryJob nginx = jobs.job()
      .image(NGINX)
      .port("http", 80, ports.localPort("http"))
      .registration("nginx", "http", "http")
      .deploy();

  // run a container that does SRV lookup to find the nginx service and then curl's it
  final TemporaryJob alpine = jobs.job()
      .image(ALPINE)
      .port("nc", 4711, ports.localPort("nc"))
      .command("sh", "-c",
          "apk add --update bind-tools "
          + "&& export SRV=$(dig -t SRV +short _nginx._http.test.$SPOTIFY_DOMAIN) "
          + "&& export HOST=$(echo $SRV | cut -d' ' -f4) "
          + "&& export PORT=$(echo $SRV | cut -d' ' -f3) "
          + "&& nc -lk -p 4711 -e curl http://$HOST:$PORT"
      )
      .deploy();

  final HostAndPort alpineAddress = alpine.address("nc");

  // Connect to alpine container to get the curl response. If we get back the nginx welcome page
  // we know that helios properly registered the nginx service in SkyDNS.
  final Callable<String> socketResponse = () -> {
    try (final Socket s = new Socket(alpineAddress.getHost(), alpineAddress.getPort())) {
      return IOUtils.toString(s.getInputStream(), Charsets.UTF_8).trim();
    }
  };
  // allow a few retries for a delay in the apk install of bind-tools
  Awaitility.await("alpine container returns nginx welcome")
      .atMost(10, TimeUnit.SECONDS)
      .until(socketResponse, containsString("Welcome to nginx!"));

  // also throw in a check to make sure log streaming is working
  assertThat(new String(logStreamProvider.getStderr(nginx.job().getId())),
      containsString("nginx"));
}