List of usage examples for java.util.concurrent BlockingQueue poll
E poll(long timeout, TimeUnit unit) throws InterruptedException;
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void deleteKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); final BlockingQueue<Boolean> queue = DataStructures.getLTQInstance(Boolean.class); client.kv(collection(), key).delete().on(new ResponseAdapter<Boolean>() { @Override//from w w w. j a va2 s .co m public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final Boolean object) { queue.add(object); } }); final Boolean result = queue.poll(5000, TimeUnit.MILLISECONDS); assertTrue(result); }
From source file:io.orchestrate.client.itest.KvTest.java
@Test public void postValueAsync() throws InterruptedException, IOException { final String collection = collection(); final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class); client.postValue(collection, "{}").on(new ResponseAdapter<KvMetadata>() { @Override/* w w w . j a v a 2 s . c o m*/ public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final KvMetadata object) { queue.add(object); } }); final KvMetadata kvMetadata = queue.poll(5000, TimeUnit.MILLISECONDS); assertNotNull(kvMetadata); assertNotNull(kvMetadata.getKey()); assertEquals(collection, kvMetadata.getCollection()); }
From source file:gobblin.couchbase.writer.CouchbaseWriter.java
@Override public Future<WriteResponse> write(final D record, final WriteCallback callback) { assertRecordWritable(record);//from w w w.j a v a 2s . c om if (record instanceof TupleDocument) { ((TupleDocument) record).content().value1().retain(); } Observable<D> observable = _bucket.async().upsert(record); if (callback == null) { return new WriteResponseFuture<>( observable.timeout(_operationTimeout, _operationTimeunit).toBlocking().toFuture(), _defaultWriteResponseMapper); } else { final AtomicBoolean callbackFired = new AtomicBoolean(false); final BlockingQueue<Pair<WriteResponse, Throwable>> writeResponseQueue = new ArrayBlockingQueue<>(1); final Future<WriteResponse> writeResponseFuture = new Future<WriteResponse>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return callbackFired.get(); } @Override public WriteResponse get() throws InterruptedException, ExecutionException { Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take(); return getWriteResponseorThrow(writeResponseThrowablePair); } @Override public WriteResponse get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout, unit); if (writeResponseThrowablePair == null) { throw new TimeoutException("Timeout exceeded while waiting for future to be done"); } else { return getWriteResponseorThrow(writeResponseThrowablePair); } } }; observable.timeout(_operationTimeout, _operationTimeunit).subscribe(new Subscriber<D>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { callbackFired.set(true); writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, e)); callback.onFailure(e); } @Override public void onNext(D doc) { try { callbackFired.set(true); WriteResponse writeResponse = new GenericWriteResponse<D>(doc); writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null)); callback.onSuccess(writeResponse); } finally { if (doc instanceof TupleDocument) { ((TupleDocument) doc).content().value1().release(); } } } }); return writeResponseFuture; } }
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void putKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class); client.kv(collection(), key).put("{}").on(new ResponseAdapter<KvMetadata>() { @Override//w w w . j a v a 2 s .co m public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final KvMetadata object) { queue.add(object); } }); final KvMetadata kvMetadata = queue.poll(5000, TimeUnit.MILLISECONDS); final KvObject<String> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey()) .get(String.class).get(); assertNotNull(kvMetadata); assertNotNull(kvObject); assertEquals(kvMetadata.getCollection(), kvObject.getCollection()); assertEquals(kvMetadata.getKey(), kvObject.getKey()); assertEquals(kvMetadata.getRef(), kvObject.getRef()); assertEquals("{}", kvObject.getValue()); }
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void purgeKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); final KvMetadata obj = insertItem(key, "{}"); final BlockingQueue<Boolean> queue = DataStructures.getLTQInstance(Boolean.class); client.kv(obj.getCollection(), obj.getKey()).delete(Boolean.TRUE).on(new ResponseAdapter<Boolean>() { @Override//ww w.j a v a 2 s. com public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final Boolean object) { queue.add(object); } }); final Boolean result = queue.poll(5000, TimeUnit.MILLISECONDS); final KvObject<String> nullObj = client.kv(obj.getCollection(), obj.getKey()) .get(String.class, obj.getRef()).get(); assertNotNull(obj); assertTrue(result); assertNull(nullObj); }
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void putKeyIfAbsentAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); thrown.expect(RuntimeException.class); final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class); client.kv(collection(), key).ifAbsent(Boolean.TRUE).put("{}").on(new ResponseAdapter<KvMetadata>() { @Override/* w w w . j a v a 2s . c om*/ public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final KvMetadata object) { queue.add(object); } }); final KvMetadata kvMetadata = queue.poll(5000, TimeUnit.MILLISECONDS); final KvObject<String> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey()) .get(String.class).get(); assertNotNull(kvMetadata); assertNotNull(kvObject); assertEquals(kvMetadata.getCollection(), kvObject.getCollection()); assertEquals(kvMetadata.getKey(), kvObject.getKey()); assertEquals(kvMetadata.getRef(), kvObject.getRef()); assertEquals("{}", kvObject.getValue()); final KvMetadata kvMetadata2 = client.kv(kvMetadata.getCollection(), kvMetadata.getKey()) .ifAbsent(Boolean.TRUE).put("{}").get(); assertNull(kvMetadata2); }
From source file:io.orchestrate.client.itest.KvTest.java
@Theory public void mergePatchKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); String name1 = Long.toHexString(RAND.nextLong()); final KvMetadata kvMetadata = insertItem(key, "{`name1`:`%s`}", name1); String name2 = Long.toHexString(RAND.nextLong()); final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class); client.kv(collection(), key).merge("{\"name2\":\"" + name2 + "\"}").on(new ResponseAdapter<KvMetadata>() { @Override/* w w w.ja v a2 s . c om*/ public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final KvMetadata object) { queue.add(object); } }); final KvMetadata patched = queue.poll(5000, TimeUnit.MILLISECONDS); assertNotEquals(kvMetadata, patched); final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey()) .get(ObjectNode.class).get(); assertEquals(patched.getRef(), kvObject.getRef()); assertEquals(name1, kvObject.getValue().get("name1").asText()); assertEquals(name2, kvObject.getValue().get("name2").asText()); }
From source file:gov.nasa.ensemble.resources.TestProjectProperties.java
@Test public void writing() throws CoreException, IOException, InterruptedException { final String key = "key", val1 = "val1", val2 = "val2"; final IFile propFile = ProjectProperties.propFile(file, key); final ProjectProperties props = projProps(file); assertTrue(props.get(key).isNone()); assertFalse(propFile.exists());// ww w.j av a 2s .c o m final BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(); ResourcesPlugin.getWorkspace().addResourceChangeListener(new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { if (event.getDelta() != null) { try { event.getDelta().accept(new IResourceDeltaVisitor() { @Override public boolean visit(IResourceDelta delta) { if (propFile.equals(delta.getResource())) try { queue.put(delta.getKind()); } catch (InterruptedException e) { LogUtil.error(e); } return true; } }); } catch (CoreException e) { throw new RuntimeException(e); } } } }); final long timeout = 1000; // create props.set(key, val1); assertEquals(ADDED, (int) queue.poll(timeout, MILLISECONDS)); assertTrue("Property file does not exist after setting property in memory", propFile.exists()); assertEquals(val1, getStringContents(propFile)); // update props.set(key, val2); assertEquals(CHANGED, (int) queue.poll(timeout, MILLISECONDS)); assertEquals("Property file does not exist after updating property in memory", val2, getStringContents(propFile)); // delete props.unset(key); assertEquals(REMOVED, (int) queue.poll(timeout, MILLISECONDS)); assertFalse("Property file still exists after unsetting property in memory", propFile.exists()); }
From source file:org.springframework.integration.mqtt.MqttAdapterTests.java
@Test public void testInboundOptionsApplied() throws Exception { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setCleanSession(false);/*w w w. j a v a 2 s .co 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:io.orchestrate.client.itest.KvTest.java
@Theory @org.junit.Ignore//from w w w. ja va 2s. c om public void getKeyWithListenerAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException { assumeThat(key, not(isEmptyString())); final BlockingQueue<KvObject> queue = DataStructures.getLTQInstance(KvObject.class); client.kv(collection(), key).get(String.class).on(new ResponseAdapter<KvObject<String>>() { @Override public void onFailure(final Throwable error) { fail(error.getMessage()); } @Override public void onSuccess(final KvObject<String> object) { queue.add(object); } }); @SuppressWarnings("unchecked") final KvObject<String> result = queue.poll(5000, TimeUnit.MILLISECONDS); // FIXME }