Example usage for com.google.common.util.concurrent Futures makeChecked

List of usage examples for com.google.common.util.concurrent Futures makeChecked

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(ListenableFuture<V> future,
        Function<? super Exception, X> mapper) 

Source Link

Document

Creates a CheckedFuture out of a normal ListenableFuture and a Function that maps from Exception instances into the appropriate checked type.

Usage

From source file:diskCacheV111.srm.dcache.Storage.java

@Override
public CheckedFuture<String, ? extends SRMException> unPinFile(SRMUser user, String fileId, String pinId) {
    if (PinCompanion.isFakePinId(pinId)) {
        return Futures.immediateCheckedFuture(null);
    }//  ww w .j  a v  a  2s.  c  om

    try {
        Subject subject = (user == null) ? Subjects.ROOT : asDcacheUser(user).getSubject();
        return Futures.makeChecked(UnpinCompanion.unpinFile(subject, new PnfsId(fileId), Long.parseLong(pinId),
                _pinManagerStub, _executor), new ToSRMException());
    } catch (SRMAuthorizationException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }
}

From source file:diskCacheV111.srm.dcache.Storage.java

@Override
public CheckedFuture<String, ? extends SRMException> unPinFileBySrmRequestId(SRMUser user, String fileId,
        String requestToken) {/*from  www . j  av  a 2 s .c  o  m*/
    try {
        return Futures.makeChecked(UnpinCompanion.unpinFileBySrmRequestId(asDcacheUser(user).getSubject(),
                new PnfsId(fileId), requestToken, _pinManagerStub, _executor), new ToSRMException());
    } catch (SRMAuthorizationException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }
}

From source file:diskCacheV111.srm.dcache.Storage.java

@Override
public CheckedFuture<String, ? extends SRMException> unPinFile(SRMUser user, String fileId) {
    try {/*from  w  w  w.ja  v  a2 s  . c om*/
        return Futures.makeChecked(UnpinCompanion.unpinFile(asDcacheUser(user).getSubject(), new PnfsId(fileId),
                _pinManagerStub, _executor), new ToSRMException());
    } catch (SRMAuthorizationException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

@Override
public <T extends DataObject> CheckedFuture<Void, DTxException> mergeAndRollbackOnFailure(
        DTXLogicalTXProviderType logicalTXProviderType, LogicalDatastoreType logicalDatastoreType,
        InstanceIdentifier<T> instanceIdentifier, T t, InstanceIdentifier<?> nodeId) {
    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    final DTXReadWriteTransaction transaction = this.perNodeTransactionsbyLogicalType.get(logicalTXProviderType)
            .get(nodeId);//  w  w w.ja v a  2s. c  o m

    CheckedFuture<Void, DTxException> mergeFuture = transaction.asyncMerge(logicalDatastoreType,
            instanceIdentifier, t);

    final SettableFuture<Void> retFuture = SettableFuture.create();

    Futures.addCallback(mergeFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void aVoid) {
            retFuture.set(null);
        }

        @Override
        public void onFailure(Throwable throwable) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback();
                    Futures.addCallback(rollExcept, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void aVoid) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.EditFailedException(
                                    "Failed to merge but succeed to rollback"));
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.RollbackFailedException(throwable));
                        }
                    });
                }
            };

            new Thread(runnable).start();
        }
    });

    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("Merge failed and rollback failure", e);
        }
    });
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

@Override
public <T extends DataObject> CheckedFuture<Void, DTxException> putAndRollbackOnFailure(
        DTXLogicalTXProviderType logicalTXProviderType, LogicalDatastoreType logicalDatastoreType,
        InstanceIdentifier<T> instanceIdentifier, T t, InstanceIdentifier<?> nodeId) {
    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    final DTXReadWriteTransaction transaction = this.perNodeTransactionsbyLogicalType.get(logicalTXProviderType)
            .get(nodeId);//from w w w  .ja  v a  2 s  .  c om
    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    CheckedFuture<Void, DTxException> putFuture = transaction.asyncPut(logicalDatastoreType, instanceIdentifier,
            t);

    final SettableFuture<Void> retFuture = SettableFuture.create();

    Futures.addCallback(putFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void aVoid) {
            retFuture.set(null);
        }

        @Override
        public void onFailure(Throwable throwable) {
            LOG.trace("asyncput failure callback begin to roll back ");
            Runnable rolllbackRoutine = new Runnable() {
                @Override
                public void run() {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback();

                    Futures.addCallback(rollExcept, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void result) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.EditFailedException(
                                    "Failed to put but succeed to rollback"));
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.RollbackFailedException(t));
                        }
                    });
                }
            };

            new Thread(rolllbackRoutine).start();
        }
    });

    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 failed and rollback failure", e);
        }
    });
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

@Override
public CheckedFuture<Void, DTxException> deleteAndRollbackOnFailure(
        DTXLogicalTXProviderType logicalTXProviderType, LogicalDatastoreType logicalDatastoreType,
        InstanceIdentifier<?> instanceIdentifier, InstanceIdentifier<?> nodeId) {

    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    final DTXReadWriteTransaction transaction = this.perNodeTransactionsbyLogicalType.get(logicalTXProviderType)
            .get(nodeId);//from w  w w.  j  a va2 s  .  co  m
    CheckedFuture<Void, DTxException> deleteFuture = transaction.asyncDelete(logicalDatastoreType,
            instanceIdentifier);

    final SettableFuture<Void> retFuture = SettableFuture.create();

    Futures.addCallback(deleteFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void aVoid) {
            retFuture.set(null);
        }

        @Override
        public void onFailure(Throwable throwable) {

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback();

                    Futures.addCallback(rollExcept, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void aVoid) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.EditFailedException(
                                    "Failed to delete but succeed to rollback"));
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.RollbackFailedException(throwable));
                        }
                    });

                }
            };
            new Thread(runnable).start();
        }
    });

    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("delete failed and rollback failure", e);
        }
    });
}

From source file:diskCacheV111.srm.dcache.Storage.java

@Override
public CheckedFuture<String, ? extends SRMException> prepareToPut(final SRMUser srmUser, URI surl, Long size,
        String accessLatency, String retentionPolicy, String spaceToken, boolean overwrite) {
    try {//from ww w .  j  a v a  2  s. c o m
        DcacheUser user = asDcacheUser(srmUser);
        Subject subject = user.getSubject();
        Restriction restriction = user.getRestriction();
        FsPath fullPath = config.getPath(surl);

        if (spaceToken != null) {
            if (!_isSpaceManagerEnabled) {
                return immediateFailedCheckedFuture(
                        new SRMNotSupportedException(SPACEMANAGER_DISABLED_MESSAGE));
            }

            /* This check could and maybe should be done on the SRM side of AbstractStorageElement:
             * The targetSpaceToken is the same for all SURLs in an srmPrepareToPut request, and the
             * SRM_EXCEED_ALLOCATION should also be returned if the entire srmPrepareToPut request
             * is larger than available space in the reservation - that's a check we cannot possibly
             * to on an individual SURL.
             */
            try {
                Optional<Space> optionalSpace = spaces.get(spaceToken);
                if (!optionalSpace.isPresent()) {
                    return immediateFailedCheckedFuture(new SRMInvalidRequestException("The space token "
                            + spaceToken + " does not refer to an existing known space reservation."));
                }
                Space space = optionalSpace.get();
                if (space.getExpirationTime() != null
                        && space.getExpirationTime() < System.currentTimeMillis()) {
                    return immediateFailedCheckedFuture(new SRMSpaceLifetimeExpiredException(
                            "Space reservation associated with the space token " + spaceToken
                                    + " is expired."));
                }
                if (size != null && space.getAvailableSpaceInBytes() < size) {
                    return immediateFailedCheckedFuture(
                            new SRMExceedAllocationException("Space associated with the space token "
                                    + spaceToken + " is not enough to hold SURL."));
                }
            } catch (ExecutionException e) {
                return immediateFailedCheckedFuture(new SRMException(
                        "Failure while querying space reservation: " + e.getCause().getMessage()));
            }
        }

        AccessLatency al = (accessLatency != null) ? AccessLatency.valueOf(accessLatency) : null;
        RetentionPolicy rp = (retentionPolicy != null) ? RetentionPolicy.valueOf(retentionPolicy) : null;
        EnumSet<CreateOption> options = EnumSet.noneOf(CreateOption.class);
        if (overwrite) {
            options.add(CreateOption.OVERWRITE_EXISTING);
        }
        if (config.isRecursiveDirectoryCreation()) {
            options.add(CreateOption.CREATE_PARENTS);
        }
        PnfsCreateUploadPath msg = new PnfsCreateUploadPath(subject, restriction, fullPath, user.getRoot(),
                size, al, rp, spaceToken, options);

        final SettableFuture<String> future = SettableFuture.create();
        CellStub.addCallback(_pnfsStub.send(msg), new AbstractMessageCallback<PnfsCreateUploadPath>() {
            int failures = 0;

            @Override
            public void success(PnfsCreateUploadPath message) {
                future.set(message.getUploadPath().toString());
            }

            @Override
            public void failure(int rc, Object error) {
                failures++;
                String msg = Objects.toString(error, "");
                switch (rc) {
                case CacheException.PERMISSION_DENIED:
                    future.setException(new SRMAuthorizationException(msg));
                    break;
                case CacheException.FILE_EXISTS:
                    future.setException(new SRMDuplicationException(msg));
                    break;
                case CacheException.FILE_NOT_FOUND:
                case CacheException.NOT_DIR:
                    future.setException(new SRMInvalidPathException(msg));
                    break;
                case CacheException.LOCKED:
                    if (failures < 3) {
                        /* Usually due to concurrent uploads to the same non-existing target
                         * directory. Retry a few times.
                         */
                        PnfsCreateUploadPath retry = new PnfsCreateUploadPath(subject, restriction, fullPath,
                                user.getRoot(), size, al, rp, spaceToken, options);
                        CellStub.addCallback(_pnfsStub.send(retry), this, _executor);
                    } else {
                        future.setException(new SRMInternalErrorException(msg));
                    }
                    break;
                case CacheException.TIMEOUT:
                default:
                    future.setException(new SRMInternalErrorException(msg));
                    break;
                }
            }
        }, _executor);
        return Futures.makeChecked(future, new ToSRMException());
    } catch (SRMAuthorizationException | SRMInvalidPathException e) {
        return immediateFailedCheckedFuture(e);
    }
}