List of usage examples for com.google.common.util.concurrent Futures immediateFailedCheckedFuture
@GwtIncompatible("TODO") @CheckReturnValue public static <V, X extends Exception> CheckedFuture<V, X> immediateFailedCheckedFuture(X exception)
From source file:org.opendaylight.faas.fabric.general.FabricManagementAPIProvider.java
@Override public Future<RpcResult<Void>> decomposeFabric(DecomposeFabricInput input) { final RpcResult<Void> result = RpcResultBuilder.<Void>success().build(); if (input == null) { return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("fabricId can not be empty!")); }//from w w w. j av a2 s. c o m final FabricId fabricId = input.getFabricId(); if (fabricId == null) { return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("fabricId can not be empty!")); } ReadWriteTransaction rt = dataBroker.newReadWriteTransaction(); final InstanceIdentifier<Node> fabricpath = Constants.DOM_FABRICS_PATH.child(Node.class, new NodeKey(fabricId)); CheckedFuture<Optional<Node>, ReadFailedException> readFuture = rt.read(LogicalDatastoreType.OPERATIONAL, fabricpath); return Futures.transform(readFuture, (AsyncFunction<Optional<Node>, RpcResult<Void>>) optional -> { if (optional.isPresent()) { Node fabric = optional.get(); FabricInstanceCache.INSTANCE.retrieveFabric(fabricId).notifyFabricDeleted(fabric); WriteTransaction wt = dataBroker.newWriteOnlyTransaction(); wt.delete(LogicalDatastoreType.OPERATIONAL, fabricpath); wt.delete(LogicalDatastoreType.CONFIGURATION, fabricpath); wt.delete(LogicalDatastoreType.OPERATIONAL, MdSalUtils.createTopoIId(fabricId.getValue())); MdSalUtils.wrapperSubmit(wt, executor); FabricInstanceCache.INSTANCE.removeFabric(fabricId); } return Futures.immediateFuture(result); }); }
From source file:org.opendaylight.controller.features_service.impl.FeaturesServiceImpl.java
private void checkStatusAndInstallFeature(final InstallFeatureInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); ListenableFuture<Optional<Features>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, FEATURE_SERVICE_IID);/*www . j av a 2 s . c om*/ final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<Features>, Void>() { @Override public ListenableFuture<Void> apply(final Optional<Features> featuresData) throws Exception { FeaturesServiceStatus featuresServiceStatus = FeaturesServiceStatus.Available; if (featuresData.isPresent()) { featuresServiceStatus = featuresData.get().getFeaturesServiceStatus(); } LOG.debug("Read featuresServiceStatus status: {}", featuresServiceStatus); if (featuresServiceStatus == FeaturesServiceStatus.Available) { LOG.debug("Setting features service to unavailable (in use)"); tx.put(LogicalDatastoreType.OPERATIONAL, FEATURE_SERVICE_IID, buildFeatures(FeaturesServiceStatus.Unavailable)); return tx.submit(); } LOG.debug("Something went wrong while installing feature: " + input.getName()); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeFeaturesServiceInUseError())); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { // OK to install a feature currentInstallFeaturesTask.set(executor.submit(new InstallFeaturesTask(input, futureResult))); } @Override public void onFailure(final Throwable ex) { if (ex instanceof OptimisticLockFailedException) { // Another thread is likely trying to install a feature // simultaneously and updated the // status before us. Try reading the status again - if // another install is now in progress, we should // get FeaturesService.available and fail. if ((tries - 1) > 0) { LOG.debug("Got OptimisticLockFailedException - trying again"); checkStatusAndInstallFeature(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(ErrorType.APPLICATION, ex.getMessage()).build()); } } else { LOG.debug("Failed to commit FeaturesService status", ex); futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } } }); }
From source file:ncmount.impl.NcmountDomProvider.java
/** * This method is the implementation of the 'show-node' RESTCONF service, * which is one of the external APIs into the ncmount application. The * service provides two example functions: * 1. Browse through a subset of a mounted node's configuration data * 2. Browse through a subset of a mounted node's operational data * * @param input Input parameter from the show-node service yang model - * the node's configured name * @return Retrieved configuration and operational data *//*from w w w . j ava 2 s . co m*/ private CheckedFuture<DOMRpcResult, DOMRpcException> showNode(final NormalizedNode<?, ?> normalizedNode) { LOG.info("invoked showNode: {}", normalizedNode); // TODO: Method need to be implemented. return Futures .immediateFailedCheckedFuture((DOMRpcException) new MethodNotImplemented("method not implemented")); }
From source file:org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker.java
@Override public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final YangInstanceIdentifier route, final CompositeNode input) { if (defaultDelegate == null) { return Futures.immediateFailedCheckedFuture( new RpcImplementationUnavailableException("No RPC implementation found")); }// w w w. jav a2 s . c o m LOG.debug("Forwarding RPC {} path {} to delegate {}", rpc, route); return defaultDelegate.invokeRpc(rpc, route, input); }
From source file:org.opendaylight.distributed.tx.impl.CachingReadWriteTx.java
public <T extends DataObject> CheckedFuture<Void, DTxException> asyncPut( final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier, final T t) { increaseOperation();/*from ww w.j a v a 2s . c o m*/ final SettableFuture<Void> retFuture = SettableFuture.create(); CheckedFuture<Optional<T>, ReadFailedException> readFuture = null; try { readFuture = delegate.read(logicalDatastoreType, instanceIdentifier); } catch (Exception e) { readFuture = Futures .immediateFailedCheckedFuture(new ReadFailedException("Read exception in put action")); } Futures.addCallback(readFuture, new FutureCallback<Optional<T>>() { @Override public void onSuccess(final Optional<T> result) { synchronized (this) { cache.add(new CachedData(logicalDatastoreType, instanceIdentifier, result.orNull(), ModifyAction.REPLACE)); } final ListeningExecutorService executorService = MoreExecutors .listeningDecorator(executorPoolPerCache); final ListenableFuture asyncPutFuture = executorService.submit(new Callable() { @Override public Object call() throws Exception { delegate.put(logicalDatastoreType, instanceIdentifier, t); return null; } }); Futures.addCallback(asyncPutFuture, new FutureCallback() { @Override public void onSuccess(@Nullable Object result) { decreaseOperation(); retFuture.set(null); } @Override public void onFailure(Throwable t) { decreaseOperation(); LOG.trace("async put failure"); retFuture.setException(new DTxException.EditFailedException("async put failure", t)); } }); } @Override public void onFailure(final Throwable t) { decreaseOperation(); retFuture.setException( new DTxException.ReadFailedException("failed to read from node in put action", t)); } }); return Futures.makeChecked(retFuture, new Function<Exception, DTxException>() { @Nullable @Override public DTxException apply(@Nullable Exception e) { e = (Exception) e.getCause(); return e instanceof DTxException ? (DTxException) e : new DTxException("put operation failed", e); } }); }
From source file:com.toro.torod.connection.DefaultToroTransaction.java
@Override public ListenableFuture<UpdateResponse> update(String collection, List<? extends UpdateOperation> updates, WriteFailMode mode, UpdateActionVisitor<ToroDocument, Void> updateActionVisitorDocumentToInsert, UpdateActionVisitor<UpdatedToroDocument, ToroDocument> updateActionVisitorDocumentToUpdate) { cache.createCollection(executor, collection, null); UpdateResponse.Builder builder = new UpdateResponse.Builder(); for (int updateIndex = 0; updateIndex < updates.size(); updateIndex++) { UpdateOperation update = updates.get(updateIndex); try {/*from ww w .j a v a 2 s.co m*/ update(collection, update, updateIndex, updateActionVisitorDocumentToInsert, updateActionVisitorDocumentToUpdate, builder); } catch (InterruptedException | ExecutionException | RetryTransactionException ex) { return Futures.immediateFailedCheckedFuture(ex); } catch (UserToroException ex) { builder.addError(new WriteError(updateIndex, -1, ex.getLocalizedMessage())); } } return Futures.immediateCheckedFuture(builder.build()); }
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 w w w. j a va 2 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()); } } }); }
From source file:org.opendaylight.controller.sample.toaster.provider.OpendaylightToaster.java
private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { // Read the ToasterStatus and, if currently Up, try to write the status to Down. // If that succeeds, then we essentially have an exclusive lock and can proceed // to make toast. final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); ListenableFuture<Optional<Toaster>> readFuture = tx.read(OPERATIONAL, TOASTER_IID); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, (AsyncFunction<Optional<Toaster>, Void>) toasterData -> { ToasterStatus toasterStatus = ToasterStatus.Up; if (toasterData.isPresent()) { toasterStatus = toasterData.get().getToasterStatus(); }/*from www .j av a 2s .com*/ LOG.debug("Read toaster status: {}", toasterStatus); if (toasterStatus == ToasterStatus.Up) { if (outOfBread()) { LOG.debug("Toaster is out of bread"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeToasterOutOfBreadError())); } LOG.debug("Setting Toaster status to Down"); // We're not currently making toast - try to update the status to Down // to indicate we're going to make toast. This acts as a lock to prevent // concurrent toasting. tx.put(OPERATIONAL, TOASTER_IID, buildToaster(ToasterStatus.Down)); return tx.submit(); } LOG.debug("Oops - already making toast!"); // Return an error since we are already making toast. This will get // propagated to the commitFuture below which will interpret the null // TransactionStatus in the RpcResult as an error condition. return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeToasterInUseError())); }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { // OK to make toast currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult))); } @Override public void onFailure(final Throwable ex) { if (ex instanceof OptimisticLockFailedException) { // Another thread is likely trying to make toast simultaneously and updated the // status before us. Try reading the status again - if another make toast is // now in progress, we should get ToasterStatus.Down and fail. if ((tries - 1) > 0) { LOG.debug("Got OptimisticLockFailedException - trying again"); checkStatusAndMakeToast(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(ErrorType.APPLICATION, ex.getMessage()).build()); } } else { LOG.debug("Failed to commit Toaster status", ex); // Probably already making toast. futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } } }); }
From source file:org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver.java
@Override public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource( final SourceIdentifier sourceIdentifier) { final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier); LOG.debug("Lookup {} result {}", sourceIdentifier, ret); if (ret.isEmpty()) { return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException( "URL for " + sourceIdentifier + " not registered", sourceIdentifier)); }//from w w w .j av a2 s.co m return Futures.immediateCheckedFuture(ret.iterator().next()); }
From source file:org.opendaylight.camera.impl.CameraProvider.java
/** * Read the CameraStatus and, if currently Off, try to write the status to * On. If that succeeds, then we essentially have an exclusive lock and can * proceed to click the photo./*from ww w.j ava 2 s. c o m*/ * * @param input * @param futureResult * @param tries */ private void checkStatusandClickPhoto(final ClickPhotoInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { /* * We create a ReadWriteTransaction by using the databroker. Then, we * read the status of the camera with getCameraStatus() using the * databroker again. Once we have the status, we analyze it and then * databroker submit function is called to effectively change the camera * status. This all affects the MD-SAL tree, more specifically the part * of the tree that contain the camera (the nodes). */ LOG.info("In checkStatusandClickPhoto()"); final ReadWriteTransaction tx = db.newReadWriteTransaction(); ListenableFuture<Optional<CameraParams>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, CAMERA_IID); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<CameraParams>, Void>() { @SuppressWarnings("deprecation") @Override public ListenableFuture<Void> apply(Optional<CameraParams> cameraParamsData) throws Exception { // TODO Auto-generated method stub if (cameraParamsData.isPresent()) { status = cameraParamsData.get().getCameraStatus(); } else { throw new Exception("Error reading CameraParams data from the store."); } LOG.info("Read camera status: {}", status); if (status == CameraStatus.Off) { //Check if numberOfPhotosAvailable is not 0, if yes Notify outOfStock if (numberOfPhotosAvailable.get() == 0) { LOG.info("No more photos availble for clicking"); notificationProvider.publish(new CameraOutOfPhotosBuilder().build()); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", clickNoMorePhotosError())); } LOG.info("Setting Camera status to On"); // We're not currently clicking photo - try to // update the status to On // to indicate we're going to click photo. This acts // as a lock to prevent // concurrent clicking. tx.put(LogicalDatastoreType.OPERATIONAL, CAMERA_IID, buildCameraParams(CameraStatus.On)); return tx.submit(); } LOG.info("Oops - already clicking photo!"); // Return an error since we are already clicking photo. // This will get // propagated to the commitFuture below which will // interpret the null // TransactionStatus in the RpcResult as an error // condition. return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", clickPhotoInUseError())); } private RpcError clickNoMorePhotosError() { return RpcResultBuilder.newError(ErrorType.APPLICATION, "resource-denied", "No more photos available for clicking", "out-of-stock", null, null); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { if (t instanceof OptimisticLockFailedException) { // Another thread is likely trying to click a photo // simultaneously and updated the // status before us. Try reading the status again - if // another click-photo is // now in progress, we should get CameraStatus.Off and fail. if ((tries - 1) > 0) { LOG.info("Got OptimisticLockFailedException - trying again"); checkStatusandClickPhoto(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(ErrorType.APPLICATION, t.getMessage()).build()); } } else { LOG.info("Failed to commit Camera status", t); // Probably already clicking a photo. futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) t).getErrorList()).build()); } } @Override public void onSuccess(Void result) { // OK to click a photo currentClickPhotoTask.set(executor.submit(new ClickPhotoTask(input, futureResult))); } }); }