Example usage for com.google.common.base Optional transform

List of usage examples for com.google.common.base Optional transform

Introduction

In this page you can find the example usage for com.google.common.base Optional transform.

Prototype

public abstract <V> Optional<V> transform(Function<? super T, V> function);

Source Link

Document

If the instance is present, it is transformed with the given Function ; otherwise, Optional#absent is returned.

Usage

From source file:com.eucalyptus.auth.euare.RegionDelegatingPrincipalProvider.java

private <R> R regionDispatch(final Optional<RegionInfo> regionInfo,
        final NonNullFunction<PrincipalProvider, R> invoker) throws AuthException {
    try {//ww w  . j  a v  a2s  .  com
        if (regionInfo.isPresent()
                && !RegionConfigurations.getRegionName().asSet().contains(regionInfo.get().getName())) {
            final Optional<Set<String>> endpoints = regionInfo
                    .transform(RegionInfo.serviceEndpoints("identity"));
            if (endpoints.isPresent() && !endpoints.get().isEmpty()) {
                final PrincipalProvider remoteProvider = new RemotePrincipalProvider(endpoints.get());
                return invoker.apply(remoteProvider);
            }
            return invoker.apply(localProvider);
        } else {
            return invoker.apply(localProvider);
        }
    } catch (final RuntimeException e) {
        Exceptions.findAndRethrow(e, AuthException.class);
        throw e;
    }
}

From source file:org.apache.aurora.scheduler.state.TaskStateMachine.java

/**
 * Attempt to transition the state machine to the provided state.
 * At the time this method returns, any work commands required to satisfy the state transition
 * will be appended to the work queue.//w ww  . j a v a  2s  . co  m
 *
 * TODO(maxim): The current StateManager/TaskStateMachine interaction makes it hard to expose
 * a dedicated task deletion method without leaking out the state machine implementation details.
 * Consider refactoring here to allow for an unambiguous task deletion without resorting to
 * Optional.absent().
 *
 * @param status Status to apply to the task or absent if a task deletion is required.
 * @return {@code true} if the state change was allowed, {@code false} otherwise.
 */
public synchronized TransitionResult updateState(final Optional<ScheduleStatus> status) {
    requireNonNull(status);
    Preconditions.checkState(sideEffects.isEmpty());

    /**
     * Don't bother applying noop state changes.  If we end up modifying task state without a
     * state transition (e.g. storing resource consumption of a running task), we need to find
     * a different way to suppress noop transitions.
     */
    TaskState taskState = status.transform(STATUS_TO_TASK_STATE).or(DELETED);
    if (stateMachine.getState() == taskState) {
        return new TransitionResult(NOOP, ImmutableSet.of());
    }

    boolean success = stateMachine.transition(taskState);
    ImmutableSet<SideEffect> transitionEffects = ImmutableSet.copyOf(sideEffects);
    sideEffects.clear();
    if (success) {
        return new TransitionResult(SUCCESS, transitionEffects);
    }
    return new TransitionResult(transitionEffects.isEmpty() ? ILLEGAL : ILLEGAL_WITH_SIDE_EFFECTS,
            transitionEffects);
}

From source file:org.opendaylight.nemo.user.tenantmanager.TenantManage.java

/**
*
* @return null if an error was encountered, or an empty map if there was no
*         error but no data was retrieved.
*//*from   w  ww .j  a  va2s .  co  m*/
public Map<UserId, User> getUsers() {
    InstanceIdentifier<Users> usersInsId = InstanceIdentifier.builder(Users.class).build();
    ListenableFuture<Optional<Users>> usersFuture = dataBroker.newReadOnlyTransaction()
            .read(LogicalDatastoreType.CONFIGURATION, usersInsId);

    final Optional<Users> usersOpt;
    try {
        // TODO: consider time out here?
        usersOpt = usersFuture.get();
    } catch (InterruptedException e) {
        LOG.error("Cannot read user information.", e);
        return null;
    } catch (ExecutionException e) {
        LOG.error("Cannot read user information.", e);
        return null;
    }

    // TODO: change to Java 8 lambda expressions
    return usersOpt.transform(new Function<Users, Map<UserId, User>>() {
        @Override
        public Map<UserId, User> apply(Users input) {
            return Maps.uniqueIndex(input.getUser(), new Function<User, UserId>() {
                @Override
                public UserId apply(User user) {
                    return user.getUserId();
                }
            });
        }
    }).or(new HashMap<UserId, User>());
}

From source file:org.opendaylight.nemo.user.tenantmanager.TenantManage.java

/**
 *
 * @return null if an error was encountered, or an empty map if there was no
 *         error but no data was retrieved.
 *//*ww  w  .  j a v a 2s .  co m*/
public Map<UserRoleName, UserRole> getUserRoles() {

    InstanceIdentifier<UserRoles> userRolesInsId = InstanceIdentifier.builder(UserRoles.class).build();
    ListenableFuture<Optional<UserRoles>> userRolesFuture = this.dataBroker.newReadOnlyTransaction()
            .read(LogicalDatastoreType.CONFIGURATION, userRolesInsId);

    final Optional<UserRoles> userRolesOpt;
    try {
        // TODO: consider time out here?
        userRolesOpt = userRolesFuture.get();
    } catch (InterruptedException e) {
        LOG.error("Cannot read role information.", e);
        return null;
    } catch (ExecutionException e) {
        LOG.error("Cannot read role information.", e);
        return null;
    }

    // TODO: change to Java 8 lambda expressions
    return userRolesOpt.transform(new Function<UserRoles, Map<UserRoleName, UserRole>>() {
        @Override
        public Map<UserRoleName, UserRole> apply(UserRoles input) {
            return Maps.uniqueIndex(input.getUserRole(), new Function<UserRole, UserRoleName>() {
                @Override
                public UserRoleName apply(UserRole role) {
                    return role.getRoleName();
                }
            });
        }
    }).or(new HashMap<UserRoleName, UserRole>());
}

From source file:com.b2international.snowowl.snomed.api.impl.SnomedBrowserService.java

@Override
public List<ISnomedBrowserParentConcept> getConceptParents(final String branchPath, final String conceptId,
        final List<ExtendedLocale> locales, boolean isStatedForm,
        SnomedBrowserDescriptionType preferredDescriptionType) {
    final DescriptionService descriptionService = new DescriptionService(getBus(), branchPath);

    return new FsnJoinerOperation<ISnomedBrowserParentConcept>(conceptId, locales, descriptionService,
            preferredDescriptionType) {/* w w w .  java 2s . c o  m*/

        @Override
        protected Iterable<SnomedConcept> getConceptEntries(String conceptId) {
            SnomedConcept concept = SnomedRequests.prepareGetConcept(conceptId)
                    .setExpand(isStatedForm ? "statedAncestors(direct:true)" : "ancestors(direct:true)")
                    .setLocales(locales).build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath)
                    .execute(getBus()).getSync();
            return isStatedForm ? concept.getStatedAncestors() : concept.getAncestors();
        }

        @Override
        protected ISnomedBrowserParentConcept convertConceptEntry(SnomedConcept conceptEntry,
                Optional<SnomedDescription> descriptionOptional) {
            final String childConceptId = conceptEntry.getId();
            final SnomedBrowserParentConcept convertedConcept = new SnomedBrowserParentConcept();

            convertedConcept.setConceptId(childConceptId);
            convertedConcept.setDefinitionStatus(conceptEntry.getDefinitionStatus());

            String term = descriptionOptional.transform(description -> description.getTerm())
                    .or(conceptEntry.getId());
            if (preferredDescriptionType == SnomedBrowserDescriptionType.FSN) {
                convertedConcept.setFsn(term);
            } else if (preferredDescriptionType == SnomedBrowserDescriptionType.SYNONYM) {
                convertedConcept.setPreferredSynonym(term);
            }

            return convertedConcept;
        }

    }.run();
}

From source file:com.eucalyptus.simpleworkflow.stateful.TimeoutManager.java

private void timeoutDecisionTasksAndWorkflows() {
    final Set<NotifyTaskList> taskLists = Sets.newHashSet();
    try {/*from w  ww.  ja  v  a2s  .  c o m*/
        final long now = System.currentTimeMillis();
        for (final WorkflowExecution workflowExecution : workflowExecutions.listTimedOut(now,
                Functions.<WorkflowExecution>identity())) {
            try (final WorkflowLock lock = WorkflowLock.lock(workflowExecution.getOwnerAccountNumber(),
                    workflowExecution.getDomainUuid(), workflowExecution.getDisplayName())) {
                workflowExecutions.withRetries().updateByExample(workflowExecution,
                        workflowExecution.getOwner(), workflowExecution.getDisplayName(),
                        new Function<WorkflowExecution, Void>() {
                            @Override
                            public Void apply(final WorkflowExecution workflowExecution) {
                                final Date timeout = workflowExecution.calculateNextTimeout();
                                if (timeout != null) {
                                    if (workflowExecution.isWorkflowTimedOut(now,
                                            getWorkflowExecutionDurationMillis())) {
                                        workflowExecution.closeWorkflow(WorkflowExecution.CloseStatus.Timed_Out,
                                                WorkflowHistoryEvent.create(workflowExecution,
                                                        new WorkflowExecutionTimedOutEventAttributes()
                                                                .withTimeoutType("START_TO_CLOSE")
                                                                .withChildPolicy(
                                                                        workflowExecution.getChildPolicy())));
                                    } else { // decision task timed out
                                        final List<WorkflowHistoryEvent> events = workflowExecution
                                                .getWorkflowHistory();
                                        final List<WorkflowHistoryEvent> reverseEvents = Lists.reverse(events);
                                        final WorkflowHistoryEvent scheduled = Iterables.find(reverseEvents,
                                                CollectionUtils.propertyPredicate("DecisionTaskScheduled",
                                                        WorkflowExecutions.WorkflowHistoryEventStringFunctions.EVENT_TYPE));
                                        final Optional<WorkflowHistoryEvent> previousStarted = Iterables
                                                .tryFind(reverseEvents, CollectionUtils.propertyPredicate(
                                                        "DecisionTaskStarted",
                                                        WorkflowExecutions.WorkflowHistoryEventStringFunctions.EVENT_TYPE));
                                        workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                workflowExecution,
                                                new DecisionTaskTimedOutEventAttributes()
                                                        .withTimeoutType("START_TO_CLOSE")
                                                        .withScheduledEventId(scheduled.getEventId())
                                                        .withStartedEventId(previousStarted.transform(
                                                                WorkflowExecutions.WorkflowHistoryEventLongFunctions.EVENT_ID)
                                                                .orNull())));
                                        workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                workflowExecution,
                                                new DecisionTaskScheduledEventAttributes()
                                                        .withTaskList(new TaskList()
                                                                .withName(workflowExecution.getTaskList()))
                                                        .withStartToCloseTimeout(
                                                                String.valueOf(workflowExecution
                                                                        .getTaskStartToCloseTimeout()))));
                                        workflowExecution.setDecisionStatus(Pending);
                                        workflowExecution.setDecisionTimestamp(new Date());
                                        addToNotifyLists(taskLists, workflowExecution);
                                    }
                                }
                                return null;
                            }
                        });
            } catch (final SwfMetadataException e) {
                if (!handleException(e)) {
                    logger.error("Error processing workflow execution/decision task timeout: "
                            + workflowExecution.getDisplayName(), e);
                }
            }
        }
    } catch (final SwfMetadataException e) {
        logger.error("Error processing workflow execution/decision task timeouts", e);
    }
    notifyLists(taskLists);
}

From source file:com.b2international.snowowl.snomed.api.impl.SnomedBrowserService.java

@Override
public List<ISnomedBrowserChildConcept> getConceptChildren(String branchPath, String conceptId,
        List<ExtendedLocale> locales, boolean isStatedForm,
        SnomedBrowserDescriptionType preferredDescriptionType, int limit) {

    final DescriptionService descriptionService = new DescriptionService(getBus(), branchPath);

    return new FsnJoinerOperation<ISnomedBrowserChildConcept>(conceptId, locales, descriptionService,
            preferredDescriptionType) {/*from  w  w w  .  ja  va 2 s .  co m*/

        @Override
        protected Iterable<SnomedConcept> getConceptEntries(String conceptId) {
            return SnomedRequests.prepareSearchConcept().setLimit(limit)
                    .setExpand("statedDescendants(direct:true,limit:0),descendants(direct:true,limit:0)")
                    .filterByActive(true).filterByParent(isStatedForm ? null : conceptId)
                    .filterByStatedParent(isStatedForm ? conceptId : null)
                    .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath).execute(getBus()).getSync();
        }

        @Override
        protected ISnomedBrowserChildConcept convertConceptEntry(SnomedConcept conceptEntry,
                Optional<SnomedDescription> descriptionOptional) {

            final String childConceptId = conceptEntry.getId();
            final SnomedBrowserChildConcept convertedConcept = new SnomedBrowserChildConcept();

            convertedConcept.setConceptId(childConceptId);
            convertedConcept.setActive(conceptEntry.isActive());
            convertedConcept.setDefinitionStatus(conceptEntry.getDefinitionStatus());
            convertedConcept.setModuleId(conceptEntry.getModuleId());

            String term = descriptionOptional.transform(description -> description.getTerm())
                    .or(conceptEntry.getId());
            if (preferredDescriptionType == SnomedBrowserDescriptionType.FSN) {
                convertedConcept.setFsn(term);
            } else if (preferredDescriptionType == SnomedBrowserDescriptionType.SYNONYM) {
                convertedConcept.setPreferredSynonym(term);
            }

            convertedConcept.setIsLeafStated(conceptEntry.getStatedDescendants().getTotal() == 0);
            convertedConcept.setIsLeafInferred(conceptEntry.getDescendants().getTotal() == 0);

            return convertedConcept;
        }

    }.run();
}

From source file:com.github.filosganga.geogson.gson.PositionsAdapter.java

private Positions parsePositions(JsonReader in) throws IOException {

    Optional<Positions> parsed = Optional.absent();

    if (in.peek() != JsonToken.BEGIN_ARRAY) {
        throw new IllegalArgumentException("The given json is not a valid positions");
    }/*from ww  w .j  a va  2s  .  co m*/

    in.beginArray();
    if (in.peek() == JsonToken.NUMBER) {
        parsed = Optional.of(parseSinglePosition(in));
    } else if (in.peek() == JsonToken.BEGIN_ARRAY) {
        while (in.hasNext()) {
            Positions thisPositions = parsePositions(in);
            // fix bug #30: according to the recursion (i.e. the array structure;
            // recognize that we came from a recursion because no parsed has no
            // value yet): convert the already parsed Positions to the
            // LinearPositions/AreaPositions matching the recursion level
            if (parsed.equals(Optional.absent()) && thisPositions instanceof LinearPositions) {
                AreaPositions areaPositions = new AreaPositions(
                        ImmutableList.of((LinearPositions) thisPositions));
                parsed = Optional.of((Positions) areaPositions);
            } else if (parsed.equals(Optional.absent()) && thisPositions instanceof AreaPositions) {
                MultiDimensionalPositions multiPositions = new MultiDimensionalPositions(
                        ImmutableList.of((AreaPositions) thisPositions));
                parsed = Optional.of((Positions) multiPositions);
            } else {
                // mergeFn() does all the rest, if parsed has a value
                parsed = parsed.transform(mergeFn(thisPositions)).or(Optional.of(thisPositions));
            }

        }
    }

    in.endArray();

    return parsed.orNull();
}

From source file:com.eucalyptus.simpleworkflow.SimpleWorkflowService.java

public DecisionTask pollForDecisionTask(final PollForDecisionTaskRequest request)
        throws SimpleWorkflowException {
    final Context ctx = Contexts.lookup();
    final UserFullName userFullName = ctx.getUserFullName();
    final AccountFullName accountFullName = userFullName.asAccountFullName();
    final Predicate<? super WorkflowExecution> accessible = SimpleWorkflowMetadatas
            .filteringFor(WorkflowExecution.class).byPrivileges().buildPredicate();

    final String domain = request.getDomain();
    final String taskList = request.getTaskList().getName();
    final Callable<DecisionTask> taskCallable = new Callable<DecisionTask>() {
        @Override//from w w  w .  ja  v  a 2s  .co  m
        public DecisionTask call() throws Exception {
            final List<WorkflowExecution> pending = workflowExecutions.listByExample(
                    WorkflowExecution.exampleWithPendingDecision(accountFullName, domain, taskList), accessible,
                    Functions.<WorkflowExecution>identity());
            Collections.sort(pending, Ordering.natural().onResultOf(AbstractPersistentSupport.creation()));
            DecisionTask decisionTask = null;
            for (final WorkflowExecution execution : pending) {
                if (decisionTask != null)
                    break;
                boolean retry = true;
                while (retry)
                    try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, execution.getDomainUuid(),
                            execution.getDisplayName())) {
                        retry = false;
                        decisionTask = workflowExecutions.updateByExample(
                                WorkflowExecution.exampleWithUniqueName(accountFullName,
                                        execution.getDomainName(), execution.getDisplayName()),
                                accountFullName, execution.getDisplayName(),
                                new Function<WorkflowExecution, DecisionTask>() {
                                    @Nullable
                                    @Override
                                    public DecisionTask apply(final WorkflowExecution workflowExecution) {
                                        if (workflowExecution.getDecisionStatus() == Pending) {
                                            final List<WorkflowHistoryEvent> events = workflowExecution
                                                    .getWorkflowHistory();
                                            final List<WorkflowHistoryEvent> reverseEvents = Lists
                                                    .reverse(events);
                                            final WorkflowHistoryEvent scheduled = Iterables.find(reverseEvents,
                                                    CollectionUtils.propertyPredicate("DecisionTaskScheduled",
                                                            EVENT_TYPE));
                                            final Optional<WorkflowHistoryEvent> previousStarted = Iterables
                                                    .tryFind(reverseEvents, CollectionUtils.propertyPredicate(
                                                            "DecisionTaskStarted", EVENT_TYPE));
                                            workflowExecution.setDecisionStatus(Active);
                                            workflowExecution.setDecisionTimestamp(new Date());
                                            final WorkflowHistoryEvent started = WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new DecisionTaskStartedEventAttributes()
                                                            .withIdentity(request.getIdentity())
                                                            .withScheduledEventId(scheduled.getEventId()));
                                            workflowExecution.addHistoryEvent(started);
                                            return new DecisionTask().withWorkflowExecution(
                                                    new com.eucalyptus.simpleworkflow.common.model.WorkflowExecution()
                                                            .withWorkflowId(workflowExecution.getWorkflowId())
                                                            .withRunId(workflowExecution.getDisplayName()))
                                                    .withWorkflowType(
                                                            new com.eucalyptus.simpleworkflow.common.model.WorkflowType()
                                                                    .withName(workflowExecution
                                                                            .getWorkflowType().getDisplayName())
                                                                    .withVersion(
                                                                            workflowExecution.getWorkflowType()
                                                                                    .getWorkflowVersion()))
                                                    .withTaskToken(taskTokenManager.encryptTaskToken(
                                                            new TaskToken(accountFullName.getAccountNumber(),
                                                                    workflowExecution.getDomain()
                                                                            .getNaturalId(),
                                                                    workflowExecution.getDisplayName(),
                                                                    scheduled.getEventId(),
                                                                    started.getEventId(),
                                                                    System.currentTimeMillis(),
                                                                    System.currentTimeMillis()))) //TODO:STEVE: token expiry date
                                                    .withStartedEventId(started.getEventId())
                                                    .withPreviousStartedEventId(previousStarted.transform(
                                                            WorkflowExecutions.WorkflowHistoryEventLongFunctions.EVENT_ID)
                                                            .or(0L))
                                                    .withEvents(Collections2.transform(
                                                            Objects.firstNonNull(request.isReverseOrder(),
                                                                    Boolean.FALSE) ? reverseEvents : events,
                                                            TypeMappers.lookup(WorkflowHistoryEvent.class,
                                                                    HistoryEvent.class)));
                                        }
                                        return null;
                                    }
                                });
                    } catch (Exception e) {
                        final StaleObjectStateException stale = Exceptions.findCause(e,
                                StaleObjectStateException.class);
                        if (stale != null)
                            try {
                                Entities.evictCache(Class.forName(stale.getEntityName()));
                            } catch (ClassNotFoundException ce) {
                                /* eviction failure */ }
                        if (PersistenceExceptions.isStaleUpdate(e)) {
                            logger.info("Decision task for workflow " + execution.getDisplayName()
                                    + " already taken.");
                        } else if (PersistenceExceptions.isLockError(e)) {
                            logger.info("Decision task for workflow " + execution.getDisplayName()
                                    + " locking error, will retry.");
                            Thread.sleep(10);
                            retry = true;
                        } else {
                            logger.error(
                                    "Error taking decision task for workflow " + execution.getDisplayName(), e);
                        }
                    }
            }
            return decisionTask;
        }
    };

    try {
        handleTaskPolling(accountFullName, domain, "decision", taskList, request.getCorrelationId(),
                new DecisionTask(), taskCallable);
    } catch (Exception e) {
        throw handleException(e);
    }

    return null;
}