List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback
FutureCallback
From source file:org.opendaylight.netvirt.elan.l2gw.jobs.DeleteL2GwDeviceMacsFromElanJob.java
@Override public List<ListenableFuture<Void>> call() { LOG.debug("Deleting l2gw device [{}] macs from other l2gw devices for elan [{}]", this.l2GwDevice.getHwvtepNodeId(), this.elanName); final String logicalSwitchName = ElanL2GatewayUtils.getLogicalSwitchFromElan(this.elanName); ConcurrentMap<String, L2GatewayDevice> elanL2GwDevices = ElanL2GwCacheUtils .getInvolvedL2GwDevices(this.elanName); List<ListenableFuture<Void>> futures = new ArrayList<>(); for (L2GatewayDevice otherDevice : elanL2GwDevices.values()) { if (!otherDevice.getHwvtepNodeId().equals(this.l2GwDevice.getHwvtepNodeId()) && !ElanL2GatewayUtils.areMLAGDevices(this.l2GwDevice, otherDevice)) { final String hwvtepId = otherDevice.getHwvtepNodeId(); // never batch deletes ListenableFuture<Void> uninstallFuture = HwvtepUtils.deleteRemoteUcastMacs(this.broker, new NodeId(hwvtepId), logicalSwitchName, this.macAddresses); Futures.addCallback(uninstallFuture, new FutureCallback<Void>() { @Override// w w w . j a v a 2 s . co m public void onSuccess(Void noarg) { LOG.trace("Successful in initiating ucast_remote_macs deletion related to {} in {}", logicalSwitchName, hwvtepId); } @Override public void onFailure(Throwable error) { LOG.error(String.format("Failed removing ucast_remote_macs related to %s in %s", logicalSwitchName, hwvtepId), error); } }); futures.add(uninstallFuture); } } return futures; }
From source file:com.google.cloud.pubsub.spi.v1.PollingSubscriberConnection.java
private void initialize() { ListenableFuture<Subscription> subscriptionInfo = stub .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS) .getSubscription(GetSubscriptionRequest.newBuilder().setSubscription(subscription).build()); Futures.addCallback(subscriptionInfo, new FutureCallback<Subscription>() { @Override//from w w w .jav a 2 s. c o m public void onSuccess(Subscription result) { messageDispatcher.setMessageDeadlineSeconds(result.getAckDeadlineSeconds()); pullMessages(INITIAL_BACKOFF); } @Override public void onFailure(Throwable cause) { notifyFailed(cause); } }); }
From source file:us.physion.ovation.ui.editor.PlainTextVisualizationFactory.java
@Override public DataVisualization createVisualization(final Content r) { return new AbstractDataVisualization() { @Override//from www.j a va2 s . co m public JComponent generatePanel() { class PlainTextArea extends JTextArea { private boolean scrollableTracksViewportWidth = false; @Override public boolean getScrollableTracksViewportWidth() { return scrollableTracksViewportWidth; } private void setScrollableTracksViewportWidth(boolean b) { if (b == scrollableTracksViewportWidth) { return; } scrollableTracksViewportWidth = b; } private void failed() { setText(Bundle.LBL_TextLoadingFailed(ContentUtils.contentLabel(r))); } @Override public void addNotify() { super.addNotify(); ListenableFuture<File> data; try { data = r.getData(); } catch (ResourceNotFoundException ex) { log.warn("Resource not found", ex); failed(); return; } Futures.addCallback(data, new FutureCallback<File>() { @Override public void onSuccess(File f) { try { FileReader fr = new FileReader(f); try { final String text = IOUtils.toString(fr); EventQueue.invokeLater(new Runnable() { @Override public void run() { setText(text); setCaretPosition(0); repaint(); } }); } finally { IOUtils.closeQuietly(fr); } } catch (IOException ex) { log.warn("Could not load text", ex); failed(); } } @Override public void onFailure(Throwable ex) { log.warn("Could not get file", ex); failed(); } }, loadFileExecutors); } } final PlainTextArea t = new PlainTextArea(); t.setEditable(false); t.setText(Bundle.LBL_TextLoading()); ParentWidthPanel panel = new ParentWidthPanel(); panel.add(new JScrollPane(t), BorderLayout.CENTER); { JToolBar toolbar = new JToolBar(SwingConstants.HORIZONTAL); toolbar.setBackground(Color.WHITE); toolbar.add(new JToggleButton(new AbstractAction(Bundle.LBL_LineWrap()) { @Override public void actionPerformed(ActionEvent e) { boolean selected = ((JToggleButton) e.getSource()).isSelected(); t.setLineWrap(selected); t.setScrollableTracksViewportWidth(selected); t.setCaretPosition(0); t.revalidate(); t.repaint(); } })); panel.add(toolbar, BorderLayout.NORTH); } return panel; } @Override public boolean shouldAdd(Content r) { return false; } @Override public void add(Content r) { throw new UnsupportedOperationException(); } @Override public Iterable<? extends OvationEntity> getEntities() { return Sets.newHashSet((OvationEntity) r); } }; }
From source file:org.opendaylight.groupbasedpolicy.renderer.apic.ApicRenderer.java
private void readConfig() { ListenableFuture<Optional<ApicConfig>> dao = dataBroker.newReadOnlyTransaction() .read(LogicalDatastoreType.CONFIGURATION, configIid); Futures.addCallback(dao, new FutureCallback<Optional<ApicConfig>>() { @Override//from w ww. j a va 2 s. c o m public void onSuccess(final Optional<ApicConfig> result) { if (!result.isPresent()) return; if (result.get() instanceof ApicConfig) { config = (ApicConfig) result.get(); applyConfig(); } } @Override public void onFailure(Throwable t) { LOG.error("Failed to read configuration", t); } }, executor); }
From source file:org.apache.flink.streaming.connectors.cassandra.CassandraRowWriteAheadSink.java
@Override protected boolean sendValues(Iterable<Row> values, long checkpointId, long timestamp) throws Exception { final AtomicInteger updatesCount = new AtomicInteger(0); final AtomicInteger updatesConfirmed = new AtomicInteger(0); final AtomicReference<Throwable> exception = new AtomicReference<>(); FutureCallback<ResultSet> callback = new FutureCallback<ResultSet>() { @Override//from ww w .j av a 2 s . com public void onSuccess(ResultSet resultSet) { updatesConfirmed.incrementAndGet(); if (updatesCount.get() > 0) { // only set if all updates have been sent if (updatesCount.get() == updatesConfirmed.get()) { synchronized (updatesConfirmed) { updatesConfirmed.notifyAll(); } } } } @Override public void onFailure(Throwable throwable) { if (exception.compareAndSet(null, throwable)) { LOG.error("Error while sending value.", throwable); synchronized (updatesConfirmed) { updatesConfirmed.notifyAll(); } } } }; //set values for prepared statement int updatesSent = 0; for (Row value : values) { for (int x = 0; x < arity; x++) { fields[x] = value.getField(x); } //insert values and send to cassandra BoundStatement s = preparedStatement.bind(fields); s.setDefaultTimestamp(timestamp); ResultSetFuture result = session.executeAsync(s); updatesSent++; if (result != null) { //add callback to detect errors Futures.addCallback(result, callback); } } updatesCount.set(updatesSent); synchronized (updatesConfirmed) { while (exception.get() == null && updatesSent != updatesConfirmed.get()) { updatesConfirmed.wait(); } } if (exception.get() != null) { LOG.warn("Sending a value failed.", exception.get()); return false; } else { return true; } }
From source file:org.opendaylight.router.UserDataHandler.java
public void deleteDataFromOprDataStore(InstanceIdentifier<?> iid) { WriteTransaction wtx = dataBroker.newWriteOnlyTransaction(); wtx.delete(LogicalDatastoreType.OPERATIONAL, iid); CheckedFuture<Void, TransactionCommitFailedException> future = wtx.submit(); Futures.addCallback(future, new FutureCallback<Void>() { @Override//w ww. j av a 2 s .c o m public void onSuccess(Void result) { LOG.info("deleted the subinterface"); } @Override public void onFailure(Throwable t) { LOG.info("failed to delete the subinterface"); } }); }
From source file:com.palantir.giraffe.internal.ProcessStreamHandler.java
private void submitCopier(StreamCopier copier, Executor executor) { ListenableFutureTask<Void> task = ListenableFutureTask.create(copier); Futures.addCallback(task, new FutureCallback<Void>() { @Override/* w w w . j a v a2 s . c om*/ public void onSuccess(Void result) { copierLatch.countDown(); } @Override public void onFailure(Throwable t) { copierLatch.countDown(); for (ExceptionListener listener : listeners) { listener.onException(t); } } }); executor.execute(task); }
From source file:xyz.cloudbans.bukkit.command.TempBanCommand.java
@Override public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { // /tempban <player> <duration> <reason> if (!sender.hasPermission("cloudbans.ban.tempban")) { sender.sendMessage(ChatColor.RED + "You don't have enough permissions for that."); return true; }//from w ww .ja v a2 s .c om if (args.length < 2) { sender.sendMessage(ChatColor.RED + "Your missing arguments for this command."); return false; } if (sender instanceof BlockCommandSender) { sender.sendMessage(ChatColor.RED + "For security reasons this command can only executed by a player or the console!"); return true; } BanRequestBuilder builder = new BanRequestBuilder(); builder.setServer(config.getServerUuid()); if (args.length > 2) { String[] reason = Arrays.copyOfRange(args, 2, args.length); String finalReason = Joiner.on(" ").join(reason); builder.setDescription(finalReason); } if (sender instanceof Player) { builder.setIssuer(((Player) sender).getUniqueId()); } try { builder.setValidUntil(TimeParser.addToNow(args[1])); } catch (NumberFormatException exception) { sender.sendMessage(ChatColor.RED + "The given time is invalid."); } BanRequest request = builder.build(); CommandUtils.parseTarget(request, args[0]); Future<BanResponse> future = client.createBan(request); Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future, executor), new FutureCallback<BanResponse>() { @Override public void onSuccess(BanResponse result) { switch (result.getBan().getDelayState()) { case EXECUTED: sender.sendMessage(ChatColor.GREEN + "Ban executed"); break; case QUEUED: sender.sendMessage(ChatColor.GREEN + "Ban will be executed soon."); break; } } @Override public void onFailure(Throwable t) { sender.sendMessage(ChatColor.RED + "Ban was not executed successfully."); LOGGER.log(Level.SEVERE, "An error occurred while executing ban request.", t); } }); return true; }
From source file:org.apache.flink.streaming.connectors.cassandra.CassandraTupleWriteAheadSink.java
@Override protected boolean sendValues(Iterable<IN> values, long timestamp) throws Exception { final AtomicInteger updatesCount = new AtomicInteger(0); final AtomicInteger updatesConfirmed = new AtomicInteger(0); final AtomicReference<Throwable> exception = new AtomicReference<>(); FutureCallback<ResultSet> callback = new FutureCallback<ResultSet>() { @Override//from www.jav a2 s . co m public void onSuccess(ResultSet resultSet) { updatesConfirmed.incrementAndGet(); if (updatesCount.get() > 0) { // only set if all updates have been sent if (updatesCount.get() == updatesConfirmed.get()) { synchronized (updatesConfirmed) { updatesConfirmed.notifyAll(); } } } } @Override public void onFailure(Throwable throwable) { if (exception.compareAndSet(null, throwable)) { LOG.error("Error while sending value.", throwable); synchronized (updatesConfirmed) { updatesConfirmed.notifyAll(); } } } }; //set values for prepared statement int updatesSent = 0; for (IN value : values) { for (int x = 0; x < value.getArity(); x++) { fields[x] = value.getField(x); } //insert values and send to cassandra BoundStatement s = preparedStatement.bind(fields); s.setDefaultTimestamp(timestamp); ResultSetFuture result = session.executeAsync(s); updatesSent++; if (result != null) { //add callback to detect errors Futures.addCallback(result, callback); } } updatesCount.set(updatesSent); synchronized (updatesConfirmed) { while (exception.get() == null && updatesSent != updatesConfirmed.get()) { updatesConfirmed.wait(); } } if (exception.get() != null) { LOG.warn("Sending a value failed.", exception.get()); return false; } else { return true; } }
From source file:com.spotify.folsom.reconnect.ReconnectingClient.java
private void retry() { try {//w ww .j ava 2 s. c o m final ListenableFuture<RawMemcacheClient> future = connector.connect(); Futures.addCallback(future, new FutureCallback<RawMemcacheClient>() { @Override public void onSuccess(final RawMemcacheClient result) { log.info("Successfully connected to {}", address); reconnectCount = 0; client = result; notifyConnectionChange(); Futures.addCallback(ConnectFuture.disconnectFuture(result), new FutureCallback<Void>() { @Override public void onSuccess(final Void ignore) { log.info("Lost connection to {}", address); notifyConnectionChange(); if (stayConnected) { retry(); } } @Override public void onFailure(final Throwable t) { throw new RuntimeException("Programmer bug - this should be unreachable"); } }); } @Override public void onFailure(final Throwable t) { ReconnectingClient.this.onFailure(); } }); } catch (final Exception e) { ReconnectingClient.this.onFailure(); } }