List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testStart() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override/*from w w w .j a v a 2s .com*/ public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a message to the start endpoint HashMap<String, Object> start = new HashMap<String, Object>(); start.put("data", "Some Data"); start.put("type", "start"); this.stompSession.send(String.format("/app/%s", topicUuid), start); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "start"); new JsonPathExpectationsHelper("serverTime").exists(json); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Start response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:org.apache.accumulo.tserver.replication.AccumuloReplicaSystem.java
protected Status replicateLogs(ClientContext peerContext, final HostAndPort peerTserver, final ReplicationTarget target, final Path p, final Status status, final long sizeLimit, final String remoteTableId, final TCredentials tcreds, final ReplicaSystemHelper helper, final UserGroupInformation accumuloUgi) throws TTransportException, AccumuloException, AccumuloSecurityException { log.debug("Replication WAL to peer tserver"); final Set<Integer> tids; final DataInputStream input; Span span = Trace.start("Read WAL header"); span.data("file", p.toString()); try {//from ww w . j a v a 2s . c o m input = getWalStream(p); } catch (LogHeaderIncompleteException e) { log.warn( "Could not read header from {}, assuming that there is no data present in the WAL, therefore replication is complete", p); Status newStatus; // Bump up the begin to the (infinite) end, trying to be accurate if (status.getInfiniteEnd()) { newStatus = Status.newBuilder(status).setBegin(Long.MAX_VALUE).build(); } else { newStatus = Status.newBuilder(status).setBegin(status.getEnd()).build(); } span = Trace.start("Update replication table"); try { helper.recordNewStatus(p, newStatus, target); } catch (TableNotFoundException tnfe) { log.error("Tried to update status in replication table for {} as {}, but the table did not exist", p, ProtobufUtil.toString(newStatus), e); throw new RuntimeException("Replication table did not exist, will retry", e); } finally { span.stop(); } return newStatus; } catch (IOException e) { log.error("Could not create stream for WAL", e); // No data sent (bytes nor records) and no progress made return status; } finally { span.stop(); } log.debug("Skipping unwanted data in WAL"); span = Trace.start("Consume WAL prefix"); span.data("file", p.toString()); try { // We want to read all records in the WAL up to the "begin" offset contained in the Status message, // building a Set of tids from DEFINE_TABLET events which correspond to table ids for future mutations tids = consumeWalPrefix(target, input, p, status, sizeLimit); } catch (IOException e) { log.warn("Unexpected error consuming file."); return status; } finally { span.stop(); } log.debug("Sending batches of data to peer tserver"); Status lastStatus = status, currentStatus = status; final AtomicReference<Exception> exceptionRef = new AtomicReference<>(); while (true) { // Set some trace info span = Trace.start("Replicate WAL batch"); span.data("Batch size (bytes)", Long.toString(sizeLimit)); span.data("File", p.toString()); span.data("Peer instance name", peerContext.getInstance().getInstanceName()); span.data("Peer tserver", peerTserver.toString()); span.data("Remote table ID", remoteTableId); ReplicationStats replResult; try { // Read and send a batch of mutations replResult = ReplicationClient.executeServicerWithReturn(peerContext, peerTserver, new WalClientExecReturn(target, input, p, currentStatus, sizeLimit, remoteTableId, tcreds, tids)); } catch (Exception e) { log.error("Caught exception replicating data to {} at {}", peerContext.getInstance().getInstanceName(), peerTserver, e); throw e; } finally { span.stop(); } // Catch the overflow long newBegin = currentStatus.getBegin() + replResult.entriesConsumed; if (newBegin < 0) { newBegin = Long.MAX_VALUE; } currentStatus = Status.newBuilder(currentStatus).setBegin(newBegin).build(); log.debug("Sent batch for replication of {} to {}, with new Status {}", p, target, ProtobufUtil.toString(currentStatus)); // If we got a different status if (!currentStatus.equals(lastStatus)) { span = Trace.start("Update replication table"); try { if (null != accumuloUgi) { final Status copy = currentStatus; accumuloUgi.doAs(new PrivilegedAction<Void>() { @Override public Void run() { try { helper.recordNewStatus(p, copy, target); } catch (Exception e) { exceptionRef.set(e); } return null; } }); Exception e = exceptionRef.get(); if (null != e) { if (e instanceof TableNotFoundException) { throw (TableNotFoundException) e; } else if (e instanceof AccumuloSecurityException) { throw (AccumuloSecurityException) e; } else if (e instanceof AccumuloException) { throw (AccumuloException) e; } else { throw new RuntimeException("Received unexpected exception", e); } } } else { helper.recordNewStatus(p, currentStatus, target); } } catch (TableNotFoundException e) { log.error( "Tried to update status in replication table for {} as {}, but the table did not exist", p, ProtobufUtil.toString(currentStatus), e); throw new RuntimeException("Replication table did not exist, will retry", e); } finally { span.stop(); } log.debug("Recorded updated status for {}: {}", p, ProtobufUtil.toString(currentStatus)); // If we don't have any more work, just quit if (!StatusUtil.isWorkRequired(currentStatus)) { return currentStatus; } else { // Otherwise, let it loop and replicate some more data lastStatus = currentStatus; } } else { log.debug("Did not replicate any new data for {} to {}, (state was {})", p, target, ProtobufUtil.toString(lastStatus)); // otherwise, we didn't actually replicate (likely because there was error sending the data) // we can just not record any updates, and it will be picked up again by the work assigner return status; } } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testJoin() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override/*from w w w.ja v a2 s. com*/ public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; this.stompSession.subscribe("/user/queue/device", null); try { JoinMessage join = new JoinMessage(); Device d = new Device(); d.setUuid(UUID.randomUUID()); join.setDevice(d); join.setGeo(new float[] { lat, lon }); join.setType(JoinMessage.Types.exit); join.setPoint(new int[] { 0, 0 }); join.setVector(new float[] { 1, 1 }); stompSession.send("/app/join", join); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("devices").exists(json); new JsonPathExpectationsHelper("devices").assertValueIsArray(json); new JsonPathExpectationsHelper("type").assertValue(json, "join"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Join response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testPair() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override/*from ww w.jav a2 s. c o m*/ public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; this.stompSession.subscribe("/user/queue/device", null); try { PairMessage pair = new PairMessage(); Device d = new Device(); d.setUuid(UUID.randomUUID()); pair.setDevice(d); pair.setType(PairMessage.Types.exit); pair.setGeo(new float[] { lat, lon }); pair.setPoint(new int[] { 0, 0 }); pair.setVector(new float[] { 1, 1 }); stompSession.send("/app/pair", pair); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("devices").exists(json); new JsonPathExpectationsHelper("devices").assertValueIsArray(json); new JsonPathExpectationsHelper("type").assertValue(json, "pair"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Pair response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java
@Override public void asyncDelete(final DeleteLedgerCallback callback, final Object ctx) { // Delete the managed ledger without closing, since we are not interested in gracefully closing cursors and // ledgers/*from w ww. ja v a 2s. c o m*/ STATE_UPDATER.set(this, State.Fenced); List<ManagedCursor> cursors = Lists.newArrayList(this.cursors); if (cursors.isEmpty()) { // No cursors to delete, proceed with next step deleteAllLedgers(callback, ctx); return; } AtomicReference<ManagedLedgerException> cursorDeleteException = new AtomicReference<>(); AtomicInteger cursorsToDelete = new AtomicInteger(cursors.size()); for (ManagedCursor cursor : cursors) { asyncDeleteCursor(cursor.getName(), new DeleteCursorCallback() { @Override public void deleteCursorComplete(Object ctx) { if (cursorsToDelete.decrementAndGet() == 0) { if (cursorDeleteException.get() != null) { // Some cursor failed to delete callback.deleteLedgerFailed(cursorDeleteException.get(), ctx); return; } // All cursors deleted, continue with deleting all ledgers deleteAllLedgers(callback, ctx); } } @Override public void deleteCursorFailed(ManagedLedgerException exception, Object ctx) { log.warn("[{}] Failed to delete cursor {}", name, cursor, exception); cursorDeleteException.compareAndSet(null, exception); if (cursorsToDelete.decrementAndGet() == 0) { // Trigger callback only once callback.deleteLedgerFailed(exception, ctx); } } }, null); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testUpdate() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override//from www . j a v a2 s . co m public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { HashMap<String, Object> update = new HashMap<String, Object>(); update.put("data", "TEST-UPDATE Data"); update.put("type", "update"); this.stompSession.send(String.format("/app/%s", topicUuid), update); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) throws MessagingException { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "update"); new JsonPathExpectationsHelper("serverTime").exists(json); new JsonPathExpectationsHelper("data").assertValue(json, "TEST-UPDATE Data"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Update response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testData() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override/*from w w w . ja v a 2s . c om*/ public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a simple hashmap to the data endpoint HashMap<String, Object> data = new HashMap<String, Object>(); data.put("data", "TEST-DATA Data"); data.put("type", "data"); this.stompSession.send(String.format("/app/%s", topicUuid), data); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "data"); new JsonPathExpectationsHelper("serverTime").exists(json); new JsonPathExpectationsHelper("data").assertValue(json, "TEST-DATA Data"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Data response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testDevices() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override// w w w .java 2 s . co m public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); // Call again to get a second device in the session simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a message to the devices endpoint HashMap<String, Object> devices = new HashMap<String, Object>(); devices.put("type", "devices"); this.stompSession.send(String.format("/app/%s", topicUuid), devices); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("devices").exists(json); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "devices"); new JsonPathExpectationsHelper("serverTime").exists(json); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Devices response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:io.realm.RealmTests.java
@Test public void executeTransaction_canceled() { final AtomicReference<RuntimeException> thrownException = new AtomicReference<>(null); assertEquals(0, realm.allObjects(Owner.class).size()); try {/*from w w w . ja v a2 s . com*/ realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); thrownException.set(new RuntimeException("Boom")); throw thrownException.get(); } }); } catch (RuntimeException e) { //noinspection ThrowableResultOfMethodCallIgnored assertTrue(e == thrownException.get()); } assertEquals(0, realm.allObjects(Owner.class).size()); }
From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java
/** * Delete this ManagedLedger completely from the system. * * @throws Exception/*from w w w. ja v a 2s . co m*/ */ @Override public void delete() throws InterruptedException, ManagedLedgerException { final CountDownLatch counter = new CountDownLatch(1); final AtomicReference<ManagedLedgerException> exception = new AtomicReference<>(); asyncDelete(new DeleteLedgerCallback() { @Override public void deleteLedgerComplete(Object ctx) { counter.countDown(); } @Override public void deleteLedgerFailed(ManagedLedgerException e, Object ctx) { exception.set(e); counter.countDown(); } }, null); if (!counter.await(AsyncOperationTimeoutSeconds, TimeUnit.SECONDS)) { throw new ManagedLedgerException("Timeout during managed ledger delete operation"); } if (exception.get() != null) { log.error("[{}] Error deleting managed ledger", name, exception.get()); throw exception.get(); } }