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:org.opendaylight.genius.utils.batching.ResourceBatchingManager.java

public void merge(String resourceType, InstanceIdentifier identifier, DataObject updatedData) {
    BlockingQueue<ActionableResource> queue = getQueue(resourceType);
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.UPDATE, updatedData, null/*oldData*/);
        queue.add(actResource);
    }//  w  ww . j  a  v  a  2 s  . com
}

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

public void put(String resourceType, InstanceIdentifier identifier, DataObject updatedData) {
    BlockingQueue<ActionableResource> queue = getQueue(resourceType);
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.CREATE, updatedData, null/*oldData*/);
        queue.add(actResource);
    }/*from ww w .j av  a2  s .c  o m*/
}

From source file:org.geppetto.simulation.manager.ExperimentRunManager.java

/**
 * @param user//ww  w  .  j  a v  a  2s  . com
 * @param experiment
 * @param status
 */
private synchronized void addExperimentToQueue(IUser user, IExperiment experiment, ExperimentStatus status) {
    BlockingQueue<IExperiment> userExperiments = queue.get(user);
    if (userExperiments == null) {
        userExperiments = new ArrayBlockingQueue<IExperiment>(100);
        queue.put(user, userExperiments);
    }
    if (experiment.getStatus() == status) {
        experiment.setStatus(ExperimentStatus.QUEUED);
        userExperiments.add(experiment);
    }
}

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

public void merge(ShardResource shardResource, InstanceIdentifier identifier, DataObject updatedData) {
    BlockingQueue<ActionableResource> queue = shardResource.getQueue();
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.UPDATE, updatedData, null/*oldData*/);
        queue.add(actResource);
    }/*  w  ww .  j av a2 s  .  c om*/
}

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

public void put(ShardResource shardResource, InstanceIdentifier identifier, DataObject updatedData) {
    BlockingQueue<ActionableResource> queue = shardResource.getQueue();
    if (queue != null) {
        ActionableResource actResource = new ActionableResourceImpl(identifier.toString(), identifier,
                ActionableResource.CREATE, updatedData, null/*oldData*/);
        queue.add(actResource);
    }/*from w w  w .ja  v  a  2  s.  c o m*/
}

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

/**
 * Test for {@link MediaSessionStartedEvent}
 * // w w w  .  j  av a  2  s.co  m
 * @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:coral.service.ExpServable.java

@Override
public void broadcast(Integer id, String msg) {
    BlockingQueue<Message> outQueue = clients.get(id);

    FileWriter fw = screenwriter.get(id);
    if (fw != null) {
        try {//  www.  j av  a2  s.com
            fw.append(msg);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    outQueue.add(new Message("vset", viewname, "text/html", "YES", msg.getBytes()));
}

From source file:org.springframework.integration.mqtt.MqttAdapterTests.java

@Test
public void testInboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);//from  w w w.  ja va 2 s  . c  o  m
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);

    factory = spy(factory);
    final IMqttClient client = mock(IMqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());

    final AtomicBoolean connectCalled = new AtomicBoolean();
    final AtomicBoolean failConnection = new AtomicBoolean();
    final CountDownLatch waitToFail = new CountDownLatch(1);
    final CountDownLatch failInProcess = new CountDownLatch(1);
    final CountDownLatch goodConnection = new CountDownLatch(2);
    final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
    willAnswer(invocation -> {
        if (failConnection.get()) {
            failInProcess.countDown();
            waitToFail.await(10, TimeUnit.SECONDS);
            throw reconnectException;
        }
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        goodConnection.countDown();
        return null;
    }).given(client).connect(any(MqttConnectOptions.class));

    final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
    willAnswer(invocation -> {
        callback.set(invocation.getArgument(0));
        return null;
    }).given(client).setCallback(any(MqttCallback.class));

    given(client.isConnected()).willReturn(true);

    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory,
            "baz", "fix");
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.setBeanFactory(mock(BeanFactory.class));
    ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
    final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
    willAnswer(invocation -> {
        events.add(invocation.getArgument(0));
        return null;
    }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
    adapter.setApplicationEventPublisher(applicationEventPublisher);
    adapter.setRecoveryInterval(500);
    adapter.afterPropertiesSet();
    adapter.start();

    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());

    MqttMessage message = new MqttMessage("qux".getBytes());
    callback.get().messageArrived("baz", message);
    Message<?> outMessage = outputChannel.receive(0);
    assertNotNull(outMessage);
    assertEquals("qux", outMessage.getPayload());

    MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());

    // lose connection and make first reconnect fail
    failConnection.set(true);
    RuntimeException e = new RuntimeException("foo");
    adapter.connectionLost(e);

    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), e);

    assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
    waitToFail.countDown();
    failConnection.set(false);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), reconnectException);

    // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
    assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
    int n = 0;
    while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
        event = events.poll(10, TimeUnit.SECONDS);
    }
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    taskScheduler.destroy();
}

From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java

@Test
public void testExclusiveAccess() throws Exception {
    DefaultLockRepository client1 = new DefaultLockRepository(dataSource);
    client1.afterPropertiesSet();/* ww w  . j  ava  2  s. c  o  m*/
    final DefaultLockRepository client2 = new DefaultLockRepository(dataSource);
    client2.afterPropertiesSet();
    Lock lock1 = new JdbcLockRegistry(client1).obtain("foo");
    final BlockingQueue<Integer> data = new LinkedBlockingQueue<Integer>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    lock1.lockInterruptibly();
    Executors.newSingleThreadExecutor().execute(() -> {
        Lock lock2 = new JdbcLockRegistry(client2).obtain("foo");
        try {
            latch1.countDown();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            lock2.lockInterruptibly();
            stopWatch.stop();
            data.add(4);
            Thread.sleep(10);
            data.add(5);
            Thread.sleep(10);
            data.add(6);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock2.unlock();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    data.add(1);
    Thread.sleep(1000);
    data.add(2);
    Thread.sleep(1000);
    data.add(3);
    lock1.unlock();
    for (int i = 0; i < 6; i++) {
        Integer integer = data.poll(10, TimeUnit.SECONDS);
        assertNotNull(integer);
        assertEquals(i + 1, integer.intValue());
    }
}

From source file:coral.ScreenshotServable.java

@Override
public void process(Message cmd, final BlockingQueue<Message> outQueue) {

    final String dest = cmd.getFullContent();

    Display display = Display.getDefault();
    display.syncExec(new Runnable() {
        public void run() {
            final Image image = new Image(shell.getDisplay(), shell.getSize().x, shell.getSize().y);
            GC gc = new GC(image);
            shell.getChildren()[0].print(gc);
            gc.dispose();/*from w ww . j a v  a  2s. co m*/

            ImageLoader imageLoader = new ImageLoader();
            imageLoader.data = new ImageData[] { image.getImageData() };

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            imageLoader.save(baos, SWT.IMAGE_PNG);

            outQueue.add(new Message("put://host/" + dest, baos.toByteArray()));

        }
    });

}