List of usage examples for com.google.common.util.concurrent Futures addCallback
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)
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 ww w .j a v a 2s.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.microsoftopentechnologies.auth.AuthenticationContext.java
public ListenableFuture<AuthenticationResult> acquireTokenInteractiveAsync(final String tenantName, final String resource, final String clientId, final String redirectUri, 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, windowTitle, promptValue); Futures.addCallback(authCodeFuture, new FutureCallback<String>() { @Override//from www .j a v a 2 s . 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( JsonUtils.getJsonStringProp(root, OAuthReservedClaim.TokenType), JsonUtils.getJsonStringProp(root, OAuthReservedClaim.AccessToken), JsonUtils.getJsonStringProp(root, OAuthReservedClaim.RefreshToken), JsonUtils.getJsonLongProp(root, OAuthReservedClaim.ExpiresOn), JsonUtils.getJsonStringProp(root, OAuthReservedClaim.Resource), UserInfo.parse(JsonUtils.getJsonStringProp(root, OAuthReservedClaim.IdToken))); future.set(result); } catch (Exception e) { future.setException(e); } finally { try { if (output != null) { output.close(); } if (reader != null) { reader.close(); } } catch (IOException ignored) { } } } @Override public void onFailure(Throwable throwable) { future.setException(throwable); } }); return future; }
From source file:com.microsoft.office.integration.test.MessagesAsyncTestCase.java
public void testUpdate() { // create message first counter = new CountDownLatch(1); prepareMessage();//from w w w . j a v a 2 s . c o m Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); counter.countDown(); } public void onSuccess(Void result) { try { try { updateAndCheck(); } finally { // clean up removeMessage(); } } catch (Throwable t) { reportError(t); } counter.countDown(); } }); try { if (!counter.await(60000, TimeUnit.MILLISECONDS)) { fail("testUpdate() timed out"); } } catch (InterruptedException e) { fail("testUpdate() has been interrupted"); } }
From source file:org.opendaylight.vpnservice.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 = Lists.newArrayList(); 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/*from w ww .j a va 2 s. c o 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); } }); // TODO: why to create a new arraylist for uninstallFuture? futures.addAll(Lists.newArrayList(uninstallFuture)); } } return futures; }
From source file:xyz.cloudbans.bukkit.command.TempNoticeCommand.java
@Override public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { // /tempnotice <player> <duration> <notice> if (!sender.hasPermission("cloudbans.notice.tempnotice")) { sender.sendMessage(ChatColor.RED + "You don't have enough permissions for that."); return true; }/*from w ww .java2 s .co 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 > 2) { String[] notice = Arrays.copyOfRange(args, 2, 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: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 w w w.j av a 2s . c o m*/ public void onSuccess(Boolean result) { future.set(session); } @Override public void onFailure(Throwable t) { future.setException(t); } }); return future; }
From source file:com.example.office.ui.calendar.EventFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater;/*from w w w . j ava2 s.com*/ 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.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// ww w. j a v a 2 s. 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:org.dcache.poolmanager.PoolManagerHandlerSubscriber.java
@PostConstruct public synchronized void start() { current = transformAsync(startGate,/*w ww . ja va 2 s.c o 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:odl.example.impl.ApplicationRegistryUtils.java
public void writeToApplicationRegistry(AddApplicationInput input) { LOG.info("Writing to application registry input {}.", input); WriteTransaction transaction = db.newWriteOnlyTransaction(); InstanceIdentifier<ApplicationRegistryEntry> iid = toInstanceIdentifier(input); ApplicationRegistryEntry application = new ApplicationRegistryEntryBuilder().setAppId(input.getAppId()) .setJitter(input.getJitter()).setPacketLoss(input.getPacketLoss()) .setPacketDelay(input.getPacketDelay()).setBandwidth(input.getBandwidth()).build(); transaction.put(LogicalDatastoreType.OPERATIONAL, iid, application); CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit(); Futures.addCallback(future, new LoggingFuturesCallBack<Void>("Failed to write to application registry", LOG)); }