Example usage for java.util.concurrent BlockingQueue add

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

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Usage

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

/**
 * Test for {@link MediaSessionStartedEvent}
 * //  www  .j a  v  a  2s . com
 * @throws InterruptedException
 */
@Test
public void testEventMediaSessionStarted() throws InterruptedException {
    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    HttpPostEndpoint httpEP = pipeline.newHttpPostEndpoint().build();
    player.connect(httpEP);

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

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

    httpEP.addMediaSessionStartedListener(new MediaEventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    });

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        // This should trigger MediaSessionStartedEvent
        httpclient.execute(new HttpGet(httpEP.getUrl()));
    } catch (ClientProtocolException e) {
        throw new KurentoMediaFrameworkException();
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException();
    }

    Assert.assertNotNull(eosEvents.poll(7, SECONDS));

    httpEP.release();
    player.release();
}

From source file:org.kurento.client.test.HttpGetEndpointTest.java

/**
 * Test for {@link MediaSessionTerminatedEvent}
 *
 * @throws InterruptedException/*ww w  . j av  a  2 s .  c  o  m*/
 * @throws IOException
 * @throws ClientProtocolException
 */
@Test
public void testEventMediaSessionTerminated()
        throws InterruptedException, ClientProtocolException, IOException {

    final PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, URL_SMALL).build();

    HttpGetEndpoint httpEP = new HttpGetEndpoint.Builder(pipeline).terminateOnEOS().build();

    player.connect(httpEP);

    httpEP.addMediaSessionStartedListener(new EventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    });

    final BlockingQueue<MediaSessionTerminatedEvent> events = new ArrayBlockingQueue<>(1);
    httpEP.addMediaSessionTerminatedListener(new EventListener<MediaSessionTerminatedEvent>() {

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

    try (CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
        // This should trigger MediaSessionStartedEvent
        httpclient.execute(new HttpGet(httpEP.getUrl()));
    }

    Assert.assertNotNull("MediaSessionTerminatedEvent not sent in 20s", events.poll(20, SECONDS));

    httpEP.release();
    player.release();
}

From source file:se.vgregion.pubsub.push.impl.DefaultFeedRetrieverTest.java

/**
 * Fragments should only be used during retrievel and stripped before publication
 *//*from   w  ww  .j  ava2s .  com*/
@Test
public void retrievalWithFragment() throws Exception {
    final BlockingQueue<String> paths = new LinkedBlockingQueue<String>();

    server.register("/*", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            paths.add(request.getRequestLine().getUri());
            response.setEntity(testEntity);
        }
    });

    String retrivalPath = "/test#foo";
    URI publicationUrl = buildTestUrl("/test");
    URI url = buildTestUrl(retrivalPath);

    retriever.retrieve(url);

    String path = paths.poll(2000, TimeUnit.MILLISECONDS);

    // retrived URI must contain fragment
    Assert.assertEquals(retrivalPath, path);

    ArgumentCaptor<Feed> publishedFeed = ArgumentCaptor.forClass(Feed.class);

    // published URI must no contain fragment
    Mockito.verify(pushSubscriberManager).publish(Mockito.eq(publicationUrl), publishedFeed.capture());

    Assert.assertEquals("f1", publishedFeed.getValue().getFeedId());
}

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

/**
 * @throws InterruptedException// www.  j a va2  s  .c  o  m
 * 
 */
@Test
public void testWindowOverlay() throws InterruptedException {

    PointerDetectorWindowMediaParam window0 = new PointerDetectorWindowMediaParam("window0", 50, 50, 200, 50);
    filter.addWindow(window0);

    final BlockingQueue<WindowInEvent> eventsIn = new ArrayBlockingQueue<WindowInEvent>(1);

    final BlockingQueue<WindowOutEvent> eventsOut = new ArrayBlockingQueue<WindowOutEvent>(1);

    filter.addWindowInListener(new MediaEventListener<WindowInEvent>() {

        @Override
        public void onEvent(WindowInEvent event) {
            eventsIn.add(event);
        }
    });

    filter.addWindowOutListener(new MediaEventListener<WindowOutEvent>() {

        @Override
        public void onEvent(WindowOutEvent event) {
            eventsOut.add(event);
        }
    });

    player.play();
    Assert.assertNotNull(eventsIn.poll(10, TimeUnit.SECONDS));
    Assert.assertNotNull(eventsOut.poll(5, TimeUnit.SECONDS));
    player.stop();
}

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

/**
 * @throws InterruptedException/*from ww  w.  j a  va  2 s.co m*/
 * 
 */
@Test
public void testWindowEvents() throws InterruptedException {

    PointerDetectorWindowMediaParam window0 = new PointerDetectorWindowMediaParam("window0", 50, 50, 200, 50);

    PointerDetectorWindowMediaParam window1 = new PointerDetectorWindowMediaParam("window1", 50, 50, 200, 150);

    filter.addWindow(window0);
    filter.addWindow(window1);

    final BlockingQueue<WindowInEvent> eventsIn = new ArrayBlockingQueue<WindowInEvent>(1);

    final BlockingQueue<WindowOutEvent> eventsOut = new ArrayBlockingQueue<WindowOutEvent>(1);

    filter.addWindowInListener(new MediaEventListener<WindowInEvent>() {

        @Override
        public void onEvent(WindowInEvent event) {
            eventsIn.add(event);
        }
    });

    filter.addWindowOutListener(new MediaEventListener<WindowOutEvent>() {

        @Override
        public void onEvent(WindowOutEvent event) {
            eventsOut.add(event);
        }
    });

    player.play();
    Assert.assertTrue("window0".equals(eventsIn.poll(20, SECONDS).getWindowId()));
    Assert.assertTrue("window0".equals(eventsOut.poll(5, SECONDS).getWindowId()));

    player.stop();
}

From source file:org.apache.hadoop.hbase.client.TestAsyncTable.java

@Test
public void testSimpleMultiple() throws Exception {
    AsyncTableBase table = getTable.get();
    int count = 100;
    CountDownLatch putLatch = new CountDownLatch(count);
    IntStream.range(0, count)/*from w w  w.  j  ava  2 s .c  o m*/
            .forEach(i -> table.put(new Put(concat(row, i)).addColumn(FAMILY, QUALIFIER, concat(VALUE, i)))
                    .thenAccept(x -> putLatch.countDown()));
    putLatch.await();
    BlockingQueue<Boolean> existsResp = new ArrayBlockingQueue<>(count);
    IntStream.range(0, count).forEach(i -> table.exists(new Get(concat(row, i)).addColumn(FAMILY, QUALIFIER))
            .thenAccept(x -> existsResp.add(x)));
    for (int i = 0; i < count; i++) {
        assertTrue(existsResp.take());
    }
    BlockingQueue<Pair<Integer, Result>> getResp = new ArrayBlockingQueue<>(count);
    IntStream.range(0, count).forEach(i -> table.get(new Get(concat(row, i)).addColumn(FAMILY, QUALIFIER))
            .thenAccept(x -> getResp.add(Pair.newPair(i, x))));
    for (int i = 0; i < count; i++) {
        Pair<Integer, Result> pair = getResp.take();
        assertArrayEquals(concat(VALUE, pair.getFirst()), pair.getSecond().getValue(FAMILY, QUALIFIER));
    }
    CountDownLatch deleteLatch = new CountDownLatch(count);
    IntStream.range(0, count)
            .forEach(i -> table.delete(new Delete(concat(row, i))).thenAccept(x -> deleteLatch.countDown()));
    deleteLatch.await();
    IntStream.range(0, count).forEach(i -> table.exists(new Get(concat(row, i)).addColumn(FAMILY, QUALIFIER))
            .thenAccept(x -> existsResp.add(x)));
    for (int i = 0; i < count; i++) {
        assertFalse(existsResp.take());
    }
    IntStream.range(0, count).forEach(i -> table.get(new Get(concat(row, i)).addColumn(FAMILY, QUALIFIER))
            .thenAccept(x -> getResp.add(Pair.newPair(i, x))));
    for (int i = 0; i < count; i++) {
        Pair<Integer, Result> pair = getResp.take();
        assertTrue(pair.getSecond().isEmpty());
    }
}

From source file:ubic.gemma.apps.ArrayDesignBlatCli.java

@Override
protected Exception doWork(String[] args) {
    Exception err = processCommandLine(
            "Array design sequence BLAT - only works if server is already started or if a PSL file is provided!",
            args);/*  ww  w . j  a  va2s .  co m*/
    if (err != null)
        return err;

    final Date skipIfLastRunLaterThan = getLimitingDate();

    if (!this.arrayDesignsToProcess.isEmpty()) {

        if (this.blatResultFile != null && this.arrayDesignsToProcess.size() > 1) {
            throw new IllegalArgumentException(
                    "Cannot provide a blat result file when multiple arrays are being analyzed");
        }

        for (ArrayDesign arrayDesign : this.arrayDesignsToProcess) {
            if (!needToRun(skipIfLastRunLaterThan, arrayDesign, ArrayDesignSequenceAnalysisEvent.class)) {
                log.warn(arrayDesign + " was last run more recently than " + skipIfLastRunLaterThan);
                return null;
            }

            arrayDesign = unlazifyArrayDesign(arrayDesign);
            Collection<BlatResult> persistedResults;
            try {
                if (this.blatResultFile != null) {
                    Collection<BlatResult> blatResults = getBlatResultsFromFile(arrayDesign);

                    if (blatResults == null || blatResults.size() == 0) {
                        throw new IllegalStateException("No blat results in file!");
                    }

                    log.info("Got " + blatResults.size() + " blat records");
                    persistedResults = arrayDesignSequenceAlignmentService.processArrayDesign(arrayDesign,
                            taxon, blatResults);
                    audit(arrayDesign, "BLAT results read from file: " + blatResultFile);
                } else {
                    // Run blat from scratch.
                    persistedResults = arrayDesignSequenceAlignmentService.processArrayDesign(arrayDesign,
                            this.sensitive);
                    audit(arrayDesign, "Based on a fresh alignment analysis; BLAT score threshold was "
                            + this.blatScoreThreshold + "; sensitive mode was " + this.sensitive);
                }
                log.info("Persisted " + persistedResults.size() + " results");
            } catch (FileNotFoundException e) {
                this.errorObjects.add(e);
            } catch (IOException e) {
                this.errorObjects.add(e);
            }
        }

    } else if (taxon != null) {

        Collection<ArrayDesign> allArrayDesigns = arrayDesignService.findByTaxon(taxon);
        log.warn("*** Running BLAT for all " + taxon.getCommonName() + " Array designs *** ["
                + allArrayDesigns.size() + " items]");

        final SecurityContext context = SecurityContextHolder.getContext();

        // split over multiple threads so we can multiplex. Put the array designs in a queue.

        /*
         * Here is our task runner.
         */
        class Consumer implements Runnable {
            private final BlockingQueue<ArrayDesign> queue;

            public Consumer(BlockingQueue<ArrayDesign> q) {
                queue = q;
            }

            @Override
            public void run() {
                SecurityContextHolder.setContext(context);
                while (true) {
                    ArrayDesign ad = queue.poll();
                    if (ad == null) {
                        break;
                    }
                    consume(ad);
                }
            }

            void consume(ArrayDesign x) {

                x = arrayDesignService.thaw(x);

                processArrayDesign(skipIfLastRunLaterThan, x);

            }
        }

        BlockingQueue<ArrayDesign> arrayDesigns = new ArrayBlockingQueue<ArrayDesign>(allArrayDesigns.size());
        for (ArrayDesign ad : allArrayDesigns) {
            arrayDesigns.add(ad);
        }

        /*
         * Start the threads
         */
        Collection<Thread> threads = new ArrayList<Thread>();
        for (int i = 0; i < this.numThreads; i++) {
            Consumer c1 = new Consumer(arrayDesigns);
            Thread k = new Thread(c1);
            threads.add(k);
            k.start();
        }

        waitForThreadPoolCompletion(threads);

        /*
         * All done
         */
        summarizeProcessing();

    } else {
        bail(ErrorCode.MISSING_ARGUMENT);
    }

    return null;
}

From source file:org.sourcepit.docker.watcher.DockerWatcher.java

public synchronized void start() {
    isTrue(client == null);//w ww.  j  av a  2  s  .co m
    isTrue(eventObserverThread == null);
    isTrue(scheduler == null);

    final State state = new State() {
        @Override
        protected void handle(List<JsonObject> events) {
            DockerWatcher.this.handle(events);
        }
    };

    final BlockingQueue<JsonElement> queue = new LinkedBlockingQueue<>();

    client = clientFactory.createHttpClient();

    final FetchConatinersCommand fetchContainersCommand = new FetchConatinersCommand(client, uri) {
        @Override
        protected void handle(JsonArray status) {
            LOG.debug("Fetched: {}", status.toString());
            queue.add(status);
        }
    };

    final DockerEventObserver eventObserver = new DockerEventObserver(client, uri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(event);
        }
    };

    eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };

    scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Docker State Fetcher");
        }
    });

    final SyncStateCommand syncStateCommand = new SyncStateCommand(queue) {

        @Override
        protected void requestNewStatus() {
            LOG.debug("Requesting new status.");
            scheduler.execute(fetchContainersCommand);
        }

        @Override
        protected void applyLastKnownState(JsonArray status) {
            LOG.debug("Applying new status: {}", status.toString());
            state.applyLastKnownState(status);
        }

    };

    scheduler.scheduleWithFixedDelay(fetchContainersCommand, 0, 30, TimeUnit.SECONDS);
    scheduler.scheduleWithFixedDelay(syncStateCommand, 0, 1, TimeUnit.SECONDS);
    eventObserverThread.start();
}

From source file:org.opendaylight.genius.utils.batching.ResourceBatchingManager.java

public void delete(String resourceType, InstanceIdentifier identifier) {
    BlockingQueue<ActionableResource> queue = getQueue(resourceType);
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.DELETE, null, null/*oldData*/);
        queue.add(actResource);
    }//from w  ww.  j ava 2  s  .  c  om
}

From source file:org.opendaylight.genius.utils.batching.ResourceBatchingManager.java

public void delete(ShardResource shardResource, InstanceIdentifier identifier) {
    BlockingQueue<ActionableResource> queue = shardResource.getQueue();
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.DELETE, null, null/*oldData*/);
        queue.add(actResource);
    }/*from w  w w  . j  a v a  2s  .co m*/
}