Search in sources :

Example 6 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project cassandra by apache.

the class LocalSessions method handlePrepareMessage.

/**
     * The PrepareConsistentRequest effectively promotes the parent repair session to a consistent
     * incremental session, and begins the 'pending anti compaction' which moves all sstable data
     * that is to be repaired into it's own silo, preventing it from mixing with other data.
     *
     * No response is sent to the repair coordinator until the pending anti compaction has completed
     * successfully. If the pending anti compaction fails, a failure message is sent to the coordinator,
     * cancelling the session.
     */
public void handlePrepareMessage(InetAddress from, PrepareConsistentRequest request) {
    logger.debug("received {} from {}", request, from);
    UUID sessionID = request.parentSession;
    InetAddress coordinator = request.coordinator;
    Set<InetAddress> peers = request.participants;
    ActiveRepairService.ParentRepairSession parentSession;
    try {
        parentSession = getParentRepairSession(sessionID);
    } catch (Throwable e) {
        logger.debug("Error retrieving ParentRepairSession for session {}, responding with failure", sessionID);
        sendMessage(coordinator, new FailSession(sessionID));
        return;
    }
    LocalSession session = createSessionUnsafe(sessionID, parentSession, peers);
    putSessionUnsafe(session);
    logger.debug("created local session for {}", sessionID);
    ExecutorService executor = Executors.newFixedThreadPool(parentSession.getColumnFamilyStores().size());
    ListenableFuture pendingAntiCompaction = submitPendingAntiCompaction(session, executor);
    Futures.addCallback(pendingAntiCompaction, new FutureCallback() {

        public void onSuccess(@Nullable Object result) {
            logger.debug("pending anti-compaction for {} completed", sessionID);
            setStateAndSave(session, PREPARED);
            sendMessage(coordinator, new PrepareConsistentResponse(sessionID, getBroadcastAddress(), true));
            executor.shutdown();
        }

        public void onFailure(Throwable t) {
            logger.debug("pending anti-compaction for {} failed", sessionID);
            failSession(sessionID);
            executor.shutdown();
        }
    });
}
Also used : ActiveRepairService(org.apache.cassandra.service.ActiveRepairService) PrepareConsistentResponse(org.apache.cassandra.repair.messages.PrepareConsistentResponse) FailSession(org.apache.cassandra.repair.messages.FailSession) ExecutorService(java.util.concurrent.ExecutorService) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) UUID(java.util.UUID) InetAddress(java.net.InetAddress) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 7 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project flink by apache.

the class CassandraTupleWriteAheadSink method sendValues.

@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
        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;
    }
}
Also used : ResultSetFuture(com.datastax.driver.core.ResultSetFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSet(com.datastax.driver.core.ResultSet) AtomicReference(java.util.concurrent.atomic.AtomicReference) BoundStatement(com.datastax.driver.core.BoundStatement) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 8 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project binnavi by google.

the class OpenInLastWindowAndZoomToAddressAction method actionPerformed.

@Override
public void actionPerformed(final ActionEvent event) {
    final FutureCallback<Boolean> callBack = new FutureCallback<Boolean>() {

        @Override
        public void onFailure(final Throwable t) {
            CUtilityFunctions.logException(t);
        }

        @Override
        public void onSuccess(final Boolean result) {
            ZyGraph graph = null;
            final List<CGraphWindow> windows = CWindowManager.instance().getOpenWindows();
            for (final CGraphWindow graphContainer : windows) {
                for (final IGraphPanel window : graphContainer) {
                    if (reference.getView().equals(window.getModel().getGraph().getRawView())) {
                        graph = window.getModel().getGraph();
                    }
                }
            }
            for (final NaviNode node : graph.getNodes()) {
                if (node.getRawNode() instanceof INaviCodeNode) {
                    final INaviCodeNode codeNode = (INaviCodeNode) node.getRawNode();
                    for (final INaviInstruction instruction : codeNode.getInstructions()) {
                        if (instruction.getAddress().equals(reference.getAddress())) {
                            ZyZoomHelpers.zoomToAddress(graph, reference.getAddress());
                            CrossReferencePainter.paintCrossReference(node, codeNode, reference, instruction);
                        }
                    }
                }
            }
        }
    };
    CShowViewFunctions.showViewsAndPerformCallBack(m_parent, m_container, m_views, CWindowManager.instance().getLastWindow(), callBack);
}
Also used : CGraphWindow(com.google.security.zynamics.binnavi.Gui.GraphWindows.CGraphWindow) INaviCodeNode(com.google.security.zynamics.binnavi.disassembly.INaviCodeNode) ZyGraph(com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph) IGraphPanel(com.google.security.zynamics.binnavi.Gui.GraphWindows.IGraphPanel) NaviNode(com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode) FutureCallback(com.google.common.util.concurrent.FutureCallback) INaviInstruction(com.google.security.zynamics.binnavi.disassembly.INaviInstruction)

Example 9 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project Minigames by AddstarMC.

the class BackendCommand method onCommand.

@Override
public boolean onCommand(final CommandSender sender, Minigame minigame, String label, String[] args) {
    if (args == null || args.length != 2) {
        return false;
    }
    BackendManager manager = Minigames.plugin.getBackend();
    if (args[0].equalsIgnoreCase("export")) {
        try {
            ListenableFuture<Void> future = manager.exportTo(args[1], Minigames.plugin.getConfig(), new Notifier(sender));
            sender.sendMessage(ChatColor.GOLD + "Exporting backend to " + args[1] + "...");
            Futures.addCallback(future, new FutureCallback<Void>() {

                @Override
                public void onFailure(Throwable t) {
                    sender.sendMessage(ChatColor.RED + "An internal error occured while exporting.");
                }

                @Override
                public void onSuccess(Void result) {
                }
            });
        } catch (IllegalArgumentException e) {
            sender.sendMessage(ChatColor.RED + e.getMessage());
        }
    } else if (args[0].equalsIgnoreCase("switch")) {
        try {
            ListenableFuture<Void> future = manager.switchBackend(args[1], Minigames.plugin.getConfig());
            sender.sendMessage(ChatColor.GOLD + "Switching minigames backend to " + args[1] + "...");
            Futures.addCallback(future, new FutureCallback<Void>() {

                @Override
                public void onFailure(Throwable t) {
                    sender.sendMessage(ChatColor.RED + "An internal error occured while switching backend.");
                }

                @Override
                public void onSuccess(Void result) {
                    sender.sendMessage(ChatColor.GOLD + "The backend has been successfully switched");
                    sender.sendMessage(ChatColor.GOLD + "!!! This change is " + ChatColor.BOLD + "temporary" + ChatColor.GOLD + ". Please update the config !!!");
                }
            });
        } catch (IllegalArgumentException e) {
            sender.sendMessage(ChatColor.RED + e.getMessage());
        }
    } else {
        sender.sendMessage(ChatColor.RED + "Unknown option " + args[0]);
    }
    return true;
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BackendManager(au.com.mineauz.minigames.backend.BackendManager) FutureCallback(com.google.common.util.concurrent.FutureCallback) ExportNotifier(au.com.mineauz.minigames.backend.ExportNotifier)

Example 10 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project android by JetBrains.

the class DumpSysAction method performAction.

public void performAction() {
    final CountDownLatch completionLatch = new CountDownLatch(1);
    final CollectingOutputReceiver receiver = new CollectingOutputReceiver();
    String description = myClient == null ? null : myClient.getClientData().getClientDescription();
    final String pkgName = description != null ? description : "";
    final String command = String.format(Locale.US, "dumpsys %1$s %2$s", myService, pkgName).trim();
    ApplicationManager.getApplication().invokeAndWait(new Runnable() {

        @Override
        public void run() {
            ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        myDevice.executeShellCommand(command, receiver, 0, null);
                        ApplicationManager.getApplication().invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    final CaptureService service = CaptureService.getInstance(myProject);
                                    String name = service.getSuggestedName(myClient);
                                    CaptureHandle handle = service.startCaptureFile(SystemInfoCaptureType.class, name, false);
                                    service.appendData(handle, receiver.getOutput().getBytes());
                                    service.finalizeCaptureFileAsynchronous(handle, new FutureCallback<Capture>() {

                                        @Override
                                        public void onSuccess(@Nullable Capture result) {
                                            if (result != null) {
                                                result.getFile().refresh(true, false);
                                                service.notifyCaptureReady(result);
                                            }
                                        }

                                        @Override
                                        public void onFailure(@NotNull Throwable t) {
                                            showError(myProject, "Unexpected error while saving system information", t);
                                        }
                                    }, EdtExecutor.INSTANCE);
                                } catch (IOException e) {
                                    showError(myProject, "Unexpected error while saving system information", e);
                                }
                            }
                        });
                    } catch (Exception e) {
                        showError(myProject, "Unexpected error while obtaining system information", e);
                    } finally {
                        completionLatch.countDown();
                    }
                }
            });
            new ShellTask(myProject, completionLatch, receiver).queue();
        }
    });
}
Also used : CollectingOutputReceiver(com.android.ddmlib.CollectingOutputReceiver) CaptureService(com.android.tools.idea.profiling.capture.CaptureService) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) NotNull(org.jetbrains.annotations.NotNull) Capture(com.android.tools.idea.profiling.capture.Capture) IOException(java.io.IOException) SystemInfoCaptureType(com.android.tools.idea.editors.systeminfo.SystemInfoCaptureType) CaptureHandle(com.android.tools.idea.profiling.capture.CaptureHandle) FutureCallback(com.google.common.util.concurrent.FutureCallback) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

FutureCallback (com.google.common.util.concurrent.FutureCallback)20 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)7 IOException (java.io.IOException)6 List (java.util.List)3 Nullable (javax.annotation.Nullable)3 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 ImmutableList (com.google.common.collect.ImmutableList)2 Futures (com.google.common.util.concurrent.Futures)2 ListeningExecutorService (com.google.common.util.concurrent.ListeningExecutorService)2 SettableFuture (com.google.common.util.concurrent.SettableFuture)2 SegmentDescriptor (io.druid.query.SegmentDescriptor)2 Map (java.util.Map)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 KeeperException (org.apache.zookeeper.KeeperException)2 Watcher (org.apache.zookeeper.Watcher)2 NotNull (org.jetbrains.annotations.NotNull)2 Nullable (org.jetbrains.annotations.Nullable)2 BackendManager (au.com.mineauz.minigames.backend.BackendManager)1 ExportNotifier (au.com.mineauz.minigames.backend.ExportNotifier)1 ResourceModifier (co.cask.cdap.common.zookeeper.coordination.ResourceModifier)1