// submits a task to the executor to be run private void runTask(CalculationTask task, ScenarioMarketData marketData, ReferenceData refData, System.Action <CalculationResults> consumer) { // the task is executed, with the result passed to the consumer // the consumer wraps the listener to ensure thread-safety System.Func <CalculationResults> taskExecutor = () => task.execute(marketData, refData); CompletableFuture.supplyAsync(taskExecutor, executor).thenAccept(consumer); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldTimeoutIfLeaderCommitIsNeverKnown() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldTimeoutIfLeaderCommitIsNeverKnown() { OnDemandJobScheduler jobScheduler = new OnDemandJobScheduler(); MembershipWaiter waiter = new MembershipWaiter(member(0), jobScheduler, () => _dbHealth, 1, NullLogProvider.Instance, new Monitors()); ExposedRaftState raftState = RaftStateBuilder.raftState().leaderCommit(-1).build().copy(); RaftMachine raft = mock(typeof(RaftMachine)); when(raft.State()).thenReturn(raftState); CompletableFuture <bool> future = waiter.WaitUntilCaughtUpMember(raft); jobScheduler.RunJob(); try { future.get(10, MILLISECONDS); fail("Should have timed out."); } catch (TimeoutException) { // expected } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldWaitForNonNullValue() throws InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldWaitForNonNullValue() { // given int threads = 3; assertNull(_leaderProvider.currentLeader()); // when CompletableFuture <List <MemberId> > futures = CompletableFuture.completedFuture(new List <List <MemberId> >()); for (int i = 0; i < threads; i++) { CompletableFuture <MemberId> future = CompletableFuture.supplyAsync(CurrentLeader, _executorService); futures = futures.thenCombine(future, (completableFutures, memberId) => { completableFutures.add(memberId); return(completableFutures); }); } // then Thread.Sleep(100); assertFalse(futures.Done); // when _leaderProvider.Leader = _memberId; List <MemberId> memberIds = futures.get(5, TimeUnit.SECONDS); // then assertTrue(memberIds.All(memberId => memberId.Equals(_memberId))); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotScheduleNewJobIfHandlingSchedulingError() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldNotScheduleNewJobIfHandlingSchedulingError() { AtomicInteger handleSchedulingErrorCounter = new AtomicInteger(0); AtomicBoolean exitCondition = new AtomicBoolean(); BoltConnection newConnection = newConnection(System.Guid.randomUUID().ToString()); doAnswer(NewBlockingAnswer(handleSchedulingErrorCounter, exitCondition)).when(newConnection).handleSchedulingError(any()); BlockAllThreads(); // register connection _boltScheduler.created(newConnection); // send a job and wait for it to enter handleSchedulingError and block there CompletableFuture.runAsync(() => _boltScheduler.enqueued(newConnection, Jobs.noop())); Predicates.awaitForever(() => handleSchedulingErrorCounter.get() > 0, 500, MILLISECONDS); // allow all threads to complete _afterExecuteEvent.Signal(); _afterExecuteBarrier.await(); // post a job _boltScheduler.enqueued(newConnection, Jobs.noop()); // exit handleSchedulingError exitCondition.set(true); // verify that handleSchedulingError is called once and processNextBatch never. assertEquals(1, handleSchedulingErrorCounter.get()); verify(newConnection, never()).processNextBatch(); }
//------------------------------------------------------------------------- public virtual void test_poll() { AtomicInteger counter = new AtomicInteger(); System.Func <string> pollingFn = () => { switch (counter.incrementAndGet()) { case 1: return(null); case 2: return("Yes"); default: throw new AssertionError("Test failed"); } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); CompletableFuture <string> future = Guavate.poll(executor, Duration.ofMillis(100), Duration.ofMillis(100), pollingFn); assertEquals(future.join(), "Yes"); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static org.neo4j.causalclustering.identity.MemberId waitForLeaderAgreement(Iterable<org.neo4j.causalclustering.core.consensus.RaftMachine> validRafts, long maxTimeMillis) throws InterruptedException, java.util.concurrent.TimeoutException public static MemberId WaitForLeaderAgreement(IEnumerable <RaftMachine> validRafts, long maxTimeMillis) { long viewCount = Iterables.count(validRafts); IDictionary <MemberId, MemberId> leaderViews = new Dictionary <MemberId, MemberId>(); CompletableFuture <MemberId> futureAgreedLeader = new CompletableFuture <MemberId>(); ICollection <ThreadStart> destructors = new List <ThreadStart>(); foreach (RaftMachine raft in validRafts) { destructors.Add(LeaderViewUpdatingListener(raft, validRafts, leaderViews, viewCount, futureAgreedLeader)); } try { try { return(futureAgreedLeader.get(maxTimeMillis, TimeUnit.MILLISECONDS)); } catch (ExecutionException e) { throw new Exception(e); } } finally { destructors.forEach(ThreadStart.run); } }
public virtual void test_poll_exception() { AtomicInteger counter = new AtomicInteger(); System.Func <string> pollingFn = () => { switch (counter.incrementAndGet()) { case 1: return(null); case 2: throw new System.InvalidOperationException("Expected"); default: throw new AssertionError("Test failed"); } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { CompletableFuture <string> future = Guavate.poll(executor, Duration.ofMillis(100), Duration.ofMillis(100), pollingFn); assertThrows(() => future.join(), typeof(CompletionException), "java.lang.IllegalStateException: Expected"); } finally { executor.shutdown(); } }
public virtual void test_toCombinedFutureMap() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } return("B"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: CompletableFuture <IDictionary <string, string> > test = input.SetOfKeyValuePairs().collect(Guavate.toCombinedFutureMap()); assertEquals(test.Done, false); latch.Signal(); IDictionary <string, string> combined = test.join(); assertEquals(test.Done, true); assertEquals(combined.Count, 2); assertEquals(combined["a"], "A"); assertEquals(combined["b"], "B"); }
public virtual void test_combineFuturesAsMap_exception() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } throw new System.InvalidOperationException("Oops"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input); assertEquals(test.Done, false); latch.Signal(); assertThrows(typeof(CompletionException), () => test.join()); assertEquals(test.Done, true); assertEquals(test.CompletedExceptionally, true); }
//------------------------------------------------------------------------- public virtual void test_combineFuturesAsMap() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } return("B"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input); assertEquals(test.Done, false); latch.Signal(); IDictionary <string, string> combined = test.join(); assertEquals(test.Done, true); assertEquals(combined.Count, 2); assertEquals(combined["a"], "A"); assertEquals(combined["b"], "B"); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void start() throws Throwable public override void Start() { CompletableFuture <bool> caughtUp = _membershipWaiter.waitUntilCaughtUpMember(_raft); try { caughtUp.get(_joinCatchupTimeout, MILLISECONDS); } catch (ExecutionException e) { _log.error("Server failed to join cluster", e.InnerException); throw e.InnerException; } catch (Exception e) when(e is InterruptedException || e is TimeoutException) { string message = format("Server failed to join cluster within catchup time limit [%d ms]", _joinCatchupTimeout); _log.error(message, e); throw new Exception(message, e); } finally { caughtUp.cancel(true); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReplicateTokenRequestForNewToken() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldReplicateTokenRequestForNewToken() { // given StorageEngine storageEngine = MockedStorageEngine(); when(_storageEngineSupplier.get()).thenReturn(storageEngine); IdGeneratorFactory idGeneratorFactory = mock(typeof(IdGeneratorFactory)); IdGenerator idGenerator = mock(typeof(IdGenerator)); when(idGenerator.NextId()).thenReturn(1L); when(idGeneratorFactory.Get(any(typeof(IdType)))).thenReturn(idGenerator); TokenRegistry registry = new TokenRegistry("Label"); int generatedTokenId = 1; ReplicatedTokenHolder tokenHolder = new ReplicatedLabelTokenHolder(registry, (content, trackResult) => { CompletableFuture <object> completeFuture = new CompletableFuture <object>(); completeFuture.complete(generatedTokenId); return(completeFuture); }, idGeneratorFactory, _storageEngineSupplier); // when int?tokenId = tokenHolder.GetOrCreateId("name1"); // then assertThat(tokenId, equalTo(generatedTokenId)); }
internal Evaluator(MembershipWaiter outerInstance, RaftMachine raft, CompletableFuture <bool> catchUpFuture, System.Func <DatabaseHealth> dbHealthSupplier) { this._outerInstance = outerInstance; this.Raft = raft; this.CatchUpFuture = catchUpFuture; this.LastLeaderCommit = raft.State().leaderCommit(); this.DbHealthSupplier = dbHealthSupplier; }
private void InitiateHandshake(Channel channel, HandshakeClient handshakeClient) { _debugLog.info("Initiating handshake local %s remote %s", channel.localAddress(), channel.remoteAddress()); SimpleNettyChannel channelWrapper = new SimpleNettyChannel(channel, _debugLog); CompletableFuture <ProtocolStack> handshake = handshakeClient.Initiate(channelWrapper, _applicationProtocolRepository, _modifierProtocolRepository); handshake.whenComplete((protocolStack, failure) => onHandshakeComplete(protocolStack, channel, failure)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldFailDifferentlyIfTooManyFailedAuthAttempts() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldFailDifferentlyIfTooManyFailedAuthAttempts() { // Given //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long timeout = System.currentTimeMillis() + 60_000; long timeout = DateTimeHelper.CurrentUnixTimeMillis() + 60_000; FailureMessage failureMessage = null; // When while (failureMessage == null) { if (DateTimeHelper.CurrentUnixTimeMillis() > timeout) { fail("Timed out waiting for the authentication failure to occur."); } ExecutorService executor = Executors.newFixedThreadPool(10); // Fire up some parallel connections that all send wrong authentication tokens IList <CompletableFuture <FailureMessage> > futures = new List <CompletableFuture <FailureMessage> >(); for (int i = 0; i < 10; i++) { futures.Add(CompletableFuture.supplyAsync(this.collectAuthFailureOnFailedAuth, executor)); } try { // Wait for all tasks to complete CompletableFuture.allOf(futures.ToArray()).get(30, SECONDS); // We want at least one of the futures to fail with our expected code for (int i = 0; i < futures.Count; i++) { FailureMessage recordedMessage = futures[i].get(); if (recordedMessage != null) { failureMessage = recordedMessage; break; } } } catch (TimeoutException) { // if jobs did not complete, let's try again // do nothing } finally { executor.shutdown(); } } assertThat(failureMessage.Status(), equalTo(Org.Neo4j.Kernel.Api.Exceptions.Status_Security.AuthenticationRateLimit)); assertThat(failureMessage.Message(), containsString("The client has provided incorrect authentication details too many times in a row.")); }
private CompletableFuture <bool> ScheduleBatchOrHandleError(BoltConnection connection) { try { return(CompletableFuture.supplyAsync(() => ExecuteBatch(connection), _threadPool)); } catch (RejectedExecutionException ex) { return(failedFuture(ex)); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldSuccessfullyHandshakeKnownProtocolOnClientNoModifiers() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldSuccessfullyHandshakeKnownProtocolOnClientNoModifiers() { // when CompletableFuture <ProtocolStack> clientHandshakeFuture = _handshakeClient.initiate(new SimpleNettyChannel(_client.channel, NullLog.Instance), _raftApplicationProtocolRepository, _unsupportingModifierProtocolRepository); // then ProtocolStack clientProtocolStack = clientHandshakeFuture.get(1, TimeUnit.MINUTES); assertThat(clientProtocolStack.ApplicationProtocol(), equalTo(TestProtocols_TestApplicationProtocols.latest(RAFT))); assertThat(clientProtocolStack.ModifierProtocols(), empty()); }
public override void Start() { lock (this) { _state = TX_PULLING; _timer = _timerService.create(TX_PULLER_TIMER, Group.PULL_UPDATES, timeout => onTimeout()); _timer.set(fixedTimeout(_txPullIntervalMillis, MILLISECONDS)); _dbHealth = _databaseHealthSupplier.get(); _upToDateFuture = new CompletableFuture <bool>(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAcceptCorrectMagic() public virtual void ShouldAcceptCorrectMagic() { // given CompletableFuture <ProtocolStack> protocolStackCompletableFuture = _client.initiate(_channel, _applicationProtocolRepository, _modifierProtocolRepository); // when _client.handle(InitialMagicMessage.Instance()); // then assertFalse(protocolStackCompletableFuture.Done); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldExceptionallyCompleteProtocolStackOnReceivingIncorrectMagic() public virtual void ShouldExceptionallyCompleteProtocolStackOnReceivingIncorrectMagic() { // given CompletableFuture <ProtocolStack> protocolStackCompletableFuture = _client.initiate(_channel, _applicationProtocolRepository, _modifierProtocolRepository); // when _client.handle(new InitialMagicMessage("totally legit")); // then AssertCompletedExceptionally(protocolStackCompletableFuture); }
internal virtual CompletableFuture <bool> WaitUntilCaughtUpMember(RaftMachine raft) { CompletableFuture <bool> catchUpFuture = new CompletableFuture <bool>(); Evaluator evaluator = new Evaluator(this, raft, catchUpFuture, _dbHealthSupplier); JobHandle jobHandle = _jobScheduler.schedule(Group.MEMBERSHIP_WAITER, evaluator, _currentCatchupDelayInMs, MILLISECONDS); catchUpFuture.whenComplete((result, e) => jobHandle.cancel(true)); return(catchUpFuture); }
public override bool OnFileContent(CompletableFuture <T> signal, FileChunk fileChunk) { try { _storeFileStream.write(fileChunk.Bytes()); } catch (Exception e) { signal.completeExceptionally(e); } return(fileChunk.Last); }
public void SetColor(Context context, int rgb) { lock (this) { if (!solidColorMaterialCache.ContainsKey(rgb)) { solidColorMaterialCache[rgb] = MaterialFactory.MakeOpaqueWithColor(context, new Color(rgb)); } CompletableFuture loadMaterial = solidColorMaterialCache[rgb]; loadMaterial.ThenAccept(new FutureResultConsumer <Material>(SetMaterial)); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldSuccessfullyHandshakeKnownProtocolOnServerWithCompression() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldSuccessfullyHandshakeKnownProtocolOnServerWithCompression() { // when CompletableFuture <ProtocolStack> clientFuture = _handshakeClient.initiate(new SimpleNettyChannel(_client.channel, NullLog.Instance), _raftApplicationProtocolRepository, _compressionModifierProtocolRepository); CompletableFuture <ProtocolStack> serverHandshakeFuture = GetServerHandshakeFuture(clientFuture); // then ProtocolStack serverProtocolStack = serverHandshakeFuture.get(1, TimeUnit.MINUTES); assertThat(serverProtocolStack.ApplicationProtocol(), equalTo(TestProtocols_TestApplicationProtocols.latest(RAFT))); assertThat(serverProtocolStack.ModifierProtocols(), contains(TestProtocols_TestModifierProtocols.latest(COMPRESSION))); }
private void AssertCompletedExceptionally(CompletableFuture <ProtocolStack> protocolStackCompletableFuture) { assertTrue(protocolStackCompletableFuture.CompletedExceptionally); try { protocolStackCompletableFuture.getNow(null); } catch (CompletionException ex) { assertThat(ex.InnerException, instanceOf(typeof(ClientHandshakeException))); } }
public virtual CompletableFuture <object> Apply(CompletableFuture <object> future) { if (_exception != null) { future.completeExceptionally(_exception); } else { future.complete(_result); } return(future); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldExceptionallyCompleteProtocolStackWhenProtocolStackNotSet() public virtual void ShouldExceptionallyCompleteProtocolStackWhenProtocolStackNotSet() { // given CompletableFuture <ProtocolStack> protocolStackCompletableFuture = _client.initiate(_channel, _applicationProtocolRepository, _modifierProtocolRepository); _client.handle(InitialMagicMessage.Instance()); // when _client.handle(new SwitchOverResponse(StatusCode.Success)); // then AssertCompletedExceptionally(protocolStackCompletableFuture); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldExceptionallyCompleteProtocolStackWhenApplicationProtocolResponseForUnsupportedVersion() public virtual void ShouldExceptionallyCompleteProtocolStackWhenApplicationProtocolResponseForUnsupportedVersion() { // given CompletableFuture <ProtocolStack> protocolStackCompletableFuture = _client.initiate(_channel, _applicationProtocolRepository, _modifierProtocolRepository); _client.handle(InitialMagicMessage.Instance()); // when _client.handle(new ApplicationProtocolResponse(StatusCode.Success, _applicationProtocolIdentifier.canonicalName(), int.MaxValue)); // then AssertCompletedExceptionally(protocolStackCompletableFuture); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldExceptionallyCompleteProtocolStackWhenApplicationProtocolResponseForIncorrectProtocol() public virtual void ShouldExceptionallyCompleteProtocolStackWhenApplicationProtocolResponseForIncorrectProtocol() { // given CompletableFuture <ProtocolStack> protocolStackCompletableFuture = _client.initiate(_channel, _applicationProtocolRepository, _modifierProtocolRepository); _client.handle(InitialMagicMessage.Instance()); // when _client.handle(new ApplicationProtocolResponse(StatusCode.Success, "zab", _raftVersion)); // then AssertCompletedExceptionally(protocolStackCompletableFuture); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); arSceneView = (ArSceneView)FindViewById(Resource.Id.ar_scene_view); exampleLayout = ViewRenderable.InvokeBuilder().SetView(this, Resource.Layout.example_layout).Build(); CompletableFuture.AllOf(exampleLayout).Handle(this); arSceneView.Scene.AddOnUpdateListener(this); ARLocationPermissionHelper.RequestPermission(this); }