Exemplo n.º 1
1
 private Integer startTunnelSSH(Instance instance) throws InterruptedException {
   Instance tunnelInstance = runningInstances(tunnelResourceId).get(0);
   Integer localPort = Double.valueOf(Randoms.number(3000, 10000)).intValue();
   CountDownLatch latch = new CountDownLatch(1);
   Thread tunnelThread =
       new Thread(
           () -> {
             Process process = null;
             try {
               Path keyPath = KeyPair.keyFile(tunnelInstance.getKeyName(), env);
               String userAndHost = "ubuntu@" + hostName(tunnelInstance);
               String portBinding =
                   Strings.format("{}:{}:22", localPort, instance.getPrivateIpAddress());
               List<String> command = tunnelCommand(keyPath, userAndHost, portBinding);
               logger.info("tunnel command => {}", String.join(" ", command));
               process = new ProcessBuilder().command(command).start();
               process.getInputStream().read(); // wait until there is output
               latch.countDown();
               process.waitFor();
             } catch (InterruptedException | IOException e) {
               throw new IllegalStateException(e);
             } finally {
               if (process != null) process.destroy();
             }
           });
   tunnelThread.setDaemon(true);
   tunnelThread.start();
   latch.await();
   return localPort;
 }
  public void testDataProvider() {
    assertNotNull(mDataManager);

    android.location.Location currentLocation = AppLocationManager.getCurrentLocation();
    Location location =
        new Location(
            String.valueOf(currentLocation.getLatitude()),
            String.valueOf(currentLocation.getLongitude()));

    final List<Place> eventList =
        mDataManager.getPlaceList(location, PlaceCategoryFilter.HOTEL, "8", ""); // see parameters
    assertNotNull(eventList);
    assertTrue(eventList.size() > 0);

    final Place place = eventList.get(0);

    final CountDownLatch latch = new CountDownLatch(1);

    mPlaceActivity.runOnUiThread(
        new Runnable() {

          @Override
          public void run() {
            mPlaceActivity.showPlace(place);
            latch.countDown();
          }
        });

    try {
      latch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  } // end testDataProvider
Exemplo n.º 3
0
  public void testSendManyMessages() throws Exception {
    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);
    frame = receiveFrame(10000);

    Assert.assertTrue(frame.startsWith("CONNECTED"));
    int count = 1000;
    final CountDownLatch latch = new CountDownLatch(count);
    consumer.setMessageListener(
        new MessageListener() {

          public void onMessage(Message arg0) {
            latch.countDown();
          }
        });

    frame =
        "SEND\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n\n"
            + "Hello World"
            + Stomp.NULL;
    for (int i = 1; i <= count; i++) {
      // Thread.sleep(1);
      // System.out.println(">>> " + i);
      sendFrame(frame);
    }

    assertTrue(latch.await(60, TimeUnit.SECONDS));
  }
Exemplo n.º 4
0
  @Test
  public void testCreateFile() throws Exception {
    log.debug(" **** testCreateFile **** ");
    File f = new File(mytempdir + File.separator + "just_created");
    try {
      fw = new FolderWatcher(new File(mytempdir), 100);
      fw.initialRun();

      final CountDownLatch latch = new CountDownLatch(1);
      fw.addListener(
          new IModificationListener() {

            public void fileModified(File f, ModifyActions action) {
              Assert.assertEquals("just_created", f.getName());
              Assert.assertEquals(ModifyActions.CREATED, action);
              latch.countDown();
            }
          });
      fw.run();

      f.createNewFile();

      log.debug("We expect CREATED");
      if (!latch.await(3, TimeUnit.SECONDS)) {
        Assert.fail("No callback occured");
      }
      f.delete();
      fw.cancel();
    } catch (Exception e) {
      fw.cancel();
      f.delete();
      throw e;
    }
  }
Exemplo n.º 5
0
 public void invokeAndWait(final IManagerCommand command) {
   if (isManagerThread()) {
     myThread.processCommand(command);
   } else {
     final CountDownLatch countDown = new CountDownLatch(1);
     schedule(
         Commands.fromClosure(
             new _FunctionTypes._void_P0_E0() {
               public void invoke() {
                 try {
                   command.invoke();
                 } finally {
                   countDown.countDown();
                 }
               }
             },
             new _FunctionTypes._void_P0_E0() {
               public void invoke() {
                 try {
                   command.cancel();
                 } finally {
                   countDown.countDown();
                 }
               }
             }));
     try {
       countDown.await();
     } catch (InterruptedException ignore) {
     }
   }
 }
  @Test
  public void bufferStopsWhenStopped() throws IOException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Pair<InputStream, List<byte[]>> stream = TestUtils.generateStream(100);

    MJpegStreamBufferer buffer = new MJpegStreamBufferer(5);

    buffer.start(
        new MJpegStreamBufferListener() {
          @Override
          public void stopped() {
            latch.countDown();
          }

          @Override
          public void streamBuffered(byte[] stream) {
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              throw new RuntimeException(e);
            }
          }

          @Override
          public void streamDiscarded(byte[] stream) {}
        },
        new MJpegStreamIterator(stream.getLeft()));

    buffer.stop();
    latch.await();
  }
  @Test
  public void test() throws IOException, InterruptedException {

    // val client = new ImportIO(UUID.fromString("d22d14f3-6c98-44af-a301-f822288ebbe3"),
    // "tMFNJzytLe8sgYF9hFNhKI7akyiPLMhfu8UfomNVCVr5fqWWLyiQMfpDDyfucQKF++BAoVi6jnGnavYqRKP/9g==");

    // If doing login rather than API key
    ImportIO client = new ImportIO();
    client.login(System.getProperty("username"), System.getProperty("password"));

    client.connect();

    final CountDownLatch latch = new CountDownLatch(3);

    MessageCallback messageCallback =
        new MessageCallback() {
          public void onMessage(Query query, QueryMessage message, Progress progress) {
            if (message.getType() == MessageType.MESSAGE) {
              System.err.println(message);
            }
            if (progress.isFinished()) {
              latch.countDown();
            }
          }
        };

    client.query(makeQuery("mac mini"), messageCallback);
    client.query(makeQuery("ibm"), messageCallback);
    client.query(makeQuery("handbag"), messageCallback);

    // wait until all 3 queryies are finished
    latch.await();

    client.shutdown();
  }
Exemplo n.º 8
0
  @Test
  public void testFutureUpdateExpiration() throws Exception {
    CyclicBarrier loadBarrier = new CyclicBarrier(2);
    CountDownLatch flushLatch = new CountDownLatch(2);
    CountDownLatch commitLatch = new CountDownLatch(1);

    Future<Boolean> first = updateFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
    Future<Boolean> second = updateFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
    awaitOrThrow(flushLatch);

    Map contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    assertEquals(FutureUpdate.class, contents.get(itemId).getClass());
    commitLatch.countDown();
    first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
    second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);

    // since we had two concurrent updates, the result should be invalid
    contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    Object value = contents.get(itemId);
    if (value instanceof FutureUpdate) {
      // DB did not blocked two concurrent updates
      TIME_SERVICE.advance(timeout + 1);
      assertNull(entityCache.get(itemId));
      contents = Caches.entrySet(entityCache).toMap();
      assertEquals(Collections.EMPTY_MAP, contents);
    } else {
      // DB left only one update to proceed, and the entry should not be expired
      assertNotNull(value);
      assertEquals(StandardCacheEntryImpl.class, value.getClass());
      TIME_SERVICE.advance(timeout + 1);
      assertEquals(value, entityCache.get(itemId));
    }
  }
  @Test
  public void testRegBundleIsRefBundle() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      BundleContext context = bundle.getBundleContext();
      context.addServiceListener(listener);

      Object service = bundle.loadClass(A.class.getName()).newInstance();
      ServiceRegistration reg = context.registerService(A.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundle, A.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundle.uninstall();
    }
  }
Exemplo n.º 10
0
  @Test
  public void writeContainerEmptyTreeTest() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);

    DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
    assertNotNull(
        "DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);

    final TestDataTreeListener listener = new TestDataTreeListener(latch);
    final ListenerRegistration<TestDataTreeListener> listenerReg =
        dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);

    final DOMDataTreeWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
    writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
    writeTx.submit();

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(1, listener.getReceivedChanges().size());
    final Collection<DataTreeCandidate> changes = listener.getReceivedChanges().get(0);
    assertEquals(1, changes.size());

    DataTreeCandidate candidate = changes.iterator().next();
    assertNotNull(candidate);
    DataTreeCandidateNode candidateRoot = candidate.getRootNode();
    checkChange(null, TEST_CONTAINER, ModificationType.WRITE, candidateRoot);
    listenerReg.close();
  }
  public ModelController createController(final ModelNode model, final Setup registration)
      throws InterruptedException {
    final ServiceController<?> existingController =
        serviceContainer.getService(ServiceName.of("ModelController"));
    if (existingController != null) {
      final CountDownLatch latch = new CountDownLatch(1);
      existingController.addListener(
          new AbstractServiceListener<Object>() {
            public void listenerAdded(ServiceController<?> serviceController) {
              serviceController.setMode(ServiceController.Mode.REMOVE);
            }

            public void transition(
                ServiceController<?> serviceController, ServiceController.Transition transition) {
              if (transition.equals(ServiceController.Transition.REMOVING_to_REMOVED)) {
                latch.countDown();
              }
            }
          });
      latch.await();
    }

    ServiceTarget target = serviceContainer.subTarget();
    ControlledProcessState processState = new ControlledProcessState(true);
    ModelControllerService svc = new ModelControllerService(processState, registration, model);
    ServiceBuilder<ModelController> builder =
        target.addService(ServiceName.of("ModelController"), svc);
    builder.install();
    svc.latch.await();
    ModelController controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);
    processState.setRunning();
    return controller;
  }
  public void collectQueueStats(
      final Azure azure,
      final String namespaceName,
      Set<String> queueNames,
      Set<String> queueStats,
      int queueThreads)
      throws TaskExecutionException {

    final Map<String, String> valueMap = createValueMap(azure, namespaceName, QUEUES, queueStats);

    ListeningExecutorService queueService =
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(queueThreads));
    final CountDownLatch countDownLatch = new CountDownLatch(queueNames.size());

    try {
      for (final String queueName : queueNames) {
        try {
          ListenableFuture getQueueNames =
              queueService.submit(
                  new Runnable() {
                    public void run() {
                      getStatsFromAzure(azure, namespaceName, valueMap, queueName, QUEUES);
                    }
                  });

          Futures.addCallback(
              getQueueNames,
              new FutureCallback<Void>() {
                public void onSuccess(Void nothing) {
                  countDownLatch.countDown();
                }

                public void onFailure(Throwable thrown) {
                  countDownLatch.countDown();
                  logger.error(
                      "Unable to get stats for queue ["
                          + queueName
                          + "] in namespace ["
                          + namespaceName
                          + "]",
                      thrown);
                }
              });

        } catch (Exception e) {
          logger.error(
              "Error getting stats for queue [" + namespaceName + "/" + queueName + "]", e);
          throw new TaskExecutionException(
              "Error getting stats for queue [" + namespaceName + "/" + queueName + "]", e);
        }
      }
    } finally {
      queueService.shutdown();
    }
    try {
      countDownLatch.await();
    } catch (InterruptedException e) {
      logger.error("Unable to wait till getting the queue stats", e);
    }
  }
  private void assertActionProducesLogMessage(
      final Runnable action, final String loggerName, final Level logLevel, final String message)
      throws Exception {
    final CountDownLatch logMessageReceivedLatch = new CountDownLatch(1);
    ch.qos.logback.classic.Logger rootLogger =
        (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> appender = new ListAppender<>();
    appender.addFilter(
        new Filter<ILoggingEvent>() {
          @Override
          public FilterReply decide(final ILoggingEvent event) {
            if (event.getLoggerName().equals(loggerName)
                && event.getLevel().equals(logLevel)
                && event.getFormattedMessage().contains(message)) {
              logMessageReceivedLatch.countDown();
            }
            return FilterReply.NEUTRAL;
          }
        });
    appender.setContext(rootLogger.getLoggerContext());
    appender.start();
    rootLogger.addAppender(appender);

    action.run();
    assertTrue(
        "Did not receive expected log message", logMessageReceivedLatch.await(2, TimeUnit.SECONDS));
  }
  @Test
  public void shouldTimeoutSleepingScript() throws Exception {
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);

    final CountDownLatch timeOutCount = new CountDownLatch(1);

    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .scriptEvaluationTimeout(250)
            .afterFailure((b, e) -> failureCalled.set(true))
            .afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeOutCount.countDown())
            .create();
    try {
      gremlinExecutor.eval("Thread.sleep(1000);10").get();
      fail("This script should have timed out with an exception");
    } catch (Exception ex) {
      assertEquals(TimeoutException.class, ex.getCause().getClass());
    }

    assertTrue(timeOutCount.await(2000, TimeUnit.MILLISECONDS));

    assertFalse(successCalled.get());
    assertFalse(failureCalled.get());
    assertEquals(0, timeOutCount.getCount());
    gremlinExecutor.close();
  }
  @Test
  public void shouldEvalScriptWithMapBindingsAndLanguageThenConsume() throws Exception {
    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .addEngineSettings(
                "nashorn",
                Collections.emptyList(),
                Collections.emptyList(),
                Collections.emptyList(),
                Collections.emptyMap())
            .create();
    final Map<String, Object> b = new HashMap<>();
    b.put("x", 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger result = new AtomicInteger(0);
    assertEquals(
        2.0,
        gremlinExecutor
            .eval(
                "1+x",
                "nashorn",
                b,
                r -> {
                  result.set(((Double) r).intValue() * 2);
                  latch.countDown();
                })
            .get());

    latch.await();
    assertEquals(4, result.get());
    gremlinExecutor.close();
  }
Exemplo n.º 16
0
 private void showImage(String title) throws Exception {
   if (!HEADLESS && SHOW_IMAGE) {
     CountDownLatch latch = new CountDownLatch(1);
     WaitingImageFrame.showImage(image, title, latch);
     latch.await();
   }
 }
Exemplo n.º 17
0
  @Test
  public void testEvictUpdateExpiration() throws Exception {
    CyclicBarrier loadBarrier = new CyclicBarrier(2);
    CountDownLatch preFlushLatch = new CountDownLatch(1);
    CountDownLatch postEvictLatch = new CountDownLatch(1);
    CountDownLatch flushLatch = new CountDownLatch(1);
    CountDownLatch commitLatch = new CountDownLatch(1);

    Future<Boolean> first = evictWait(itemId, loadBarrier, null, postEvictLatch);
    Future<Boolean> second =
        updateFlushWait(itemId, loadBarrier, preFlushLatch, flushLatch, commitLatch);
    awaitOrThrow(postEvictLatch);

    Map contents = Caches.entrySet(entityCache).toMap();
    assertEquals(Collections.EMPTY_MAP, contents);
    assertNull(contents.get(itemId));

    preFlushLatch.countDown();
    awaitOrThrow(flushLatch);
    contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    assertEquals(FutureUpdate.class, contents.get(itemId).getClass());

    commitLatch.countDown();
    first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
    second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);

    contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    Object value = contents.get(itemId);
    assertNotNull(value);
    assertEquals(StandardCacheEntryImpl.class, value.getClass());
    TIME_SERVICE.advance(timeout + 1);
    assertEquals(value, entityCache.get(itemId));
  }
  @Test
  public void testOwnerCannotSeeServiceClass() throws Exception {
    final Bundle bundleA = installBundle(getBundleArchiveA());
    final Bundle bundleB = installBundle(getBundleArchiveB());
    try {
      bundleA.start();
      bundleB.start();

      BundleContext contextA = bundleA.getBundleContext();
      BundleContext contextB = bundleB.getBundleContext();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      contextB.addServiceListener(listener);

      Object service = bundleB.loadClass(B.class.getName()).newInstance();
      ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundleA, B.class.getName()));
      assertTrue(ref.isAssignableTo(bundleB, B.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundleA.uninstall();
      bundleB.uninstall();
    }
  }
Exemplo n.º 19
0
  @Test
  public void testRemoveUpdateExpiration() throws Exception {
    CyclicBarrier loadBarrier = new CyclicBarrier(2);
    CountDownLatch preFlushLatch = new CountDownLatch(1);
    CountDownLatch flushLatch = new CountDownLatch(1);
    CountDownLatch commitLatch = new CountDownLatch(1);

    Future<Boolean> first = removeFlushWait(itemId, loadBarrier, null, flushLatch, commitLatch);
    Future<Boolean> second = updateFlushWait(itemId, loadBarrier, preFlushLatch, null, commitLatch);
    awaitOrThrow(flushLatch);

    Map contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    assertEquals(Tombstone.class, contents.get(itemId).getClass());

    preFlushLatch.countDown();
    commitLatch.countDown();
    first.get(WAIT_TIMEOUT, TimeUnit.SECONDS);
    second.get(WAIT_TIMEOUT, TimeUnit.SECONDS);

    contents = Caches.entrySet(entityCache).toMap();
    assertEquals(1, contents.size());
    assertEquals(Tombstone.class, contents.get(itemId).getClass());

    TIME_SERVICE.advance(timeout + 1);
    assertNull(entityCache.get(itemId)); // force expiration
    contents = Caches.entrySet(entityCache).toMap();
    assertEquals(Collections.EMPTY_MAP, contents);
  }
  // -------------------------------------------------------------------------
  private static void multiThreadZones() {
    final CountDownLatch latch = new CountDownLatch(1);
    final List<DateTimeZone> zones = createZones();
    List<Runnable> runnables = new ArrayList<Runnable>();
    for (int i = 0; i < 100; i++) {
      Runnable r =
          new Runnable() {
            public void run() {
              try {
                latch.await();
                List<DateTimeZone> shuffled = new ArrayList<DateTimeZone>(zones);
                Collections.shuffle(shuffled);
                String name = Thread.currentThread().getName();
                for (int j = 0; j < 100; j++) {
                  for (DateTimeZone zn : shuffled) {
                    ISOChronology chrono = ISOChronology.getInstance(zn);
                    Assert.assertEquals(zn, chrono.getZone());
                  }
                }
                System.out.println("Finished: " + name);

              } catch (Exception ex) {
                ex.printStackTrace();
                System.exit(1);
              }
            }
          };
      new Thread(r).start();
      runnables.add(r);
    }
    latch.countDown();
  }
  @Test
  public void bufferDiscardsStreamWhenFull() throws IOException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Pair<InputStream, List<byte[]>> stream = TestUtils.generateStream(100);

    MJpegStreamBufferer buffer = new MJpegStreamBufferer(5);

    AtomicInteger discardedCount = new AtomicInteger(0);

    buffer.start(
        new MJpegStreamBufferListener() {
          @Override
          public void stopped() {
            latch.countDown();
          }

          @Override
          public void streamBuffered(byte[] stream) {}

          @Override
          public void streamDiscarded(byte[] stream) {
            discardedCount.incrementAndGet();
          }
        },
        new MJpegStreamIterator(stream.getLeft()));

    latch.await();

    for (int x = 0; x < 5; ++x) {
      assertThat(buffer.get(), is(stream.getRight().get(x + 95)));
    }

    assertNull(buffer.get());
    assertThat(discardedCount.get(), is(95));
  }
  // -------------------------------------------------------------------------
  private static void multiThreadGJLocale() {
    final CountDownLatch latch = new CountDownLatch(1);
    final List<Locale> locales = createLocales();
    List<Runnable> runnables = new ArrayList<Runnable>();
    for (int i = 0; i < 100; i++) {
      Runnable r =
          new Runnable() {
            public void run() {
              try {
                latch.await();
                List<Locale> shuffled = new ArrayList<Locale>(locales);
                Collections.shuffle(shuffled);
                String name = Thread.currentThread().getName();
                for (int j = 0; j < 100; j++) {
                  for (Locale locale : shuffled) {
                    GJLocaleSymbols symbols = GJLocaleSymbols.forLocale(locale);
                    Assert.assertEquals(GJLocaleSymbols.class, symbols.getClass());
                  }
                }
                System.out.println("Finished: " + name);

              } catch (Exception ex) {
                ex.printStackTrace();
                System.exit(1);
              }
            }
          };
      new Thread(r).start();
      runnables.add(r);
    }
    latch.countDown();
  }
Exemplo n.º 23
0
  @Override
  public void handlePerspective(
      final Message<Event, Object> action, final PerspectiveLayout perspectiveLayout) {
    if (action.messageBodyEquals(MessageUtil.INIT)) {

      perspectiveLayout.registerRootComponent(createRoot());
      GridPane.setVgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS);
      GridPane.setHgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS);

      // register left panel
      perspectiveLayout.registerTargetLayoutComponent("content0", this.content1);
      perspectiveLayout.registerTargetLayoutComponent("content1", this.content2);
      perspectiveLayout.registerTargetLayoutComponent("content2", this.content3);
      ApplicationLauncherPerspectiveMessaginTest.latch.countDown();
    } else {
      if (counter.get() > 1) {
        counter.decrementAndGet();
        context.send("id10", "message");
      } else {
        System.out.println("Perspective id12: FINISH");
        if (wait.getCount() > 0) wait.countDown();
        if (PerspectiveMessagingTestP1.wait.getCount() > 0) context.send("id10", "message");
      }
    }
  }
Exemplo n.º 24
0
  @Test
  public void testNoActions() throws Exception {

    setupServer(true);
    StorageManager storage = getStorage();
    manager = liveServer.getReplicationManager();
    waitForComponent(manager);

    Journal replicatedJournal = new ReplicatedJournal((byte) 1, new FakeJournal(), manager);

    replicatedJournal.appendPrepareRecord(1, new FakeData(), false);

    final CountDownLatch latch = new CountDownLatch(1);
    storage.afterCompleteOperations(
        new IOAsyncTask() {

          public void onError(final int errorCode, final String errorMessage) {}

          public void done() {
            latch.countDown();
          }
        });

    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));

    Assert.assertEquals(
        "should be empty " + manager.getActiveTokens(), 0, manager.getActiveTokens().size());
  }
  @Test
  public void testNoApiLimitOnRootAdmin() throws Exception {
    // issue list Accounts calls
    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("response", "json");
    params.put("listAll", "true");
    params.put("sessionkey", sessionKey);
    // assuming ApiRateLimitService set api.throttling.max = 25
    int clientCount = 26;
    Runnable[] clients = new Runnable[clientCount];
    final boolean[] isUsable = new boolean[clientCount];

    final CountDownLatch startGate = new CountDownLatch(1);

    final CountDownLatch endGate = new CountDownLatch(clientCount);

    for (int i = 0; i < isUsable.length; ++i) {
      final int j = i;
      clients[j] =
          new Runnable() {

            /** {@inheritDoc} */
            @Override
            public void run() {
              try {
                startGate.await();

                sendRequest("listAccounts", params);

                isUsable[j] = true;

              } catch (CloudRuntimeException e) {
                isUsable[j] = false;
                e.printStackTrace();
              } catch (InterruptedException e) {
                e.printStackTrace();
              } finally {
                endGate.countDown();
              }
            }
          };
    }

    ExecutorService executor = Executors.newFixedThreadPool(clientCount);

    for (Runnable runnable : clients) {
      executor.execute(runnable);
    }

    startGate.countDown();

    endGate.await();

    int rejectCount = 0;
    for (int i = 0; i < isUsable.length; ++i) {
      if (!isUsable[i]) rejectCount++;
    }

    assertEquals("No request should be rejected!", 0, rejectCount);
  }
  private void randomLoadTest(Srdi[] indices) throws InterruptedException {
    CountDownLatch completionLatch = new CountDownLatch(indices.length);
    IndexRandomLoadTester[] testers = new IndexRandomLoadTester[indices.length];

    try {
      for (int i = 0; i < indices.length; i++) {
        testers[i] = new IndexRandomLoadTester(indices[i], OPS_PER_INDEX, completionLatch);
        new Thread(testers[i]).start();
      }

      Assert.assertTrue(
          "Timed out waiting for thread completion",
          completionLatch.await(TEST_TIMEOUT, TimeUnit.SECONDS));

      for (int i = 0; i < indices.length; i++) {
        Assert.assertTrue(testers[i].isSuccessful());
      }
    } finally {
      for (int i = 0; i < indices.length; i++) {
        if (indices[i] != null) {
          indices[i].stop();
        }
      }
    }
  }
Exemplo n.º 27
0
  @Test
  public void testStats() throws InterruptedException {
    l.lock();
    assertTrue(l.isLocked());
    assertTrue(l.isLockedByCurrentThread());
    assertEquals(1, l.getLockCount());

    l.unlock();
    assertFalse(l.isLocked());
    assertEquals(0, l.getLockCount());
    assertEquals(-1L, l.getRemainingLeaseTime());

    l.lock(1, TimeUnit.MINUTES);
    assertTrue(l.isLocked());
    assertTrue(l.isLockedByCurrentThread());
    assertEquals(1, l.getLockCount());
    assertTrue(l.getRemainingLeaseTime() > 1000 * 30);

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread() {
      public void run() {
        assertTrue(l.isLocked());
        assertFalse(l.isLockedByCurrentThread());
        assertEquals(1, l.getLockCount());
        assertTrue(l.getRemainingLeaseTime() > 1000 * 30);
        latch.countDown();
      }
    }.start();
    assertTrue(latch.await(1, TimeUnit.MINUTES));
  }
Exemplo n.º 28
0
  @Test(enabled = false)
  public void testInvokeFunctionWithTrackMessageSizeDecoder_CombinedMessages() throws Exception {
    List<String> originalMessages = createMessages(5);
    List<String> modifiableMessages = new ArrayList<>(originalMessages);
    CountDownLatch latch = new CountDownLatch(modifiableMessages.size());
    List<Decoder<?, ?>> decoders = withTrackMessageSizeDecoder();
    List<FunctionWrapper> functions = withMessageFunction(modifiableMessages, latch);

    String firstMessage = originalMessages.get(0);
    String combinedMessages = "";
    for (String message : originalMessages.subList(1, originalMessages.size())) {
      combinedMessages += withLengthPrefixed(message);
    }
    assertTrue(
        TransportsUtil.invokeFunction(
            decoders,
            functions,
            String.class,
            withLengthPrefixed(firstMessage),
            FUNCTION_NAME_MESSAGE,
            FunctionResolver.DEFAULT));
    assertTrue(
        TransportsUtil.invokeFunction(
            decoders,
            functions,
            String.class,
            withLengthPrefixed(combinedMessages),
            FUNCTION_NAME_MESSAGE,
            FunctionResolver.DEFAULT));

    assertTrue(latch.await(3, TimeUnit.SECONDS), "latch count was " + latch.getCount());
    assertTrue(modifiableMessages.isEmpty());
  }
Exemplo n.º 29
0
  @Test
  public void testSubscribe() throws InterruptedException {
    RedisClient c = new RedisClient("localhost", 6379);
    RedisPubSubConnection pubSubConnection = c.connectPubSub();
    final CountDownLatch latch = new CountDownLatch(2);
    pubSubConnection.addListener(
        new RedisPubSubListener<Object>() {

          @Override
          public boolean onStatus(PubSubType type, String channel) {
            assertThat(type).isEqualTo(PubSubType.SUBSCRIBE);
            assertThat(Arrays.asList("test1", "test2").contains(channel)).isTrue();
            latch.countDown();
            return true;
          }

          @Override
          public void onMessage(String channel, Object message) {}

          @Override
          public void onPatternMessage(String pattern, String channel, Object message) {}
        });
    pubSubConnection.subscribe(StringCodec.INSTANCE, "test1", "test2");

    latch.await(10, TimeUnit.SECONDS);
  }
  @Test
  public void testConfirmReceivedAfterPublisherCallbackChannelScheduleClose() throws Exception {
    final CountDownLatch latch = new CountDownLatch(40);
    templateWithConfirmsEnabled.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            latch.countDown();
          }
        });

    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 20; i++) {
      executorService.execute(
          new Runnable() {

            @Override
            public void run() {
              templateWithConfirmsEnabled.convertAndSend(
                  ROUTE, (Object) "message", new CorrelationData("abc"));
              templateWithConfirmsEnabled.convertAndSend(
                  "BAD_ROUTE", (Object) "bad", new CorrelationData("cba"));
            }
          });
    }

    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
  }