List of usage examples for com.google.common.util.concurrent Futures transform
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function)
From source file:org.opendaylight.openflowplugin.impl.statistics.StatisticsGatheringUtils.java
private static ListenableFuture<Boolean> transformAndStoreStatisticsData( final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture, final DeviceContext deviceContext, final EventIdentifier eventIdentifier, final MultipartType type) { return Futures.transform(statisticsDataInFuture, new Function<RpcResult<List<MultipartReply>>, Boolean>() { @Nullable/*from w w w .j a v a 2 s.c o m*/ @Override public Boolean apply(final RpcResult<List<MultipartReply>> rpcResult) { if (rpcResult.isSuccessful()) { LOG.debug("Stats reply successfully received for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type); boolean isMultipartProcessed = Boolean.TRUE; // TODO: in case the result value is null then multipart data probably got processed on the fly - // TODO: this contract should by clearly stated and enforced - now simple true value is returned if (null != rpcResult.getResult()) { Iterable<? extends DataObject> allMultipartData = Collections.emptyList(); DataObject multipartData = null; try { for (final MultipartReply singleReply : rpcResult.getResult()) { final List<? extends DataObject> multipartDataList = MULTIPART_REPLY_TRANSLATOR .translate(deviceContext, singleReply); multipartData = multipartDataList.get(0); allMultipartData = Iterables.concat(allMultipartData, multipartDataList); } } catch (Exception e) { LOG.warn("stats processing of type {} for node {} failed during transfomation step", type, deviceContext.getDeviceState().getNodeId(), e); throw e; } try { if (multipartData instanceof GroupStatisticsUpdated) { processGroupStatistics((Iterable<GroupStatisticsUpdated>) allMultipartData, deviceContext); } else if (multipartData instanceof MeterStatisticsUpdated) { processMetersStatistics((Iterable<MeterStatisticsUpdated>) allMultipartData, deviceContext); } else if (multipartData instanceof NodeConnectorStatisticsUpdate) { processNodeConnectorStatistics( (Iterable<NodeConnectorStatisticsUpdate>) allMultipartData, deviceContext); } else if (multipartData instanceof FlowTableStatisticsUpdate) { processFlowTableStatistics((Iterable<FlowTableStatisticsUpdate>) allMultipartData, deviceContext); } else if (multipartData instanceof QueueStatisticsUpdate) { processQueueStatistics((Iterable<QueueStatisticsUpdate>) allMultipartData, deviceContext); } else if (multipartData instanceof FlowsStatisticsUpdate) { processFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData, deviceContext); EventsTimeCounter.markEnd(eventIdentifier); } else if (multipartData instanceof GroupDescStatsUpdated) { processGroupDescStats((Iterable<GroupDescStatsUpdated>) allMultipartData, deviceContext); } else if (multipartData instanceof MeterConfigStatsUpdated) { processMeterConfigStatsUpdated((Iterable<MeterConfigStatsUpdated>) allMultipartData, deviceContext); } else { isMultipartProcessed = Boolean.FALSE; } } catch (Exception e) { LOG.warn("stats processing of type {} for node {} failed during write-to-tx step", type, deviceContext.getDeviceState().getNodeId(), e); throw e; } LOG.debug("Stats reply added to transaction for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type); //TODO : implement experimenter } else { LOG.debug("Stats reply was empty for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type); } return isMultipartProcessed; } else { LOG.debug("Stats reply FAILED for node {} of type {}: {}", deviceContext.getDeviceState().getNodeId(), type, rpcResult.getErrors()); } return Boolean.FALSE; } }); }
From source file:com.sk89q.worldguard.commands.region.MemberCommands.java
@Command(aliases = { "removeowner", "remowner", "ro" }, usage = "<id> <owners...>", flags = "naw:", desc = "Remove an owner to a region", min = 1) public void removeOwner(CommandContext args, Actor sender) throws CommandException { warnAboutSaveFailures(sender);//from w w w.j a v a 2 s . c o m World world = checkWorld(args, sender, 'w'); // Get the world String id = args.getString(0); RegionManager manager = checkRegionManager(world); ProtectedRegion region = checkExistingRegion(manager, id, true); // Check permissions if (!getPermissionModel(sender).mayRemoveOwners(region)) { throw new CommandPermissionsException(); } ListenableFuture<?> future; if (args.hasFlag('a')) { region.getOwners().removeAll(); future = Futures.immediateFuture(null); } else { if (args.argsLength() < 2) { throw new CommandException("List some names to remove, or use -a to remove all."); } // Resolve owners asynchronously DomainInputResolver resolver = new DomainInputResolver(WorldGuard.getInstance().getProfileService(), args.getParsedPaddedSlice(1, 0)); resolver.setLocatorPolicy( args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME); // Then remove it from the owners future = Futures.transform(WorldGuard.getInstance().getExecutorService().submit(resolver), resolver.createRemoveAllFunction(region.getOwners())); } AsyncCommandHelper.wrap(future, worldGuard.getSupervisor(), sender, worldGuard.getExceptionConverter()) .formatUsing(region.getId(), world.getName()) .registerWithSupervisor("Removing owners from the region '%s' on '%s'") .sendMessageAfterDelay("(Please wait... querying player names...)") .thenRespondWith("Region '%s' updated with owners removed.", "Failed to remove owners"); }
From source file:org.opendaylight.controller.sal.connect.netconf.sal.tx.NetconfDeviceWriteOnlyTx.java
@Override public ListenableFuture<RpcResult<TransactionStatus>> commit() { checkNotFinished();/* ww w .jav a 2s .c om*/ finished.set(true); if (candidateSupported == false) { return Futures.immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build()); } final ListenableFuture<RpcResult<CompositeNode>> rpcResult = rpc.invokeRpc( NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, NetconfMessageTransformUtil.COMMIT_RPC_CONTENT); final ListenableFuture<RpcResult<TransactionStatus>> transformed = Futures.transform(rpcResult, new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() { @Override public RpcResult<TransactionStatus> apply(final RpcResult<CompositeNode> input) { if (input.isSuccessful()) { return RpcResultBuilder.success(TransactionStatus.COMMITED).build(); } else { final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed(); for (final RpcError rpcError : input.getErrors()) { failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(), rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause()); } return failed.build(); } } }); Futures.addCallback(transformed, this); return transformed; }
From source file:com.github.charithe.kafka.KafkaHelper.java
/** * Consume specified number of string messages * * @param topic Topic to consume from * @param numMessagesToConsume Number of messages to consume * @return ListenableFuture/*from ww w . ja v a 2 s . c om*/ */ public ListenableFuture<List<String>> consumeStrings(String topic, int numMessagesToConsume) { KafkaConsumer<String, String> consumer = createStringConsumer(); ListenableFuture<List<ConsumerRecord<String, String>>> records = consume(topic, consumer, numMessagesToConsume); return Futures.transform(records, this::extractValues); }
From source file:org.thingsboard.server.dao.alarm.BaseAlarmService.java
@Override public ListenableFuture<AlarmInfo> findAlarmInfoByIdAsync(TenantId tenantId, AlarmId alarmId) { log.trace("Executing findAlarmInfoByIdAsync [{}]", alarmId); validateId(alarmId, "Incorrect alarmId " + alarmId); return Futures.transformAsync(alarmDao.findAlarmByIdAsync(tenantId, alarmId.getId()), a -> { AlarmInfo alarmInfo = new AlarmInfo(a); return Futures.transform(entityService.fetchEntityNameAsync(tenantId, alarmInfo.getOriginator()), originatorName -> {//ww w . ja v a 2 s . c o m alarmInfo.setOriginatorName(originatorName); return alarmInfo; }); }); }
From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.PolicyManager.java
/** * @param tableIDs - IDs of tables to delete * @return ListenableFuture<Void> - which will be filled when clearing is done *//* w w w . ja v a 2s . c om*/ private ListenableFuture<Void> removeUnusedTables(final List<Short> tableIDs) { List<ListenableFuture<Void>> checkList = new ArrayList<>(); final ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction(); for (Short tableId : tableIDs) { for (NodeId nodeId : switchManager.getReadySwitches()) { final InstanceIdentifier<Table> tablePath = FlowUtils.createTablePath(nodeId, tableId); checkList.add(deleteTableIfExists(rwTx, tablePath)); } } ListenableFuture<List<Void>> allAsListFuture = Futures.allAsList(checkList); return Futures.transform(allAsListFuture, new AsyncFunction<List<Void>, Void>() { @Override public ListenableFuture<Void> apply(List<Void> readyToSubmit) { return rwTx.submit(); } }); }
From source file:com.datastax.driver.mapping.Mapper.java
private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<PropertyMapper, Object> values = new HashMap<PropertyMapper, Object>(); boolean saveNullFields = shouldSaveNullFields(options); for (PropertyMapper col : mapper.allColumns) { Object value = col.getValue(entity); if (!col.isComputed() && (saveNullFields || value != null)) { values.put(col, value);/*from ww w .j av a2s . c o m*/ } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<PropertyMapper, Object> entry : values.entrySet()) { PropertyMapper mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option opt : options.values()) { opt.checkValidFor(QueryType.SAVE, manager); opt.addToPreparedStatement(bs, i++); } return bs; } }); }
From source file:com.google.caliper.runner.ExperimentingCaliperRun.java
/** * Schedule all the trials./*from w w w . java 2 s.com*/ * * <p>This method arranges all the {@link ScheduledTrial trials} to run according to their * scheduling criteria. The executor instance is responsible for enforcing max parallelism. */ private List<ListenableFuture<TrialResult>> scheduleTrials(List<ScheduledTrial> trials, final ListeningExecutorService executor) { List<ListenableFuture<TrialResult>> pendingTrials = Lists.newArrayList(); List<ScheduledTrial> serialTrials = Lists.newArrayList(); for (final ScheduledTrial scheduledTrial : trials) { if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) { pendingTrials.add(executor.submit(scheduledTrial.trialTask())); } else { serialTrials.add(scheduledTrial); } } // A future representing the completion of all prior tasks. Futures.successfulAsList allows us // to ignore failure. ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials); for (final ScheduledTrial scheduledTrial : serialTrials) { // each of these trials can only start after all prior trials have finished, so we use // Futures.transform to force the sequencing. ListenableFuture<TrialResult> current = Futures.transform(previous, new AsyncFunction<Object, TrialResult>() { @Override public ListenableFuture<TrialResult> apply(Object ignored) { return executor.submit(scheduledTrial.trialTask()); } }); pendingTrials.add(current); // ignore failure of the prior task. previous = Futures.withFallback(current, FALLBACK_TO_NULL); } return pendingTrials; }
From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java
@Override public void onRemoveFloatingIp(final BigInteger dpnId, String routerId, Uuid networkId, final String externalIp, String internalIp, final long label) { final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId, LOG); if (vpnName == null) { LOG.info("No VPN associated with ext nw {} to handle remove floating ip configuration {} in router {}", networkId, externalIp, routerId); return;// w w w .jav a 2 s .com } //Remove Prefix from BGP String rd = NatUtil.getVpnRd(dataBroker, vpnName); removePrefixFromBGP(rd, externalIp + "/32"); //Remove custom FIB routes //Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input); RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName).setSourceDpid(dpnId) .setIpAddress(externalIp + "/32").setServiceId(label).build(); Future<RpcResult<Void>> future = fibService.removeFibEntry(input); ListenableFuture<RpcResult<Void>> labelFuture = Futures.transform( JdkFutureAdapters.listenInPoolThread(future), new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(RpcResult<Void> result) throws Exception { //Release label if (result.isSuccessful()) { removeTunnelTableEntry(dpnId, label); removeLFibTableEntry(dpnId, label); RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder().setVpnName(vpnName) .setIpPrefix(externalIp).build(); Future<RpcResult<Void>> labelFuture = vpnService.removeVpnLabel(labelInput); return JdkFutureAdapters.listenInPoolThread(labelFuture); } else { String errMsg = String.format( "RPC call to remove custom FIB entries on dpn %s for prefix %s Failed - %s", dpnId, externalIp, result.getErrors()); LOG.error(errMsg); return Futures.immediateFailedFuture(new RuntimeException(errMsg)); } } }); Futures.addCallback(labelFuture, new FutureCallback<RpcResult<Void>>() { @Override public void onFailure(Throwable error) { LOG.error("Error in removing the label or custom fib entries", error); } @Override public void onSuccess(RpcResult<Void> result) { if (result.isSuccessful()) { LOG.debug("Successfully removed the label for the prefix {} from VPN {}", externalIp, vpnName); } else { LOG.error("Error in removing the label for prefix {} from VPN {}, {}", externalIp, vpnName, result.getErrors()); } } }); }
From source file:org.opendaylight.toaster.impl.ToasterProvider.java
private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { LOG.info("checkStatusAndMakeToast"); final ReadWriteTransaction tx = dataService.newReadWriteTransaction(); ListenableFuture<Optional<Toaster>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<Toaster>, Void>() { @Override//from www. j av a2 s.c om public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception { Toaster.ToasterStatus toasterStatus = Toaster.ToasterStatus.Up; if (toasterData.isPresent()) { toasterStatus = toasterData.get().getToasterStatus(); } LOG.debug("Read toaster status: {}", toasterStatus); if (toasterStatus == Toaster.ToasterStatus.Up) { if (outOfBread()) { LOG.debug("Toaster is out of bread"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeToasterOutOBreadError())); } LOG.debug("Setting Toaster status to Down"); tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, buildToaster(Toaster.ToasterStatus.Down)); return tx.submit(); } LOG.debug("Oops - already making toast!"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeToasterInUseError())); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult))); } @Override public void onFailure(final Throwable ex) { if (ex instanceof OptimisticLockFailedException) { if ((tries - 1) > 0) { LOG.debug("Got OptimisticLockFailedException - try again"); checkStatusAndMakeToast(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(RpcError.ErrorType.APPLICATION, ex.getMessage()).build()); } } else { LOG.debug("Failed to commit Toaster status", ex); futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } } }); }