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:se.vgregion.pubsub.push.impl.DefaultFeedRetrieverTest.java

/**
 * Fragments should only be used during retrievel and stripped before publication
 *///from   ww w  .  ja  v a  2s . c o m
@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.test.HttpGetEndpointTest.java

/**
 * Test for {@link MediaSessionTerminatedEvent}
 *
 * @throws InterruptedException//  ww  w . j ava 2  s  . com
 * @throws IOException
 * @throws ClientProtocolException
 */
@Test
public void testEventMediaSessionTerminated()
        throws InterruptedException, ClientProtocolException, IOException {
    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    HttpGetEndpoint httpEP = pipeline.newHttpGetEndpoint().terminateOnEOS().build();
    player.connect(httpEP);

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

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

    final BlockingQueue<MediaSessionTerminatedEvent> events = new ArrayBlockingQueue<>(1);
    httpEP.addMediaSessionTerminatedListener(new MediaEventListener<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:org.kurento.client.test.HttpGetEndpointTest.java

/**
 * Test for {@link MediaSessionTerminatedEvent}
 *
 * @throws InterruptedException//from   w  ww.j  ava2 s .c  om
 * @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:com.netflix.curator.framework.imps.TestFrameworkEdges.java

@Test
public void testMissedResponseOnBackgroundESCreate() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*  w ww. j  a  v a2s .c o  m*/
    try {
        CreateBuilderImpl createBuilder = (CreateBuilderImpl) client.create();
        createBuilder.failNextCreateForTesting = true;

        final BlockingQueue<String> queue = Queues.newArrayBlockingQueue(1);
        BackgroundCallback callback = new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                queue.put(event.getPath());
            }
        };
        createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback)
                .forPath("/");
        String ourPath = queue.poll(10, TimeUnit.SECONDS);
        Assert.assertTrue(ourPath.startsWith(ZKPaths.makePath("/", CreateBuilderImpl.PROTECTED_PREFIX)));
        Assert.assertFalse(createBuilder.failNextCreateForTesting);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

/**
 * @throws InterruptedException//from ww  w .  ja v a2s  .com
 * 
 */
@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   w  w w.java 2  s.  c o  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:com.example.SampleStreamExample.java

public static void run(String consumerKey, String consumerSecret, String token, String secret)
        throws InterruptedException {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
    endpoint.stallWarnings(false);//from   w w  w .j av  a2s  .c  o m

    File file = new File("/usr/local/Output11.txt");

    if (!file.exists()) {
        try {
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("[");
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client = new ClientBuilder().name("sampleExampleClient").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++) {
        if (client.isDone()) {
            System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
            break;
        }

        String msg = queue.poll(5, TimeUnit.SECONDS);
        //  String Time="time",Text="Text";
        //Lang id;
        if (msg == null) {
            System.out.println("Did not receive a message in 5 seconds");
        } else {

            System.out.println(msg);
            //System.out.println("**************hahahahahahahah********************");

            try {
                FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);

                if (msgRead == 999)
                    bw.write(msg);
                else
                    bw.write(msg + ",");

                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*     JSONParser jsonParser = new JSONParser();
                   //JsonElement jsonElement = null;
                           
                   String key="";
                try {
                   //jsonElement= (JsonElement) jsonParser.parse(msg); 
                 JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
                 //JsonObject jsonObjec = jsonElement.getAsJsonObject();
                 //for(Entry<String, JsonElement> entry : jsonObjec.entrySet())
              //   {  key = entry.getKey();
                 //   if(key=="delete")
                    //      System.out.println("this comment is deleted");
              //   }   
                   //JsonElement value = entry.getValue();
                         
                 //***** printing date
              //   Time = (String) jsonObject.get("created_at");
                    System.out.println("Date of creation====: " + jsonObject.get("created_at"));
                    //******printing id
                  //   id = (Lang) jsonObject.get("id");
                 //   System.out.println("id=========: " + jsonObject.get("id"));
                    //*******text
                     //Text = (String) jsonObject.get("text");
                   //System.out.println("Text==========: " + jsonObject.get("text"));
                            
                    //************inside user************
                    JSONObject structure = (JSONObject) jsonObject.get("user");
                    System.out.println("Into user structure ,  id====: " + structure.get("id"));
                    System.out.println("Into user structure ,  name====: " + structure.get("name"));
                    System.out.println("Into user structure ,  screen_name====: " + structure.get("screen_name"));
                    System.out.println("Into user structure ,  location====: " + structure.get("location"));
                    System.out.println("Into user structure ,  description====: " + structure.get("description"));
                    System.out.println("Into user structure ,  followers====: " + structure.get("followers_count"));
                    System.out.println("Into user structure ,  friends====: " + structure.get("friends_count"));
                    System.out.println("Into user structure ,  listed====: " + structure.get("listed_count"));
                    System.out.println("Into user structure ,  favorite====: " + structure.get("favorites_count"));
                    System.out.println("Into user structure ,  status_count====: " + structure.get("status_count"));
                    System.out.println("Into user structure ,  created at====: " + structure.get("created at"));
                            
                            
                            
                         
              } catch (ParseException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
              }
                    
                  */
        }
    }
    FileWriter fw;
    try {
        fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("]");
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());

}

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

/**
 * Test for {@link MediaSessionStartedEvent}
 * // w w  w .j ava2s. com
 * @throws InterruptedException
 */
@Test
public void testEventMediaSessionStarted() throws InterruptedException {

    final PlayerEndpoint player = pipeline.newPlayerEndpoint(URL_SMALL).build();
    player.connect(httpEp);

    final CountDownLatch eosLatch = new CountDownLatch(1);
    player.addEndOfStreamListener(new MediaEventListener<EndOfStreamEvent>() {

        @Override
        public void onEvent(EndOfStreamEvent event) {
            eosLatch.countDown();
        }
    });

    final BlockingQueue<ListenerRegistration> events = new ArrayBlockingQueue<ListenerRegistration>(1);
    httpEp.addMediaSessionStartedListener(new MediaEventListener<MediaSessionStartedEvent>() {

        @Override
        public void onEvent(MediaSessionStartedEvent event) {
            player.play();
        }
    }, new Continuation<ListenerRegistration>() {

        @Override
        public void onSuccess(ListenerRegistration result) {
            events.add(result);
        }

        @Override
        public void onError(Throwable cause) {
            throw new KurentoMediaFrameworkException(cause);
        }
    });

    ListenerRegistration reg = events.poll(500, MILLISECONDS);
    Assert.assertNotNull(reg);

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

    try {
        eosLatch.await(500, MILLISECONDS);
    } catch (InterruptedException e) {
        player.release();
        throw new KurentoMediaFrameworkException(e);
    }

}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedPriorityQueue.java

@Test
public void testSortingWhileTaking() throws Exception {
    Timing timing = new Timing();
    DistributedPriorityQueue<Integer> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();/*from  w  w w  . j ava 2  s .  c o  m*/
    try {
        final BlockingQueue<Integer> blockingQueue = new SynchronousQueue<Integer>();
        QueueConsumer<Integer> consumer = new QueueConsumer<Integer>() {
            @Override
            public void consumeMessage(Integer message) throws Exception {
                blockingQueue.put(message);
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0);
        queue.start();

        for (int i = 0; i < 10; ++i) {
            queue.put(i, 10);
        }

        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(0));
        timing.sleepABit();
        queue.put(1000, 1); // lower priority
        timing.sleepABit();
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1)); // is in consumer already
        Assert.assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1000));
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:gridool.processors.job.GridJobWorker.java

private void aggregateTaskResults(final Map<String, Pair<GridTask, List<Future<?>>>> taskMap,
        final BlockingQueue<GridTaskResult> resultQueue, final TextProgressBar progressBar)
        throws GridException {
    final int numTasks = taskMap.size();
    for (int finishedTasks = 0; finishedTasks < numTasks; finishedTasks++) {
        GridTaskResult result = null;/*from w w w  .  j  a v a2  s  .  c  om*/
        try {
            if (JOB_INSPECTION_INTERVAL_SEC == -1L) {
                result = resultQueue.take();
            } else {
                while (true) {
                    result = resultQueue.poll(JOB_INSPECTION_INTERVAL_SEC, TimeUnit.SECONDS);
                    if (result != null) {
                        break;
                    }
                    if (LOG.isInfoEnabled()) {
                        showRemainingTasks(job, taskMap);
                    }
                }
            }
        } catch (InterruptedException e) {
            LOG.warn("GridTask is interrupted", e);
            throw new GridException("GridTask is interrupted", e);
        }
        final String taskId = result.getTaskId();
        final GridTaskResultPolicy policy = job.result(result);
        switch (policy) {
        case CONTINUE: {
            progressBar.inc();
            taskMap.remove(taskId);
            break;
        }
        case CONTINUE_WITH_SPECULATIVE_TASKS: {
            progressBar.inc();
            taskMap.remove(taskId);
            for (final GridTask task : result.getSpeculativeTasks()) {
                String speculativeTaskId = task.getTaskId();
                Pair<GridTask, List<Future<?>>> entry = taskMap.get(speculativeTaskId);
                if (entry == null) {// Is the task already finished?
                    LOG.info("No need to run a speculative task: " + speculativeTaskId);
                } else {
                    Future<?> newFuture = runSpeculativeTask(task, resultQueue); // SKIP handling is required for speculative tasks
                    if (newFuture != null) {
                        List<Future<?>> futures = entry.getSecond();
                        futures.add(newFuture);
                    }
                }
            }
            break;
        }
        case RETURN:
            taskMap.remove(taskId);
            return;
        case CANCEL_RETURN: {
            taskMap.remove(taskId);
            if (!taskMap.isEmpty()) {
                cancelRemainingTasks(taskMap);
            }
            return;
        }
        case FAILOVER: {
            Pair<GridTask, List<Future<?>>> entry = taskMap.get(taskId);
            GridTask task = entry.getFirst();
            Future<?> newFuture = failover(task, resultQueue);
            List<Future<?>> futureList = entry.getSecond();
            futureList.add(newFuture);
            finishedTasks--;
            break;
        }
        case SKIP:
            finishedTasks--;
            break;
        default:
            assert false : "Unexpected policy: " + policy;
        }
    }
}