Example usage for com.google.common.base Predicates alwaysTrue

List of usage examples for com.google.common.base Predicates alwaysTrue

Introduction

In this page you can find the example usage for com.google.common.base Predicates alwaysTrue.

Prototype

@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysTrue() 

Source Link

Document

Returns a predicate that always evaluates to true .

Usage

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateVpcResponseType createVpc(final CreateVpcType request) throws EucalyptusCloudException {
    final CreateVpcResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final UserFullName userFullName = ctx.getUserFullName();
    final boolean createDefault = ctx.isAdministrator() && request.getCidrBlock().matches("[0-9]{12}");
    if (!Cidr.parse().apply(request.getCidrBlock()).transform(Cidr.prefix())
            .transform(Functions.forPredicate(Range.closed(16, 28))).or(createDefault)) {
        throw new ClientComputeException("InvalidVpcRange", "Cidr range invalid: " + request.getCidrBlock());
    }//from ww w.j ava 2s .c o  m
    final Supplier<Vpc> allocator = new Supplier<Vpc>() {
        @Override
        public Vpc get() {
            try {
                final String vpcCidr;
                final AccountFullName vpcAccountFullName;
                final UserFullName vpcOwnerFullName;
                Vpc vpc = null;
                RouteTable routeTable = null;
                NetworkAcl networkAcl = null;
                if (createDefault) {
                    final UserPrincipal user = Accounts.lookupPrincipalByAccountNumber(request.getCidrBlock());
                    vpcCidr = Vpcs.DEFAULT_VPC_CIDR;
                    vpcAccountFullName = AccountFullName.getInstance(user.getAccountNumber());
                    vpcOwnerFullName = UserFullName.getInstance(user);

                    // check for existing vpc
                    try {
                        vpc = vpcs.lookupDefault(vpcAccountFullName, Functions.<Vpc>identity());
                        routeTable = routeTables.lookupMain(vpc.getDisplayName(),
                                Functions.<RouteTable>identity());
                        networkAcl = networkAcls.lookupDefault(vpc.getDisplayName(),
                                Functions.<NetworkAcl>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        // so create it
                    }
                } else {
                    vpcCidr = request.getCidrBlock();
                    vpcAccountFullName = userFullName.asAccountFullName();
                    vpcOwnerFullName = userFullName;
                }
                if (vpc == null) {
                    DhcpOptionSet options;
                    try {
                        options = dhcpOptionSets.lookupByExample(
                                DhcpOptionSet.exampleDefault(vpcAccountFullName), vpcAccountFullName, "default",
                                Predicates.alwaysTrue(), Functions.<DhcpOptionSet>identity());
                    } catch (VpcMetadataNotFoundException e) {
                        options = dhcpOptionSets.save(DhcpOptionSet.createDefault(vpcOwnerFullName,
                                Identifier.dopt.generate(), VmInstances.INSTANCE_SUBDOMAIN));
                    }
                    vpc = vpcs.save(Vpc.create(vpcOwnerFullName, Identifier.vpc.generate(), options, vpcCidr,
                            createDefault));
                    routeTable = routeTables.save(RouteTable.create(vpcOwnerFullName, vpc,
                            Identifier.rtb.generate(), vpc.getCidr(), true));
                    networkAcl = networkAcls
                            .save(NetworkAcl.create(vpcOwnerFullName, vpc, Identifier.acl.generate(), true));
                    final NetworkGroup group = NetworkGroup.create(vpcOwnerFullName, vpc,
                            ResourceIdentifiers.generateString(NetworkGroup.ID_PREFIX),
                            NetworkGroups.defaultNetworkName(), "default VPC security group");
                    final Collection<NetworkPeer> peers = Lists.newArrayList(NetworkPeer
                            .create(group.getOwnerAccountNumber(), group.getName(), group.getGroupId()));
                    group.addNetworkRules(Lists.newArrayList(
                            NetworkRule.create(null/*protocol name*/, -1, null/*low port*/, null/*high port*/,
                                    peers, null/*cidrs*/ ),
                            NetworkRule.createEgress(null/*protocol name*/, -1, null/*low port*/,
                                    null/*high port*/, null/*peers*/, Collections.singleton("0.0.0.0/0"))));
                    securityGroups.save(group);
                }
                if (createDefault && routeTable != null && networkAcl != null) {
                    // ensure there is an internet gateway for the vpc and a route in place
                    InternetGateway internetGateway;
                    try {
                        internetGateway = internetGateways.lookupByVpc(vpcAccountFullName, vpc.getDisplayName(),
                                Functions.<InternetGateway>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        internetGateway = internetGateways
                                .save(InternetGateway.create(vpcOwnerFullName, Identifier.igw.generate()));
                        internetGateway.setVpc(vpc);
                    }

                    final Optional<Route> defaultRoute = Iterables.tryFind(routeTable.getRoutes(),
                            CollectionUtils.propertyPredicate("0.0.0.0/0",
                                    RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));

                    if (!defaultRoute.isPresent()) {
                        routeTable.getRoutes().add(Route.create(routeTable, Route.RouteOrigin.CreateRouteTable,
                                "0.0.0.0/0", internetGateway));
                        routeTable.updateTimeStamps(); // ensure version of table increments also
                    }

                    // ensure there is a default subnet in each availability zone
                    final Set<String> cidrsInUse = Sets.newHashSet();
                    final Set<String> zonesWithoutSubnets = Sets.newTreeSet();
                    for (final String zone : Iterables.transform(Clusters.getInstance().listValues(),
                            CloudMetadatas.toDisplayName())) {
                        try {
                            cidrsInUse.add(subnets.lookupDefault(vpcAccountFullName, zone,
                                    Subnets.FilterStringFunctions.CIDR));
                        } catch (final VpcMetadataNotFoundException e) {
                            zonesWithoutSubnets.add(zone);
                        }
                    }
                    final List<String> subnetCidrs = Lists.newArrayList(
                            Iterables.transform(Cidr.parseUnsafe().apply(Vpcs.DEFAULT_VPC_CIDR).split(16),
                                    Functions.toStringFunction()));
                    subnetCidrs.removeAll(cidrsInUse);
                    for (final String zone : zonesWithoutSubnets) {
                        final Subnet subnet = subnets.save(Subnet.create(vpcOwnerFullName, vpc, networkAcl,
                                Identifier.subnet.generate(), subnetCidrs.remove(0), zone));
                        subnet.setDefaultForAz(true);
                        subnet.setMapPublicIpOnLaunch(true);
                    }
                }
                return vpc;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    reply.setVpc(allocate(allocator, Vpc.class, VpcType.class));
    invalidate(reply.getVpc().getVpcId());
    return reply;
}

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

public SimpleWorkflowMessage respondActivityTaskCompleted(final RespondActivityTaskCompletedRequest 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();

    try {//ww w.j  ava2  s  . c o  m
        final TaskToken token = taskTokenManager.decryptTaskToken(accountFullName.getAccountNumber(),
                request.getTaskToken());
        final Domain domain = domains.lookupByExample(
                Domain.exampleWithUuid(accountFullName, token.getDomainUuid()), accountFullName,
                token.getDomainUuid(), Predicates.alwaysTrue(), Functions.<Domain>identity());

        final WorkflowExecution workflowExecution;
        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domain, token.getRunId())) {
            workflowExecution = workflowExecutions.withRetries().updateByExample(
                    WorkflowExecution.exampleWithUniqueName(accountFullName, domain.getDisplayName(),
                            token.getRunId()),
                    accountFullName, token.getRunId(), new Function<WorkflowExecution, WorkflowExecution>() {
                        @Nullable
                        @Override
                        public WorkflowExecution apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                try {
                                    activityTasks.deleteByExample(ActivityTask.exampleWithUniqueName(
                                            accountFullName, token.getRunId(), token.getScheduledEventId()));
                                } catch (SwfMetadataException e) {
                                    throw up(e);
                                }

                                // TODO:STEVE: verify token valid (no reuse, etc)
                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(workflowExecution,
                                        new ActivityTaskCompletedEventAttributes()
                                                .withResult(request.getResult())
                                                .withScheduledEventId(token.getScheduledEventId())
                                                .withStartedEventId(token.getStartedEventId())));
                                if (workflowExecution.getDecisionStatus() != Pending) {
                                    workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                            workflowExecution,
                                            new DecisionTaskScheduledEventAttributes()
                                                    .withTaskList(new TaskList()
                                                            .withName(workflowExecution.getTaskList()))
                                                    .withStartToCloseTimeout(String.valueOf(
                                                            workflowExecution.getTaskStartToCloseTimeout()))));
                                    if (workflowExecution.getDecisionStatus() == Idle) {
                                        workflowExecution.setDecisionStatus(Pending);
                                        workflowExecution.setDecisionTimestamp(new Date());
                                    }
                                }
                            }
                            return workflowExecution;
                        }
                    });
        }

        if (workflowExecution.getDecisionStatus() == Pending) {
            notifyTaskList(accountFullName, workflowExecution.getDomainName(), "decision",
                    workflowExecution.getTaskList());
        }
    } catch (Exception e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}

From source file:com.eucalyptus.autoscaling.backend.AutoScalingBackendService.java

public DeleteAutoScalingGroupResponseType deleteAutoScalingGroup(final DeleteAutoScalingGroupType request)
        throws EucalyptusCloudException {
    final DeleteAutoScalingGroupResponseType reply = request.getReply();

    final Context ctx = Contexts.lookup();
    try {//from w  w w.  j  a v a 2  s . c om
        final AutoScalingGroupCoreView group = autoScalingGroups.lookup(
                ctx.getUserFullName().asAccountFullName(), request.getAutoScalingGroupName(),
                TypeMappers.lookup(AutoScalingGroup.class, AutoScalingGroupCoreView.class));
        if (RestrictedTypes.filterPrivileged().apply(group)) {
            // Terminate instances first if requested (but don't wait for success ...)
            if (Objects.firstNonNull(request.getForceDelete(), Boolean.FALSE)) {
                final List<String> instanceIds = autoScalingInstances.listByGroup(group,
                        Predicates.alwaysTrue(), AutoScalingInstances.instanceId());
                if (!instanceIds.isEmpty()) {
                    final List<ScalingActivity> activities = activityManager.terminateInstances(group,
                            instanceIds);
                    if (activities == null || activities.isEmpty()) {
                        throw new ScalingActivityInProgressException("Scaling activity in progress");
                    }
                    autoScalingInstances.deleteByGroup(group);
                }
            } else {
                failIfScaling(activityManager, group);
            }
            autoScalingGroups.delete(group);
        } // else treat this as though the group does not exist
    } catch (AutoScalingMetadataNotFoundException e) {
        // so nothing to delete, move along      
    } catch (Exception e) {
        handleException(e);
    }

    return reply;
}

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

public SimpleWorkflowMessage respondActivityTaskFailed(final RespondActivityTaskFailedRequest 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();

    try {//from  w ww  .j a va  2 s. c  om
        final TaskToken token = taskTokenManager.decryptTaskToken(accountFullName.getAccountNumber(),
                request.getTaskToken());
        final Domain domain = domains.lookupByExample(
                Domain.exampleWithUuid(accountFullName, token.getDomainUuid()), accountFullName,
                token.getDomainUuid(), Predicates.alwaysTrue(), Functions.<Domain>identity());

        final WorkflowExecution workflowExecution;
        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domain, token.getRunId())) {
            workflowExecution = workflowExecutions.withRetries().updateByExample(
                    WorkflowExecution.exampleWithUniqueName(accountFullName, domain.getDisplayName(),
                            token.getRunId()),
                    accountFullName, token.getRunId(), new Function<WorkflowExecution, WorkflowExecution>() {
                        @Nullable
                        @Override
                        public WorkflowExecution apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                try {
                                    activityTasks.deleteByExample(ActivityTask.exampleWithUniqueName(
                                            accountFullName, token.getRunId(), token.getScheduledEventId()));
                                } catch (SwfMetadataException e) {
                                    throw up(e);
                                }

                                // TODO:STEVE: verify token valid (no reuse, etc)
                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(workflowExecution,
                                        new ActivityTaskFailedEventAttributes()
                                                .withDetails(request.getDetails())
                                                .withReason(request.getReason())
                                                .withScheduledEventId(token.getScheduledEventId())
                                                .withStartedEventId(token.getStartedEventId())));
                                if (workflowExecution.getDecisionStatus() != Pending) {
                                    workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                            workflowExecution,
                                            new DecisionTaskScheduledEventAttributes()
                                                    .withTaskList(new TaskList()
                                                            .withName(workflowExecution.getTaskList()))
                                                    .withStartToCloseTimeout(String.valueOf(
                                                            workflowExecution.getTaskStartToCloseTimeout()))));
                                    if (workflowExecution.getDecisionStatus() == Idle) {
                                        workflowExecution.setDecisionStatus(Pending);
                                        workflowExecution.setDecisionTimestamp(new Date());
                                    }
                                }
                            }
                            return workflowExecution;
                        }
                    });
        }

        if (workflowExecution.getDecisionStatus() == Pending) {
            notifyTaskList(accountFullName, workflowExecution.getDomainName(), "decision",
                    workflowExecution.getTaskList());
        }
    } catch (Exception e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}

From source file:com.eucalyptus.images.Images.java

public static void cleanDeregistered() {
    List<String> imageIdentifiers;
    try {/*from  w  w w.j a va 2s. com*/
        imageIdentifiers = Transactions.filteredTransform(
                Images.exampleWithImageState(ImageMetadata.State.deregistered), Predicates.alwaysTrue(),
                RestrictedTypes.toDisplayName());
    } catch (TransactionException e) {
        LOG.error("Error loading deregistered image list", e);
        imageIdentifiers = Collections.emptyList();
    }

    for (final String imageIdentifier : imageIdentifiers)
        try {
            Transactions.delete(Images.exampleWithImageId(imageIdentifier));
        } catch (RuntimeException | TransactionException e) {
            Logs.extreme().debug("Attempted image delete failed (image still referenced?): " + imageIdentifier,
                    e);
        }
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public DeleteVpcResponseType deleteVpc(final DeleteVpcType request) throws EucalyptusCloudException {
    final DeleteVpcResponseType reply = request.getReply();
    delete(Identifier.vpc, request.getVpcId(), new Function<Pair<Optional<AccountFullName>, String>, Vpc>() {
        @Override/*from w ww .jav  a 2s  . c  o  m*/
        public Vpc apply(final Pair<Optional<AccountFullName>, String> accountAndId) {
            try {
                final Vpc vpc = vpcs.lookupByName(accountAndId.getLeft().orNull(), accountAndId.getRight(),
                        Functions.<Vpc>identity());
                if (RestrictedTypes.filterPrivileged().apply(vpc)) {
                    if (Boolean.TRUE.equals(vpc.getDefaultVpc()) && Contexts.lookup().isAdministrator()) {
                        final List<Subnet> defaultSubnets = subnets
                                .listByExample(
                                        Subnet.exampleDefault(
                                                AccountFullName.getInstance(vpc.getOwnerAccountNumber()), null),
                                        Predicates.alwaysTrue(), Functions.<Subnet>identity());
                        for (final Subnet subnet : defaultSubnets) {
                            subnets.delete(subnet);
                        }
                        try {
                            final InternetGateway internetGateway = internetGateways.lookupByVpc(null,
                                    vpc.getDisplayName(), Functions.<InternetGateway>identity());
                            internetGateways.delete(internetGateway);
                        } catch (VpcMetadataNotFoundException e) {
                            /* so no need to delete */ }
                    }
                    try {
                        networkAcls.delete(networkAcls.lookupDefault(vpc.getDisplayName(),
                                Functions.<NetworkAcl>identity()));
                    } catch (VpcMetadataNotFoundException e) {
                        /* so no need to delete */ }
                    try {
                        routeTables.delete(
                                routeTables.lookupMain(vpc.getDisplayName(), Functions.<RouteTable>identity()));
                    } catch (VpcMetadataNotFoundException e) {
                        /* so no need to delete */ }
                    try {
                        securityGroups.delete(securityGroups.lookupDefault(vpc.getDisplayName(),
                                Functions.<NetworkGroup>identity()));
                    } catch (VpcMetadataNotFoundException e) {
                        /* so no need to delete */ }
                    vpcs.delete(vpc);
                } else {
                    throw Exceptions.toUndeclared(
                            new ClientUnauthorizedComputeException("Not authorized to delete vpc"));
                }
                return null;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });
    return reply;
}

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

public SimpleWorkflowMessage respondDecisionTaskCompleted(final RespondDecisionTaskCompletedRequest 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();

    try {//from ww  w .j  ava2  s.c om
        final TaskToken token = taskTokenManager.decryptTaskToken(accountFullName.getAccountNumber(),
                request.getTaskToken());
        final Domain domain = domains.lookupByExample(
                Domain.exampleWithUuid(accountFullName, token.getDomainUuid()), accountFullName,
                token.getDomainUuid(), Predicates.alwaysTrue(), Functions.<Domain>identity());

        final Set<Pair<String, String>> notificationTypeListPairs = Sets.newHashSet();
        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domain, token.getRunId())) {
            workflowExecutions.withRetries().updateByExample(
                    WorkflowExecution.exampleWithUniqueName(accountFullName, domain.getDisplayName(),
                            token.getRunId()),
                    accountFullName, token.getRunId(), new Function<WorkflowExecution, WorkflowExecution>() {
                        @Nullable
                        @Override
                        public WorkflowExecution apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                // clear pending notifications in case of retries
                                notificationTypeListPairs.clear();

                                // verify token is valid
                                final List<WorkflowHistoryEvent> events = workflowExecution
                                        .getWorkflowHistory();
                                final List<WorkflowHistoryEvent> reverseEvents = Lists.reverse(events);
                                final WorkflowHistoryEvent started = Iterables.find(reverseEvents,
                                        CollectionUtils.propertyPredicate("DecisionTaskStarted", EVENT_TYPE));
                                if (!started.getEventId().equals(token.getStartedEventId())) {
                                    throw upClient("ValidationError", "Bad token");
                                }
                                final WorkflowHistoryEvent scheduled = Iterables.find(reverseEvents,
                                        CollectionUtils.propertyPredicate("DecisionTaskScheduled", EVENT_TYPE));
                                if (scheduled.getEventId() < started.getEventId()) {
                                    workflowExecution.setDecisionStatus(Idle);
                                    workflowExecution.setDecisionTimestamp(new Date());
                                } else {
                                    workflowExecution.setDecisionStatus(Pending);
                                    workflowExecution.setDecisionTimestamp(new Date());
                                    notificationTypeListPairs
                                            .add(Pair.pair("decision", workflowExecution.getTaskList()));
                                }

                                // setup activity count supplier
                                int activityTaskScheduledCount = 0;
                                final Supplier<Long> activityTaskCounter = Suppliers
                                        .memoize(new Supplier<Long>() {
                                            @Override
                                            public Long get() {
                                                try {
                                                    return activityTasks.countByWorkflowExecution(
                                                            accountFullName, domain.getDisplayName(),
                                                            workflowExecution.getDisplayName());
                                                } catch (SwfMetadataException e) {
                                                    throw up(e);
                                                }
                                            }
                                        });

                                // process decision task response
                                workflowExecution.setLatestExecutionContext(request.getExecutionContext());
                                final Long completedId = workflowExecution
                                        .addHistoryEvent(WorkflowHistoryEvent.create(workflowExecution,
                                                new DecisionTaskCompletedEventAttributes()
                                                        .withExecutionContext(request.getExecutionContext())
                                                        .withScheduledEventId(token.getScheduledEventId())
                                                        .withStartedEventId(token.getStartedEventId())));
                                boolean scheduleDecisionTask = false;
                                if (request.getDecisions() != null)
                                    for (final Decision decision : request.getDecisions()) {
                                        switch (decision.getDecisionType()) {
                                        case "CancelTimer":
                                            final CancelTimerDecisionAttributes cancelTimer = decision
                                                    .getCancelTimerDecisionAttributes();
                                            try {
                                                final List<Timer> timerList = timers.listByExample(
                                                        Timer.exampleWithTimerId(accountFullName,
                                                                workflowExecution.getDomainName(),
                                                                workflowExecution.getDisplayName(),
                                                                cancelTimer.getTimerId()),
                                                        Predicates.alwaysTrue(), Functions.<Timer>identity());

                                                if (!timerList.isEmpty()) {
                                                    final Timer timer = Iterables.getOnlyElement(timerList);
                                                    timers.deleteByExample(timer);
                                                    workflowExecution.addHistoryEvent(
                                                            WorkflowHistoryEvent.create(workflowExecution,
                                                                    new TimerCanceledEventAttributes()
                                                                            .withDecisionTaskCompletedEventId(
                                                                                    completedId)
                                                                            .withStartedEventId(
                                                                                    timer.getStartedEventId())
                                                                            .withTimerId(
                                                                                    cancelTimer.getTimerId())));
                                                } else {
                                                    workflowExecution.addHistoryEvent(
                                                            WorkflowHistoryEvent.create(workflowExecution,
                                                                    new CancelTimerFailedEventAttributes()
                                                                            .withCause(
                                                                                    CancelTimerFailedCause.TIMER_ID_UNKNOWN)
                                                                            .withDecisionTaskCompletedEventId(
                                                                                    completedId)
                                                                            .withTimerId(
                                                                                    cancelTimer.getTimerId())));
                                                    scheduleDecisionTask = true;
                                                }
                                            } catch (SwfMetadataException e) {
                                                throw up(e);
                                            }
                                            break;
                                        case "CancelWorkflowExecution":
                                            final CancelWorkflowExecutionDecisionAttributes cancelWorkflowExecution = decision
                                                    .getCancelWorkflowExecutionDecisionAttributes();
                                            workflowExecution.closeWorkflow(
                                                    WorkflowExecution.CloseStatus.Canceled,
                                                    WorkflowHistoryEvent.create(workflowExecution,
                                                            new WorkflowExecutionCanceledEventAttributes()
                                                                    .withDecisionTaskCompletedEventId(
                                                                            completedId)
                                                                    .withDetails(cancelWorkflowExecution
                                                                            .getDetails())));
                                            deleteActivities(activityTasks, accountFullName, workflowExecution);
                                            break;
                                        case "CompleteWorkflowExecution":
                                            final CompleteWorkflowExecutionDecisionAttributes completed = decision
                                                    .getCompleteWorkflowExecutionDecisionAttributes();
                                            workflowExecution.closeWorkflow(
                                                    WorkflowExecution.CloseStatus.Completed,
                                                    WorkflowHistoryEvent.create(workflowExecution,
                                                            new WorkflowExecutionCompletedEventAttributes()
                                                                    .withDecisionTaskCompletedEventId(
                                                                            completedId)
                                                                    .withResult(completed.getResult())));
                                            break;
                                        case "ContinueAsNewWorkflowExecution":
                                            workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new ContinueAsNewWorkflowExecutionFailedEventAttributes()
                                                            .withCause(
                                                                    ContinueAsNewWorkflowExecutionFailedCause.OPERATION_NOT_PERMITTED)
                                                            .withDecisionTaskCompletedEventId(completedId)));
                                            scheduleDecisionTask = true;
                                            break;
                                        case "FailWorkflowExecution":
                                            final FailWorkflowExecutionDecisionAttributes failed = decision
                                                    .getFailWorkflowExecutionDecisionAttributes();
                                            workflowExecution.closeWorkflow(
                                                    WorkflowExecution.CloseStatus.Failed,
                                                    WorkflowHistoryEvent.create(workflowExecution,
                                                            new WorkflowExecutionFailedEventAttributes()
                                                                    .withDecisionTaskCompletedEventId(
                                                                            completedId)
                                                                    .withDetails(failed.getDetails())
                                                                    .withReason(failed.getReason())));
                                            deleteActivities(activityTasks, accountFullName, workflowExecution);
                                            break;
                                        case "RecordMarker":
                                            final RecordMarkerDecisionAttributes mark = decision
                                                    .getRecordMarkerDecisionAttributes();
                                            workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new MarkerRecordedEventAttributes()
                                                            .withDetails(mark.getDetails())
                                                            .withDecisionTaskCompletedEventId(completedId)
                                                            .withMarkerName(mark.getMarkerName())));
                                            break;
                                        case "RequestCancelActivityTask":
                                            final RequestCancelActivityTaskDecisionAttributes cancelActivity = decision
                                                    .getRequestCancelActivityTaskDecisionAttributes();
                                            try {
                                                activityTasks.updateByExample(
                                                        ActivityTask.exampleWithActivityId(accountFullName,
                                                                workflowExecution.getDomainName(),
                                                                workflowExecution.getDisplayName(),
                                                                cancelActivity.getActivityId()),
                                                        accountFullName, cancelActivity.getActivityId(),
                                                        new Function<ActivityTask, Void>() {
                                                            @Override
                                                            public Void apply(final ActivityTask activityTask) {
                                                                final Long cancelRequestedId = workflowExecution
                                                                        .addHistoryEvent(WorkflowHistoryEvent
                                                                                .create(workflowExecution,
                                                                                        new ActivityTaskCancelRequestedEventAttributes()
                                                                                                .withDecisionTaskCompletedEventId(
                                                                                                        completedId)
                                                                                                .withActivityId(
                                                                                                        cancelActivity
                                                                                                                .getActivityId())));

                                                                if (activityTask
                                                                        .getState() == ActivityTask.State.Active) {
                                                                    activityTask.setCancelRequestedEventId(
                                                                            cancelRequestedId);
                                                                } else {
                                                                    workflowExecution.addHistoryEvent(
                                                                            WorkflowHistoryEvent.create(
                                                                                    workflowExecution,
                                                                                    new ActivityTaskCanceledEventAttributes()
                                                                                            .withLatestCancelRequestedEventId(
                                                                                                    cancelRequestedId)
                                                                                            .withScheduledEventId(
                                                                                                    activityTask
                                                                                                            .getScheduledEventId())
                                                                                            .withStartedEventId(
                                                                                                    activityTask
                                                                                                            .getStartedEventId())));
                                                                    Entities.delete(activityTask);
                                                                }
                                                                return null;
                                                            }
                                                        });
                                            } catch (SwfMetadataNotFoundException e) {
                                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                        workflowExecution,
                                                        new RequestCancelActivityTaskFailedEventAttributes()
                                                                .withCause(
                                                                        RequestCancelActivityTaskFailedCause.ACTIVITY_ID_UNKNOWN)
                                                                .withDecisionTaskCompletedEventId(completedId)
                                                                .withActivityId(
                                                                        cancelActivity.getActivityId())));
                                            } catch (SwfMetadataException e) {
                                                throw up(e);
                                            }
                                            scheduleDecisionTask = true;
                                            break;
                                        case "RequestCancelExternalWorkflowExecution":
                                            final RequestCancelExternalWorkflowExecutionDecisionAttributes cancelExternalWorkflow = decision
                                                    .getRequestCancelExternalWorkflowExecutionDecisionAttributes();
                                            workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new RequestCancelExternalWorkflowExecutionFailedEventAttributes()
                                                            .withCause(
                                                                    RequestCancelExternalWorkflowExecutionFailedCause.UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION)
                                                            .withControl(cancelExternalWorkflow.getControl())
                                                            .withDecisionTaskCompletedEventId(completedId)
                                                            .withRunId(cancelExternalWorkflow.getRunId())
                                                            .withWorkflowId(
                                                                    cancelExternalWorkflow.getWorkflowId())));
                                            scheduleDecisionTask = true;
                                            break;
                                        case "ScheduleActivityTask":
                                            workflowExecution.setLatestActivityTaskScheduled(new Date());
                                            final ScheduleActivityTaskDecisionAttributes scheduleActivity = decision
                                                    .getScheduleActivityTaskDecisionAttributes();
                                            final Long scheduledId = workflowExecution.addHistoryEvent(
                                                    WorkflowHistoryEvent.create(workflowExecution,
                                                            new ActivityTaskScheduledEventAttributes()
                                                                    .withDecisionTaskCompletedEventId(
                                                                            completedId)
                                                                    .withActivityId(
                                                                            scheduleActivity.getActivityId())
                                                                    .withActivityType(
                                                                            scheduleActivity.getActivityType())
                                                                    .withControl(scheduleActivity.getControl())
                                                                    .withHeartbeatTimeout(scheduleActivity
                                                                            .getHeartbeatTimeout())
                                                                    .withInput(scheduleActivity.getInput())
                                                                    .withScheduleToCloseTimeout(scheduleActivity
                                                                            .getScheduleToCloseTimeout())
                                                                    .withScheduleToStartTimeout(scheduleActivity
                                                                            .getScheduleToStartTimeout())
                                                                    .withStartToCloseTimeout(scheduleActivity
                                                                            .getStartToCloseTimeout())
                                                                    .withTaskList(
                                                                            scheduleActivity.getTaskList())));
                                            try {
                                                final ActivityType activityType;
                                                try {
                                                    activityType = activityTypes.lookupByExample(
                                                            ActivityType.exampleWithUniqueName(accountFullName,
                                                                    domain.getDisplayName(),
                                                                    scheduleActivity.getActivityType()
                                                                            .getName(),
                                                                    scheduleActivity.getActivityType()
                                                                            .getVersion()),
                                                            accountFullName,
                                                            scheduleActivity.getActivityType().getName(),
                                                            Predicates.alwaysTrue(),
                                                            Functions.<ActivityType>identity());
                                                } catch (final SwfMetadataNotFoundException e) {
                                                    throw new ScheduleActivityTaskException(
                                                            ACTIVITY_TYPE_DOES_NOT_EXIST);
                                                }

                                                if (ActivityType.Status.Deprecated.apply(activityType)) {
                                                    throw new ScheduleActivityTaskException(
                                                            ACTIVITY_TYPE_DEPRECATED);
                                                }

                                                final String list = scheduleActivity.getTaskList() == null
                                                        ? activityType.getDefaultTaskList()
                                                        : scheduleActivity.getTaskList().getName();
                                                if (list == null) {
                                                    throw new ScheduleActivityTaskException(
                                                            DEFAULT_TASK_LIST_UNDEFINED);
                                                }

                                                if (activityTaskCounter.get()
                                                        + activityTaskScheduledCount >= SimpleWorkflowProperties
                                                                .getOpenActivityTasksPerWorkflowExecution()) {
                                                    throw new ScheduleActivityTaskException(
                                                            OPEN_ACTIVITIES_LIMIT_EXCEEDED);
                                                }

                                                activityTasks.save(com.eucalyptus.simpleworkflow.ActivityTask
                                                        .create(userFullName, workflowExecution,
                                                                domain.getDisplayName(), domain.getNaturalId(),
                                                                scheduleActivity.getActivityId(),
                                                                scheduleActivity.getActivityType().getName(),
                                                                scheduleActivity.getActivityType().getVersion(),
                                                                scheduleActivity.getInput(), scheduledId, list,
                                                                parseActivityPeriod(
                                                                        scheduleActivity
                                                                                .getScheduleToCloseTimeout(),
                                                                        activityType
                                                                                .getDefaultTaskScheduleToCloseTimeout(),
                                                                        DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED),
                                                                parseActivityPeriod(
                                                                        scheduleActivity
                                                                                .getScheduleToStartTimeout(),
                                                                        activityType
                                                                                .getDefaultTaskScheduleToStartTimeout(),
                                                                        DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED),
                                                                parseActivityPeriod(
                                                                        scheduleActivity
                                                                                .getStartToCloseTimeout(),
                                                                        activityType
                                                                                .getDefaultTaskStartToCloseTimeout(),
                                                                        DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED),
                                                                parseActivityPeriod(
                                                                        scheduleActivity.getHeartbeatTimeout(),
                                                                        activityType
                                                                                .getDefaultTaskHeartbeatTimeout(),
                                                                        DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED)));
                                                activityTaskScheduledCount++;

                                                notificationTypeListPairs.add(Pair.pair("activity", list));
                                            } catch (final ScheduleActivityTaskException e) {
                                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                        workflowExecution,
                                                        new ScheduleActivityTaskFailedEventAttributes()
                                                                .withActivityId(
                                                                        scheduleActivity.getActivityId())
                                                                .withActivityType(
                                                                        scheduleActivity.getActivityType())
                                                                .withCause(e.getFailedCause())
                                                                .withDecisionTaskCompletedEventId(
                                                                        completedId)));
                                                scheduleDecisionTask = true;
                                            } catch (final Exception e) {
                                                throw up(e);
                                            }
                                            break;
                                        case "SignalExternalWorkflowExecution":
                                            final SignalExternalWorkflowExecutionDecisionAttributes signalExternalWorkflow = decision
                                                    .getSignalExternalWorkflowExecutionDecisionAttributes();
                                            workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new SignalExternalWorkflowExecutionFailedEventAttributes()
                                                            .withCause(
                                                                    SignalExternalWorkflowExecutionFailedCause.UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION)
                                                            .withControl(signalExternalWorkflow.getControl())
                                                            .withDecisionTaskCompletedEventId(completedId)
                                                            .withRunId(signalExternalWorkflow.getRunId())
                                                            .withWorkflowId(
                                                                    signalExternalWorkflow.getWorkflowId())));
                                            scheduleDecisionTask = true;
                                            break;
                                        case "StartChildWorkflowExecution":
                                            final StartChildWorkflowExecutionDecisionAttributes startChildWorkflow = decision
                                                    .getStartChildWorkflowExecutionDecisionAttributes();
                                            workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                    workflowExecution,
                                                    new StartChildWorkflowExecutionFailedEventAttributes()
                                                            .withCause(
                                                                    StartChildWorkflowExecutionFailedCause.OPERATION_NOT_PERMITTED)
                                                            .withControl(startChildWorkflow.getControl())
                                                            .withDecisionTaskCompletedEventId(completedId)
                                                            .withWorkflowId(startChildWorkflow.getWorkflowId())
                                                            .withWorkflowType(
                                                                    startChildWorkflow.getWorkflowType())));
                                            scheduleDecisionTask = true;
                                            break;
                                        case "StartTimer":
                                            final StartTimerDecisionAttributes startTimer = decision
                                                    .getStartTimerDecisionAttributes();
                                            try {
                                                if (!timers.listByExample(
                                                        Timer.exampleWithTimerId(accountFullName,
                                                                workflowExecution.getDomainName(),
                                                                workflowExecution.getDisplayName(),
                                                                startTimer.getTimerId()),
                                                        Predicates.alwaysTrue(), Functions.<Timer>identity())
                                                        .isEmpty()) {
                                                    throw new StartTimerException(
                                                            StartTimerFailedCause.TIMER_ID_ALREADY_IN_USE);
                                                }
                                                final Long startedId = workflowExecution.addHistoryEvent(
                                                        WorkflowHistoryEvent.create(workflowExecution,
                                                                new TimerStartedEventAttributes()
                                                                        .withControl(startTimer.getControl())
                                                                        .withDecisionTaskCompletedEventId(
                                                                                completedId)
                                                                        .withStartToFireTimeout(startTimer
                                                                                .getStartToFireTimeout())
                                                                        .withTimerId(startTimer.getTimerId())));
                                                if (timers.countByWorkflowExecution(accountFullName,
                                                        domain.getDisplayName(),
                                                        workflowExecution
                                                                .getDisplayName()) >= SimpleWorkflowProperties
                                                                        .getOpenTimersPerWorkflowExecution()) {
                                                    throw new StartTimerException(
                                                            StartTimerFailedCause.OPEN_TIMERS_LIMIT_EXCEEDED);
                                                }
                                                timers.save(Timer.create(userFullName, workflowExecution,
                                                        workflowExecution.getDomainName(),
                                                        workflowExecution.getDomainUuid(),
                                                        startTimer.getTimerId(), startTimer.getControl(),
                                                        parsePeriod(startTimer.getStartToFireTimeout(), 0),
                                                        completedId, startedId));
                                            } catch (StartTimerException e) {
                                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                                        workflowExecution,
                                                        new StartTimerFailedEventAttributes()
                                                                .withCause(e.getFailedCause())
                                                                .withDecisionTaskCompletedEventId(completedId)
                                                                .withTimerId(startTimer.getTimerId())));
                                                scheduleDecisionTask = true;
                                            } catch (SwfMetadataException e) {
                                                throw up(e);
                                            }
                                            break;
                                        default:
                                            throw up(new SimpleWorkflowException("InternalFailure",
                                                    Role.Receiver, "Unsupported decision type: "
                                                            + decision.getDecisionType()));
                                        }
                                    }
                                if (scheduleDecisionTask && workflowExecution.getDecisionStatus() != Pending) {
                                    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());
                                    notificationTypeListPairs
                                            .add(Pair.pair("decision", workflowExecution.getTaskList()));
                                } else {
                                    workflowExecution.updateTimeStamps();
                                }
                            }
                            return workflowExecution;
                        }
                    });
        }

        //TODO:STEVE: update API to allow batch notification
        for (final Pair<String, String> notificationTypeListPair : notificationTypeListPairs) {
            notifyTaskList(accountFullName, domain.getDisplayName(), notificationTypeListPair.getLeft(),
                    notificationTypeListPair.getRight());
        }
    } catch (Exception e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}

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

public SimpleWorkflowMessage signalWorkflowExecution(final SignalWorkflowExecutionRequest 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();

    try {/*www  .  j a va  2s . co  m*/
        final WorkflowExecution example = WorkflowExecution.exampleForOpenWorkflow(accountFullName,
                request.getDomain(), request.getWorkflowId(), request.getRunId());
        final Pair<String, String> domainUuidRunIdPair = workflowExecutions.lookupByExample(example,
                accountFullName, request.getWorkflowId(), Predicates.alwaysTrue(),
                Pair.builder(WorkflowExecutions.WorkflowExecutionStringFunctions.DOMAIN_UUID,
                        SimpleWorkflowMetadatas.toDisplayName()));

        final Pair<String, String> domainTaskListPair;
        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domainUuidRunIdPair)) {
            domainTaskListPair = workflowExecutions.withRetries().updateByExample(example, accountFullName,
                    request.getWorkflowId(), new Function<WorkflowExecution, Pair<String, String>>() {
                        @Override
                        public Pair<String, String> apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(workflowExecution,
                                        new WorkflowExecutionSignaledEventAttributes()
                                                .withExternalInitiatedEventId(0L).withInput(request.getInput())
                                                .withSignalName(request.getSignalName())));
                                if (workflowExecution.getDecisionStatus() != Pending) {
                                    workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                            workflowExecution,
                                            new DecisionTaskScheduledEventAttributes()
                                                    .withTaskList(new TaskList()
                                                            .withName(workflowExecution.getTaskList()))
                                                    .withStartToCloseTimeout(String.valueOf(
                                                            workflowExecution.getTaskStartToCloseTimeout()))));
                                    if (workflowExecution.getDecisionStatus() == Idle) {
                                        workflowExecution.setDecisionStatus(Pending);
                                        workflowExecution.setDecisionTimestamp(new Date());
                                        return Pair.pair(workflowExecution.getDomainName(),
                                                workflowExecution.getTaskList());
                                    }
                                }
                            }
                            return null;
                        }
                    });
        }

        if (domainTaskListPair != null) {
            notifyTaskList(accountFullName, domainTaskListPair.getLeft(), "decision",
                    domainTaskListPair.getRight());
        }
    } catch (SwfMetadataNotFoundException e) {
        throw new SimpleWorkflowClientException("UnknownResourceFault",
                request.getRunId() == null ? "Unknown execution, workflowId = " + request.getWorkflowId()
                        : "Unknown execution: WorkflowExecution=[workflowId=" + request.getWorkflowId()
                                + ", runId=" + request.getRunId() + "]");
    } catch (SwfMetadataException e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}

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

public SimpleWorkflowMessage requestCancelWorkflowExecution(final RequestCancelWorkflowExecutionRequest 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();

    try {//from  ww  w  .  j ava  2s.  co  m
        final WorkflowExecution example = WorkflowExecution.exampleForOpenWorkflow(accountFullName,
                request.getDomain(), request.getWorkflowId(), request.getRunId());
        final Pair<String, String> domainUuidRunIdPair = workflowExecutions.lookupByExample(example,
                accountFullName, request.getWorkflowId(), Predicates.alwaysTrue(),
                Pair.builder(WorkflowExecutions.WorkflowExecutionStringFunctions.DOMAIN_UUID,
                        SimpleWorkflowMetadatas.toDisplayName()));

        final Pair<String, String> domainTaskListPair;
        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domainUuidRunIdPair)) {
            domainTaskListPair = workflowExecutions.withRetries().updateByExample(example, accountFullName,
                    request.getWorkflowId(), new Function<WorkflowExecution, Pair<String, String>>() {
                        @Override
                        public Pair<String, String> apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                workflowExecution.setCancelRequested(true);
                                workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(workflowExecution,
                                        new WorkflowExecutionCancelRequestedEventAttributes()
                                                .withExternalInitiatedEventId(0L)));
                                if (workflowExecution.getDecisionStatus() != Pending) {
                                    workflowExecution.addHistoryEvent(WorkflowHistoryEvent.create(
                                            workflowExecution,
                                            new DecisionTaskScheduledEventAttributes()
                                                    .withTaskList(new TaskList()
                                                            .withName(workflowExecution.getTaskList()))
                                                    .withStartToCloseTimeout(String.valueOf(
                                                            workflowExecution.getTaskStartToCloseTimeout()))));
                                    if (workflowExecution.getDecisionStatus() == Idle) {
                                        workflowExecution.setDecisionStatus(Pending);
                                        workflowExecution.setDecisionTimestamp(new Date());
                                        return Pair.pair(workflowExecution.getDomainName(),
                                                workflowExecution.getTaskList());
                                    }
                                }
                            }
                            return null;
                        }
                    });
        }

        if (domainTaskListPair != null) {
            notifyTaskList(accountFullName, domainTaskListPair.getLeft(), "decision",
                    domainTaskListPair.getRight());
        }
    } catch (SwfMetadataNotFoundException e) {
        throw new SimpleWorkflowClientException("UnknownResourceFault",
                request.getRunId() == null ? "Unknown execution, workflowId = " + request.getWorkflowId()
                        : "Unknown execution: WorkflowExecution=[workflowId=" + request.getWorkflowId()
                                + ", runId=" + request.getRunId() + "]");
    } catch (SwfMetadataException e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}

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

public SimpleWorkflowMessage terminateWorkflowExecution(final TerminateWorkflowExecutionRequest 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();

    try {//from w  w  w. ja  v a  2s  .com
        final WorkflowExecution example = WorkflowExecution.exampleForOpenWorkflow(accountFullName,
                request.getDomain(), request.getWorkflowId(), request.getRunId());
        final Pair<String, String> domainUuidRunIdPair = workflowExecutions.lookupByExample(example,
                accountFullName, request.getWorkflowId(), Predicates.alwaysTrue(),
                Pair.builder(WorkflowExecutions.WorkflowExecutionStringFunctions.DOMAIN_UUID,
                        SimpleWorkflowMetadatas.toDisplayName()));

        try (final WorkflowLock lock = WorkflowLock.lock(accountFullName, domainUuidRunIdPair)) {
            workflowExecutions.withRetries().updateByExample(example, accountFullName, request.getWorkflowId(),
                    new Function<WorkflowExecution, Void>() {
                        @Override
                        public Void apply(final WorkflowExecution workflowExecution) {
                            if (accessible.apply(workflowExecution)) {
                                workflowExecution
                                        .closeWorkflow(WorkflowExecution.CloseStatus.Terminated,
                                                WorkflowHistoryEvent
                                                        .create(workflowExecution,
                                                                new WorkflowExecutionTerminatedEventAttributes()
                                                                        .withChildPolicy(Objects.firstNonNull(
                                                                                request.getChildPolicy(),
                                                                                workflowExecution
                                                                                        .getChildPolicy()))
                                                                        .withDetails(request.getDetails())
                                                                        .withReason(request.getReason())));
                            }
                            deleteActivities(activityTasks, accountFullName, workflowExecution);
                            return null;
                        }
                    });
        }
    } catch (SwfMetadataNotFoundException e) {
        throw new SimpleWorkflowClientException("UnknownResourceFault",
                request.getRunId() == null ? "Unknown execution, workflowId = " + request.getWorkflowId()
                        : "Unknown execution: WorkflowExecution=[workflowId=" + request.getWorkflowId()
                                + ", runId=" + request.getRunId() + "]");
    } catch (SwfMetadataException e) {
        throw handleException(e);
    }

    return request.reply(new SimpleWorkflowMessage());
}