Example usage for com.google.common.util.concurrent CheckedFuture checkedGet

List of usage examples for com.google.common.util.concurrent CheckedFuture checkedGet

Introduction

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

Prototype

V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X;

Source Link

Document

Exception checking version of Future#get(long,TimeUnit) that will translate InterruptedException , CancellationException and ExecutionException into application-specific exceptions.

Usage

From source file:org.opendaylight.vtn.manager.internal.util.DataStoreUtils.java

/**
 * Wait for completion of the given read transaction future, and return
 * data./*from w  ww. ja  v a  2  s .c o m*/
 *
 * @param future  A future associated with a MD-SAL datastore read
 *                transaction.
 * @param <T>    Type of data to be read.
 * @return  An {@link Optional} instance that contains the result.
 *          {@code null} if no data is present.
 * @throws VTNException
 *    Failed to read data.
 */
public static <T extends DataObject> Optional<T> read(CheckedFuture<Optional<T>, ReadFailedException> future)
        throws VTNException {
    try {
        return future.checkedGet(READ_TIMEOUT, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        Status st = new Status(StatusCode.TIMEOUT, "Datastore read timed out.");
        throw new VTNException(st, e);
    } catch (Exception e) {
        throw new VTNException("Failed to read data from datastore.", e);
    }
}

From source file:org.opendaylight.vtn.manager.it.ofmock.DataStoreUtils.java

/**
 * Submit the given MD-SAL datastore transaction.
 *
 * @param tx  A {@link ReadWriteTransaction} instance.
 * @throws IllegalStateException//from   ww  w .  j  a  v  a2 s . co  m
 *    Failed to submit the given transaction.
 */
public static void submit(ReadWriteTransaction tx) {
    CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
    try {
        future.checkedGet(SUBMIT_TIMEOUT, TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        throw new IllegalStateException("Datastore submit timed out.", e);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to submit the transaction.", e);
    }
}

From source file:org.opendaylight.vtn.manager.it.ofmock.DataStoreUtils.java

/**
 * Wait for completion of the given read transaction future, and return
 * data.//ww  w .ja v a2s.c  om
 *
 * @param future  A future associated with a MD-SAL datastore read
 *                transaction.
 * @param <T>    Type of data to be read.
 * @return  An {@link Optional} instance that contains the result.
 *          {@code null} if no data is present.
 * @throws IllegalStateException
 *    Failed to read data.
 */
public static <T extends DataObject> Optional<T> read(CheckedFuture<Optional<T>, ReadFailedException> future)
        throws IllegalStateException {
    try {
        return future.checkedGet(READ_TIMEOUT, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        throw new IllegalStateException("Datastore read timed out.", e);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to read data from datastore.", e);
    }
}

From source file:org.opendaylight.vtn.manager.neutron.impl.MdsalUtils.java

/**
 * Executes read as a blocking transaction.
 *
 * @param rtx   Readable transaction for MD-SAL datastore.
 * @param store {@link LogicalDatastoreType} to read
 * @param path  {@link InstanceIdentifier} for path to read
 * @param <D>   The data object type
 * @return  An {@link Optional} instance that contains the result.
 * @throws ReadFailedException/*  w  w  w  .  j a  v a 2  s .c o  m*/
 *    Datastore read failed.
 * @throws TimeoutException
 *    Read operation timed out.
 */
private static <D extends DataObject> Optional<D> readImpl(final ReadTransaction rtx,
        final LogicalDatastoreType store, final InstanceIdentifier<D> path)
        throws ReadFailedException, TimeoutException {
    CheckedFuture<Optional<D>, ReadFailedException> future = rtx.read(store, path);
    return future.checkedGet(READ_TIMEOUT, TimeUnit.SECONDS);
}

From source file:org.dcache.srm.request.BringOnlineFileRequest.java

public static TReturnStatus unpinBySURL(AbstractStorageElement storage, SRMUser user, URI surl)
        throws SRMInternalErrorException {
    String fileId;//from w  ww  .  ja  v a 2s  .  co  m
    try {
        fileId = storage.getFileMetaData(user, surl, true).fileId;
    } catch (SRMInternalErrorException e) {
        throw e;
    } catch (SRMAuthorizationException e) {
        return new TReturnStatus(TStatusCode.SRM_AUTHORIZATION_FAILURE, e.getMessage());
    } catch (SRMInvalidPathException e) {
        return new TReturnStatus(TStatusCode.SRM_INVALID_PATH, e.getMessage());
    } catch (SRMException e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, e.getMessage());
    }

    CheckedFuture<String, ? extends SRMException> future = storage.unPinFile(user, fileId);
    try {
        future.checkedGet(60, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        throw new SRMInternalErrorException("Operation timed out");
    } catch (SRMException e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, "Failed to unpin: " + e.getMessage());
    }
    return new TReturnStatus(TStatusCode.SRM_SUCCESS, null);
}

From source file:org.dcache.srm.request.BringOnlineFileRequest.java

public static TReturnStatus unpinBySURLandRequestToken(AbstractStorageElement storage, SRMUser user,
        String requestToken, URI surl) throws SRMInternalErrorException {
    String fileId;//  www .j  a  va 2 s  . co  m
    try {
        fileId = storage.getFileMetaData(user, surl, true).fileId;
    } catch (SRMInternalErrorException e) {
        throw e;
    } catch (SRMAuthorizationException e) {
        return new TReturnStatus(TStatusCode.SRM_AUTHORIZATION_FAILURE, e.getMessage());
    } catch (SRMInvalidPathException e) {
        return new TReturnStatus(TStatusCode.SRM_INVALID_PATH, e.getMessage());
    } catch (SRMException e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, e.getMessage());
    }

    CheckedFuture<String, ? extends SRMException> future = storage.unPinFileBySrmRequestId(user, fileId,
            requestToken);
    try {
        future.checkedGet(60, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        throw new SRMInternalErrorException("Operation timed out");
    } catch (SRMException e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, "Failed to unpin: " + e.getMessage());
    }
    return new TReturnStatus(TStatusCode.SRM_SUCCESS, null);
}

From source file:org.opendaylight.vtn.manager.it.ofmock.impl.TxTask.java

/**
 * Submit the given DS transaction./*from w ww  .  j  a  va2 s . c o  m*/
 *
 * @param tx        A read-write MD-SAL datastore transaction.
 * @param attempts  The number of calls of this method.
 *                  0 is passed for the first call.
 * @return  {@code true} if the transaction was submitted.
 *          {@code false} if the MD-SAL DS transaction should be retried.
 * @throws TransactionCommitFailedException
 *    Failed to submit the transaction.
 * @throws TimeoutException
 *    Operation timed out.
 */
private boolean submit(ReadWriteTransaction tx, int attempts)
        throws TransactionCommitFailedException, TimeoutException {
    boolean submitted = false;
    try {
        CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
        future.checkedGet(SUBMIT_TIMEOUT, TimeUnit.NANOSECONDS);
        submitted = true;
    } catch (OptimisticLockFailedException e) {
        if (attempts < MAX_RETRY) {
            // In this case the transaction should be retried.
            Logger logger = getLogger();
            logger.debug("Transaction failed due to data conflict.", e);
        } else {
            throw e;
        }
    }

    return submitted;
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager.java

/**
 * change role on each connected device/*from www. ja  va  2s.co m*/
 *
 * @param role openflow role
 */
public void manageRoleChange(final OfpRole role) {
    for (final SessionContext session : sessionManager.getAllSessions()) {
        try {
            workQueue.put(new RolePushTask(role, session));
        } catch (InterruptedException e) {
            LOG.warn("Processing of role request failed while enqueueing role task: {}", e.getMessage());
        }
    }

    while (!workQueue.isEmpty()) {
        RolePushTask task = workQueue.poll();
        ListenableFuture<Boolean> rolePushResult = broadcastPool.submit(task);
        CheckedFuture<Boolean, RolePushException> rolePushResultChecked = RoleUtil
                .makeCheckedRuleRequestFxResult(rolePushResult);
        try {
            Boolean succeeded = rolePushResultChecked.checkedGet(TIMEOUT, TIMEOUT_UNIT);
            if (!MoreObjects.firstNonNull(succeeded, Boolean.FALSE)) {
                if (task.getRetryCounter() < RETRY_LIMIT) {
                    workQueue.offer(task);
                }
            }
        } catch (RolePushException | TimeoutException e) {
            LOG.warn("failed to process role request: {}", e);
        }
    }
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager.java

public void manageRoleChange(final OfpRole role, List<String> datapathIds) {
    LOG.info("manageRoleChange with role:" + role.toString());
    for (final SessionContext session : sessionManager.getAllSessions()) {
        if (datapathIds.contains(session.getFeatures().getDatapathId().toString())) {
            //                try {
            //                        workQueue.put(new RolePushTask(role, session));
            //                } catch (InterruptedException e) {
            //                        LOG.warn("Processing of role request failed while enqueueing role task: {}", e.getMessage());
            //                }
            if (role.equals(OfpRole.BECOMESLAVE))
                OFSessionUtil.setRole(session, ControllerRole.OFPCRROLESLAVE);
            if (role.equals(OfpRole.BECOMEMASTER))
                OFSessionUtil.setRole(session, ControllerRole.OFPCRROLEMASTER);
            if (role.equals(OfpRole.BECOMEEQUAL))
                OFSessionUtil.setRole(session, ControllerRole.OFPCRROLEEQUAL);

        }//from w w w  .java 2s.c  om
    }

    while (!workQueue.isEmpty()) {
        RolePushTask task = workQueue.poll();
        ListenableFuture<Boolean> rolePushResult = broadcastPool.submit(task);
        CheckedFuture<Boolean, RolePushException> rolePushResultChecked = RoleUtil
                .makeCheckedRuleRequestFxResult(rolePushResult);
        try {
            Boolean succeeded = rolePushResultChecked.checkedGet(TIMEOUT, TIMEOUT_UNIT);
            if (!MoreObjects.firstNonNull(succeeded, Boolean.FALSE)) {
                if (task.getRetryCounter() < RETRY_LIMIT) {
                    workQueue.offer(task);
                }
            }
        } catch (RolePushException | TimeoutException e) {
            LOG.warn("failed to process role request: {}", e);
        }
    }
}

From source file:org.dcache.srm.request.BringOnlineFileRequest.java

public TReturnStatus release(SRMUser user) throws SRMInternalErrorException {
    String fileId;//  w  w  w  .j a  v a 2s .  c  o  m
    String pinId;

    wlock();
    try {
        State state = getState();
        switch (state) {
        case DONE:
            fileId = getFileId();
            pinId = getPinId();
            if (fileId == null || pinId == null) {
                return new TReturnStatus(TStatusCode.SRM_FAILURE, "SURL is not pinned");
            }
            // Unpinning is done below, outside the lock
            break;
        case CANCELED:
            return new TReturnStatus(TStatusCode.SRM_ABORTED, "SURL has been aborted and cannot be released");
        case FAILED:
            return new TReturnStatus(TStatusCode.SRM_FAILURE, "Pinning failed");
        default:
            setState(State.CANCELED, "Aborted by srmReleaseFile request.");
            return new TReturnStatus(TStatusCode.SRM_ABORTED, "SURL is not yet pinned, pinning aborted");
        }
    } catch (IllegalStateTransition e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, e.getMessage());
    } finally {
        wunlock();
    }

    LOGGER.debug("srmReleaseFile, unpinning fileId={} pinId={}", fileId, pinId);
    CheckedFuture<String, ? extends SRMException> future = getStorage().unPinFile(user, fileId, pinId);
    try {
        future.checkedGet(60, TimeUnit.SECONDS);
        setPinId(null);
        saveJob(true);
        return new TReturnStatus(TStatusCode.SRM_SUCCESS, null);
    } catch (TimeoutException e) {
        throw new SRMInternalErrorException("Operation timed out.");
    } catch (SRMException e) {
        return new TReturnStatus(TStatusCode.SRM_FAILURE, "Failed to unpin SURL: " + e.getMessage());
    }
}