@Test
 public void runTestWithFailBeforeAsync() throws Exception {
   AtomicReference<AssertionError> failure = new AtomicReference<>();
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 try {
                   context.fail();
                 } catch (AssertionError e) {
                   failure.set(e);
                 }
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   reporter.await();
   Async async = queue.poll(2, TimeUnit.SECONDS);
   async.complete();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertFalse(result.succeeded());
   assertTrue(result.failed());
   assertNotNull(result.failure());
   assertSame(failure.get(), result.failure().cause());
 }
 private void registerWrite() throws CancelledKeyException {
   int size = oqueue.size();
   for (int i = 0; i < size; i++) {
     WebSocketImpl conn = oqueue.remove();
     conn.key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
   }
 }
Beispiel #3
0
 public static void main(String[] args) {
   final BlockingQueue<Character> bq;
   bq = new ArrayBlockingQueue<Character>(26);
   final ExecutorService executor = Executors.newFixedThreadPool(2);
   Runnable producer =
       () -> {
         for (char ch = 'A'; ch <= 'Z'; ch++) {
           try {
             bq.put(ch);
             System.out.printf("%c produced by " + "producer.%n", ch);
           } catch (InterruptedException ie) {
           }
         }
       };
   executor.execute(producer);
   Runnable consumer =
       () -> {
         char ch = '\0';
         do {
           try {
             ch = bq.take();
             System.out.printf("%c consumed by " + "consumer.%n", ch);
           } catch (InterruptedException ie) {
           }
         } while (ch != 'Z');
         executor.shutdownNow();
       };
   executor.execute(consumer);
 }
Beispiel #4
0
  public static boolean tryWaitZkEventsCleaned(ZkClient zkclient) throws Exception {
    java.lang.reflect.Field field = getField(zkclient.getClass(), "_eventThread");
    field.setAccessible(true);
    Object eventThread = field.get(zkclient);
    // System.out.println("field: " + eventThread);

    java.lang.reflect.Field field2 = getField(eventThread.getClass(), "_events");
    field2.setAccessible(true);
    BlockingQueue queue = (BlockingQueue) field2.get(eventThread);
    // System.out.println("field2: " + queue + ", " + queue.size());

    if (queue == null) {
      LOG.error("fail to get event-queue from zkclient. skip waiting");
      return false;
    }

    for (int i = 0; i < 20; i++) {
      if (queue.size() == 0) {
        return true;
      }
      Thread.sleep(100);
      System.out.println("pending zk-events in queue: " + queue);
    }
    return false;
  }
Beispiel #5
0
 @Test
 public void testLateRegisterSuccess() throws Exception {
   TestEventLoopGroup group = new TestEventLoopGroup();
   try {
     ServerBootstrap bootstrap = new ServerBootstrap();
     bootstrap.group(group);
     bootstrap.channel(LocalServerChannel.class);
     bootstrap.childHandler(new DummyHandler());
     bootstrap.localAddress(new LocalAddress("1"));
     ChannelFuture future = bootstrap.bind();
     assertFalse(future.isDone());
     group.promise.setSuccess();
     final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
     future.addListener(
         new ChannelFutureListener() {
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
             queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
             queue.add(future.isSuccess());
           }
         });
     assertTrue(queue.take());
     assertTrue(queue.take());
   } finally {
     group.shutdownGracefully();
     group.terminationFuture().sync();
   }
 }
  public void run() {

    while (true) {
      String message;
      try {
        message = messages.take();

        for (Socket socket : sockets) {

          // if (socket.isClosed());

          try {
            OutputStream out = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(out);
            writer.println(message);
            writer.flush();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      messages.clear();
    }
  }
  @Test
  public void receiveMessagesAckCheck() throws Exception {
    BlockingQueue<MmsMessage> q = new LinkedBlockingQueue<>();

    Session s = connectNormally(msg -> q.add(msg));

    t.send(new Broadcast().setSenderId("abc"), 1, 0);

    MmsMessage mm = q.poll(2, TimeUnit.SECONDS);
    assertEquals(1, mm.getMessageId());
    assertEquals(0, mm.getLatestReceivedId());
    assertEquals("abc", mm.cast(Broadcast.class).getSenderId());

    // We need to acquire this lock to make sure we are out of the receiving loop (last ack adjusted
    s.receiveLock.lock();
    s.receiveLock.unlock();

    CompletableFuture<Void> cf = new CompletableFuture<>();
    s.sendMessage(new Broadcast().setSenderId("cba"), cf);

    mm = t.t();
    assertEquals(1, mm.getMessageId());
    assertEquals(1, mm.getLatestReceivedId());
    assertEquals("cba", mm.cast(Broadcast.class).getSenderId());

    s.closeSession(MmsConnectionClosingCode.NORMAL);
  }
  @Test(timeout = TIMEOUT)
  public void connectToLocalhost() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("hi"));
  }
  @Test(timeout = TIMEOUT)
  public void receiveMultibyteUTF8StringsWithPolling() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.send("cash money €€€");
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    if ("hi".equals(args[0])) return;
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("cash money €€€"));
  }
  @Override
  protected long runQueuePass() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    fizzBuzzQueueProcessor.reset(latch);

    Future<?>[] futures = new Future[NUM_EVENT_PROCESSORS];
    futures[0] = executor.submit(fizzQueueProcessor);
    futures[1] = executor.submit(buzzQueueProcessor);
    futures[2] = executor.submit(fizzBuzzQueueProcessor);

    long start = System.currentTimeMillis();

    for (long i = 0; i < ITERATIONS; i++) {
      Long value = Long.valueOf(i);
      fizzInputQueue.put(value);
      buzzInputQueue.put(value);
    }

    latch.await();
    long opsPerSecond = (ITERATIONS * 1000L) / (System.currentTimeMillis() - start);

    fizzQueueProcessor.halt();
    buzzQueueProcessor.halt();
    fizzBuzzQueueProcessor.halt();

    for (Future<?> future : futures) {
      future.cancel(true);
    }

    Assert.assertEquals(expectedResult, fizzBuzzQueueProcessor.getFizzBuzzCounter());

    return opsPerSecond;
  }
  @Test(timeout = TIMEOUT)
  public void notSendPacketsIfSocketCloses() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            final boolean[] noPacket = new boolean[] {true};
            socket.on(
                Socket.EVENT_PACKET_CREATE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    noPacket[0] = false;
                  }
                });
            socket.close();
            Timer timer = new Timer();
            timer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {
                    values.offer(noPacket[0]);
                  }
                },
                1200);
          }
        });
    socket.open();
    assertThat((Boolean) values.take(), is(true));
  }
  /** {@inheritDoc} */
  public void destroy() {
    started.set(false);
    destroyed.set(true);
    releaseExternalResources();
    if (notifierFuture != null) {
      notifierFuture.cancel(true);
    }

    if (asyncWriteFuture != null) {
      asyncWriteFuture.cancel(true);
    }

    if (bc != null) {
      bc.destroy();
    }

    if (broadcasterCache != null) {
      broadcasterCache.stop();
    }
    resources.clear();
    broadcastOnResume.clear();
    messages.clear();
    asyncWriteQueue.clear();
    delayedBroadcast.clear();
    broadcasterCache = null;

    if (BroadcasterFactory.getDefault() != null) {
      BroadcasterFactory.getDefault().remove(this, name);
    }

    if (currentLifecycleTask != null) {
      currentLifecycleTask.cancel(true);
    }
  }
 @Test
 public void testAssertAsyncFailureHandlerSucceededAsync() throws Exception {
   BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
   BlockingQueue<Async> resultQueue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 handlerQueue.add(
                     context.<String>asyncAssertFailure(
                         r -> {
                           resultQueue.add(context.async());
                         }));
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
   handler.handle(Future.failedFuture(new Throwable()));
   Async result = resultQueue.poll(2, TimeUnit.SECONDS);
   assertFalse(reporter.completed());
   result.complete();
   reporter.await();
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   assertEquals("my_test", reporter.results.get(0).name());
   assertFalse(reporter.results.get(0).failed());
 }
 @Test
 public void runTestWithAsyncCompletion() throws Exception {
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   AtomicInteger count = new AtomicInteger();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 count.compareAndSet(0, 1);
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Async async = queue.poll(2, TimeUnit.SECONDS);
   assertEquals(1, count.get());
   assertFalse(reporter.completed());
   completeAsync.accept(async);
   reporter.await();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertTrue(result.succeeded());
   assertFalse(result.failed());
   assertNull(result.failure());
 }
  @Test
  public void testBasicHandling() throws IOException, InterruptedException {
    final List<String> messages = new ArrayList<>();
    messages.add("1 syslog 20 this is message 1234\n");
    messages.add("2 syslog 22 this is message 456789\n");
    messages.add("3 syslog 21 this is message ABCDE\n");

    run(messages);
    Assert.assertEquals(messages.size(), events.size());

    boolean found1 = false;
    boolean found2 = false;
    boolean found3 = false;

    TestEvent event;
    while ((event = events.poll()) != null) {
      Map<String, String> metadata = event.metadata;
      Assert.assertTrue(metadata.containsKey(RELPMetadata.TXNR_KEY));

      final String txnr = metadata.get(RELPMetadata.TXNR_KEY);
      if (txnr.equals("1")) {
        found1 = true;
      } else if (txnr.equals("2")) {
        found2 = true;
      } else if (txnr.equals("3")) {
        found3 = true;
      }
    }

    Assert.assertTrue(found1);
    Assert.assertTrue(found2);
    Assert.assertTrue(found3);
  }
  @Test(timeout = TIMEOUT)
  public void receiveEmoji() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.send("\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF");
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    if ("hi".equals(args[0])) return;
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF"));
  }
Beispiel #17
0
  /**
   * Passes image to fully-qualified name.
   *
   * @param instanceId
   * @param fullInName
   * @param image
   */
  public void put(String instanceId, String outName, String fullInName, ItemWrapper item) {
    // show debugging information
    if (null != m_debugger) {
      String inName = fullInName;
      int index = fullInName.indexOf('.');
      if (index > 0) {
        inName = fullInName.substring(++index);
      }
      DebugInfo debugInfo = new DebugInfo(instanceId, outName + " to " + inName, item);
      m_debugger.addDebugInfo(debugInfo);
    }

    boolean success = false;
    BlockingQueue<ItemWrapper> queue = getQueue(fullInName);
    // TODO currently using an unlimited LinkedBlockingQueue, so will never block
    while (!success) {
      try {
        success = queue.offer(item, 100, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Put interrupted");
      }
      if (m_quit) {
        throw new TeardownException("Teardown");
      }
    }
  }
Beispiel #18
0
 /**
  * Drains the queue as {@link java.util.concurrent.BlockingQueue#drainTo(java.util.Collection,
  * int)}, but if the requested {@code numElements} elements are not available, it will wait for
  * them up to the specified timeout.
  *
  * @param q the blocking queue to be drained
  * @param buffer where to add the transferred elements
  * @param numElements the number of elements to be waited for
  * @param timeout how long to wait before giving up, in units of {@code unit}
  * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
  * @return the number of elements transferred
  * @throws InterruptedException if interrupted while waiting
  */
 @Beta
 public static <E> int drain(
     BlockingQueue<E> q,
     Collection<? super E> buffer,
     int numElements,
     long timeout,
     TimeUnit unit)
     throws InterruptedException {
   Preconditions.checkNotNull(buffer);
   /*
    * This code performs one System.nanoTime() more than necessary, and in return, the time to
    * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
    * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
    */
   long deadline = System.nanoTime() + unit.toNanos(timeout);
   int added = 0;
   while (added < numElements) {
     // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
     // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
     added += q.drainTo(buffer, numElements - added);
     if (added < numElements) { // not enough elements immediately available; will have to poll
       E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
       if (e == null) {
         break; // we already waited enough, and there are no more elements in sight
       }
       buffer.add(e);
       added++;
     }
   }
   return added;
 }
  @Test
  public void sendMessageCompletable() throws Exception {
    BlockingQueue<MmsMessage> q = new LinkedBlockingQueue<>();
    Session s = connectNormally(msg -> q.add(msg));

    CompletableFuture<Void> cf = new CompletableFuture<>();
    s.sendMessage(new Broadcast().setSenderId("abc"), cf);
    t.t(); // take and ignore

    t.send(new Broadcast().setSenderId("abc"), 1, 1);

    cf.get(2, TimeUnit.SECONDS);

    for (int i = 2; i < 100; i++) {
      cf = new CompletableFuture<>();
      s.sendMessage(new Broadcast().setSenderId("abc" + i), cf);

      MmsMessage mm = t.t();
      assertEquals(i, mm.getMessageId());
      t.send(new Broadcast().setSenderId("abc"), i, mm.getMessageId());

      cf.get(2, TimeUnit.SECONDS);
    }
    // if this breaks it is a timeing issue, just keep trying until its 99
    assertEquals(99, s.latestReceivedId);

    s.closeSession(MmsConnectionClosingCode.NORMAL);
  }
 /**
  * Updates concerning switch disconnect and port down are not processed. LinkDiscoveryManager is
  * expected to process those messages and send multiple link removed messages. However, all the
  * updates from LinkDiscoveryManager would be propagated to the listeners of topology.
  */
 @LogMessageDoc(
     level = "ERROR",
     message = "Error reading link discovery update.",
     explanation = "Unable to process link discovery update",
     recommendation = LogMessageDoc.REPORT_CONTROLLER_BUG)
 public void applyUpdates() {
   appliedUpdates.clear();
   LDUpdate update = null;
   while (ldUpdates.peek() != null) {
     try {
       update = ldUpdates.take();
     } catch (Exception e) {
       log.error("Error reading link discovery update.", e);
     }
     if (log.isTraceEnabled()) {
       log.trace("Applying update: {}", update);
     }
     if (update.getOperation() == UpdateOperation.LINK_UPDATED) {
       addOrUpdateLink(
           update.getSrc(),
           update.getSrcPort(),
           update.getDst(),
           update.getDstPort(),
           update.getType());
     } else if (update.getOperation() == UpdateOperation.LINK_REMOVED) {
       removeLink(
           update.getSrc(), update.getSrcPort(),
           update.getDst(), update.getDstPort());
     }
     // Add to the list of applied updates.
     appliedUpdates.add(update);
   }
 }
  @Listener
  public void onGamePreInitializationEvent(GamePreInitializationEvent event) {
    if (game.getPlatform().getType() == Platform.Type.SERVER) {

      try {
        game.getServiceManager()
            .setProvider(this, IRegistrationService.class, new SimpleRegistrationService());
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      }

      game.getScheduler()
          .createTaskBuilder()
          .execute(
              (task) -> {
                try {
                  if (!requestQueue.isEmpty()) requestQueue.take().run();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              })
          .name("FDS-WSAPI - CheckRequestsTask")
          .delayTicks(50)
          .interval(1, TimeUnit.MILLISECONDS)
          .submit(this);
    }
  }
Beispiel #22
0
  public static void streaming(String... track) throws InterruptedException {
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
    StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();

    // add some track terms
    endpoint.trackTerms(Lists.newArrayList(track));

    // Create a new BasicClient. By default gzip is enabled.
    Client client =
        new ClientBuilder()
            .hosts(Constants.STREAM_HOST)
            .endpoint(endpoint)
            .authentication(auth)
            .processor(new StringDelimitedProcessor(queue))
            .build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 1000; msgRead++) {
      String msg = queue.take();
      System.out.println(msg);
    }

    client.stop();
  }
  /**
   * Data event callback.
   *
   * @param data The data object
   * @param workerThreadId The worker thread identifier
   */
  @Override
  public synchronized void onDataArrival(Object data, String workerThreadId) {
    Guard.check(data, workerThreadId);
    LocalControllerDataTransporter monitoringData = (LocalControllerDataTransporter) data;
    String localControllerId = monitoringData.getLocalControllerId();
    if (localControllerIds_.get(workerThreadId) == null) {
      log_.debug(
          String.format(
              "No mapping exists for this worker thread! Adding %s to %s mapping",
              workerThreadId, localControllerId));
      localControllerIds_.put(workerThreadId, localControllerId);
    }

    if (monitoringData.getData() == null) {
      // log_.debug(String.format("Ignoring received heartbeat data from %s!", workerThreadId));
      dataQueue_.add(monitoringData);
      // return;
    }

    log_.debug(
        String.format(
            "Worker thread: %s received local controller summary information from: %s",
            workerThreadId, localControllerId));

    if (stateMachine_.isBusy() && !monitoringData.getState().equals(LocalControllerState.STABLE)) {
      log_.debug(
          "System is BUSY! Skipping overloaded/underloaded local controller monitoring data!");
      return;
    }

    log_.debug(
        String.format(
            "Adding local controller %s summary information for to the queue", localControllerId));
    dataQueue_.add(monitoringData);
  }
  public void testConsumerCancellationInterruptsQueuingConsumerWait()
      throws IOException, InterruptedException {
    final BlockingQueue<Boolean> result = new ArrayBlockingQueue<Boolean>(1);
    channel.queueDeclare(queue, false, true, false, null);
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    Runnable receiver =
        new Runnable() {

          public void run() {
            try {
              try {
                consumer.nextDelivery();
              } catch (ConsumerCancelledException e) {
                result.put(true);
                return;
              } catch (ShutdownSignalException e) {
              } catch (InterruptedException e) {
              }
              result.put(false);
            } catch (InterruptedException e) {
              fail();
            }
          }
        };
    Thread t = new Thread(receiver);
    t.start();
    channel.basicConsume(queue, consumer);
    channel.queueDelete(queue);
    assertTrue(result.take());
    t.join();
  }
Beispiel #25
0
  @Test
  public void testPoll3() throws InterruptedException {
    // 插入1条消息
    String myType = TYPE + "_";
    SwallowMessage myTypeMsg = createMessage();
    myTypeMsg.setType(myType);
    messageDAO.saveMessage(TOPIC_NAME, myTypeMsg);

    Set<String> messageTypeSet = new HashSet<String>();
    messageTypeSet.add(myType);
    ConsumerInfo consumerInfo =
        new ConsumerInfo(
            "consumerId", Destination.topic(TOPIC_NAME), ConsumerType.DURABLE_AT_LEAST_ONCE);
    BlockingQueue<SwallowMessage> queue =
        swallowBuffer.createMessageQueue(
            consumerInfo,
            tailMessageId,
            tailMessageId,
            MessageFilter.createInSetMessageFilter(messageTypeSet));

    SwallowMessage m = queue.poll(500, TimeUnit.MILLISECONDS);
    while (m == null) {
      m = queue.poll(50, TimeUnit.MILLISECONDS);
    }
    Assert.assertEquals(myType, m.getType());
  }
 public boolean putMessage(String message, long timeout) {
   BufferListener listener = listenerRef.get();
   if (listener != null) {
     try {
       if (queue.size() == 0) {
         return listener.onMessage(message);
       } else {
         ArrayList<String> messages = new ArrayList<String>(queue.size() + 1);
         queue.drainTo(messages);
         messages.add(message);
         return listener.onMessages(messages);
       }
     } catch (Throwable t) {
       return false;
     }
   } else {
     try {
       if (!inputSemaphore.tryAcquire(message.length(), timeout, TimeUnit.MILLISECONDS)) {
         return false;
       }
       queue.offer(message);
       return true;
     } catch (InterruptedException e) {
       return false;
     }
   }
 }
Beispiel #27
0
  /** 将数据提交到运营商 */
  private void startSubmitData() {
    while (isContinue) {
      List<SmQueue> tempList = new LinkedList<SmQueue>();

      try {
        // 每晚23:58分暂停操作
        if (ConstantUtils.isPause_23_58()) {
          Thread.sleep(10 * 60 * 1000);
        }

        if (queue.size() >= (smgFlowLimit / 2) || isDrainTo()) {
          int num = queue.drainTo(tempList, (smgFlowLimit / 2));
          lastDrainToTime = System.currentTimeMillis();

          if (num > 0) {
            submitDataThreadPool.execute(new SubmitChildThread(tempList, channel));
          }
        } else {
          Thread.sleep(1000);
        }
      } catch (InterruptedException e1) {

      }
    }
  }
  @Test(timeout = 60000)
  public void testAppRejectionWithCancelledDelegationToken() throws Exception {
    MyFS dfs = (MyFS) FileSystem.get(conf);
    LOG.info("dfs=" + (Object) dfs.hashCode() + ";conf=" + conf.hashCode());

    MyToken token = dfs.getDelegationToken(new Text("user1"));
    token.cancelToken();

    Credentials ts = new Credentials();
    ts.addToken(token.getKind(), token);

    // register the tokens for renewal
    ApplicationId appId = BuilderUtils.newApplicationId(0, 0);
    delegationTokenRenewer.addApplication(appId, ts, true, false);
    int waitCnt = 20;
    while (waitCnt-- > 0) {
      if (!eventQueue.isEmpty()) {
        Event evt = eventQueue.take();
        if (evt.getType() == RMAppEventType.APP_REJECTED) {
          Assert.assertTrue(((RMAppEvent) evt).getApplicationId().equals(appId));
          return;
        }
      } else {
        Thread.sleep(500);
      }
    }
    fail("App submission with a cancelled token should have failed");
  }
Beispiel #29
0
  @Override
  public void observe(Event event) {
    if (event instanceof MoveSelectedEvent) {
      Move theMove = ((MoveSelectedEvent) event).getMove();
      if (theQueue.size() < 2) {
        theQueue.add(theMove);
      }
    } else if (event instanceof ServerNewGameStateEvent) {
      stateFromServer = ((ServerNewGameStateEvent) event).getState();
    } else if (event instanceof ServerCompletedMatchEvent) {
      theGUI.updateGameState(stateFromServer);

      List<Role> theRoles = getStateMachine().getRoles();
      List<Integer> theGoals = ((ServerCompletedMatchEvent) event).getGoals();

      StringBuilder finalMessage = new StringBuilder();
      finalMessage.append("Goals: ");
      for (int i = 0; i < theRoles.size(); i++) {
        finalMessage.append(theRoles.get(i));
        finalMessage.append(" = ");
        finalMessage.append(theGoals.get(i));
        if (i < theRoles.size() - 1) {
          finalMessage.append(", ");
        }
      }

      theGUI.showFinalMessage(finalMessage.toString());
    }
  }
 @Test
 public void runTestWithFailAfterAsync() throws Exception {
   RuntimeException failure = new RuntimeException();
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 queue.add(context.async());
                 throw failure;
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   reporter.await();
   Async async = queue.poll(2, TimeUnit.SECONDS);
   async.complete();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertFalse(result.succeeded());
   assertTrue(result.failed());
   assertNotNull(result.failure());
   assertSame(failure, result.failure().cause());
 }