List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction
AsyncFunction
From source file:org.opendaylight.centinel.impl.CentinelStreamImpl.java
@Override public Future<RpcResult<UpdateStreamOutput>> updateStream(final UpdateStreamInput input) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); final SettableFuture<RpcResult<UpdateStreamOutput>> futureResult = SettableFuture.create(); boolean idMatches = false; if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()) { LOG.debug("STREAM ID CANNOT BE NULL"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("inalid-input", streamIdcannotbenullError())); }/*w w w.jav a 2 s. c o m*/ final UpdateStreamOutputBuilder updateStreamRuleOutputBuilder = new UpdateStreamOutputBuilder(); updateStreamRuleOutputBuilder.setTitle(input.getTitle()); updateStreamRuleOutputBuilder.setDescription(input.getDescription()); ListenableFuture<Optional<StreamRecord>> readFutureOperational = tx.read(LogicalDatastoreType.OPERATIONAL, streamRecordId); ListenableFuture<Optional<StreamRecord>> readFutureConfigure = tx.read(LogicalDatastoreType.CONFIGURATION, streamRecordId); String configId = null; try { Optional<StreamRecord> record = readFutureOperational.get(); if (record.isPresent()) { StreamRecord operationalRecord = readFutureOperational.get().get(); List<StreamList> streamRulesList = new ArrayList<StreamList>(); if (!operationalRecord.getStreamList().isEmpty()) { streamRulesList = operationalRecord.getStreamList(); Iterator<StreamList> iterator = streamRulesList.iterator(); while (iterator.hasNext()) { StreamList operationalObject = iterator.next(); if (operationalObject.getStreamID().equals(input.getStreamID())) { configId = operationalObject.getConfigID(); idMatches = true; } } if (!idMatches) { return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException( "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input", "Invalid Stream id or The stream is not present in operational data store"))); } } } else { return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input", "Record is not present in operational data store"))); } } catch (InterruptedException | ExecutionException e) { futureResult.set(RpcResultBuilder.<UpdateStreamOutput>failed() .withRpcErrors(((TransactionCommitFailedException) e).getErrorList()).build()); return futureResult; } final String confId = configId; final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure, new AsyncFunction<Optional<StreamRecord>, Void>() { @Override public ListenableFuture<Void> apply(final Optional<StreamRecord> streamRulesRecord) throws Exception { List<StreamList> streamRuleList = new ArrayList<StreamList>(); List<StreamList> updatedStreamRuleList = new ArrayList<StreamList>(); if (streamRulesRecord.isPresent()) { streamRuleList = streamRulesRecord.get().getStreamList(); StreamList configObject = null; Iterator<StreamList> iterator = streamRuleList.iterator(); while (iterator.hasNext()) { configObject = iterator.next(); if (configObject.getConfigID().equalsIgnoreCase(confId)) { updatedStreamRuleList.add(buildUpdateStreamListRecord(input, configObject)); tx.merge(LogicalDatastoreType.CONFIGURATION, streamRecordId, new StreamRecordBuilder().setStreamList(updatedStreamRuleList).build()); } } } return tx.submit(); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { futureResult.set(RpcResultBuilder.<UpdateStreamOutput>success(updateStreamRuleOutputBuilder.build()) .build()); } @Override public void onFailure(final Throwable ex) { LOG.debug("Failed to commit Rule", ex); futureResult.set(RpcResultBuilder.<UpdateStreamOutput>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } }); return futureResult; }
From source file:org.opendaylight.centinel.impl.CentinelImpl.java
/** * sets alert field content rule in configurational datastore * /*from w w w. java 2s . c o m*/ */ @Override public Future<RpcResult<SetAlertFieldContentRuleOutput>> setAlertFieldContentRule( final SetAlertFieldContentRuleInput input) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); final SettableFuture<RpcResult<SetAlertFieldContentRuleOutput>> futureResult = SettableFuture.create(); final SetAlertFieldContentRuleOutputBuilder setAlertFieldContentRuleOutputBuilder = new SetAlertFieldContentRuleOutputBuilder(); setAlertFieldContentRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier()); setAlertFieldContentRuleOutputBuilder.setFieldContentBacklog(input.getFieldContentBacklog()); setAlertFieldContentRuleOutputBuilder.setFieldContentCompareToValue(input.getFieldContentCompareToValue()); setAlertFieldContentRuleOutputBuilder.setFieldContentField(input.getFieldContentField()); setAlertFieldContentRuleOutputBuilder.setFieldContentGrace(input.getFieldContentGrace()); setAlertFieldContentRuleOutputBuilder.setNodeType(input.getNodeType()); setAlertFieldContentRuleOutputBuilder.setRuleID(input.getRuleID()); setAlertFieldContentRuleOutputBuilder.setStreamID(input.getStreamID()); setAlertFieldContentRuleOutputBuilder.setTimeStamp(input.getTimeStamp()); ListenableFuture<Optional<AlertFieldContentRuleRecord>> readFuture = tx .read(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<AlertFieldContentRuleRecord>, Void>() { @Override public ListenableFuture<Void> apply( final Optional<AlertFieldContentRuleRecord> alertFieldContentRuleRecord) throws Exception { List<StreamAlertFieldContentRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldContentRuleList>(); if (alertFieldContentRuleRecord.isPresent()) { streamAlertRuleList = alertFieldContentRuleRecord.get() .getStreamAlertFieldContentRuleList(); } streamAlertRuleList.add(buildAlertFieldContentRuleRecord(input)); tx.put(LogicalDatastoreType.CONFIGURATION, alertFeildContentRuleRecordId, new AlertFieldContentRuleRecordBuilder() .setStreamAlertFieldContentRuleList(streamAlertRuleList).build()); return tx.submit(); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { futureResult.set(RpcResultBuilder .<SetAlertFieldContentRuleOutput>success(setAlertFieldContentRuleOutputBuilder.build()) .build()); } @Override public void onFailure(final Throwable ex) { LOG.debug("Failed to commit Rule", ex); futureResult.set(RpcResultBuilder.<SetAlertFieldContentRuleOutput>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } }); return futureResult; }
From source file:org.litecoinj.protocols.channels.PaymentChannelServer.java
@GuardedBy("lock") private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException { // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls // close() on us here below via the stored channel state. // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes. channelSettling = true;//from ww w . j ava2 s . c o m ListenableFuture<KeyParameter> keyFuture = conn.getUserKey(); ListenableFuture<Transaction> result; if (keyFuture != null) { result = Futures.transform(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() { @Override public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception { return state.close(userKey); } }); } else { result = state.close(); } Futures.addCallback(result, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction result) { // Send the successfully accepted transaction back to the client. final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder(); msg.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE); if (result != null) { // Result can be null on various error paths, like if we never actually opened // properly and so on. msg.getSettlementBuilder().setTx(ByteString.copyFrom(result.unsafeBitcoinSerialize())); log.info("Sending CLOSE back with broadcast settlement tx."); } else { log.info("Sending CLOSE back without broadcast settlement tx."); } conn.sendToClient(msg.build()); conn.destroyConnection(clientRequestedClose); } @Override public void onFailure(Throwable t) { log.error("Failed to broadcast settlement tx", t); conn.destroyConnection(clientRequestedClose); } }); }
From source file:org.bitcoinj.protocols.channels.PaymentChannelServer.java
@GuardedBy("lock") private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException { // Setting channelSettling here prevents us from sending another CLOSE when state.close() calls // close() on us here below via the stored channel state. // TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes. channelSettling = true;/*from w w w.j ava 2s. co m*/ ListenableFuture<KeyParameter> keyFuture = conn.getUserKey(); ListenableFuture<Transaction> result; if (keyFuture != null) { result = Futures.transformAsync(conn.getUserKey(), new AsyncFunction<KeyParameter, Transaction>() { @Override public ListenableFuture<Transaction> apply(KeyParameter userKey) throws Exception { return state.close(userKey); } }); } else { result = state.close(); } Futures.addCallback(result, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction result) { // Send the successfully accepted transaction back to the client. final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder(); msg.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE); if (result != null) { // Result can be null on various error paths, like if we never actually opened // properly and so on. msg.getSettlementBuilder().setTx(ByteString.copyFrom(result.unsafeBitcoinSerialize())); log.info("Sending CLOSE back with broadcast settlement tx."); } else { log.info("Sending CLOSE back without broadcast settlement tx."); } conn.sendToClient(msg.build()); conn.destroyConnection(clientRequestedClose); } @Override public void onFailure(Throwable t) { log.error("Failed to broadcast settlement tx", t); conn.destroyConnection(clientRequestedClose); } }); }
From source file:org.opendaylight.bgpcep.pcep.topology.provider.Stateful07TopologySessionListener.java
@Override public synchronized ListenableFuture<OperationResult> removeLsp(final RemoveLspArgs input) { Preconditions.checkArgument(input != null && input.getName() != null && input.getNode() != null, MISSING_XML_TAG);//from www . j a v a 2 s. co m LOG.trace("RemoveLspArgs {}", input); // Make sure the LSP exists, we need it for PLSP-ID final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName()); final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp); if (f == null) { return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future(); } return Futures.transform(f, new AsyncFunction<Optional<ReportedLsp>, OperationResult>() { @Override public ListenableFuture<OperationResult> apply(final Optional<ReportedLsp> rep) { final Lsp reportedLsp = validateReportedLsp(rep, input); if (reportedLsp == null) { return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future(); } final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER); final Requests rb = buildRequest(rep, reportedLsp); ib.setRequests(Collections.singletonList(rb)); return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null); } }); }
From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java
@Override public Future<RpcResult<CreateLogicalPortOutput>> createLogicalPort(CreateLogicalPortInput input) { final RpcResultBuilder<CreateLogicalPortOutput> resultBuilder = RpcResultBuilder .<CreateLogicalPortOutput>success(); final CreateLogicalPortOutputBuilder outputBuilder = new CreateLogicalPortOutputBuilder(); final FabricId fabricId = input.getFabricId(); final String name = input.getName(); final NodeId nodeId = input.getLogicalDevice(); final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId); if (fabricObj == null) { return Futures.immediateFailedFuture( new IllegalArgumentException(String.format("fabric %s does not exist", fabricId))); }// ww w . j a va2s. c o m final TpId tpid = new TpId(name == null ? UUID.randomUUID().toString() : name); TerminationPointBuilder tpBuilder = new TerminationPointBuilder(); tpBuilder.setTpId(tpid); tpBuilder.setKey(new TerminationPointKey(tpid)); LportAttributeBuilder lpAttr = new LportAttributeBuilder(); lpAttr.setName(input.getName()); Attribute portAttr = input.getAttribute(); if (portAttr != null) { lpAttr.setPortLayer(portAttr.getPortLayer()); lpAttr.setFabricAcl(portAttr.getFabricAcl()); lpAttr.setPortFunction(portAttr.getPortFunction()); } fabricObj.buildLogicalPort(tpid, lpAttr, input); LogicalPortAugmentBuilder lpCtx = new LogicalPortAugmentBuilder(); lpCtx.setLportAttribute(lpAttr.build()); tpBuilder.addAugmentation(LogicalPortAugment.class, lpCtx.build()); InstanceIdentifier<TerminationPoint> tpIId = MdSalUtils.createLogicPortIId(fabricId, nodeId, tpid); WriteTransaction trans = dataBroker.newWriteOnlyTransaction(); trans.put(LogicalDatastoreType.OPERATIONAL, tpIId, tpBuilder.build()); return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<CreateLogicalPortOutput>>() { @Override public ListenableFuture<RpcResult<CreateLogicalPortOutput>> apply(Void submitResult) throws Exception { outputBuilder.setTpId(tpid); outputBuilder.setName(name); return Futures.immediateFuture(resultBuilder.withResult(outputBuilder.build()).build()); } }, executor); }
From source file:com.microsoftopentechnologies.intellij.helpers.o365.Office365RestAPIManager.java
@Override public ListenableFuture<Application> registerApplication(@NotNull final Application application) throws ParseException { return requestWithToken(new RequestCallback<Application>() { @Override/*from ww w.j ava2 s .c o m*/ public ListenableFuture<Application> execute() throws ParseException { // register the app and then create a service principal for the app if there isn't already one return Futures.transform(getDirectoryClient().getapplications().add(application), new AsyncFunction<Application, Application>() { @Override public ListenableFuture<Application> apply(final Application application) throws Exception { return Futures.transform(getServicePrincipalsForApp(application), new AsyncFunction<List<ServicePrincipal>, Application>() { @Override public ListenableFuture<Application> apply( List<ServicePrincipal> servicePrincipals) throws Exception { if (servicePrincipals.size() == 0) { return createServicePrincipalForApp(application); } return Futures.immediateFuture(application); } }); } }); } }); }
From source file:org.opendaylight.vpnservice.alivenessmonitor.internal.AlivenessMonitor.java
private void associateMonitorIdWithInterface(final Long monitorId, final String interfaceName) { LOG.debug("associate monitor Id {} with interface {}", monitorId, interfaceName); final ReadWriteTransaction tx = broker.newReadWriteTransaction(); ListenableFuture<Optional<InterfaceMonitorEntry>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, getInterfaceMonitorMapId(interfaceName)); ListenableFuture<Void> updateFuture = Futures.transform(readFuture, new AsyncFunction<Optional<InterfaceMonitorEntry>, Void>() { @Override/*from w ww . jav a2 s .c o m*/ public ListenableFuture<Void> apply(Optional<InterfaceMonitorEntry> optEntry) throws Exception { if (optEntry.isPresent()) { InterfaceMonitorEntry entry = optEntry.get(); List<Long> monitorIds = entry.getMonitorIds(); monitorIds.add(monitorId); InterfaceMonitorEntry newEntry = new InterfaceMonitorEntryBuilder() .setKey(new InterfaceMonitorEntryKey(interfaceName)).setMonitorIds(monitorIds) .build(); tx.merge(LogicalDatastoreType.OPERATIONAL, getInterfaceMonitorMapId(interfaceName), newEntry); } else { //Create new monitor entry LOG.debug("Adding new interface-monitor association for interface {} with id {}", interfaceName, monitorId); List<Long> monitorIds = new ArrayList<>(); monitorIds.add(monitorId); InterfaceMonitorEntry newEntry = new InterfaceMonitorEntryBuilder() .setInterfaceName(interfaceName).setMonitorIds(monitorIds).build(); tx.put(LogicalDatastoreType.OPERATIONAL, getInterfaceMonitorMapId(interfaceName), newEntry, CREATE_MISSING_PARENT); } return tx.submit(); } }); Futures.addCallback(updateFuture, new FutureCallbackImpl( String.format("Association of monitorId %d with Interface %s", monitorId, interfaceName))); }
From source file:org.opendaylight.centinel.impl.CentinelImpl.java
/** * sets sets alertfield value rule in configurational data store. * /*from w w w. j av a 2 s. co m*/ */ @Override public Future<RpcResult<SetAlertFieldValueRuleOutput>> setAlertFieldValueRule( final SetAlertFieldValueRuleInput input) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); final SettableFuture<RpcResult<SetAlertFieldValueRuleOutput>> futureResult = SettableFuture.create(); final SetAlertFieldValueRuleOutputBuilder setAlertFieldValueRuleOutputBuilder = new SetAlertFieldValueRuleOutputBuilder(); setAlertFieldValueRuleOutputBuilder.setAlertTypeClassifier(input.getAlertTypeClassifier()); setAlertFieldValueRuleOutputBuilder.setFieldValueBacklog(input.getFieldValueBacklog()); setAlertFieldValueRuleOutputBuilder.setFieldValueField(input.getFieldValueField()); setAlertFieldValueRuleOutputBuilder.setFieldValueGrace(input.getFieldValueGrace()); setAlertFieldValueRuleOutputBuilder.setFieldValueThreshhold(input.getFieldValueThreshhold()); setAlertFieldValueRuleOutputBuilder.setFieldValueThreshholdType(input.getFieldValueThreshholdType()); setAlertFieldValueRuleOutputBuilder.setFieldValueType(input.getFieldValueType()); setAlertFieldValueRuleOutputBuilder.setNodeType(input.getNodeType()); setAlertFieldValueRuleOutputBuilder.setRuleID(input.getRuleID()); setAlertFieldValueRuleOutputBuilder.setRuleTypeClassifier(input.getRuleTypeClassifier()); setAlertFieldValueRuleOutputBuilder.setStreamID(input.getStreamID()); setAlertFieldValueRuleOutputBuilder.setTimeStamp(input.getTimeStamp()); ListenableFuture<Optional<AlertFieldValueRuleRecord>> readFuture = tx .read(LogicalDatastoreType.CONFIGURATION, alertFieldValueRuleRecordId); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<AlertFieldValueRuleRecord>, Void>() { @Override public ListenableFuture<Void> apply( final Optional<AlertFieldValueRuleRecord> alertFieldValueRuleRecord) throws Exception { List<StreamAlertFieldValueRuleList> streamAlertRuleList = new ArrayList<StreamAlertFieldValueRuleList>(); if (alertFieldValueRuleRecord.isPresent()) { streamAlertRuleList = alertFieldValueRuleRecord.get() .getStreamAlertFieldValueRuleList(); } streamAlertRuleList.add(buildAlertFieldValueRuleRecord(input)); tx.put(LogicalDatastoreType.CONFIGURATION, alertFieldValueRuleRecordId, new AlertFieldValueRuleRecordBuilder() .setStreamAlertFieldValueRuleList(streamAlertRuleList).build()); return tx.submit(); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { futureResult.set(RpcResultBuilder .<SetAlertFieldValueRuleOutput>success(setAlertFieldValueRuleOutputBuilder.build()) .build()); } @Override public void onFailure(final Throwable ex) { LOG.debug("Failed to commit Rule", ex); futureResult.set(RpcResultBuilder.<SetAlertFieldValueRuleOutput>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } }); return futureResult; }
From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java
@Override public Future<RpcResult<Void>> addAcl(AddAclInput input) { String aclName = input.getAclName(); FabricId fabricId = input.getFabricId(); NodeId ldev = input.getLogicalDevice(); TpId tpId = input.getLogicalPort();//from ww w.j a v a 2 s . c om final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId); if (fabricObj == null) { return Futures.immediateFailedFuture( new IllegalArgumentException(String.format("fabric %s does not exist", fabricId))); } final InstanceIdentifier<FabricAcl> aclIId = fabricObj.addAcl(ldev, tpId, aclName); if (aclIId == null) { return Futures.immediateFailedFuture( new IllegalArgumentException("Can not add acl, maybe the target is not exists !")); } FabricAclBuilder aclBuilder = new FabricAclBuilder(); aclBuilder.setFabricAclName(aclName); aclBuilder.setKey(new FabricAclKey(aclName)); WriteTransaction trans = dataBroker.newWriteOnlyTransaction(); trans.merge(LogicalDatastoreType.OPERATIONAL, aclIId, aclBuilder.build(), false); return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(Void submitResult) throws Exception { fabricObj.notifyAclUpdated(aclIId, false); return Futures.immediateFuture(RpcResultBuilder.<Void>success().build()); } }, executor); }