コード例 #1
0
  /**
   * Concurrent write with eviction RAM_DISK can hold 9 replicas 4 threads each write 5 replicas
   *
   * @throws IOException
   * @throws InterruptedException
   */
  @Test
  public void testConcurrentWrites() throws IOException, InterruptedException {
    startUpCluster(true, 9);
    final String METHOD_NAME = GenericTestUtils.getMethodName();
    final int SEED = 0xFADED;
    final int NUM_WRITERS = 4;
    final int NUM_WRITER_PATHS = 5;

    Path paths[][] = new Path[NUM_WRITERS][NUM_WRITER_PATHS];
    for (int i = 0; i < NUM_WRITERS; i++) {
      paths[i] = new Path[NUM_WRITER_PATHS];
      for (int j = 0; j < NUM_WRITER_PATHS; j++) {
        paths[i][j] = new Path("/" + METHOD_NAME + ".Writer" + i + ".File." + j + ".dat");
      }
    }

    final CountDownLatch latch = new CountDownLatch(NUM_WRITERS);
    final AtomicBoolean testFailed = new AtomicBoolean(false);

    ExecutorService executor = Executors.newFixedThreadPool(THREADPOOL_SIZE);
    for (int i = 0; i < NUM_WRITERS; i++) {
      Runnable writer = new WriterRunnable(i, paths[i], SEED, latch, testFailed);
      executor.execute(writer);
    }

    Thread.sleep(3 * LAZY_WRITER_INTERVAL_SEC * 1000);
    triggerBlockReport();

    // Stop executor from adding new tasks to finish existing threads in queue
    latch.await();

    assertThat(testFailed.get(), is(false));
  }
コード例 #2
0
 public void testGetWaitsUntilSet() throws InterruptedException {
   final BlockingCell<String> cell = new BlockingCell<String>();
   final String value = "foo";
   final AtomicReference<Object> valueHolder = new AtomicReference<Object>();
   final AtomicBoolean doneHolder = new AtomicBoolean(false);
   Thread getterThread =
       new Thread() {
         @Override
         public void run() {
           try {
             valueHolder.set(cell.get());
           } catch (InterruptedException ex) {
             fail("hit InterruptedException");
             ex.printStackTrace();
           }
           doneHolder.set(true);
         }
       };
   getterThread.start();
   Thread.sleep(300);
   assertFalse(doneHolder.get());
   cell.set(value);
   getterThread.join();
   assertTrue(doneHolder.get());
   assertTrue(value == valueHolder.get());
 }
コード例 #3
0
ファイル: DebAntTaskTestCase.java プロジェクト: urchinly/jdeb
  public void testXZCompression() throws Exception {
    project.executeTarget("xz-compression");

    File deb = new File("target/test-classes/test.deb");
    assertTrue("package not build", deb.exists());

    final AtomicBoolean found = new AtomicBoolean(false);

    ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
    ArchiveWalker.walk(
        in,
        new ArchiveVisitor<ArArchiveEntry>() {
          public void visit(ArArchiveEntry entry, byte[] content) throws IOException {
            if (entry.getName().equals("data.tar.xz")) {
              found.set(true);

              assertEquals("header 0", (byte) 0xFD, content[0]);
              assertEquals("header 1", (byte) '7', content[1]);
              assertEquals("header 2", (byte) 'z', content[2]);
              assertEquals("header 3", (byte) 'X', content[3]);
              assertEquals("header 4", (byte) 'Z', content[4]);
              assertEquals("header 5", (byte) '\0', content[5]);

              TarInputStream tar =
                  new TarInputStream(
                      new XZCompressorInputStream(new ByteArrayInputStream(content)));
              while ((tar.getNextEntry()) != null) ;
              tar.close();
            }
          }
        });

    assertTrue("xz file not found", found.get());
  }
コード例 #4
0
  public void stop() {
    log.info("Shutting down proxy");
    if (stopped.get()) {
      log.info("Already stopped");
      return;
    }
    stopped.set(true);

    log.info("Closing all channels...");

    // See http://static.netty.io/3.5/guide/#start.12

    final ChannelGroupFuture future = allChannels.close();
    future.awaitUninterruptibly(10 * 1000);

    if (!future.isCompleteSuccess()) {
      final Iterator<ChannelFuture> iter = future.iterator();
      while (iter.hasNext()) {
        final ChannelFuture cf = iter.next();
        if (!cf.isSuccess()) {
          log.warn("Cause of failure for {} is {}", cf.getChannel(), cf.getCause());
        }
      }
    }
    log.info("Stopping timer");
    timer.stop();
    serverChannelFactory.releaseExternalResources();
    clientChannelFactory.releaseExternalResources();

    log.info("Done shutting down proxy");
  }
コード例 #5
0
ファイル: MockFlowRuleService.java プロジェクト: Mohdrz/Onos
 @Override
 public void apply(FlowRuleOperations ops) {
   AtomicBoolean thisSuccess = new AtomicBoolean(success);
   ops.stages()
       .forEach(
           stage ->
               stage.forEach(
                   flow -> {
                     if (errorFlow == flow.rule().id().value()) {
                       thisSuccess.set(false);
                     } else {
                       switch (flow.type()) {
                         case ADD:
                         case MODIFY: // TODO is this the right behavior for modify?
                           flows.add(flow.rule());
                           break;
                         case REMOVE:
                           flows.remove(flow.rule());
                           break;
                         default:
                           break;
                       }
                     }
                   }));
   if (thisSuccess.get()) {
     ops.callback().onSuccess(ops);
   } else {
     ops.callback().onError(ops);
   }
 }
コード例 #6
0
ファイル: BaseDataBuffer.java プロジェクト: Raveesh/nd4j
  @Override
  public int getInt(long i) {
    if (dataType() == Type.DOUBLE) {
      dirty.set(false);
      if (indexer instanceof DoubleIndexer) {
        return (int) ((DoubleIndexer) indexer).get(offset() + i);
      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    } else if (dataType() == Type.INT) {
      dirty.set(false);
      if (indexer instanceof IntIndexer) {
        return ((IntIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    } else {
      if (indexer instanceof FloatIndexer) {
        return (int) ((FloatIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    }
  }
  public void handleIncomingUpdate(Request msg) throws DialogStateException {
    assert TransactionUtils.isTransactionExecutionThread()
        : "Code run in wrong thread. Must be run in TransactionThread. Now in "
            + Thread.currentThread();
    assert !done.get();

    if (!done.get()) {
      Logger.log("Remote party has sent update");

      final Dialog dialog = getStackContext().getDialogStorage().findDialogForMessage(msg);
      assert dialog != null;

      checkUpdatePreconditions(dialog, msg);

      Logger.log(TAG, "mark dialog as update in progress");
      dialog.markUpdateInProgress(InitiateParty.REMOTE);

      // TransactionType<InviteSrvTransaction, ? extends ServerCommonInviteTransaction>
      // transactionType = SIP_REINVITE_SERVER;
      TransactionType<UpdateSrvTransaction, UpdateServerTransaction> transactionType =
          SIP_UPDATE_SERVER;

      doHandleIncomingUpdate(msg, dialog, transactionType);
    }
  }
コード例 #8
0
  /**
   * Undeploys an apk, specified by package name, from a connected emulator or usb device. Also
   * deletes the application's data and cache directories on the device.
   *
   * @param packageName the package name to undeploy.
   * @return <code>true</code> if successfully undeployed, <code>false</code> otherwise.
   */
  protected boolean undeployApk(final String packageName)
      throws MojoExecutionException, MojoFailureException {

    final AtomicBoolean result =
        new AtomicBoolean(true); // if no devices are present, it counts as successful

    doWithDevices(
        new DeviceCallback() {
          public void doWithDevice(final IDevice device) throws MojoExecutionException {
            String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix(device);
            try {
              device.uninstallPackage(packageName);
              getLog()
                  .info(
                      deviceLogLinePrefix
                          + "Successfully uninstalled "
                          + packageName
                          + " from "
                          + DeviceHelper.getDescriptiveName(device));
              result.set(true);
            } catch (InstallException e) {
              result.set(false);
              throw new MojoExecutionException(
                  deviceLogLinePrefix + "Uninstall of " + packageName + " failed.", e);
            }
          }
        });

    return result.get();
  }
コード例 #9
0
  @RequestMapping(
      value = "/import",
      method = {RequestMethod.GET, RequestMethod.POST})
  @ResponseBody
  public Map<String, Object> input(Date beginDate, Date endDate) {
    Map<String, Object> rsMap = new HashMap<String, Object>();
    boolean success = false;
    String message = "";

    if (isRun.compareAndSet(false, true)) {
      logger.info("Begin order import");

      try {
        orderBizHandler.input(cfgList, beginDate, endDate);

        success = true;
      } catch (Exception exp) {
        logger.error("Importing TAOBAO order error ", exp);
        message = exp.getMessage();
      } finally {
        isRun.set(false);
        logger.info("End import");
      }
    } else {
      logger.error("Import is running!");
    }

    rsMap.put("success", success);
    rsMap.put("message", message);

    return rsMap;
  }
コード例 #10
0
 public static void createRFiles(
     final Connector c, FileSystem fs, String path, int rows, int splits, int threads)
     throws Exception {
   fs.delete(new Path(path), true);
   ExecutorService threadPool = Executors.newFixedThreadPool(threads);
   final AtomicBoolean fail = new AtomicBoolean(false);
   for (int i = 0; i < rows; i += rows / splits) {
     final TestIngest.Opts opts = new TestIngest.Opts();
     opts.outputFile = String.format("%s/mf%s", path, i);
     opts.random = 56;
     opts.timestamp = 1;
     opts.dataSize = 50;
     opts.rows = rows / splits;
     opts.startRow = i;
     opts.cols = 1;
     threadPool.execute(
         new Runnable() {
           @Override
           public void run() {
             try {
               TestIngest.ingest(c, opts, new BatchWriterOpts());
             } catch (Exception e) {
               fail.set(true);
             }
           }
         });
   }
   threadPool.shutdown();
   threadPool.awaitTermination(1, TimeUnit.HOURS);
   assertFalse(fail.get());
 }
コード例 #11
0
  @Test
  public void go() throws Exception {
    Appender appender =
        new DefaultTestAppender() {
          @Override
          public void doAppend(LoggingEvent event) {
            if (event.getThrowableInformation() != null) {
              Throwable t = event.getThrowableInformation().getThrowable();
              if (t instanceof SecurityException) {
                authenticationFailed.set(true);
              }
              if (t instanceof NullPointerException) {
                gotNPE.set(true);
              }
            }
          }
        };
    Logger.getRootLogger().addAppender(appender);

    String connectURI = broker1.getConnectorByName("openwire").getConnectUri().toString();
    connectURI = connectURI.replace("?needClientAuth=true", "");
    broker2.addNetworkConnector("static:(" + connectURI + ")").start();

    Thread.sleep(10 * 1000);

    Logger.getRootLogger().removeAppender(appender);

    assertTrue(authenticationFailed.get());
    assertFalse(gotNPE.get());
  }
コード例 #12
0
 private void updateCurrentlyServingReplica(
     ScannerCallable scanner, Result[] result, AtomicBoolean done, ExecutorService pool) {
   if (done.compareAndSet(false, true)) {
     if (currentScannerCallable != scanner) replicaSwitched.set(true);
     currentScannerCallable = scanner;
     // store where to start the replica scanner from if we need to.
     if (result != null && result.length != 0) this.lastResult = result[result.length - 1];
     if (LOG.isTraceEnabled()) {
       LOG.trace(
           "Setting current scanner as "
               + currentScannerCallable.scannerId
               + " associated with "
               + currentScannerCallable.getHRegionInfo().getReplicaId());
     }
     // close all outstanding replica scanners but the one we heard back from
     outstandingCallables.remove(scanner);
     for (ScannerCallable s : outstandingCallables) {
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Closing scanner "
                 + s.scannerId
                 + " because this was slow and another replica succeeded");
       }
       // Submit the "close" to the pool since this might take time, and we don't
       // want to wait for the "close" to happen yet. The "wait" will happen when
       // the table is closed (when the awaitTermination of the underlying pool is called)
       s.setClose();
       RetryingRPC r = new RetryingRPC(s);
       pool.submit(r);
     }
     // now clear outstandingCallables since we scheduled a close for all the contained scanners
     outstandingCallables.clear();
   }
 }
コード例 #13
0
  /**
   * Will only ever be accessed by a single thread. Rechecks the target update time again in case a
   * second write thread was blocking the current one. {@link #lastUpdateRun} gets set to a negative
   * value to specify that this method is currently running.
   */
  public void doUpdate() {

    // Check whether entry is required.
    if (!state.get().checkNeedsUpdate(forceUpdateInterval)) {
      return;
    }

    // Prevent recursion!
    // ------------------
    // To prevent another call from entering this block it's
    // necessary to set active
    if (!active.compareAndSet(false, true)) {
      return;
    }

    try {
      final Set<String> ids = sessions.keySet();
      log.info("Synchronizing session cache. Count = " + ids.size());
      final StopWatch sw = new Slf4JStopWatch();
      for (String id : ids) {
        reload(id);
      }

      sw.stop("omero.sessions.synchronization");
      log.info(String.format("Synchronization took %s ms.", sw.getElapsedTime()));

    } catch (Exception e) {
      log.error("Error synchronizing cache", e);
    } finally {
      active.set(false);
    }
  }
コード例 #14
0
  public void handleStart() {
    if (animator == null) {
      timer = new Timer();

      if (loader == null) {
        loader = new Loader();
        loaderThread = new Thread(loader);
        Log.d(TAG, "STARTING LOADER THREAD " + loaderThread + " for " + this, Log.DEBUG_MODE);
      }

      animator = new Animator(loader);
      if (!animating.get() && !loaderThread.isAlive()) {
        isStopping.set(false);
        loaderThread.start();
      }

      currentDuration = (int) getDuration();

      animating.set(true);
      fireStart();
      timer.schedule(animator, currentDuration, currentDuration);
    } else {
      resume();
    }
  }
コード例 #15
0
    private boolean addPendingRequest(final RequestContextImpl<?, ?> requestContext) {
      final Integer messageID = requestContext.getMessageID();

      if (isClosed.get()) {
        final LocalizableMessage message = INFO_CLIENT_CONNECTION_CLOSING.get();
        requestContext.handleException(
            newLdapException(ResultCode.UNWILLING_TO_PERFORM, message.toString()));
        return false;
      } else if (pendingRequests.putIfAbsent(messageID, requestContext) != null) {
        final LocalizableMessage message =
            WARN_CLIENT_DUPLICATE_MESSAGE_ID.get(requestContext.getMessageID());
        requestContext.handleException(
            newLdapException(ResultCode.PROTOCOL_ERROR, message.toString()));
        return false;
      } else if (isClosed.get()) {
        /*
         * A concurrent close may have already removed the pending
         * request but it will have only been notified for cancellation.
         */
        pendingRequests.remove(messageID);

        final LocalizableMessage message = INFO_CLIENT_CONNECTION_CLOSING.get();
        requestContext.handleException(
            newLdapException(ResultCode.UNWILLING_TO_PERFORM, message.toString()));
        return false;
      } else {
        /*
         * If the connection is closed now then we just have to pay the
         * cost of invoking the request in the request handler.
         */
        return true;
      }
    }
コード例 #16
0
 private void closeShard(
     String reason, ShardId sId, IndexShard indexShard, Store store, IndexEventListener listener) {
   final int shardId = sId.id();
   final Settings indexSettings = this.getIndexSettings().getSettings();
   try {
     try {
       listener.beforeIndexShardClosed(sId, indexShard, indexSettings);
     } finally {
       // this logic is tricky, we want to close the engine so we rollback the changes done to it
       // and close the shard so no operations are allowed to it
       if (indexShard != null) {
         try {
           // only flush we are we closed (closed index or shutdown) and if we are not deleted
           final boolean flushEngine = deleted.get() == false && closed.get();
           indexShard.close(reason, flushEngine);
         } catch (Exception e) {
           logger.debug("[{}] failed to close index shard", e, shardId);
           // ignore
         }
       }
       // call this before we close the store, so we can release resources for it
       listener.afterIndexShardClosed(sId, indexShard, indexSettings);
     }
   } finally {
     try {
       store.close();
     } catch (Exception e) {
       logger.warn(
           "[{}] failed to close store on shard removal (reason: [{}])", e, shardId, reason);
     }
   }
 }
コード例 #17
0
ファイル: BaseDataBuffer.java プロジェクト: Raveesh/nd4j
  @Override
  public double getDouble(long i) {
    if (dataType() == Type.FLOAT) {
      dirty.set(false);
      if (indexer instanceof FloatIndexer) {
        return ((FloatIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    } else if (dataType() == Type.INT) {
      dirty.set(false);
      if (indexer instanceof IntIndexer) {
        return ((IntIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    } else {
      dirty.set(false);
      if (indexer instanceof DoubleIndexer) {
        return ((DoubleIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    }
  }
コード例 #18
0
  public void handleStart() {
    if (animator == null) {
      timer = new Timer();

      if (loader == null) {
        loader = new Loader();
        loaderThread = new Thread(loader);
        if (DBG) {
          Log.d(LCAT, "STARTING LOADER THREAD " + loaderThread + " for " + this);
        }
      }

      animator = new Animator(loader);
      if (!animating.get() && !loaderThread.isAlive()) {
        isStopping.set(false);
        loaderThread.start();
      }

      int duration = (int) getDuration();

      fireStart();
      timer.schedule(animator, duration, duration);
    } else {
      resume();
    }
  }
  /**
   * Handles server invite message
   *
   * @param msg - invite message
   */
  public void handleIncomingInvite(final Request msg) throws DialogStateException {
    assert TransactionUtils.isTransactionExecutionThread()
        : "Code run in wrong thread. Must be run in TransactionThread. Now in "
            + Thread.currentThread();

    assert !done.get();
    assert msg != null && MessageType.SIP_INVITE == MessageType.parse(msg.getMethod());

    if (!done.get()) {
      Logger.log("Remote party has sent invite");
      // ClientIdentity localParty =
      // getStackContext().getStackClientRegistry().findAddressee(msg.getTo().getUriBuilder().getShortURI());
      ClientIdentity localParty = getStackContext().getClientRouter().findAddressee(msg);
      if (localParty != null) {
        assert getStackContext().getDialogStorage().findDialogForMessage(msg) == null;
        final Dialog dialog =
            getStackContext().getDialogStorage().getDialogForIncomingMessage(localParty, msg);
        TransactionType<InviteSrvTransaction, ? extends ServerCommonInviteTransaction>
            transactionType = SIP_INVITE_SERVER;

        doHandleIncomingInvite(msg, dialog, transactionType);
      } else {
        throw new DialogStateException(null, DialogStateException.Error.ADDRESSEE_NOT_FOUND, msg);
      }
    }
  }
コード例 #20
0
  public void handleStop() {
    if (timer != null) {
      timer.cancel();
    }
    animating.set(false);
    isStopping.set(true);

    if (loaderThread != null) {
      try {
        loaderThread.join();
      } catch (InterruptedException e) {
        Log.e(LCAT, "loaderThread termination interrupted");
      }
      loaderThread = null;
    }
    if (loader != null) {
      synchronized (loader) {
        loader.notify();
      }
    }

    loader = null;
    timer = null;
    animator = null;
    paused = false;

    fireStop();
  }
  /**
   * Handles server noninvite message
   *
   * @param msg - noninvite message
   */
  public void handleIncomingBye(final Request msg) {

    assert TransactionUtils.isTransactionExecutionThread()
        : "Code run in wrong thread. Must be run in TransactionThread. Now in "
            + Thread.currentThread();
    assert !done.get();
    assert msg != null && MessageType.SIP_BYE == MessageType.parse(msg.getMethod());

    Logger.log("Remote party has sent noninvite");
    if (!done.get()) {

      final Dialog dialog = getStackContext().getDialogStorage().findDialogForMessage(msg);
      assert dialog != null;
      assert STATED == dialog.getState();

      dialog.getMessageHistory().addMessage(msg, true);

      final TransactionManager transactionManager = getTransactionManager();
      transactionManager.addListener(
          new FirstMessageResolver(SIP_BYE_SERVER.getName(), dialog, msg, transactionManager));

      final Transaction transaction =
          transactionManager.lookUpTransaction(dialog, null, SIP_BYE_SERVER);
      runAsynchronously(transaction, TRANSACTION_TIMEOUT);
    }
  }
コード例 #22
0
  @Override
  protected void doOKAction() {
    VirtualFile root = getGitRoot();
    GitLineHandler h = handler();
    final AtomicBoolean conflict = new AtomicBoolean();

    h.addLineListener(
        new GitLineHandlerAdapter() {
          public void onLineAvailable(String line, Key outputType) {
            if (line.contains("Merge conflict")) {
              conflict.set(true);
            }
          }
        });
    int rc =
        GitHandlerUtil.doSynchronously(
            h, GitBundle.getString("unstash.unstashing"), h.printableCommandLine(), false);
    root.refresh(true, true);

    if (conflict.get()) {
      boolean conflictsResolved =
          new UnstashConflictResolver(myProject, root, getSelectedStash()).merge();
      LOG.info("loadRoot " + root + ", conflictsResolved: " + conflictsResolved);
    } else if (rc != 0) {
      GitUIUtil.showOperationErrors(myProject, h.errors(), h.printableCommandLine());
    }
    super.doOKAction();
  }
コード例 #23
0
  /**
   * If received lostAdvName: <br>
   * Stop the scheduled timer. <br>
   * set isReachable to false
   *
   * @param args @param args Event handler argument
   */
  private void handleLostAdvName(Map<String, Object> args) {
    String foundSender = (String) args.get("SENDER");

    Log.d(
        TAG,
        "Received lostAdvertisedName of sender: '"
            + foundSender
            + "', my sender name is: '"
            + sender
            + "'");
    if (foundSender == null || !foundSender.equals(sender)) {
      Log.v(TAG, "Received sender: '" + foundSender + "' doesn't belong to this device");
      return;
    }

    stopDeviceFoundVerificationService();

    // Atomically sets the value to the given updated value if the current value == the expected
    // value.
    // Returns - true if successful. False return indicates that the actual value was not equal to
    // the expected value
    if (isReachable.compareAndSet(true, false)) {
      boolean newVal = isReachable.get();
      Log.d(TAG, "The device: '" + deviceId + "' isReachable set to: '" + newVal + "'");
      deviceRegistry.reachabilityChanged(this, newVal);
    }
  } // handleLostAdvName
コード例 #24
0
  public void run() {
    Log.d(logTag, "Receiver started");
    receiverThread = Thread.currentThread();
    while (true) {
      try {

        if (connection != null) {
          Log.d(logTag, "Waiting for message from PCF...");
          final Message result = connection.receive().await();
          if (result != null) {
            Log.d(logTag, "Received message from PCF: " + new String(result.getPayload()));
            SessionManager.handlePatientResults(new String(result.getPayload()));
          }
        }

      } catch (Exception e) {
        if (die.get()) {
          // user initiated disconnect
          die.set(false);
        } else {
          // unexpected failure
          SessionManager.connectionFailure(host);
        }
        break;
      }
    }
    try {
      connection.disconnect().await();
      Log.d(logTag, "Receiver stopped");
    } catch (Exception e) {
      Log.e(logTag, e.getMessage());
    }
  }
コード例 #25
0
 /** Returns the current number of objects, using its own transactions. */
 private int getObjectCount() throws Exception {
   final AtomicInteger countRef = new AtomicInteger(0);
   final AtomicReference<BigInteger> lastRef = new AtomicReference<BigInteger>();
   final AtomicBoolean done = new AtomicBoolean(false);
   while (!done.get()) {
     txnScheduler.runTask(
         new TestTask(
             new AbstractKernelRunnable() {
               public void run() {
                 BigInteger last = lastRef.get();
                 int count;
                 for (count = 0; count < 50; count++) {
                   BigInteger next = dataService.nextObjectId(last);
                   if (next == null) {
                     done.set(true);
                   }
                   last = next;
                 }
                 countRef.addAndGet(count);
                 lastRef.set(last);
               }
             }),
         taskOwner);
   }
   return countRef.get();
 }
  @Test
  public void testPublisherConfirmNotReceived() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    doReturn(new PublisherCallbackChannelImpl(mockChannel)).when(mockConnection).createChannel();

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setPublisherConfirms(true);
    final RabbitTemplate template = new RabbitTemplate(ccf);

    final AtomicBoolean confirmed = new AtomicBoolean();
    template.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            confirmed.set(true);
          }
        });
    template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc"));
    Thread.sleep(5);
    Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1);
    assertEquals(1, unconfirmed.size());
    assertEquals("abc", unconfirmed.iterator().next().getId());
    assertFalse(confirmed.get());
  }
コード例 #27
0
  private void processBackgroundCallback(CuratorEvent event) throws Exception {
    String path = null;
    boolean nodeExists = false;
    if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
      path = event.getPath();
      nodeExists = true;
    } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
      path = event.getName();
    } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) {
      log.warn("Client does not have authorisation to write node at path {}", event.getPath());
      authFailure.set(true);
      return;
    }
    if (path != null) {
      authFailure.set(false);
      nodePath.set(path);
      watchNode();

      if (nodeExists) {
        client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData());
      } else {
        initialisationComplete();
      }
    } else {
      createNode();
    }
  }
コード例 #28
0
ファイル: LocalCluster.java プロジェクト: repos-db/h-store
 @Override
 public void run() {
   assert (m_writer != null);
   assert (m_input != null);
   int location = 0;
   boolean eof = false;
   while (!eof) {
     try {
       int data = m_input.read();
       if (data == -1) {
         eof = true;
       } else {
         // look for a sequence of letters matching the server ready token.
         if (!m_witnessedReady.get() && m_token[location] == data) {
           location++;
           if (location == m_token.length) {
             synchronized (this) {
               m_witnessedReady.set(true);
               this.notifyAll();
             }
           }
         } else {
           location = 0;
         }
         m_writer.write(data);
         m_writer.flush();
       }
     } catch (IOException ex) {
       eof = true;
     }
   }
 }
コード例 #29
0
ファイル: SomeFunction.java プロジェクト: aehlig/bazel
 @Override
 public <T> void eval(
     QueryEnvironment<T> env,
     VariableContext<T> context,
     QueryExpression expression,
     List<Argument> args,
     final Callback<T> callback)
     throws QueryException, InterruptedException {
   final AtomicBoolean someFound = new AtomicBoolean(false);
   env.eval(
       args.get(0).getExpression(),
       context,
       new Callback<T>() {
         @Override
         public void process(Iterable<T> partialResult)
             throws QueryException, InterruptedException {
           if (someFound.get() || Iterables.isEmpty(partialResult)) {
             return;
           }
           callback.process(ImmutableSet.of(partialResult.iterator().next()));
           someFound.set(true);
         }
       });
   if (!someFound.get()) {
     throw new QueryException(expression, "argument set is empty");
   }
 }
コード例 #30
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mVolleyRequestQueue = Volley.newRequestQueue(getActivity());
    intilizeStatic();
    mMovieAdapter = new MovieAdapter(getActivity(), null, 0);
    trailerDataModified.set(false);
    reviewDataModified.set(false);
    movieDetailsModified.set(false);
    movieMinutesModified.set(false);

    if (savedInstanceState != null) {
      synchronized (mMovieId) {
        mMovieId = savedInstanceState.getLong(sMovieIdKey);
        YouTubeFirstTrailerURL = savedInstanceState.getParcelable("ShareYoutubeLinkKey");
        if (YouTubeFirstTrailerURL != null)
          if (mShareActionProvider != null) {
            mMenu.findItem(R.id.action_share).setVisible(true);
          } else Log.e(LOG_TAG, "mShareActionProvider not set");
        try {
          mMovieId.notifyAll();
        } catch (IllegalMonitorStateException x) {
        }
      }
      Bundle b = new Bundle();
      b.putLong(sMovieIdKey, mMovieId);
      getLoaderManager().restartLoader(MovieQuery.DETAIL_LOADER, b, this);
      getLoaderManager().restartLoader(TrailerQuery.TRAILER_LOADER, b, this);
      getLoaderManager().restartLoader(ReviewQuery.REVIEW_LOADER, b, this);
    }
  }