Example usage for com.google.common.util.concurrent FutureCallback FutureCallback

List of usage examples for com.google.common.util.concurrent FutureCallback FutureCallback

Introduction

In this page you can find the example usage for com.google.common.util.concurrent FutureCallback FutureCallback.

Prototype

FutureCallback

Source Link

Usage

From source file:org.apache.hadoop.hive.ql.exec.tez.SampleTezSessionState.java

@Override
public SettableFuture<WmTezSession> waitForAmRegistryAsync(int timeoutMs,
        ScheduledExecutorService timeoutPool) {
    final SampleTezSessionState session = this;
    final SettableFuture<WmTezSession> future = SettableFuture.create();
    Futures.addCallback(waitForAmRegFuture, new FutureCallback<Boolean>() {
        @Override/*from ww  w  .  ja va2  s.c  om*/
        public void onSuccess(Boolean result) {
            future.set(session);
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });
    return future;
}

From source file:org.apache.qpid.server.virtualhostnode.RedirectingVirtualHostNodeImpl.java

@StateTransition(currentState = { State.UNINITIALIZED, State.STOPPED,
        State.ERRORED }, desiredState = State.ACTIVE)
private ListenableFuture<Void> doActivate() {
    final SettableFuture<Void> resultFuture = SettableFuture.create();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(ConfiguredObject.NAME, getName());
    attributes.put(ConfiguredObject.TYPE, RedirectingVirtualHostImpl.VIRTUAL_HOST_TYPE);

    final ListenableFuture<VirtualHost> virtualHostFuture = getObjectFactory().createAsync(VirtualHost.class,
            attributes, this);

    addFutureCallback(virtualHostFuture, new FutureCallback<VirtualHost>() {
        @Override/* www. j a  va 2s. c  om*/
        public void onSuccess(final VirtualHost virtualHost) {
            _virtualHost = (RedirectingVirtualHostImpl) virtualHost;
            setState(State.ACTIVE);
            resultFuture.set(null);

        }

        @Override
        public void onFailure(final Throwable t) {
            setState(State.ERRORED);
            if (((Broker) getParent()).isManagementMode()) {
                LOGGER.warn("Failed to make {} active.", this, t);
                resultFuture.set(null);
            } else {
                resultFuture.setException(t);
            }
        }
    }, getTaskExecutor());

    return resultFuture;
}

From source file:org.dcache.poolmanager.PoolManagerHandlerSubscriber.java

@PostConstruct
public synchronized void start() {
    current = transformAsync(startGate,//from w  w  w.  j av  a2s .  co m
            ignored -> CellStub.transform(query(new PoolMgrGetHandler()), PoolMgrGetHandler::getHandler));

    Futures.addCallback(current, new FutureCallback<SerializablePoolManagerHandler>() {
        @Override
        public void onSuccess(SerializablePoolManagerHandler handler) {
            synchronized (PoolManagerHandlerSubscriber.this) {
                try {
                    current = Futures.immediateFuture(handler);
                    if (!isStopped) {
                        ListenableFuture<SerializablePoolManagerHandler> next = CellStub.transform(
                                query(new PoolMgrGetUpdatedHandler(handler.getVersion())),
                                PoolMgrGetHandler::getHandler);
                        Futures.addCallback(next, this);
                    }
                } catch (Throwable t) {
                    current = Futures.immediateFailedFuture(t);
                    LOGGER.error(
                            "Failure in pool manager handler subscriber. Please report to support@dcache.org.",
                            t);
                    throw t;
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            synchronized (PoolManagerHandlerSubscriber.this) {
                current = Futures.immediateFailedFuture(t);
            }
        }
    });
}

From source file:com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationContext.java

public ListenableFuture<AuthenticationResult> acquireTokenInteractiveAsync(final String tenantName,
        final String resource, final String clientId, final String redirectUri, final Project project,
        final String windowTitle, final String promptValue) throws IOException {

    final SettableFuture<AuthenticationResult> future = SettableFuture.create();

    // get the auth code
    ListenableFuture<String> authCodeFuture = acquireAuthCodeInteractiveAsync(tenantName, resource, clientId,
            redirectUri, project, windowTitle, promptValue);
    Futures.addCallback(authCodeFuture, new FutureCallback<String>() {
        @Override/* w  w w .  j a va  2s. c  o  m*/
        public void onSuccess(String code) {
            OutputStream output = null;
            BufferedReader reader = null;

            try {
                // if code is null then the user cancelled the auth
                if (code == null) {
                    future.set(null);
                    return;
                }

                URL adAuthEndpointUrl = new URL(
                        TOKEN_ENDPOINT_TEMPLATE.replace("{host}", authority).replace("{tenant}", tenantName));

                // build the a/d auth params
                Map<String, String> params = new HashMap<String, String>();
                params.put(OAuthParameter.clientId, clientId);
                params.put(OAuthParameter.code, code);
                params.put(OAuthParameter.grantType, OAuthGrantType.AuthorizationCode);
                params.put(OAuthParameter.redirectUri, redirectUri);
                params.put(OAuthParameter.resource, resource);
                byte[] requestData = EncodingHelper.toQueryString(params).getBytes(Charsets.UTF_8);

                // make a POST request to the endpoint with this data
                HttpURLConnection connection = (HttpURLConnection) adAuthEndpointUrl.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded; charset=" + Charsets.UTF_8.name());
                connection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
                output = connection.getOutputStream();
                output.write(requestData);
                output.close();
                output = null;

                // read the response
                int statusCode = connection.getResponseCode();
                if (statusCode != HttpURLConnection.HTTP_OK) {
                    // TODO: Is IOException the right exception type to raise?
                    String err = CharStreams.toString(new InputStreamReader(connection.getErrorStream()));
                    future.setException(new IOException("AD Auth token endpoint returned HTTP status code "
                            + Integer.toString(statusCode) + ". Error info: " + err));
                    return;
                }

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                reader.close();
                reader = null;

                // parse the JSON
                String response = sb.toString();
                JsonParser parser = new JsonParser();
                JsonObject root = (JsonObject) parser.parse(response);

                // construct the authentication result object
                AuthenticationResult result = new AuthenticationResult(
                        getJsonStringProp(root, OAuthReservedClaim.TokenType),
                        getJsonStringProp(root, OAuthReservedClaim.AccessToken),
                        getJsonStringProp(root, OAuthReservedClaim.RefreshToken),
                        getJsonLongProp(root, OAuthReservedClaim.ExpiresOn),
                        UserInfo.parse(getJsonStringProp(root, OAuthReservedClaim.IdToken)));
                future.set(result);

            } catch (MalformedURLException e) {
                future.setException(e);
            } catch (ProtocolException e) {
                future.setException(e);
            } catch (IOException e) {
                future.setException(e);
            } catch (ParseException e) {
                future.setException(e);
            } finally {
                try {
                    if (output != null) {
                        output.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException ignored) {
                }
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            future.setException(throwable);
        }
    });

    return future;
}

From source file:xyz.cloudbans.bukkit.command.NoticeCommand.java

@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
    // /notice <player> <notice>
    if (!sender.hasPermission("cloudbans.notice.notice")) {
        sender.sendMessage(ChatColor.RED + "You don't have enough permissions for that.");
        return true;
    }/*from w  w w  .j  ava 2  s .  c o  m*/

    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;
    }

    NoticeRequestBuilder builder = new NoticeRequestBuilder();
    builder.setServer(config.getServerUuid());

    if (args.length > 1) {
        String[] notice = Arrays.copyOfRange(args, 1, args.length);
        String finalNotice = Joiner.on(" ").join(notice);
        builder.setNotice(finalNotice);
    }

    if (sender instanceof Player) {
        builder.setIssuer(((Player) sender).getUniqueId());
    }

    final NoticeRequest request = builder.build();
    CommandUtils.parseTarget(request, args[0]);

    Future<NoticeResponse> future = client.createNotice(request);
    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future, executor),
            new FutureCallback<NoticeResponse>() {
                @Override
                public void onSuccess(NoticeResponse result) {
                    switch (result.getNotice().getDelayState()) {
                    case EXECUTED:
                        sender.sendMessage(ChatColor.GREEN + "Notice executed");
                        break;
                    case QUEUED:
                        sender.sendMessage(ChatColor.GREEN + "Notice will be executed soon.");
                        break;
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    sender.sendMessage(ChatColor.RED + "Notice was not executed successfully.");
                    LOGGER.log(Level.SEVERE, "An error occured while executing notice request.", t);
                }
            });
    return true;
}

From source file:com.example.office.ui.calendar.EventFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mInflater = inflater;/*w w w .  ja va2 s. c  o  m*/
    View rootView = inflater.inflate(getFragmentLayoutId(), container, false);

    try {
        Activity activity = getActivity();
        activity.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        Intent intent = getActivity().getIntent();
        event = (Event) intent.getExtras().get(getActivity().getString(R.string.intent_event_key));
        displayEvent(rootView);
        getActivity().setProgressBarIndeterminateVisibility(false);

        // Code below will be invoked when we receive system intent holding the path to shared image and this image is transformed into bytes[].
        mImagePicker = new ImagePicker(getActivity(), getActivity().getString(R.string.intent_event_key)) {
            @Override
            public void processImage(final byte[] imageBytes, final String fileName, final Object intentArg) {
                try {
                    String itemId = "";
                    if (intentArg instanceof Event) {
                        itemId = ((Event) intentArg).getId();
                    }

                    if (!TextUtils.isEmpty(itemId)) {
                        // Getting event by id
                        Futures.addCallback(Me.getEvents().getAsync(itemId), new FutureCallback<IEvent>() {
                            @Override
                            public void onFailure(Throwable t) {
                                if (!onError(t)) {
                                    mImagePicker.showStatusToast(Status.UPLOAD_FAILED);
                                }
                            }

                            @Override
                            public void onSuccess(IEvent event) {
                                try {
                                    IFileAttachment attachment = event.getAttachments().newFileAttachment();
                                    attachment.setContentBytes(imageBytes).setName(fileName);
                                    // Propagating changes to server
                                    Me.flush();

                                    mImagePicker.showStatusToast(Status.UPLOAD_SUCCESS);
                                } catch (Exception e) {
                                    onFailure(e);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    if (!onError(e)) {
                        mImagePicker.showStatusToast(Status.UPLOAD_FAILED);
                    }
                }
            }
        };
    } catch (Exception e) {
        Logger.logApplicationException(e, getClass().getSimpleName() + ".onCreateView(): Error.");
    }

    return rootView;
}

From source file:com.newlandframework.rpc.netty.MessageRecvExecutor.java

public static void submit(Callable<Boolean> task, final ChannelHandlerContext ctx, final MessageRequest request,
        final MessageResponse response) {
    if (threadPoolExecutor == null) {
        synchronized (MessageRecvExecutor.class) {
            if (threadPoolExecutor == null) {
                threadPoolExecutor = MoreExecutors
                        .listeningDecorator((ThreadPoolExecutor) (RpcSystemConfig.isMonitorServerSupport()
                                ? RpcThreadPool.getExecutorWithJmx(threadNums, queueNums)
                                : RpcThreadPool.getExecutor(threadNums, queueNums)));
            }/*from   w  ww .  j a  va  2  s  .c o m*/
        }
    }

    ListenableFuture<Boolean> listenableFuture = threadPoolExecutor.submit(task);
    Futures.addCallback(listenableFuture, new FutureCallback<Boolean>() {
        public void onSuccess(Boolean result) {
            ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("RPC Server Send message-id respone:" + request.getMessageId());
                }
            });
        }

        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    }, threadPoolExecutor);
}

From source file:org.excalibur.core.util.concurrent.Futures2.java

public static <V> List<V> invokeAllAndShutdownWhenFinish(List<Callable<V>> tasks,
        ListeningExecutorService executor, FutureCallback<V>[] callbacks) {
    final List<V> results = Lists.newArrayList();
    final CountDownLatch endSignal = new CountDownLatch(tasks.size());

    FutureCallback<V> endSignalCallback = new FutureCallback<V>() {
        @Override//from www.j  ava2s  .  co  m
        public void onSuccess(@Nullable V result) {
            endSignal.countDown();
            results.add(result);
        }

        @Override
        public void onFailure(Throwable t) {
            endSignal.countDown();
        }
    };

    List<FutureCallback<V>> l = Lists.newArrayList(callbacks);
    l.add(endSignalCallback);

    invokeAll(tasks, executor, l.toArray(new FutureCallback[l.size()]));

    try {
        endSignal.await();
        executor.shutdownNow();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return results;
}

From source file:com.vmware.photon.controller.clustermanager.statuschecks.MesosStatusChecker.java

private void checkStatus(String nodeAddress, final FutureCallback<String> callback) throws IOException {
    Preconditions.checkNotNull(nodeAddress, "nodeAddress cannot be null");
    logger.info("Checking Mesos: {}", nodeAddress);

    String connectionString = createConnectionString(nodeAddress);
    mesosClient.getMasterLeader(connectionString, new FutureCallback<String>() {
        @Override// ww w.j av a  2s.  c o  m
        public void onSuccess(@Nullable String leaderConnectionString) {
            callback.onSuccess(leaderConnectionString);
        }

        @Override
        public void onFailure(Throwable t) {
            logger.warn("Mesos call failed: ", t);
            callback.onFailure(t);
        }
    });
}

From source file:com.facebook.buck.intellij.plugin.autodeps.BuckAutoDepsContributor.java

public void addDependency(final Optional<VirtualFile> importClass, final Optional<VirtualFile> currentClass) {
    if (!importClass.isPresent() || !currentClass.isPresent()) {
        return;//from  ww  w. j a  v a2s  . co m
    }
    BuckAuditOwner.execute(mProject, new FutureCallback<String>() {
        @Override
        public void onSuccess(@Nullable String buckTargetResult) {
            try {
                String currentClassPath = currentClass.get().getPath();
                Map<String, List<String>> pathAndTargetData = mObjectMapper.readValue(buckTargetResult,
                        Map.class);
                String importTargetName = "";
                String importPath = "";
                String currentTargetName = "";
                String currentPath = "";

                for (Map.Entry<String, List<String>> targetAndPathEntry : pathAndTargetData.entrySet()) {
                    String[] pathAndTarget = targetAndPathEntry.getValue().get(0).replaceFirst("//", "")
                            .split(":");
                    if (currentClassPath.contains(targetAndPathEntry.getKey())) {
                        currentTargetName = pathAndTarget[1];
                        currentPath = pathAndTarget[0];
                    } else {
                        importTargetName = pathAndTarget[1];
                        importPath = pathAndTarget[0];
                    }
                }

                BuckDeps.addDeps(mProject, importPath, currentPath, importTargetName, currentTargetName);
            } catch (IOException e) {
                LOG.error(e.toString());
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
        }
    }, importClass.get().getPath(), currentClass.get().getPath());
}