public StatementIteratorConsumer(
     BoundedCQLStatementIterator statementIterator, CQLExecutor cqlExecutor, long timeout) {
   this.statementIterator = statementIterator;
   this.cqlExecutor = cqlExecutor;
   this.timeout = timeout;
   this.shutdownLatch = new CountDownLatch((new Long(statementIterator.size())).intValue());
   logger.trace("Created consumer with countdown {}", shutdownLatch.getCount());
 }
 @Test
 public void addSameListener1stToKeyThenToMap() throws InterruptedException, IOException {
   HazelcastClient hClient = getHazelcastClient();
   final IMap<String, String> map = hClient.getMap("addSameListener1stToKeyThenToMap");
   final CountDownLatch entryAddLatch = new CountDownLatch(5);
   final CountDownLatch entryUpdatedLatch = new CountDownLatch(5);
   final CountDownLatch entryRemovedLatch = new CountDownLatch(5);
   CountDownLatchEntryListener<String, String> listener1 =
       new CountDownLatchEntryListener<String, String>(
           entryAddLatch, entryUpdatedLatch, entryRemovedLatch);
   map.addEntryListener(listener1, "hello", true);
   map.addEntryListener(listener1, true);
   map.put("hello", "world");
   map.put("hello", "new world");
   map.remove("hello");
   Thread.sleep(100);
   assertEquals(3, entryAddLatch.getCount());
   assertEquals(3, entryRemovedLatch.getCount());
   assertEquals(3, entryUpdatedLatch.getCount());
 }
  /** {@inheritDoc} */
  @Override
  public String toString() {
    ClusterNode oldestNode = this.oldestNode.get();

    return S.toString(
        GridDhtPartitionsExchangeFuture.class,
        this,
        "oldest",
        oldestNode == null ? "null" : oldestNode.id(),
        "oldestOrder",
        oldestNode == null ? "null" : oldestNode.order(),
        "evtLatch",
        evtLatch == null ? "null" : evtLatch.getCount(),
        "remaining",
        remaining(),
        "super",
        super.toString());
  }
 @Test
 public void lockMapKey() throws InterruptedException {
   HazelcastClient hClient = getHazelcastClient();
   final IMap<String, String> map = hClient.getMap("lockMapKey");
   final CountDownLatch latch = new CountDownLatch(1);
   map.put("a", "b");
   Thread.sleep(10);
   map.lock("a");
   new Thread(
           new Runnable() {
             public void run() {
               map.lock("a");
               latch.countDown();
             }
           })
       .start();
   Thread.sleep(10);
   assertEquals(1, latch.getCount());
   map.unlock("a");
   assertTrue(latch.await(10, TimeUnit.SECONDS));
 }
  /**
   * Initializes store.
   *
   * @throws GridException If failed to initialize.
   */
  private void init() throws GridException {
    if (initGuard.compareAndSet(false, true)) {
      if (log.isDebugEnabled()) log.debug("Initializing cache store.");

      try {
        if (sesFactory != null)
          // Session factory has been provided - nothing to do.
          return;

        if (!F.isEmpty(hibernateCfgPath)) {
          try {
            URL url = new URL(hibernateCfgPath);

            sesFactory = new Configuration().configure(url).buildSessionFactory();

            if (log.isDebugEnabled()) log.debug("Configured session factory using URL: " + url);

            // Session factory has been successfully initialized.
            return;
          } catch (MalformedURLException e) {
            if (log.isDebugEnabled())
              log.debug("Caught malformed URL exception: " + e.getMessage());
          }

          // Provided path is not a valid URL. File?
          File cfgFile = new File(hibernateCfgPath);

          if (cfgFile.exists()) {
            sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();

            if (log.isDebugEnabled())
              log.debug("Configured session factory using file: " + hibernateCfgPath);

            // Session factory has been successfully initialized.
            return;
          }

          // Provided path is not a file. Classpath resource?
          sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

          if (log.isDebugEnabled())
            log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
        } else {
          if (hibernateProps == null) {
            U.warn(
                log, "No Hibernate configuration has been provided for store (will use default).");

            hibernateProps = new Properties();

            hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
            hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
            hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
          }

          Configuration cfg = new Configuration();

          cfg.setProperties(hibernateProps);

          assert resourceAvailable(MAPPING_RESOURCE);

          cfg.addResource(MAPPING_RESOURCE);

          sesFactory = cfg.buildSessionFactory();

          if (log.isDebugEnabled())
            log.debug("Configured session factory using properties: " + hibernateProps);
        }
      } catch (HibernateException e) {
        throw new GridException("Failed to initialize store.", e);
      } finally {
        initLatch.countDown();
      }
    } else if (initLatch.getCount() > 0) U.await(initLatch);

    if (sesFactory == null) throw new GridException("Cache store was not properly initialized.");
  }
  private void processMessage(String message) throws Exception {
    Boolean toStdOut = logAllMessagesForUsers.get(config.getUsername());
    if (toStdOut != null) {
      if (toStdOut) System.out.println("IMAPrcv[" + config.getUsername() + "]: " + message);
      else log.info("IMAPrcv[{}]: {}", config.getUsername(), message);
    }

    wireTrace.add(message);
    log.trace(message);
    if (SYSTEM_ERROR_REGEX.matcher(message).matches()
        || ". NO [ALERT] Account exceeded command or bandwidth limits. (Failure)"
            .equalsIgnoreCase(message.trim())) {
      log.warn(
          "{} disconnected by IMAP Server due to system error: {}", config.getUsername(), message);
      disconnectAbnormally(message);
      return;
    }

    try {
      if (halt) {
        log.error(
            "Mail client for {} is halted but continues to receive messages, ignoring!",
            config.getUsername());
        return;
      }
      if (loginSuccess.getCount() > 0) {
        if (message.startsWith(CAPABILITY_PREFIX)) {
          this.capabilities =
              Arrays.asList(message.substring(CAPABILITY_PREFIX.length() + 1).split("[ ]+"));
          return;
        } else if (AUTH_SUCCESS_REGEX.matcher(message).matches()) {
          log.info("Authentication success for user {}", config.getUsername());
          loginSuccess.countDown();
        } else {
          Matcher matcher = COMMAND_FAILED_REGEX.matcher(message);
          if (matcher.find()) {
            // WARNING: DO NOT COUNTDOWN THE LOGIN LATCH ON FAILURE!!!

            log.warn("Authentication failed for {} due to: {}", config.getUsername(), message);
            errorStack.push(
                new Error(
                    null /* logins have no completion */, extractError(matcher), wireTrace.list()));
            disconnectAbnormally(message);
          }
        }
        return;
      }

      // Copy to local var as the value can change underneath us.
      FolderObserver observer = this.observer;
      if (idleRequested.get() || idleAcknowledged.get()) {
        synchronized (idleMutex) {
          if (IDLE_ENDED_REGEX.matcher(message).matches()) {
            idleRequested.compareAndSet(true, false);
            idleAcknowledged.set(false);

            // Now fire the events.
            PushedData data = pushedData;
            pushedData = null;

            idler.idleEnd();
            observer.changed(
                data.pushAdds.isEmpty() ? null : data.pushAdds,
                data.pushRemoves.isEmpty() ? null : data.pushRemoves);
            return;
          }

          // Queue up any push notifications to publish to the client in a second.
          Matcher existsMatcher = IDLE_EXISTS_REGEX.matcher(message);
          boolean matched = false;
          if (existsMatcher.matches()) {
            int number = Integer.parseInt(existsMatcher.group(1));
            pushedData.pushAdds.add(number);
            pushedData.pushRemoves.remove(number);
            matched = true;
          } else {
            Matcher expungeMatcher = IDLE_EXPUNGE_REGEX.matcher(message);
            if (expungeMatcher.matches()) {
              int number = Integer.parseInt(expungeMatcher.group(1));
              pushedData.pushRemoves.add(number);
              pushedData.pushAdds.remove(number);
              matched = true;
            }
          }

          // Stop idling, when we get the idle ended message (next cycle) we can publish what's been
          // gathered.
          if (matched) {
            if (!pushedData.idleExitSent) {
              idler.done();
              pushedData.idleExitSent = true;
            }
            return;
          }
        }
      }

      complete(message);
    } catch (Exception ex) {
      CommandCompletion completion = completions.poll();
      if (completion != null) completion.error(message, ex);
      else {
        log.error(
            "Strange exception during mail processing (no completions available!): {}",
            message,
            ex);
        errorStack.push(new Error(null, "No completions available!", wireTrace.list()));
      }
      throw ex;
    }
  }
 @ManagedAttribute
 public boolean isLoggedIn() {
   return loginSuccess.getCount() == 0;
 }
 public void terminate() {
   if (snapshotLatch != null) {
     while (snapshotLatch.getCount() > 0) snapshotLatch.countDown();
   }
 }