/*
   * Launches against the agent& main
   */
  public void testAgentAndMain() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "agent,main;agent=1090");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(2, sessions.size());

    RunSession agent = sessions.get(0);
    RunSession main = sessions.get(1);

    CountDownLatch agentLatch = launch(agent);
    CountDownLatch mainLatch = launch(main);

    agent.waitTillStarted(1000);
    main.waitTillStarted(1000);
    Thread.sleep(500);

    agent.cancel();
    main.cancel();

    agentLatch.await();
    mainLatch.await();
    assertEquals(-3, agent.getExitCode());
    assertEquals(-3, main.getExitCode());

    bndrun.close();
  }
  @Test
  public void testStartAsyncThenClientStreamIdleTimeout() throws Exception {
    CountDownLatch serverLatch = new CountDownLatch(1);
    start(new AsyncOnErrorServlet(serverLatch));
    long idleTimeout = 1000;
    client.setIdleTimeout(10 * idleTimeout);

    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    FuturePromise<Stream> promise = new FuturePromise<>();
    CountDownLatch clientLatch = new CountDownLatch(1);
    session.newStream(
        frame,
        promise,
        new Stream.Listener.Adapter() {
          @Override
          public boolean onIdleTimeout(Stream stream, Throwable x) {
            clientLatch.countDown();
            return true;
          }
        });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    stream.setIdleTimeout(idleTimeout);

    // When the client resets, the server receives the
    // corresponding frame and acts by notifying the failure,
    // but the response is not sent back to the client.
    Assert.assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
  }
 @Test
 public void testLocalTopologyWithLinkedActorsAndExitTraps() throws Exception {
   ServerTopology topology = null;
   try {
     topology = new ServerTopology(HOST, PORT);
     CountDownLatch killLatch = new CountDownLatch(1);
     CountDownLatch trapLatch = new CountDownLatch(1);
     Address actorAddress1 =
         topology.spawnActor(ACTOR_ADDRESS_1, new TestKilledHandler(killLatch));
     assertNotNull(actorAddress1);
     Address actorAddress2 =
         topology.spawnActor(ACTOR_ADDRESS_2, new TestHandlerTrappingExit(trapLatch));
     assertNotNull(actorAddress2);
     Actor actor1 = topology.getActor(actorAddress1);
     Actor actor2 = topology.getActor(actorAddress2);
     actor1.link(actor2);
     actor1.send(EXPECTED_MESSAGE);
     boolean killed = killLatch.await(3, TimeUnit.SECONDS);
     assertTrue(killed);
     assertFalse(actor1.isActive());
     boolean trapped = trapLatch.await(3, TimeUnit.SECONDS);
     assertTrue(trapped);
     assertTrue(actor2.isActive());
   } finally {
     topology.shutdown();
   }
 }
  /** @throws Exception If failed. */
  @SuppressWarnings("unchecked")
  public void testCancel() throws Exception {
    Grid grid = G.grid(getTestGridName());

    grid.compute()
        .localDeployTask(GridCancelTestTask.class, U.detectClassLoader(GridCancelTestTask.class));

    GridComputeTaskFuture<?> fut = grid.compute().execute(GridCancelTestTask.class.getName(), null);

    // Wait until jobs begin execution.
    boolean await = startSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);

    assert await : "Jobs did not start.";

    info("Test task result: " + fut);

    assert fut != null;

    // Only first job should successfully complete.
    Object res = fut.get();
    assert (Integer) res == 1;

    // Wait for all jobs to finish.
    await = stopSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);
    assert await : "Jobs did not stop.";

    // One is definitely processed. But there might be some more processed or cancelled or processed
    // and cancelled.
    // Thus total number should be at least SPLIT_COUNT and at most (SPLIT_COUNT - 1) *2 +1
    assert (cancelCnt + processedCnt) >= SPLIT_COUNT
            && (cancelCnt + processedCnt) <= (SPLIT_COUNT - 1) * 2 + 1
        : "Invalid cancel count value: " + cancelCnt;
  }
  @Test
  public void testOpenedClosedAreInvoked() throws Exception {
    initConnector(null);

    final CountDownLatch openedLatch = new CountDownLatch(1);
    final CountDownLatch closedLatch = new CountDownLatch(1);
    connector.addNetworkTrafficListener(
        new NetworkTrafficListener.Adapter() {
          public volatile Socket socket;

          @Override
          public void opened(Socket socket) {
            this.socket = socket;
            openedLatch.countDown();
          }

          @Override
          public void closed(Socket socket) {
            if (this.socket == socket) closedLatch.countDown();
          }
        });
    int port = connector.getLocalPort();

    // Connect to the server
    Socket socket = new Socket("localhost", port);
    assertTrue(openedLatch.await(10, TimeUnit.SECONDS));

    socket.close();
    assertTrue(closedLatch.await(10, TimeUnit.SECONDS));
  }
  @Test(timeout = 1500l)
  public void testReentrancy() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    firstLock.lock();
    try {
      testService.submit(
          new Runnable() {
            @Override
            public void run() {
              Lock secondLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
              secondLock.lock();
              try {
                latch.countDown();
              } finally {
                secondLock.unlock();
              }
            }
          });

      boolean nowAcquired = latch.await(500, TimeUnit.MILLISECONDS);
      assertTrue("The Second lock was acquired before the first lock was released!", !nowAcquired);

      // this should be fine
      firstLock.lock();
      System.out.println("Lock acquired twice!");
      firstLock.unlock();
      // should still be locked
      nowAcquired = latch.await(500, TimeUnit.MILLISECONDS);
      assertTrue(
          "The Second lock was acquired before the first lock was released twice!", !nowAcquired);
    } finally {
      firstLock.unlock();
    }
  }
  @Test
  public void testUnregisterTwice() throws Exception {

    AeroGearGCMPushConfiguration config =
        new AeroGearGCMPushConfiguration()
            .setSenderId(TEST_SENDER_ID)
            .setVariantID(TEST_SENDER_VARIANT)
            .setSecret(TEST_SENDER_PASSWORD)
            .setPushServerURI(new URI("https://testuri"));

    AeroGearGCMPushRegistrar registrar = (AeroGearGCMPushRegistrar) config.asRegistrar();
    CountDownLatch latch = new CountDownLatch(1);
    StubHttpProvider provider = new StubHttpProvider();
    UnitTestUtils.setPrivateField(registrar, "httpProviderProvider", provider);

    StubInstanceIDProvider instanceIdProvider = new StubInstanceIDProvider();
    UnitTestUtils.setPrivateField(registrar, "instanceIdProvider", instanceIdProvider);

    VoidCallback callback = new VoidCallback(latch);

    AeroGearGCMPushRegistrar spy = Mockito.spy(registrar);

    spy.register(super.getActivity(), callback);
    latch.await(1, TimeUnit.SECONDS);

    latch = new CountDownLatch(2);
    callback = new VoidCallback(latch);
    spy.unregister(super.getActivity(), callback);
    spy.unregister(super.getActivity(), callback);
    latch.await(4, TimeUnit.SECONDS);

    Assert.assertNotNull(callback.exception);
    Assert.assertTrue(callback.exception instanceof IllegalStateException);
  }
Exemple #8
0
  @GwtIncompatible("removalListener")
  public void testRemovalNotification_clear() throws InterruptedException {
    // If a clear() happens while a computation is pending, we should not get a removal
    // notification.

    final AtomicBoolean shouldWait = new AtomicBoolean(false);
    final CountDownLatch computingLatch = new CountDownLatch(1);
    CacheLoader<String, String> computingFunction =
        new CacheLoader<String, String>() {
          @Override
          public String load(String key) throws InterruptedException {
            if (shouldWait.get()) {
              computingLatch.await();
            }
            return key;
          }
        };
    QueuingRemovalListener<String, String> listener = queuingRemovalListener();

    final LoadingCache<String, String> cache =
        CacheBuilder.newBuilder()
            .concurrencyLevel(1)
            .removalListener(listener)
            .build(computingFunction);

    // seed the map, so its segment's count > 0
    cache.getUnchecked("a");
    shouldWait.set(true);

    final CountDownLatch computationStarted = new CountDownLatch(1);
    final CountDownLatch computationComplete = new CountDownLatch(1);
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                computationStarted.countDown();
                cache.getUnchecked("b");
                computationComplete.countDown();
              }
            })
        .start();

    // wait for the computingEntry to be created
    computationStarted.await();
    cache.invalidateAll();
    // let the computation proceed
    computingLatch.countDown();
    // don't check cache.size() until we know the get("b") call is complete
    computationComplete.await();

    // At this point, the listener should be holding the seed value (a -> a), and the map should
    // contain the computed value (b -> b), since the clear() happened before the computation
    // completed.
    assertEquals(1, listener.size());
    RemovalNotification<String, String> notification = listener.remove();
    assertEquals("a", notification.getKey());
    assertEquals("a", notification.getValue());
    assertEquals(1, cache.size());
    assertEquals("b", cache.getUnchecked("b"));
  }
Exemple #9
0
  // @Test
  public void clientShouldConnectToPeer()
      throws CannotUnserializeException, CannotReadTokenException, CannotReadBencodedException,
          THPRequestException, HashException, InterruptedException {
    lock = new CountDownLatch(2);

    initGuice();
    initEventBus();
    initTorrentStream();
    initClient();

    client.loadMetaInfo(torrentStream);
    client.refreshPeerList();

    System.out.println("Refreshing peer list");
    lock.await(30, TimeUnit.SECONDS);
    assertNotNull(peers);
    assertFalse(peers.isEmpty());

    lock = new CountDownLatch(1);
    // We take the first peer of the list
    Peer testedPeer = peers.iterator().next();
    client.connectToPeer(testedPeer);
    lock.await(30, TimeUnit.SECONDS);

    assertNotNull(testedPeer.getPeerWire());
    System.out.println("A new peerwire has been created for " + peers);
  }
 @Test
 public void lockMap() throws InterruptedException {
   HazelcastClient hClient = getHazelcastClient();
   final IMap<String, String> map = hClient.getMap("lockMap");
   final CountDownLatch unlockLatch = new CountDownLatch(1);
   final CountDownLatch latch = new CountDownLatch(1);
   map.put("a", "b");
   map.lockMap(1, TimeUnit.SECONDS);
   assertTrue(map.tryPut("a", "c", 10, TimeUnit.MILLISECONDS));
   new Thread(
           new Runnable() {
             public void run() {
               assertFalse(map.lockMap(10, TimeUnit.MILLISECONDS));
               unlockLatch.countDown();
               assertTrue(map.lockMap(Long.MAX_VALUE, TimeUnit.SECONDS));
               latch.countDown();
               // map.unlockMap();
             }
           })
       .start();
   assertTrue(unlockLatch.await(10, TimeUnit.SECONDS));
   Thread.sleep(2000);
   map.unlockMap();
   assertEquals("c", map.getMapEntry("a").getValue());
   assertTrue(latch.await(10, TimeUnit.SECONDS));
 }
  public void execute() throws Exception {
    // override for connection & data setup
    setUp();

    // start threads
    ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
    try {
      for (int i = 0; i < threadCount; i++) {
        BenchmarkTask task = createTask();
        task.taskSequence = i;
        task.parent = this;
        threadPool.execute(task);
      }

      // wait for all threads ready
      startLock.await();

      // print start message
      startTime = new Date();
      printStartMessage();

      // wait for all threads finish
      finishLock.await();

      // print finish summary message
      printFinishMessage();
    } finally {
      threadPool.shutdownNow();
      // override for connection & data cleanup
      tearDown();
    }
  }
  @Test
  public void testListener() throws Exception {
    final int maxItems = 10;
    final CountDownLatch itemAddedLatch = new CountDownLatch(maxItems);
    final CountDownLatch itemRemovedLatch = new CountDownLatch(maxItems);

    final IQueue queue = client.getQueue(randomString());

    String id =
        queue.addItemListener(
            new ItemListener() {

              public void itemAdded(ItemEvent itemEvent) {
                itemAddedLatch.countDown();
              }

              public void itemRemoved(ItemEvent item) {
                itemRemovedLatch.countDown();
              }
            },
            true);

    new Thread() {
      public void run() {
        for (int i = 0; i < maxItems; i++) {
          queue.offer(i);
          queue.remove(i);
        }
      }
    }.start();

    assertTrue(itemAddedLatch.await(5, TimeUnit.SECONDS));
    assertTrue(itemRemovedLatch.await(5, TimeUnit.SECONDS));
    queue.removeItemListener(id);
  }
  @Test
  public void testListenUnlisten() throws Exception {
    final AtomicReference<Message> handshakeRef = new AtomicReference<>();
    final CountDownLatch handshakeLatch = new CountDownLatch(1);
    final AtomicReference<Message> connectRef = new AtomicReference<>();
    final CountDownLatch connectLatch = new CountDownLatch(1);
    final AtomicReference<Message> disconnectRef = new AtomicReference<>();
    final CountDownLatch disconnectLatch = new CountDownLatch(1);

    ListenUnlistenService s =
        new ListenUnlistenService(
            handshakeRef, handshakeLatch, connectRef, connectLatch, disconnectRef, disconnectLatch);
    boolean processed = processor.process(s);
    assertTrue(processed);

    bayeuxClient.handshake();
    assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
    Message handshake = handshakeRef.get();
    assertNotNull(handshake);
    assertTrue(handshake.isSuccessful());

    assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
    Message connect = connectRef.get();
    assertNotNull(connect);
    assertTrue(connect.isSuccessful());

    processed = processor.deprocessCallbacks(s);
    assertTrue(processed);

    // Listener method must not be notified, since we have deconfigured
    bayeuxClient.disconnect(1000);
  }
  @Test
  public void testAPIMPubAndReceipt() throws Exception {

    // Create a listener
    CountDownLatch listeningSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);
    Thread listener = new ListenerThread(listeningSignal, doneSignal);
    listener.start();
    listeningSignal.await();

    // Publish an APIM event
    try {
      Map<String, List<String>> mdMap = new HashMap<String, List<String>>();
      List<String> destinations = new ArrayList<String>();
      destinations.add("fedora.apim.update");
      mdMap.put(MessageType.apimUpdate.toString(), destinations);
      Messaging msg = new MessagingImpl(getBaseURL(), mdMap, jmsMgr);
      Object[] invocationHandlers = {new NotificationInvocationHandler(msg)};
      Management mgmt = new MockManagementDelegate();
      Management proxy = (Management) ProxyFactory.getProxy(mgmt, invocationHandlers);
      proxy.purgeObject(new MockContext(), "demo:test", null);
    } catch (Exception e) {
      listener.interrupt();
      throw e;
    }
    // await message receipt & evaluation
    doneSignal.await();
  }
  @Test(timeout = 1000l)
  public void testNoWritesWithASingleRead() throws Exception {
    ReadWriteLock lock = new ReentrantZkReadWriteLock(testPath, zkSessionManager);

    Lock readLock = lock.readLock();
    final Lock writeLock = lock.writeLock();
    readLock.lock();
    final CountDownLatch latch = new CountDownLatch(1);

    testService.submit(
        new Runnable() {
          @Override
          public void run() {
            writeLock.lock();
            try {
              latch.countDown();
            } finally {
              writeLock.unlock();
            }
          }
        });

    boolean acquired = latch.await(250, TimeUnit.MILLISECONDS);
    assertTrue("The Write lock was improperly acquired!", !acquired);

    // unlock the read lock, and make sure that the write lock is acquired
    readLock.unlock();
    acquired = latch.await(250, TimeUnit.MILLISECONDS);
    assertTrue("The Write lock was never acquired!", acquired);
  }
Exemple #16
0
  // @Test
  public void peerShouldHaveConsistentPieceCount()
      throws InterruptedException, THPRequestException, HashException, CannotUnserializeException,
          CannotReadTokenException, CannotReadBencodedException {
    lock = new CountDownLatch(2);
    initGuice();
    initEventBus();
    initTorrentStream();
    initClient();

    client.loadMetaInfo(torrentStream);
    client.refreshPeerList();

    System.out.println("Refreshing peer list");
    lock.await(30, TimeUnit.SECONDS);
    assertNotNull(peers);
    assertFalse(peers.isEmpty());

    Peer testedPeer = peers.iterator().next();

    expectedMessageReceived = false;
    expectedMessageType = MessageType.HANDSHAKE;
    lock = new CountDownLatch(2);
    testedPeer.connect();
    lock.await(30, TimeUnit.SECONDS);
    assertTrue(testedPeer.getPeerId() != null);
    assertEquals(metaInfo.getInformation().getPieceCount(), testedPeer.getExpectedPieceCount());
  }
  @Test
  public void testTryLock() throws InterruptedException {
    HazelcastClient hClient = getHazelcastClient();
    final ILock lock = hClient.getLock("testTryLock");
    assertTrue(lock.tryLock());
    lock.lock();
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch unlockLatch = new CountDownLatch(1);
    new Thread(
            new Runnable() {

              public void run() {
                assertFalse(lock.tryLock());
                unlockLatch.countDown();
                try {
                  assertTrue(lock.tryLock(10, TimeUnit.SECONDS));
                } catch (InterruptedException e) {
                  throw new RuntimeException(e);
                }
                latch.countDown();
              }
            })
        .start();
    assertTrue(unlockLatch.await(10, TimeUnit.SECONDS));
    lock.unlock();
    lock.unlock();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
  }
  /**
   * Ensure that {@link GridComputeJobMasterLeaveAware} callback is invoked on job which is
   * initiated by master and is currently running on it.
   *
   * @throws Exception If failed.
   */
  public void testLocalJobOnMaster() throws Exception {
    invokeLatch = new CountDownLatch(1);
    jobLatch = new CountDownLatch(1);

    Grid g = startGrid(0);

    g.compute().execute(new TestTask(1), null);

    jobLatch.await();

    // Count down the latch in a separate thread.
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  U.sleep(500);
                } catch (GridInterruptedException ignore) {
                  // No-op.
                }

                latch.countDown();
              }
            })
        .start();

    stopGrid(0, true);

    latch.countDown();

    assert invokeLatch.await(5000, MILLISECONDS);
  }
  @Test(timeout = 1000l)
  public void testMultipleClientsCannotAccessSameLock() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    final Lock sameLock =
        new ReentrantZkLock(baseLockPath, new BaseZkSessionManager(newZooKeeper()));

    firstLock.lock();
    testService.submit(
        new Runnable() {
          @Override
          public void run() {
            sameLock.lock();
            try {
              latch.countDown();
            } finally {
              sameLock.unlock();
            }
          }
        });

    boolean acquired = latch.await(500, TimeUnit.MILLISECONDS);
    assertTrue("The Lock was acquired twice by two separate threads!", !acquired);

    firstLock.unlock();

    acquired = latch.await(500, TimeUnit.MILLISECONDS);
    assertTrue("The Lock was never acquired by another thread!", acquired);
  }
  /**
   * Ensure that {@link GridComputeJobMasterLeaveAware} callback is invoked when fails to send
   * {@link GridJobExecuteResponse} to master node.
   *
   * @throws Exception If failed.
   */
  public void testCannotSendJobExecuteResponse() throws Exception {
    awaitMasterLeaveCallback = false;

    // Start grids.
    for (int i = 0; i < GRID_CNT; i++) startGrid(i);

    int lastGridIdx = GRID_CNT - 1;

    grid(lastGridIdx)
        .forPredicate(excludeLastPredicate())
        .compute()
        .execute(new TestTask(GRID_CNT - 1), null);

    jobLatch.await();

    for (int i = 0; i < lastGridIdx; i++)
      ((CommunicationSpi) grid(i).configuration().getCommunicationSpi()).waitLatch();

    latch.countDown();

    // Ensure that all worker nodes has already started job response sending.
    for (int i = 0; i < lastGridIdx; i++)
      ((CommunicationSpi) grid(i).configuration().getCommunicationSpi()).awaitResponse();

    // Now we stop master grid.
    stopGrid(lastGridIdx, true);

    // Release communication SPI wait latches. As master node is stopped, job worker will receive
    // and exception.
    for (int i = 0; i < lastGridIdx; i++)
      ((CommunicationSpi) grid(i).configuration().getCommunicationSpi()).releaseWaitLatch();

    assert invokeLatch.await(5000, MILLISECONDS);
  }
  @Test
  public void testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception {
    final CountDownLatch connectedLatch1 = new CountDownLatch(2);
    final CountDownLatch connectedLatch2 = new CountDownLatch(6);
    TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2);
    assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));
    log.info("Killing connection");
    forwarder.terminate();

    log.info("Connection down.");

    Thread.sleep(9000);
    log.info("Recreating connection soon" + forwarderPort + "->" + zkport);
    Thread.sleep(1000);
    assertEquals(
        CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
        listener.events.get(listener.events.size() - 1));
    forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
    assertTrue(connectedLatch2.await(20, TimeUnit.SECONDS));

    for (int c = 0; c < 100; c++) {
      if (CoordinateListener.Event.COORDINATE_OK
          == listener.events.get(listener.events.size() - 1)) {
        break;
      }
      Thread.sleep(300);
    }
    Thread.sleep(4500);
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));

    forwarder.terminate();
  }
  /**
   * @param expJobs Expected jobs number.
   * @param taskStarter Task started.
   * @throws Exception If failed.
   */
  private void testMasterLeaveAwareCallback(
      int expJobs, GridClosure<GridProjection, GridFuture<?>> taskStarter) throws Exception {
    jobLatch = new CountDownLatch(expJobs);
    invokeLatch = new CountDownLatch(expJobs);

    for (int i = 0; i < GRID_CNT; i++) startGrid(i);

    int lastGridIdx = GRID_CNT - 1;

    GridFuture<?> fut = taskStarter.apply(grid(lastGridIdx).forPredicate(excludeLastPredicate()));

    jobLatch.await();

    stopGrid(lastGridIdx, true);

    latch.countDown();

    assert invokeLatch.await(5000, MILLISECONDS);

    try {
      fut.get();
    } catch (GridException e) {
      log.debug("Task failed: " + e);
    }
  }
Exemple #23
0
  @Test
  public void testTopicStats() throws InterruptedException {
    String topicName = "testTopicStats" + generateRandomString(5);

    HazelcastInstance instance = createHazelcastInstance();
    ITopic<String> topic = instance.getTopic(topicName);

    final CountDownLatch latch1 = new CountDownLatch(1000);
    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message msg) {
            latch1.countDown();
          }
        });

    final CountDownLatch latch2 = new CountDownLatch(1000);
    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message msg) {
            latch2.countDown();
          }
        });

    for (int i = 0; i < 1000; i++) {
      topic.publish("sancar");
    }
    assertTrue(latch1.await(1, TimeUnit.MINUTES));
    assertTrue(latch2.await(1, TimeUnit.MINUTES));

    LocalTopicStatsImpl stats = (LocalTopicStatsImpl) topic.getLocalTopicStats();
    assertEquals(1000, stats.getPublishOperationCount());
    assertEquals(2000, stats.getReceiveOperationCount());
  }
    /** @param log Logger. */
    private void execute(GridLogger log) {
      try {
        log.info("Started execute.");

        // Countdown shared job latch so that the main thread know that all jobs are
        // inside the "execute" routine.
        jobLatch.countDown();

        log.info("After job latch.");

        // Await for the main thread to allow jobs to proceed.
        latch.await();

        log.info("After latch.");

        if (awaitMasterLeaveCallback) {
          latch0.await();

          log.info("After latch0.");
        } else log.info("Latch 0 skipped.");
      } catch (InterruptedException e) {
        // We do not expect any interruptions here, hence this statement.
        fail("Unexpected exception: " + e);
      }
    }
  @Test
  public void testStartAsyncThenClientSessionIdleTimeout() throws Exception {
    CountDownLatch serverLatch = new CountDownLatch(1);
    start(new AsyncOnErrorServlet(serverLatch));
    long idleTimeout = 1000;
    client.setIdleTimeout(idleTimeout);

    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    FuturePromise<Stream> promise = new FuturePromise<>();
    CountDownLatch clientLatch = new CountDownLatch(1);
    session.newStream(
        frame,
        promise,
        new Stream.Listener.Adapter() {
          @Override
          public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            if (response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR_500 && frame.isEndStream())
              clientLatch.countDown();
          }
        });
    Stream stream = promise.get(5, TimeUnit.SECONDS);
    stream.setIdleTimeout(10 * idleTimeout);

    // When the client closes, the server receives the
    // corresponding frame and acts by notifying the failure,
    // which sends back to the client the error response.
    Assert.assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
  }
Exemple #26
0
 @Override
 public void run() {
   log.info("Starting Copy Delete Task for table: " + m_tableName);
   try {
     List<Long> workList = new ArrayList<Long>();
     while (m_shouldContinue.get()) {
       cpDelQueue.drainTo(workList, 10);
       if (workList.size() <= 0) {
         Thread.sleep(2000);
       }
       CountDownLatch clatch = new CountDownLatch(workList.size());
       for (Long lcid : workList) {
         client.callProcedure(new InsertCopyCallback(clatch), m_cpprocName, lcid);
       }
       clatch.await();
       CountDownLatch dlatch = new CountDownLatch(workList.size());
       for (Long lcid : workList) {
         client.callProcedure(new DeleteCallback(dlatch, 2), m_delprocName, lcid);
       }
       dlatch.await();
       m_copyDeleteDoneCount += workList.size();
       workList.clear();
     }
     log.info("CopyAndDeleteTask row count: " + m_copyDeleteDoneCount);
   } catch (Exception e) {
     // on exception, log and end the thread, but don't kill the process
     log.error(
         "CopyAndDeleteDataTask failed a procedure call for table "
             + m_tableName
             + " and the thread will now stop.",
         e);
   }
 }
 @Test
 public void testLocalTopologyWithFailedActorAndAllForOneFailoverPolicy() throws Exception {
   ServerTopology topology = null;
   try {
     topology = new ServerTopology(HOST, PORT, FailoverPolicies.newAllForOnePolicy());
     CountDownLatch restartLatch1 = new CountDownLatch(1);
     CountDownLatch restartLatch2 = new CountDownLatch(1);
     Address actorAddress1 =
         topology.spawnActor(ACTOR_ADDRESS_1, new TestRestartedHandlerOnFail(restartLatch1));
     assertNotNull(actorAddress1);
     Address actorAddress2 =
         topology.spawnActor(ACTOR_ADDRESS_2, new TestRestartedHandler(restartLatch2));
     assertNotNull(actorAddress2);
     Actor actor1 = topology.getActor(actorAddress1);
     actor1.send(EXPECTED_MESSAGE);
     boolean restarted = restartLatch1.await(3, TimeUnit.SECONDS);
     assertTrue(restarted);
     Actor restartedActor = topology.getActor(actorAddress1);
     assertSame(actor1, restartedActor);
     restarted = restartLatch2.await(3, TimeUnit.SECONDS);
     assertTrue(restarted);
   } finally {
     topology.shutdown();
   }
 }
  @Test(timeout = 1000l)
  public void testOneWriteAllowed() throws Exception {
    ReadWriteLock firstLock = new ReentrantZkReadWriteLock(testPath, zkSessionManager);
    ReadWriteLock secondLock = new ReentrantZkReadWriteLock(testPath, zkSessionManager);

    final Lock firstWriteLock = firstLock.writeLock();
    final Lock secondWriteLock = secondLock.writeLock();
    firstWriteLock.lock();
    final CountDownLatch correctnessLatch = new CountDownLatch(1);

    testService.submit(
        new Runnable() {
          @Override
          public void run() {
            secondWriteLock.lock();
            try {
              correctnessLatch.countDown();
            } finally {
              secondWriteLock.unlock();
            }
          }
        });

    boolean acquired = correctnessLatch.await(250, TimeUnit.MILLISECONDS);
    assertTrue("Two Write locks were acquired concurrently!", !acquired);

    // unlock and check
    firstWriteLock.unlock();

    acquired = correctnessLatch.await(250, TimeUnit.MILLISECONDS);
    assertTrue("The second write lock was never acquired!", acquired);
  }
  @Test
  public void testPublisherConfirmReceivedTwoTemplates() throws Exception {
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    templateWithConfirmsEnabled.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            latch1.countDown();
          }
        });
    templateWithConfirmsEnabled.convertAndSend(
        ROUTE, (Object) "message", new CorrelationData("abc"));
    RabbitTemplate secondTemplate = new RabbitTemplate(connectionFactoryWithConfirmsEnabled);
    secondTemplate.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            latch2.countDown();
          }
        });
    secondTemplate.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def"));
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
    assertNull(secondTemplate.getUnconfirmed(-1));
  }
Exemple #30
0
  /**
   * Start this engine to make it available for use, and optionally start each of the repositories
   * in the configuration. Any errors starting the repositories will be logged as problems.
   *
   * <p>This method starts each repository in parallel, and returns after the supplied timeout or
   * after all repositories have been started (or failed startup), whichever comes first.
   *
   * @param validateRepositoryConfigs true if the configurations of each repository should be
   *     validated and each repository started/initialized, or false otherwise
   * @param timeout the maximum time to wait; can be 0 or a positive number, but use a negative
   *     number to wait indefinitely until all repositories are started (or failed)
   * @param timeoutUnit the time unit of the {@code timeout} argument; may not be null, but ignored
   *     if <code>timeout</code> is negative
   * @throws IllegalStateException if this method is called when already shut down.
   * @throws JcrConfigurationException if there is an error in the configuration or any of the
   *     services that prevents proper startup
   * @see #start()
   * @see #shutdown()
   */
  public void start(boolean validateRepositoryConfigs, long timeout, TimeUnit timeoutUnit) {
    start();
    if (validateRepositoryConfigs) {
      Set<String> repositoryNames = getRepositoryNames();
      if (repositoryNames.isEmpty()) return;

      final CountDownLatch latch = new CountDownLatch(repositoryNames.size());

      try {
        repositoriesLock.lock();
        // Put in a holder with a future for each repository
        // (this should proceed quickly, as nothing waits for the initialization) ...
        for (final String repositoryName : repositoryNames) {
          RepositoryInitializer initializer = new RepositoryInitializer(repositoryName, latch);
          Future<JcrRepository> future = repositoryStarterService.submit(initializer);
          JcrRepositoryHolder holder = new JcrRepositoryHolder(repositoryName, future);
          this.repositories.put(repositoryName, holder);
        }
      } finally {
        repositoriesLock.unlock();
      }

      // Now wait for the all the startups to complete ...
      try {
        if (timeout < 0L) {
          latch.await();
        } else {
          latch.await(timeout, timeoutUnit);
        }
      } catch (InterruptedException e) {
        this.problems.addError(e, JcrI18n.startingAllRepositoriesWasInterrupted, e.getMessage());
      }
    }
  }