net.jodah.concurrentunit.Waiter Java Examples

The following examples show how to use net.jodah.concurrentunit.Waiter. 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: Issue190Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
public void test() throws Throwable {
  RetryPolicy<Object> policy = new RetryPolicy<>().withMaxRetries(5);
  AtomicInteger failureEvents = new AtomicInteger();
  AtomicInteger successEvents = new AtomicInteger();
  Waiter waiter = new Waiter();

  Failsafe.with(policy).onFailure(e -> {
    failureEvents.incrementAndGet();
    waiter.resume();
  }).onSuccess(e -> {
    successEvents.incrementAndGet();
    waiter.resume();
  }).getAsyncExecution(execution -> Testing.futureResult(executor, true).whenComplete((result, failure) -> {
    execution.complete(result);
  })).get();

  waiter.await(1000);
  Assert.assertEquals(failureEvents.get(), 0);
  Assert.assertEquals(successEvents.get(), 1);
}
 
Example #2
Source File: SingleThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testMisfireListener() throws Exception {
    final String jobName = "oneJob";
    JobDetail jobDetail = createJob(TestJob.class, jobName, "oneGroup");

    final String triggerName = "trigger1";
    final String everySecond = "* * * * * ?";
    CronTrigger trigger = createCronTrigger(triggerName, "oneGroup", everySecond);


    JobDetail sleepJob = createJob(SleepJob.class, "sleepJob", "twoGroup");
    CronTrigger sleepTrigger = createCronTrigger("sleepTrigger", "twoGroup", everySecond);
    Waiter waiter = new Waiter();
    scheduler.scheduleJob(sleepJob, sleepTrigger);
    scheduler.scheduleJob(jobDetail, trigger);

    scheduler.getListenerManager().addTriggerListener(new MisfireListener(waiter), NameMatcher.triggerNameEquals(triggerName));

    // wait for MisfireListener.triggerMisfired() to be called
    waiter.await(2500);
}
 
Example #3
Source File: MultiThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testTriggerData() throws Exception {
    final String jobName = "good";
    JobDetail jobDetail = createJob(DataJob.class, jobName, "goodGroup");

    final String triggerName = "trigger1";
    final String everySecond = "* * * * * ?";
    CronTrigger trigger = createCronTrigger(triggerName, "oneGroup", everySecond);
    trigger = trigger.getTriggerBuilder()
            .usingJobData("foo", "bar")
            .build();
    scheduler.setJobFactory(new RedisJobFactory());
    scheduler.scheduleJob(jobDetail, trigger);
    Waiter waiter = new Waiter();
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(triggerName));

    // wait for CompleteListener.triggerComplete() to be called
    waiter.await(1500);

    try (Jedis jedis = jedisPool.getResource()) {
        assertThat(jedis.get("foo"), equalTo("bar"));
    }
}
 
Example #4
Source File: PythonInterpreterTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPythonProcessKilled() throws InterruptedException, TimeoutException {
  final Waiter waiter = new Waiter();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        InterpreterResult result = interpreter.interpret("import time\ntime.sleep(1000)",
                getInterpreterContext());
        waiter.assertEquals(InterpreterResult.Code.ERROR, result.code());
        waiter.assertEquals(
                "Python process is abnormally exited, please check your code and log.",
                result.message().get(0).getData());
      } catch (InterpreterException e) {
        waiter.fail("Should not throw exception\n" + ExceptionUtils.getStackTrace(e));
      }
      waiter.resume();
    }
  };
  thread.start();
  Thread.sleep(3000);
  PythonInterpreter pythonInterpreter = (PythonInterpreter)
          ((LazyOpenInterpreter) interpreter).getInnerInterpreter();
  pythonInterpreter.getPythonProcessLauncher().stop();
  waiter.await(3000);
}
 
Example #5
Source File: IPythonInterpreterTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testIPythonProcessKilled() throws InterruptedException, TimeoutException {
  final Waiter waiter = new Waiter();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        InterpreterResult result = interpreter.interpret("import time\ntime.sleep(1000)",
                getInterpreterContext());
        waiter.assertEquals(InterpreterResult.Code.ERROR, result.code());
        waiter.assertEquals(
                "IPython kernel is abnormally exited, please check your code and log.",
                result.message().get(0).getData());
      } catch (InterpreterException e) {
        waiter.fail("Should not throw exception\n" + ExceptionUtils.getStackTrace(e));
      }
      waiter.resume();
    }
  };
  thread.start();
  Thread.sleep(3000);
  IPythonInterpreter iPythonInterpreter = (IPythonInterpreter)
          ((LazyOpenInterpreter) interpreter).getInnerInterpreter();
  iPythonInterpreter.getKernelProcessLauncher().stop();
  waiter.await(3000);
}
 
Example #6
Source File: MultiThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisallowConcurrent() throws Exception {
    JobDetail job1 = createJob(SingletonSleepJob.class, "job1", "group1");
    CronTrigger trigger1 = createCronTrigger("trigger1", "group1", "* * * * * ?");
    CronTrigger trigger2 = createCronTrigger("trigger2", "group2", "* * * * * ?")
            .getTriggerBuilder()
            .forJob(job1)
            .build();

    Waiter waiter = new Waiter();
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(trigger1.getKey().getName()));
    scheduler.scheduleJob(job1, trigger1);
    //scheduler.scheduleJob(trigger2);

    waiter.await(6000, 2);

    assertThat(SingletonSleepJob.concurrentExecutions.get(), equalTo(0));
}
 
Example #7
Source File: FailsafeFutureTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that retries are stopped and completion handlers are called on cancel.
 */
public void shouldCallOnCompleteWhenCancelled() throws Throwable {
  Waiter waiter = new Waiter();
  CompletableFuture<String> future = Failsafe.with(new RetryPolicy<String>()).with(executor).onComplete(e -> {
    waiter.assertNull(e.getResult());
    waiter.assertTrue(e.getFailure() instanceof CancellationException);
    waiter.resume();
  }).getAsync(() -> {
    Thread.sleep(1000);
    throw new IllegalStateException();
  });

  // Note: We have to add whenComplete to the returned future separately, otherwise cancel will not be noticed by
  // Failsafe
  future.whenComplete((result, failure) -> {
    waiter.assertNull(result);
    waiter.assertTrue(failure instanceof CancellationException);
    waiter.resume();
  });

  future.cancel(true);
  waiter.await(1000, 2);
  future.complete("unxpected2");
  Asserts.assertThrows(future::get, CancellationException.class);
}
 
Example #8
Source File: DelegatingSchedulerTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that ForkJoinPool clears interrupt flags.
 */
public void shouldClearInterruptFlagInForkJoinPoolThreads() throws Throwable {
  Scheduler scheduler = new DelegatingScheduler(new ForkJoinPool(1));
  AtomicReference<Thread> threadRef = new AtomicReference<>();
  Waiter waiter = new Waiter();

  // Create interruptable execution
  scheduler.schedule(() -> {
    threadRef.set(Thread.currentThread());
    waiter.resume();
    Thread.sleep(10000);
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  waiter.await(1000);
  threadRef.get().interrupt();

  // Check for interrupt flag
  scheduler.schedule(() -> {
    waiter.assertFalse(Thread.currentThread().isInterrupted());
    waiter.resume();
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  waiter.await(1000);
}
 
Example #9
Source File: DelegatingSchedulerTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
public void shouldNotInterruptAlreadyDoneTask() throws Throwable {
  Waiter waiter = new Waiter();
  Future<?> future1 = scheduler.schedule(() -> null, 0, TimeUnit.MILLISECONDS);
  Future<?> future2 = scheduler.schedule(() -> {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      waiter.fail("Cancelling one future should not interrupt another");
    }
    waiter.resume();
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  Thread.sleep(100);
  assertFalse(future1.cancel(true));
  waiter.await(1000);
}
 
Example #10
Source File: DelegatingSchedulerTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
public void shouldSchedule() throws Throwable {
  // Given
  Duration delay = Duration.ofMillis(200);
  Waiter waiter = new Waiter();
  long startTime = System.nanoTime();

  // When
  scheduler.schedule(() -> {
    waiter.resume();
    return null;
  }, delay.toMillis(), TimeUnit.MILLISECONDS);

  // Then
  waiter.await(1000);
  assertTrue(System.nanoTime() - startTime > delay.toNanos());
}
 
Example #11
Source File: Issue5Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that a failure is handled as expected by a listener registered via whenFailure.
 */
public void test() throws Throwable {
  Waiter waiter = new Waiter();
  RetryPolicy<Object> retryPolicy = new RetryPolicy<>().withDelay(Duration.ofMillis(100))
      .withMaxDuration(Duration.ofSeconds(2))
      .withMaxRetries(3)
      .handleResult(null);

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  Failsafe.with(retryPolicy).with(executor).onFailure(e -> {
    waiter.assertNull(e.getResult());
    waiter.assertNull(e.getFailure());
    waiter.resume();
  }).getAsync(() -> null);

  waiter.await(1000);
}
 
Example #12
Source File: Issue131Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * More alarming async case where the Future is not even completed
 * since Failsafe does not recover from the {@link NullPointerException} thrown by the predicate.
 */
public void asyncShouldCompleteTheFuture() throws Throwable {
  CircuitBreaker<String> circuitBreaker = new CircuitBreaker<String>().handleResultIf(handleIfEqualsIgnoreCaseFoo);
  FailsafeExecutor<String> failsafe = Failsafe.with(circuitBreaker).with(Executors.newSingleThreadScheduledExecutor());

  Waiter waiter = new Waiter();

  failsafe
    .getStageAsync(() -> {
      CompletableFuture<String> future = new CompletableFuture<>();
      future.completeExceptionally(new IOException("let's blame it on network error"));
      return future;
    })
    .whenComplete((s, t) -> waiter.resume()); // Never invoked!

  waiter.await(1000);
}
 
Example #13
Source File: Issue9Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
public void test() throws Throwable {
  // Given - Fail twice then succeed
  AtomicInteger retryCounter = new AtomicInteger();
  Service service = mock(Service.class);
  when(service.connect()).thenThrow(failures(2, new IllegalStateException())).thenReturn(true);
  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  Waiter waiter = new Waiter();

  // When
  AtomicInteger successCounter = new AtomicInteger();
  Future<Boolean> future = Failsafe.with(new RetryPolicy<Boolean>().withMaxRetries(2)
      .onRetry(e -> retryCounter.incrementAndGet()))
      .with(executor)
      .onSuccess(p -> {
        successCounter.incrementAndGet();
        waiter.resume();
      })
      .getAsync(service::connect);

  // Then
  waiter.await(1000);
  verify(service, times(3)).connect();
  assertTrue(future.get());
  assertEquals(retryCounter.get(), 2);
  assertEquals(successCounter.get(), 1);
}
 
Example #14
Source File: ListenersTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
void beforeMethod() {
  reset(service);
  waiter = new Waiter();

  rpAbort.reset();
  rpFailedAttempt.reset();
  rpRetriesExceeded.reset();
  rpRetry.reset();
  rpSuccess.reset();
  rpFailure.reset();

  cbOpen.reset();
  cbHalfOpen.reset();
  cbClose.reset();
  cbSuccess.reset();
  cbFailure.reset();

  fbFailedAttempt.reset();
  fbSuccess.reset();
  fbFailure.reset();

  complete.reset();
  success.reset();
  failure.reset();
}
 
Example #15
Source File: ConnectionClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeConnectionAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        connectionProxy.createChannel();
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception actual) {
        if (!actual.equals(e))
          actual.printStackTrace();
        waiter.assertEquals(actual, e);
        waiter.resume();
      }
    }
  });

  waiter.await(10000);
}
 
Example #16
Source File: ChannelClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeChannelAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        mockChannel(1).proxy.basicCancel("foo-tag");
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception expected) {
        waiter.assertEquals(e, expected);
        waiter.resume();
      }
    }
  });

  waiter.await(100000);
}
 
Example #17
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldHandleSequentialWaiters() throws Throwable {
  final Waiter waiter = new Waiter();
  for (int i = 0; i < 1; i++) {
    circuit.open();

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          System.out.println("Waiting for circuit to be closed");
          circuit.await();
          System.out.println("Circuit closed");
          waiter.resume();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();

    Thread.sleep(500);
    circuit.close();
    waiter.await(500);
  }
}
 
Example #18
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldHandleConcurrentWaiters() throws Throwable {
  circuit.open();

  final Waiter waiter = new Waiter();
  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          System.out.println("Waiting for circuit to be closed");
          circuit.await();
          System.out.println("Circuit closed");
          waiter.resume();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();

  Thread.sleep(1000);
  circuit.close();
  waiter.await(500);
}
 
Example #19
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldInterruptWaiters() throws Throwable {
  circuit.open();

  final Waiter waiter = new Waiter();
  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          circuit.await();
        } catch (InterruptedException e) {
          waiter.resume();
        }
      }
    }).start();

  Thread.sleep(300);
  circuit.interruptWaiters();
  waiter.await(500);
}
 
Example #20
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldNotBlockOpenWhenSyncAcquired() throws Throwable {
  circuit.open();

  final Waiter waiter = new Waiter();
  new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        circuit.await();
        waiter.resume();
      } catch (InterruptedException e) {
      }
    }
  }).start();

  Thread.sleep(300);
  circuit.open();
  circuit.close();
  waiter.await(500);
}
 
Example #21
Source File: InterruptableWaiterTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldInteruptForeverWaiters() throws Throwable {
  final InterruptableWaiter iw = new InterruptableWaiter();
  final Waiter waiter = new Waiter();

  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          iw.await();
        } catch (InterruptedException expected) {
          waiter.resume();
        }
      }
    }).start();

  Thread.sleep(100);
  iw.interruptWaiters();
  waiter.await(500);
}
 
Example #22
Source File: InterruptableWaiterTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldInterruptTimedWaiters() throws Throwable {
  final InterruptableWaiter iw = new InterruptableWaiter();
  final Waiter waiter = new Waiter();
  
  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          iw.await(Duration.mins(1));
        } catch (InterruptedException expected) {
          waiter.resume();
        }
      }
    }).start();

  Thread.sleep(100);
  iw.interruptWaiters();
  waiter.await(500);
}
 
Example #23
Source File: AbstractInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
void performInvocation(ShutdownSignalException invocationFailure, Exception recoveryFailure)
    throws Throwable {
  mockConnection();
  mockInvocation(invocationFailure);
  if (recoveryFailure != null)
    mockRecovery(recoveryFailure);

  final Waiter waiter = new Waiter();
  runInThread(new Runnable() {
    public void run() {
      try {
        performInvocation();
        waiter.resume();
      } catch (Throwable t) {
        waiter.fail(t);
      }
    }
  });

  waiter.await(1000);
}
 
Example #24
Source File: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void test_client_takeover_mqtt5() throws Exception {

    final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
    final Waiter disconnectMessageWaiter = new Waiter();
    final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, true);

    final EmbeddedChannel oldChannel =
            new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
    oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5);
    final SettableFuture<Void> disconnectFuture = SettableFuture.create();
    disconnectFuture.set(null);
    oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);

    final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
    when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
    when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    final CONNECT connect1 = new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv5)
            .withClientIdentifier("sameClientId")
            .build();

    embeddedChannel.writeInbound(connect1);

    assertTrue(embeddedChannel.isOpen());
    assertFalse(oldChannel.isOpen());
    assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());

    assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
    disconnectMessageWaiter.await();

    final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
    assertNotNull(disconnectMessage);
    assertEquals(Mqtt5DisconnectReasonCode.SESSION_TAKEN_OVER, disconnectMessage.getReasonCode());
    assertEquals(ReasonStrings.DISCONNECT_SESSION_TAKEN_OVER, disconnectMessage.getReasonString());
}
 
Example #25
Source File: ConcurrentVerifyTest.java    From java-jwt with MIT License 5 votes vote down vote up
@SuppressWarnings("Convert2Lambda")
private void concurrentVerify(final JWTVerifier verifier, final String token) throws TimeoutException, InterruptedException {
    final Waiter waiter = new Waiter();
    List<VerifyTask> tasks = Collections.nCopies(REPEAT_COUNT, new VerifyTask(waiter, verifier, token));
    executor.invokeAll(tasks, TIMEOUT, TimeUnit.MILLISECONDS);
    waiter.await(TIMEOUT, REPEAT_COUNT);
}
 
Example #26
Source File: MultiThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompleteListener() throws Exception {
    final String jobName = "oneJob";
    JobDetail jobDetail = createJob(TestJob.class, jobName, "oneGroup");

    final String triggerName = "trigger1";
    CronTrigger trigger = createCronTrigger(triggerName, "oneGroup", "* * * * * ?");

    Waiter waiter = new Waiter();
    scheduler.scheduleJob(jobDetail, trigger);
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(triggerName));

    // wait for CompleteListener.triggerComplete() to be called
    waiter.await(1500);
}
 
Example #27
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that concurrent failed invocations result in recovery being performed serially.
 * 
 * TODO rewrite this test since concurrent failures no longer result in concurrent recovery
 * attempts. A ShutdownListener is only called once per recovery attempt.
 */
@Test(enabled = false)
public void shouldHandleConcurrentRetryableFailures() throws Throwable {
  mockConnection();
  mockConsumer(1, 1);
  mockConsumer(1, 2);
  mockConsumer(2, 5);
  mockConsumer(2, 6);

  doAnswer(failNTimes(4, retryableChannelShutdownSignal(), null, mockChannel(1).channelHandler)).when(
      mockChannel(1).delegate)
      .basicCancel("foo-tag");

  final Waiter waiter = new Waiter();
  for (int i = 0; i < 2; i++)
    runInThread(new Runnable() {
      public void run() {
        try {
          performInvocation();
          waiter.resume();
        } catch (Throwable t) {
          waiter.fail(t);
        }
      }
    });

  waiter.await(2000);

  // Even though both threads will fail twice, only one thread will perform recovery
  verifyCxnCreations(1);
  verifyChannelCreations(1, 3);
  verifyChannelCreations(2, 1);
  verifyConsumerCreations(1, 1, 3);
  verifyConsumerCreations(1, 2, 3);
  verifyConsumerCreations(2, 5, 1);
  verifyConsumerCreations(2, 6, 1);
  // Initial failure plus two retries for each thread
  verifyInvocations(6);
}
 
Example #28
Source File: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void test_client_takeover_mqtt3() throws Exception {

    final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
    final Waiter disconnectMessageWaiter = new Waiter();
    final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, false);

    final EmbeddedChannel oldChannel =
            new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
    oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1_1);
    final SettableFuture<Void> disconnectFuture = SettableFuture.create();
    disconnectFuture.set(null);
    oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);

    final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
    when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
    when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    final CONNECT connect1 = new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1_1)
            .withClientIdentifier("sameClientId")
            .build();

    embeddedChannel.writeInbound(connect1);

    assertTrue(embeddedChannel.isOpen());
    assertFalse(oldChannel.isOpen());
    assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());

    assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
    disconnectMessageWaiter.await();

    final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
    assertNull(disconnectMessage);
}
 
Example #29
Source File: JDBCInterpreterTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectWithRefresh() throws IOException, InterruptedException, TimeoutException {
  Properties properties = new Properties();
  properties.setProperty("common.max_count", "1000");
  properties.setProperty("common.max_retry", "3");
  properties.setProperty("default.driver", "org.h2.Driver");
  properties.setProperty("default.url", getJdbcConnection());
  properties.setProperty("default.user", "");
  properties.setProperty("default.password", "");
  JDBCInterpreter t = new JDBCInterpreter(properties);
  t.open();

  final Waiter waiter = new Waiter();
  context.getLocalProperties().put("refreshInterval", "1000");
  Thread thread = new Thread(() -> {
    String sqlQuery = "select * from test_table WHERE ID in ('a', 'b');";
    try {
      InterpreterResult interpreterResult = t.interpret(sqlQuery, context);
      assertEquals(InterpreterResult.Code.ERROR, interpreterResult.code());
    } catch (InterpreterException e) {
      fail("Should not be here");
    }
    waiter.resume();
  });

  thread.start();

  Thread.sleep(5000);
  t.cancel(context);
  waiter.await(5000);
}
 
Example #30
Source File: XmrToApiOrderParameterTest.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockWebServer = new MockWebServer();
    mockWebServer.start();

    waiter = new Waiter();

    MockitoAnnotations.initMocks(this);

    xmrToApi = new XmrToApiImpl(okHttpClient, mockWebServer.url("/"));
}