Java Code Examples for java.util.concurrent.CountDownLatch#countDown()
The following examples show how to use
java.util.concurrent.CountDownLatch#countDown() .
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: GattReadWriteTests.java From bitgatt with Mozilla Public License 2.0 | 6 votes |
@Test public void readDescriptorChangeDataTest() throws InterruptedException { final byte[] fakeData = new byte[]{'a','b','c','d','e','f','g','h','i', 'j'}; BluetoothGattDescriptor descriptor = mock(BluetoothGattDescriptor.class); // this should be the same as the real thing, the data inside could change as it's pointing // to something else. when(descriptor.getValue()).thenReturn(fakeData); when(descriptor.getUuid()).thenReturn(characteristicUuid); when(descriptor.getPermissions()).thenReturn(BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED); ReadGattDescriptorTransaction readChar = new ReadGattDescriptorTransaction(conn, GattState.WRITE_CHARACTERISTIC_SUCCESS, descriptor); CountDownLatch cdl = new CountDownLatch(1); readChar.callback = result -> { fakeData[3] = 'x'; Assert.assertNotEquals(Arrays.hashCode(fakeData), Arrays.hashCode(result.getData())); cdl.countDown(); }; // the copy would happen before the callback were delivered in the tx, so this is still // valid readChar.onDescriptorRead(null, new GattUtils().copyDescriptor(descriptor), GattStatus.GATT_SUCCESS.getCode()); cdl.await(); }
Example 2
Source File: AbstractCacheTests.java From java-technology-stack with MIT License | 5 votes |
/** * Test that a call to get with a Callable concurrently properly synchronize the * invocations. */ @Test public void testCacheGetSynchronized() throws InterruptedException { T cache = getCache(); final AtomicInteger counter = new AtomicInteger(); final List<Object> results = new CopyOnWriteArrayList<>(); final CountDownLatch latch = new CountDownLatch(10); String key = createRandomKey(); Runnable run = () -> { try { Integer value = cache.get(key, () -> { Thread.sleep(50); // make sure the thread will overlap return counter.incrementAndGet(); }); results.add(value); } finally { latch.countDown(); } }; for (int i = 0; i < 10; i++) { new Thread(run).start(); } latch.await(); assertEquals(10, results.size()); results.forEach(r -> assertThat(r, is(1))); // Only one method got invoked }
Example 3
Source File: ConnectorTraverserTest.java From connector-sdk with Apache License 2.0 | 5 votes |
@Test public void testTraverseLongRunning() throws Exception { CountDownLatch alreadyRunningLatch = new CountDownLatch(2); Runnable alreadyRunningRunnable = () -> { assertThat(alreadyRunningLatch.getCount(), not(equalTo(0))); alreadyRunningLatch.countDown(); }; CountDownLatch longRunningLatch = new CountDownLatch(2); CountDownLatch firstRunLatch = new CountDownLatch(1); Runnable longRunningRunnable = () -> { try { assertTrue(alreadyRunningLatch.await(30, TimeUnit.SECONDS)); longRunningLatch.countDown(); firstRunLatch.countDown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }; OneAtATimeRunnable subject = new OneAtATimeRunnable(longRunningRunnable, alreadyRunningRunnable); Thread thread1 = new Thread(subject); Thread thread2 = new Thread(subject); Thread thread3 = new Thread(subject); Thread thread4 = new Thread(subject); thread1.start(); thread2.start(); thread3.start(); // Try to re-run task after initial task is done. assertTrue(firstRunLatch.await(30, TimeUnit.SECONDS)); thread4.start(); assertTrue(longRunningLatch.await(30, TimeUnit.SECONDS)); assertTrue(alreadyRunningLatch.await(0, TimeUnit.SECONDS)); }
Example 4
Source File: CamelSinkAWSSNSITCase.java From camel-kafka-connector with Apache License 2.0 | 5 votes |
private void consumeMessages(CountDownLatch latch) { try { awsSqsClient.receive(AWSCommon.DEFAULT_SQS_QUEUE_FOR_SNS, this::checkMessages); } catch (Throwable t) { LOG.error("Failed to consume messages: {}", t.getMessage(), t); fail(t.getMessage()); } finally { latch.countDown(); } }
Example 5
Source File: AsynchronousBufferFileWriterTest.java From flink with Apache License 2.0 | 5 votes |
@Test public void testSubscribeAndClose() throws IOException, InterruptedException { final TestNotificationListener listener = new TestNotificationListener(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final CountDownLatch sync = new CountDownLatch(1); addRequest(); addRequest(); writer.registerAllRequestsProcessedListener(listener); final Thread asyncCloseThread = new Thread(new Runnable() { @Override public void run() { try { writer.close(); } catch (Throwable t) { error.set(t); } finally { sync.countDown(); } } }); asyncCloseThread.start(); handleRequest(); handleRequest(); sync.await(); assertEquals("Listener was not notified.", 1, listener.getNumberOfNotifications()); }
Example 6
Source File: JsAgentSpec.java From swim with Apache License 2.0 | 5 votes |
@Test public void testJsAgentCommands() throws InterruptedException { final JsKernel jsKernel = new JsKernel(); jsKernel.setRootPath(UriPath.parse(System.getProperty("project.dir"))); final Kernel kernel = ServerLoader.loadServerStack().injectKernel(jsKernel); final ActorSpaceDef spaceDef = ActorSpaceDef.fromName("test") .nodeDef(ActorNodeDef.fromNodePattern("/command/:name") .agentDef(JsAgentDef.fromModulePath("./src/test/js/TestCommandAgent"))); final ActorSpace space = (ActorSpace) kernel.openSpace(spaceDef); final CountDownLatch linkOnEvent = new CountDownLatch(1); class CommandLinkController implements OnEvent<String> { @Override public void onEvent(String value) { System.out.println("link onEvent value: " + value); linkOnEvent.countDown(); } } try { kernel.openService(WebServiceDef.standard().port(53556).spaceName("test")); kernel.start(); final EventDownlink<String> commandLink = space.downlink() .valueClass(String.class) .hostUri("warp://localhost:53556") .nodeUri("/command/hello") .laneUri("command") .observe(new CommandLinkController()) .open(); commandLink.command(Text.from("Hello, world!")); linkOnEvent.await(1, TimeUnit.SECONDS); } finally { kernel.stop(); } }
Example 7
Source File: CassandraSinkBaseTest.java From flink with Apache License 2.0 | 5 votes |
@Test(timeout = DEFAULT_TEST_TIMEOUT) public void testWaitForPendingUpdatesOnSnapshot() throws Exception { final TestCassandraSink casSinkFunc = new TestCassandraSink(); try (OneInputStreamOperatorTestHarness<String, Object> testHarness = createOpenedTestHarness(casSinkFunc)) { CompletableFuture<ResultSet> completableFuture = new CompletableFuture<>(); casSinkFunc.enqueueCompletableFuture(completableFuture); casSinkFunc.invoke("hello"); Assert.assertEquals(1, casSinkFunc.getAcquiredPermits()); final CountDownLatch latch = new CountDownLatch(1); Thread t = new CheckedThread("Flink-CassandraSinkBaseTest") { @Override public void go() throws Exception { testHarness.snapshot(123L, 123L); latch.countDown(); } }; t.start(); while (t.getState() != Thread.State.WAITING) { Thread.sleep(5); } Assert.assertEquals(1, casSinkFunc.getAcquiredPermits()); completableFuture.complete(null); latch.await(); Assert.assertEquals(0, casSinkFunc.getAcquiredPermits()); } }
Example 8
Source File: ADClusterEventListenerTests.java From anomaly-detection with Apache License 2.0 | 5 votes |
public void testInprogress() throws InterruptedException { final CountDownLatch inProgressLatch = new CountDownLatch(1); final CountDownLatch executionLatch = new CountDownLatch(1); doAnswer(invocation -> { executionLatch.countDown(); inProgressLatch.await(); return emptySet(); }).when(modelManager).getAllModelIds(); new Thread(new ListenerRunnable()).start(); executionLatch.await(); listener.clusterChanged(new ClusterChangedEvent("bar", newClusterState, oldClusterState)); assertTrue(testAppender.containsMessage(ADClusterEventListener.IN_PROGRESS_MSG)); inProgressLatch.countDown(); }
Example 9
Source File: BlockService.java From WeBASE-Node-Manager with Apache License 2.0 | 5 votes |
/** * get block from chain by groupId * ThreadPool configuration in /base/config/BeanConfig */ @Async(value = "mgrAsyncExecutor") public void pullBlockByGroupId(CountDownLatch latch, int groupId) { log.debug("start pullBlockByGroupId groupId:{}", groupId); try { //max block in chain BigInteger maxChainBlock = frontInterface.getLatestBlockNumber(groupId); //next block BigInteger nextBlock = getNextBlockNumber(groupId); //pull block while (Objects.nonNull(maxChainBlock) && maxChainBlock.compareTo(nextBlock) >= 0) { log.debug("continue pull block. maxChainBlock:{} nextBlock:{}", maxChainBlock, nextBlock); Thread.sleep(cProperties.getPullBlockSleepTime()); pullBlockByNumber(groupId, nextBlock); nextBlock = getNextBlockNumber(groupId); //reset maxChainBlock if (maxChainBlock.compareTo(nextBlock) < 0) { maxChainBlock = frontInterface.getLatestBlockNumber(groupId); } } } catch (Exception ex) { log.error("fail pullBlockByGroupId. groupId:{} ", groupId, ex); }finally { // finish one group, count down latch.countDown(); } log.debug("end pullBlockByGroupId groupId:{}", groupId); }
Example 10
Source File: ConnectorSchedulerTest.java From connector-sdk with Apache License 2.0 | 5 votes |
@Test public void testIncrementalTraversal() throws Exception { final CountDownLatch latch = new CountDownLatch(1); IncrementalConnector incremental = new IncrementalConnector() { @Override public void traverse() throws IOException, InterruptedException { throw new UnsupportedOperationException("Traversal disabled on start"); } @Override public void handleIncrementalChanges() throws IOException, InterruptedException { latch.countDown(); } }; setupConfig(Collections.singletonMap("schedule.performTraversalOnStart", "false")); ConnectorContext context = new ConnectorContextImpl.Builder() .setIncrementalTraversalExceptionHandler(new RetryExceptionHandler(-1)) .build(); ConnectorScheduler<ConnectorContext> traverser = new ConnectorScheduler.Builder().setConnector(incremental).setContext(context).build(); traverser.start(); assertTrue(latch.await(30, TimeUnit.SECONDS)); traverser.stop(); assertEquals( 1, StatsManager.getInstance() .getComponent("IncrementalTraverser") .getSuccessCount("complete")); }
Example 11
Source File: ConnectorTraverserTest.java From connector-sdk with Apache License 2.0 | 5 votes |
@Test public void testTraverseRetryAndSuccess() throws Exception { setupConfig(Collections.emptyMap()); final CountDownLatch counter = new CountDownLatch(4); final AtomicBoolean success = new AtomicBoolean(false); IndexingConnector fail3Times = new AbstractConnector() { @Override public void traverse() throws IOException, InterruptedException { assertFalse(success.get()); if (counter.getCount() == 0) { fail("Unexpected traverse call."); } // Fail for 3 times before success if (counter.getCount() > 1) { counter.countDown(); throw new IOException("Try 3 times"); } success.set(true); counter.countDown(); } }; ConnectorTraverser traverser = new ConnectorTraverser.Builder() .setConnector(fail3Times) .setContext(getContextWithExceptionHandler(4)) .build(); traverser.start(); assertTrue(counter.await(30, TimeUnit.SECONDS)); assertTrue(success.get()); traverser.stop(); }
Example 12
Source File: CassandraSinkBaseTest.java From flink with Apache License 2.0 | 5 votes |
@Test(timeout = DEFAULT_TEST_TIMEOUT) public void testWaitForPendingUpdatesOnClose() throws Exception { TestCassandraSink casSinkFunc = new TestCassandraSink(); try (OneInputStreamOperatorTestHarness<String, Object> testHarness = createOpenedTestHarness(casSinkFunc)) { CompletableFuture<ResultSet> completableFuture = new CompletableFuture<>(); casSinkFunc.enqueueCompletableFuture(completableFuture); casSinkFunc.invoke("hello"); Assert.assertEquals(1, casSinkFunc.getAcquiredPermits()); final CountDownLatch latch = new CountDownLatch(1); Thread t = new CheckedThread("Flink-CassandraSinkBaseTest") { @Override public void go() throws Exception { testHarness.close(); latch.countDown(); } }; t.start(); while (t.getState() != Thread.State.WAITING) { Thread.sleep(5); } Assert.assertEquals(1, casSinkFunc.getAcquiredPermits()); completableFuture.complete(null); latch.await(); Assert.assertEquals(0, casSinkFunc.getAcquiredPermits()); } }
Example 13
Source File: MonitorService.java From WeBASE-Node-Manager with Apache License 2.0 | 4 votes |
/** * monitor every group. */ @Async(value = "mgrAsyncExecutor") public void transMonitorByGroupId(CountDownLatch latch, int groupId) { try { Instant startTimem = Instant.now();//start time Long useTimeSum = 0L; LocalDateTime start = LocalDateTime.now(); //createTime of monitor info LocalDateTime createTime = start; do { List<TbTransHash> transHashList = transHashService .qureyUnStatTransHashList(groupId); log.info("=== groupId:{} transHashList:{}", groupId, transHashList.size()); if (transHashList.size() == 0) { log.debug("transMonitorByGroupId jump over. transHashList is empty"); return; } if (checkUnusualMax(groupId)) { return; } //monitor for (TbTransHash trans : transHashList) { if (createTime.getDayOfYear() != trans.getBlockTimestamp().getDayOfYear() || start == createTime) { log.info( "============== createTime:{} blockTimestamp:{}", createTime, trans.getBlockTimestamp()); log.info( "============== createData:{} blockTimestampData:{}", createTime.getDayOfYear(), trans.getBlockTimestamp().getDayOfYear()); createTime = trans.getBlockTimestamp(); } monitorTransHash(groupId, trans, createTime); } //monitor useTime useTimeSum = Duration.between(startTimem, Instant.now()).getSeconds(); log.debug("monitor groupId:{} useTimeSum:{}s maxTime:{}s", groupId, useTimeSum, cProperties.getTransMonitorTaskFixedRate()); } while (useTimeSum < cProperties.getTransMonitorTaskFixedRate()); log.info("=== end monitor. groupId:{} allUseTime:{}s", groupId, useTimeSum); } catch (Exception ex) { log.error("fail transMonitorByGroupId, group:{}", groupId, ex); } finally { if (Objects.nonNull(latch)) { // finish one group, count down latch.countDown(); } } }
Example 14
Source File: TestOzoneRpcClientAbstract.java From hadoop-ozone with Apache License 2.0 | 4 votes |
@Test public void testPutKeyRatisThreeNodesParallel() throws IOException, InterruptedException { String volumeName = UUID.randomUUID().toString(); String bucketName = UUID.randomUUID().toString(); Instant testStartTime = Instant.now(); store.createVolume(volumeName); OzoneVolume volume = store.getVolume(volumeName); volume.createBucket(bucketName); OzoneBucket bucket = volume.getBucket(bucketName); CountDownLatch latch = new CountDownLatch(2); AtomicInteger failCount = new AtomicInteger(0); Runnable r = () -> { try { for (int i = 0; i < 5; i++) { String keyName = UUID.randomUUID().toString(); String data = generateData(5 * 1024 * 1024, (byte) RandomUtils.nextLong()).toString(); OzoneOutputStream out = bucket.createKey(keyName, data.getBytes().length, ReplicationType.RATIS, ReplicationFactor.THREE, new HashMap<>()); out.write(data.getBytes()); out.close(); OzoneKey key = bucket.getKey(keyName); Assert.assertEquals(keyName, key.getName()); OzoneInputStream is = bucket.readKey(keyName); byte[] fileContent = new byte[data.getBytes().length]; is.read(fileContent); is.close(); Assert.assertTrue(verifyRatisReplication(volumeName, bucketName, keyName, ReplicationType.RATIS, ReplicationFactor.THREE)); Assert.assertEquals(data, new String(fileContent)); Assert.assertFalse(key.getCreationTime().isBefore(testStartTime)); Assert.assertFalse(key.getModificationTime().isBefore(testStartTime)); } latch.countDown(); } catch (IOException ex) { latch.countDown(); failCount.incrementAndGet(); } }; Thread thread1 = new Thread(r); Thread thread2 = new Thread(r); thread1.start(); thread2.start(); latch.await(600, TimeUnit.SECONDS); if (failCount.get() > 0) { fail("testPutKeyRatisThreeNodesParallel failed"); } }
Example 15
Source File: ProcessTools.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
/** * <p>Starts a process from its builder.</p> * <span>The default redirects of STDOUT and STDERR are started</span> * <p> * It is possible to wait for the process to get to a warmed-up state * via {@linkplain Predicate} condition on the STDOUT * </p> * @param name The process name * @param processBuilder The process builder * @param linePredicate The {@linkplain Predicate} to use on the STDOUT * Used to determine the moment the target app is * properly warmed-up. * It can be null - in that case the warmup is skipped. * @param timeout The timeout for the warmup waiting * @param unit The timeout {@linkplain TimeUnit} * @return Returns the initialized {@linkplain Process} * @throws IOException * @throws InterruptedException * @throws TimeoutException */ public static Process startProcess(String name, ProcessBuilder processBuilder, final Predicate<String> linePredicate, long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException { Process p = processBuilder.start(); StreamPumper stdout = new StreamPumper(p.getInputStream()); StreamPumper stderr = new StreamPumper(p.getErrorStream()); stdout.addPump(new LineForwarder(name, System.out)); stderr.addPump(new LineForwarder(name, System.err)); CountDownLatch latch = new CountDownLatch(1); if (linePredicate != null) { StreamPumper.LinePump pump = new StreamPumper.LinePump() { @Override protected void processLine(String line) { if (latch.getCount() > 0 && linePredicate.test(line)) { latch.countDown(); } } }; stdout.addPump(pump); stderr.addPump(pump); } Future<Void> stdoutTask = stdout.process(); Future<Void> stderrTask = stderr.process(); try { if (timeout > -1) { long realTimeout = Math.round(timeout * Utils.TIMEOUT_FACTOR); if (!latch.await(realTimeout, unit)) { throw new TimeoutException(); } } } catch (TimeoutException | InterruptedException e) { System.err.println("Failed to start a process (thread dump follows)"); for(Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) { printStack(s.getKey(), s.getValue()); } stdoutTask.cancel(true); stderrTask.cancel(true); throw e; } return p; }
Example 16
Source File: MediaCodecVideoDecoder.java From webrtc_android with MIT License | 4 votes |
@CalledByNativeUnchecked private void release() { Logging.d(TAG, "Java releaseDecoder. Total number of dropped frames: " + droppedFrames); checkOnMediaCodecThread(); // Run Mediacodec stop() and release() on separate thread since sometime // Mediacodec.stop() may hang. final CountDownLatch releaseDone = new CountDownLatch(1); Runnable runMediaCodecRelease = new Runnable() { @Override public void run() { try { Logging.d(TAG, "Java releaseDecoder on release thread"); mediaCodec.stop(); mediaCodec.release(); Logging.d(TAG, "Java releaseDecoder on release thread done"); } catch (Exception e) { Logging.e(TAG, "Media decoder release failed", e); } releaseDone.countDown(); } }; new Thread(runMediaCodecRelease).start(); if (!ThreadUtils.awaitUninterruptibly(releaseDone, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) { Logging.e(TAG, "Media decoder release timeout"); codecErrors++; if (errorCallback != null) { Logging.e(TAG, "Invoke codec error callback. Errors: " + codecErrors); errorCallback.onMediaCodecVideoDecoderCriticalError(codecErrors); } } mediaCodec = null; mediaCodecThread = null; runningInstance = null; if (useSurface()) { surface.release(); surface = null; textureListener.release(); } Logging.d(TAG, "Java releaseDecoder done"); }
Example 17
Source File: AbstractByteBufTest.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
private void testRefCnt0(final boolean parameter) throws Exception { for (int i = 0; i < 10; i++) { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch innerLatch = new CountDownLatch(1); final ByteBuf buffer = newBuffer(4); assertEquals(1, buffer.refCnt()); final AtomicInteger cnt = new AtomicInteger(Integer.MAX_VALUE); Thread t1 = new Thread(new Runnable() { @Override public void run() { boolean released; if (parameter) { released = buffer.release(buffer.refCnt()); } else { released = buffer.release(); } assertTrue(released); Thread t2 = new Thread(new Runnable() { @Override public void run() { cnt.set(buffer.refCnt()); latch.countDown(); } }); t2.start(); try { // Keep Thread alive a bit so the ThreadLocal caches are not freed innerLatch.await(); } catch (InterruptedException ignore) { // ignore } } }); t1.start(); latch.await(); assertEquals(0, cnt.get()); innerLatch.countDown(); } }
Example 18
Source File: SLAComplianceTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testSLAonUserTaskViolated() throws Exception { CountDownLatch latch = new CountDownLatch(1); final ProcessEventListener listener = new DefaultProcessEventListener(){ @Override public void afterSLAViolated(SLAViolatedEvent event) { latch.countDown(); } }; KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLAOnTask.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); ksession.addEventListener(listener); ProcessInstance processInstance = ksession.startProcess("UserTask"); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); WorkItem workItem = workItemHandler.getWorkItem(); assertNotNull(workItem); assertEquals("john", workItem.getParameter("ActorId")); boolean slaViolated = latch.await(10, TimeUnit.SECONDS); assertTrue(slaViolated, "SLA was not violated while it is expected"); processInstance = ksession.getProcessInstance(processInstance.getId()); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); int slaCompliance = getSLAComplianceForProcessInstance(processInstance); assertEquals(ProcessInstance.SLA_NA, slaCompliance); Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances(); assertEquals(1, active.size()); NodeInstance userTaskNode = active.iterator().next(); slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) userTaskNode, 0); assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance); ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null); assertProcessInstanceFinished(processInstance, ksession); slaCompliance = getSLAComplianceForProcessInstance(processInstance); assertEquals(ProcessInstance.SLA_NA, slaCompliance); slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) userTaskNode, 1); assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance); ksession.dispose(); }
Example 19
Source File: RouteGuideClientTest.java From grpc-nebula-java with Apache License 2.0 | 4 votes |
/** * Example for testing bi-directional call. */ @Test public void routeChat_simpleResponse() throws Exception { RouteNote fakeResponse1 = RouteNote.newBuilder().setMessage("dummy msg1").build(); RouteNote fakeResponse2 = RouteNote.newBuilder().setMessage("dummy msg2").build(); final List<String> messagesDelivered = new ArrayList<>(); final List<Point> locationsDelivered = new ArrayList<>(); final AtomicReference<StreamObserver<RouteNote>> responseObserverRef = new AtomicReference<StreamObserver<RouteNote>>(); final CountDownLatch allRequestsDelivered = new CountDownLatch(1); // implement the fake service RouteGuideImplBase routeChatImpl = new RouteGuideImplBase() { @Override public StreamObserver<RouteNote> routeChat(StreamObserver<RouteNote> responseObserver) { responseObserverRef.set(responseObserver); StreamObserver<RouteNote> requestObserver = new StreamObserver<RouteNote>() { @Override public void onNext(RouteNote value) { messagesDelivered.add(value.getMessage()); locationsDelivered.add(value.getLocation()); } @Override public void onError(Throwable t) { } @Override public void onCompleted() { allRequestsDelivered.countDown(); } }; return requestObserver; } }; serviceRegistry.addService(routeChatImpl); // start routeChat CountDownLatch latch = client.routeChat(); // request message sent and delivered for four times assertTrue(allRequestsDelivered.await(1, TimeUnit.SECONDS)); assertEquals( Arrays.asList("First message", "Second message", "Third message", "Fourth message"), messagesDelivered); assertEquals( Arrays.asList( Point.newBuilder().setLatitude(0).setLongitude(0).build(), Point.newBuilder().setLatitude(0).setLongitude(1).build(), Point.newBuilder().setLatitude(1).setLongitude(0).build(), Point.newBuilder().setLatitude(1).setLongitude(1).build() ), locationsDelivered); // Let the server send out two simple response messages // and verify that the client receives them. // Allow some timeout for verify() if not using directExecutor responseObserverRef.get().onNext(fakeResponse1); verify(testHelper).onMessage(fakeResponse1); responseObserverRef.get().onNext(fakeResponse2); verify(testHelper).onMessage(fakeResponse2); // let server complete. responseObserverRef.get().onCompleted(); assertTrue(latch.await(1, TimeUnit.SECONDS)); verify(testHelper, never()).onRpcError(any(Throwable.class)); }
Example 20
Source File: SLAComplianceTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testSLAonCatchEventViolated() throws Exception { CountDownLatch latch = new CountDownLatch(1); final ProcessEventListener listener = new DefaultProcessEventListener(){ @Override public void afterSLAViolated(SLAViolatedEvent event) { latch.countDown(); } }; KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchEventSignalWithSLAOnEvent.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); ksession.addEventListener(listener); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler()); ProcessInstance processInstance = ksession.startProcess("IntermediateCatchEvent"); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); boolean slaViolated = latch.await(5, TimeUnit.SECONDS); assertTrue(slaViolated, "SLA should be violated by timer"); processInstance = ksession.getProcessInstance(processInstance.getId()); assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE); Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances(); assertEquals(1, active.size()); NodeInstance eventNode = active.iterator().next(); ksession.signalEvent("MyMessage", null, processInstance.getId()); assertProcessInstanceFinished(processInstance, ksession); int slaCompliance = getSLAComplianceForProcessInstance(processInstance); assertEquals(ProcessInstance.SLA_NA, slaCompliance); slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) eventNode, 0); assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance); slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) eventNode, 1); assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance); ksession.dispose(); }