Example usage for java.util.concurrent BlockingQueue poll

List of usage examples for java.util.concurrent BlockingQueue poll

Introduction

In this page you can find the example usage for java.util.concurrent BlockingQueue poll.

Prototype

E poll(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.

Usage

From source file:com.betfair.testing.utils.cougar.manager.LogTailer.java

protected <T> T blockingPoll(BlockingQueue<T> queue, long ms) {
    try {/*from  w  w  w  .  j a  v  a  2  s.c o m*/
        return queue.poll(ms, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // ignore
    }
    return null;
}

From source file:org.springframework.cloud.stream.module.loggregator.source.LoggregatorSourceTest.java

@Test
public void testLogReceipt() throws Exception {

    log.info(String.format("testing application %s against CF API endpoint %s with CF user %s",
            this.loggregatorProperties.getApplicationName(), this.loggregatorProperties.getCloudFoundryApi(),
            this.loggregatorProperties.getCloudFoundryUser()));

    String traceMessage = "logged-message-" + System.currentTimeMillis();
    ResponseEntity<String> entity = this.restTemplate.getForEntity(this.urlForApplication() + "/{uri}",
            String.class, Collections.singletonMap("uri", traceMessage));
    assertEquals(entity.getStatusCode(), HttpStatus.OK);
    assertEquals(entity.getBody(), traceMessage);

    BlockingQueue<Message<?>> messageBlockingQueue = this.messageCollector.forChannel(this.channels.output());

    Message<?> message;/*w  w  w.j  a v a2  s  .  c o m*/
    int count = 0, max = 20;

    while ((message = messageBlockingQueue.poll(1, TimeUnit.MINUTES)) != null && (count++ < max)) { // this could run for for 20 minutes
        log.info(String.format("received the following log from Loggregator: %s", message.getPayload()));
        String payload = String.class.cast(message.getPayload());
        assertNotNull(payload, "the message can't be null!");
        if (payload.contains(traceMessage)) {
            log.info("---------------------------------------------");
            log.info(String.format("loggregator tracer message: %s", traceMessage));
            log.info(String.format("delivered: %s", payload));
            log.info("---------------------------------------------");
            return;
        }
    }
    fail("tracer message was never delivered");
}

From source file:org.apache.camel.component.routebox.seda.RouteboxSedaConsumer.java

public void run() {
    BlockingQueue<Exchange> queue = ((RouteboxSedaEndpoint) getRouteboxEndpoint()).getQueue();
    while (queue != null && isRunAllowed()) {
        try {/*  w w w  .j av a  2 s .  c  o m*/
            final Exchange exchange = queue.poll(getRouteboxEndpoint().getConfig().getPollInterval(),
                    TimeUnit.MILLISECONDS);
            dispatchToInnerRoute(queue, exchange);
        } catch (InterruptedException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Sleep interrupted, are we stopping? " + (isStopping() || isStopped()));
            }
            continue;
        }
    }
}

From source file:org.jboss.as.test.integration.logging.syslog.SyslogHandlerTestCase.java

/**
 * Tests if the next message in the syslog is the expected one with the given log-level.
 *
 * @param expectedLevel the expected level of the next log message
 *
 * @throws Exception//from w  ww.j  a va2s  . c om
 */
private void testLog(final BlockingQueue<SyslogServerEventIF> queue, final Level expectedLevel)
        throws Exception {
    SyslogServerEventIF log = queue.poll(15L * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    assertNotNull(log);
    String msg = log.getMessage();
    assertEquals("Message with unexpected Syslog event level received: " + msg, getSyslogLevel(expectedLevel),
            log.getLevel());
    final String expectedMsg = LoggingServiceActivator.formatMessage(MSG, expectedLevel);
    assertEquals("Message with unexpected Syslog event text received.", expectedMsg, msg);
}

From source file:com.nridge.connector.fs.con_fs.core.RunMetricReport.java

/**
 * When an object implementing interface <code>Runnable</code> is used
 * to create a thread, starting the thread causes the object's
 * <code>run</code> method to be called in that separately executing
 * thread.//from  w w  w .  j a  v a 2  s.  c  o m
 * 
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    long msTime;
    String[] phaseTimes;
    double secondsTime, docsPerSecond;
    String docId, queueItem, phaseName;
    Logger appLogger = mAppMgr.getLogger(this, "run");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    long extractCount = 0;
    DescriptiveStatistics dsExtract = new DescriptiveStatistics();
    long transformCount = 0;
    DescriptiveStatistics dsTransform = new DescriptiveStatistics();
    long publishCount = 0;
    DescriptiveStatistics dsPublish = new DescriptiveStatistics();

    BlockingQueue publishQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_PUBLISH_NAME);

    do {
        try {
            queueItem = (String) publishQueue.poll(Constants.QUEUE_POLL_TIMEOUT_DEFAULT, TimeUnit.SECONDS);
            if (mCrawlQueue.isQueueItemDocument(queueItem)) {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                docId = Connector.docIdFromQueueItem(queueItem);

                appLogger.debug(String.format("Publish Queue Item: %s", docId));

                phaseTimes = Connector.phaseTimeFromQueueItem(queueItem);
                if (phaseTimes != null) {
                    for (String phaseTime : phaseTimes) {
                        phaseName = Connector.phaseFromPhaseTime(phaseTime);
                        msTime = Connector.timeFromPhaseTime(phaseTime);
                        if (StringUtils.equals(phaseName, Connector.PHASE_EXTRACT)) {
                            extractCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsExtract.addValue(secondsTime);
                        } else if (StringUtils.equals(phaseName, Connector.PHASE_TRANSFORM)) {
                            transformCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsTransform.addValue(secondsTime);
                        } else if (StringUtils.equals(phaseName, Connector.PHASE_PUBLISH)) {
                            publishCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsPublish.addValue(secondsTime);
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            queueItem = StringUtils.EMPTY;
        }
    } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_PUBLISH, queueItem));

    // Note: This is the end of the queue processing pipeline, so we will not pass on queue item markers.

    // Generate our metrics summary for the log file.

    writePhaseMetric(Connector.PHASE_EXTRACT, extractCount, dsExtract.getSum());
    writePhaseMetric(Connector.PHASE_TRANSFORM, transformCount, dsTransform.getSum());
    writePhaseMetric(Connector.PHASE_PUBLISH, publishCount, dsPublish.getSum());

    double totalTime = dsExtract.getSum() + dsTransform.getSum() + dsPublish.getSum();
    if ((publishCount > 0L) && (totalTime > 0.0))
        docsPerSecond = publishCount / totalTime;
    else
        docsPerSecond = 0.0;
    String msgStr = String.format("Total metric summary: %d documents, %.2f seconds (%.2f docs/sec avg)",
            publishCount, totalTime, docsPerSecond);
    appLogger.info(msgStr);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.kurento.kmf.media.ZBarFilterTest.java

@Test
public void testCodeFoundEvent() throws InterruptedException {
    PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_BARCODES).build();
    player.connect(zbar);//w w  w. j  a  v a 2 s.  c  o m

    final BlockingQueue<CodeFoundEvent> events = new ArrayBlockingQueue<CodeFoundEvent>(1);

    zbar.addCodeFoundListener(new MediaEventListener<CodeFoundEvent>() {

        @Override
        public void onEvent(CodeFoundEvent event) {
            events.add(event);
        }
    });

    player.play();

    Assert.assertNotNull(events.poll(7, TimeUnit.SECONDS));

    player.stop();
    player.release();
}

From source file:com.kurento.kmf.media.GStreamerFilterTest.java

@Test
public void testInstantiation() throws InterruptedException {
    filter = pipeline.newGStreamerFilter("videoflip method=horizontal-flip").build();

    Assert.assertNotNull(filter);/*from   ww  w .jav a 2s. c o m*/

    player.connect(filter);

    final BlockingQueue<EndOfStreamEvent> eosEvents = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosEvents.add(event);
        }
    });

    player.play();
    Assert.assertNotNull(eosEvents.poll(7, SECONDS));
    filter.release();
}

From source file:com.kurento.kmf.media.FaceOverlayFilterTest.java

/**
 * Test if a {@link JackVaderFilter} can be created in the KMS. The filter
 * is pipelined with a {@link PlayerEndpoint}, which feeds video to the
 * filter. This test depends on the correct behaviour of the player and its
 * events./*from  ww w  .j  a va2s  .co  m*/
 * 
 * @throws InterruptedException
 */
@Test
public void testFaceOverlayFilter() throws InterruptedException {
    PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_POINTER_DETECTOR).build();
    player.connect(overlayFilter);

    final BlockingQueue<EndOfStreamEvent> events = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            events.add(event);
        }
    });

    player.play();

    Assert.assertNotNull(events.poll(20, SECONDS));

    player.stop();
    player.release();
}

From source file:com.kurento.kmf.media.JackVaderFilterTest.java

/**
 * Test if a {@link JackVaderFilter} can be created in the KMS. The filter
 * is pipelined with a {@link PlayerEndpoint}, which feeds video to the
 * filter. This test depends on the correct behaviour of the player and its
 * events.//from   w w w  .j  a v a  2  s.  com
 * 
 * @throws InterruptedException
 */
@Test
public void testJackVaderFilter() throws InterruptedException {
    PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    player.connect(jackVader);

    final BlockingQueue<EndOfStreamEvent> events = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            events.add(event);
        }
    });

    player.play();

    Assert.assertNotNull(events.poll(10, SECONDS));

    player.stop();
    player.release();
}

From source file:com.kurento.kmf.media.PlayerEndpointTest.java

@Test
public void testEventEndOfStream() throws InterruptedException {
    final BlockingQueue<EndOfStreamEvent> events = new ArrayBlockingQueue<EndOfStreamEvent>(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override//from  w  w w  .  ja  v  a  2 s  .  c  o m
        public void onEvent(EndOfStreamEvent event) {
            events.add(event);
        }
    });

    player.play();

    Assert.assertNotNull(events.poll(7, SECONDS));
}