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:Main.java

public static <T> T take(BlockingQueue<T> videoDrain, int ms) {
    try {/*  w w w .  j a  va 2 s. co m*/
        return videoDrain.poll(ms, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        return null;
    }
}

From source file:com.utdallas.s3lab.smvhunter.enumerate.UIEnumerator.java

/**
 * Generate a back-click event in case of focus or window change
 * @param eventQueue/*w w w .  ja  v  a  2s.  c o  m*/
 * @param viewer
 * @param device
 * @param emulator
 * @throws Exception
 */
private static void doBackClickonWindowChange(BlockingQueue<String> eventQueue, HierarchyViewer viewer,
        IDevice device, String emulator) throws Exception {
    String event = "";
    if ((event = eventQueue.poll(5, TimeUnit.SECONDS)) != null) {
        Window windows[] = DeviceBridge.loadWindows(device);
        int windowsLength = windows.length;
        if (logDebug)
            logger.debug("windowsLength after hitting::" + windowsLength + " event:" + event);
        if (StringUtils.equals(WindowUpdate.FOCUS_WINDOW_BOTH_CHANGED, event)
                || StringUtils.equals(WindowUpdate.FOCUS_CHANGED, event)
                || StringUtils.equals(WindowUpdate.WINDOW_UPDATED, event)) {
            if (windowsLength > initialWindowLength) {
                if (logDebug)
                    logger.debug("Focus + window changed HIT BACK");
                execCommand(String.format("%s input keyevent 4", emulator));
                Thread.sleep(5000);
                Window windows1[] = DeviceBridge.loadWindows(device);

                //this condition will happen when the app didn't respond to back button
                //It might be because of the popup dialog boxes which dont close on back event
                //first enter will focus on it and the second enter will trigger the action
                if (windows1.length > initialWindowLength) {
                    if (logDebug)
                        logger.debug("App didnt respond to back button...Try ENter");
                    execCommand(String.format("%s input keyevent 66", emulator));
                    execCommand(String.format("%s input keyevent 66", emulator));

                    Window windows2[] = DeviceBridge.loadWindows(device);
                    if (windows2.length == initialWindowLength) {
                        if (logDebug)
                            logger.debug("Hard press succeeded");
                    } else {
                        if (logDebug)
                            logger.debug("Something going wrong .. need to check it");
                    }
                }
                return;
            }
        }
    }
}

From source file:Main.java

/**
 * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested
 * {@code numElements} elements are not available, it will wait for them up to the specified
 * timeout.//ww w .  j a v  a2s. c om
 *
 * Taken from Google Guava 18.0 Queues
 *
 * @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
 * @param <E> the type of the queue
 * @return the number of elements transferred
 * @throws InterruptedException if interrupted while waiting
 */
public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout,
        TimeUnit unit) throws InterruptedException {
    buffer = Objects.requireNonNull(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;
}

From source file:io.fabric8.che.starter.openshift.CheDeploymentConfig.java

private boolean waitUntilReady(BlockingQueue<Object> queue) {
    try {/*from   w  w  w.  j ava 2  s.  c  o  m*/
        Object obj = queue.poll(2, TimeUnit.SECONDS);
        if (obj == null) {
            return true;
        }
        if (obj instanceof Boolean) {
            return (Boolean) obj;
        }
        return false;
    } catch (InterruptedException ex) {
        return true;
    }
}

From source file:org.bpmscript.endtoend.LoanBrokerTest.java

License:asdf

public void testLoanBroker() throws Exception {
    final int total = 10;

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    try {// w  ww  .j  a v  a  2 s  .  co  m

        final IMessageSender bus = (IMessageSender) context.getBean("bus");
        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");

        String source = StreamService.DEFAULT_INSTANCE
                .getResourceAsString("/org/bpmscript/endtoend/loanbroker.js");
        String id = engine.validate(new JavascriptProcessDefinition("loanBroker", source));

        processManager.createDefinition(id, new JavascriptProcessDefinition("loanBroker", source));

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            public void execute(int count) throws Exception {
                InvocationMessage message = new InvocationMessage();
                message.setArgs(null, "loanBroker", "requestBestRate",
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.setReplyTo("recording");
                bus.send("bpmscript-first", message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                RecordingAdapter recorder = (RecordingAdapter) context.getBean("recording");
                BlockingQueue<IInternalMessage> internalMessages = recorder.getMessages();
                for (int i = 0; i < total; i++) {
                    Object result = internalMessages.poll(2, TimeUnit.SECONDS);
                    assertNotNull(result);
                }
            }

        }, false));

    } finally {
        context.destroy();
    }
    log.info("done");
}

From source file:org.bpmscript.endtoend.JavaLoanBrokerTest.java

License:asdf

public void testLoanBroker() throws Exception {
    final int total = 10;

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    try {//  w  ww  . j ava2 s .c om

        final IMessageSender bus = (IMessageSender) context.getBean("bus");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");

        processManager.createDefinition("id",
                new JavaProcessDefinition("loanBroker", LoanBrokerProcess.class.getName()));

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            public void execute(int count) throws Exception {
                InvocationMessage message = new InvocationMessage();
                message.setArgs(null, "loanBroker", "requestBestRate",
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.setReplyTo("recording");
                bus.send("bpmscript-first", message);
                log.debug("sent message");
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                RecordingAdapter recorder = (RecordingAdapter) context.getBean("recording");
                BlockingQueue<IInternalMessage> internalMessages = recorder.getMessages();
                for (int i = 0; i < total; i++) {
                    Object result = internalMessages.poll(total, TimeUnit.SECONDS);
                    assertNotNull(result);
                    if (result instanceof ExceptionMessage) {
                        ExceptionMessage exceptionMessage = (ExceptionMessage) result;
                        log.error(exceptionMessage.getThrowable(), exceptionMessage.getThrowable());
                        fail(exceptionMessage.getThrowable().getMessage());
                    }
                }
            }
        }, false));

    } finally {
        context.destroy();
    }
    log.info("done");
}

From source file:org.bpmscript.integration.internal.memory.MemorySyncChannel.java

public Object get(String id, long duration) {
    BlockingQueue<Object> blockingQueue = null;
    blockingQueue = replies.get(id);/*www  .j a va  2s. c  o m*/
    if (blockingQueue != null) {
        try {
            if (duration > 0) {
                return blockingQueue.poll(duration, TimeUnit.MILLISECONDS);
            } else {
                return blockingQueue.take();
            }
        } catch (InterruptedException e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.bpmscript.integration.spring.SpringReplyTest.java

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final int loopcount = 2;
    final CountDownLatch latch = new CountDownLatch(total + loopcount * total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {//  ww  w  .  java 2 s .  com

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/reply.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(new Object[] { loopcount });
                message.getHeader().setAttribute("definitionName", "test");
                message.getHeader().setAttribute("operation", "test");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:org.bpmscript.integration.spring.SpringLoanBrokerTest.java

License:asdf

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final CountDownLatch latch = new CountDownLatch(total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {// w w  w  .j a v  a  2s. c  o m

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("loanBroker", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/loanbroker.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.getHeader().setAttribute("definitionName", "loanBroker");
                message.getHeader().setAttribute("operation", "requestBestRate");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:org.bpmscript.integration.spring.SpringSyncChannel.java

/**
 * @see org.bpmscript.channel.reply.ISyncService#get(java.lang.String, long)
 *///from w ww.  ja  va 2 s  .  co m
public Object get(String id, long duration) {
    BlockingQueue<Object> blockingQueue = null;
    blockingQueue = replies.get(id);
    if (blockingQueue != null) {
        try {
            if (duration > 0) {
                return blockingQueue.poll(duration, TimeUnit.MILLISECONDS);
            } else {
                return blockingQueue.take();
            }
        } catch (InterruptedException e) {
            return null;
        }
    } else {
        return null;
    }
}