Search in sources :

Example 11 with Predicate

use of org.apache.commons.collections4.Predicate in project engine by craftercms.

the class SiteItemServiceImpl method getSiteItem.

@Override
public SiteItem getSiteItem(String url, ItemProcessor processor, Predicate<Item> predicate) {
    SiteContext context = getSiteContext();
    if (!storeService.exists(context.getContext(), url)) {
        return null;
    }
    if (CollectionUtils.isNotEmpty(defaultPredicates)) {
        List<Predicate<Item>> predicates = new ArrayList<>(defaultPredicates);
        if (predicate != null) {
            predicates.add(predicate);
        }
        predicate = PredicateUtils.allPredicate(predicates);
    }
    if (CollectionUtils.isNotEmpty(defaultProcessors)) {
        ItemProcessorPipeline processorPipeline = new ItemProcessorPipeline(new ArrayList<>(defaultProcessors));
        if (processor != null) {
            processorPipeline.addProcessor(processor);
        }
        processor = processorPipeline;
    }
    Item item = storeService.findItem(context.getContext(), null, url, processor);
    if (item != null && (predicate == null || predicate.evaluate(item))) {
        return createItemWrapper(item);
    } else {
        return null;
    }
}
Also used : Item(org.craftercms.core.service.Item) SiteItem(org.craftercms.engine.model.SiteItem) DefaultSiteItem(org.craftercms.engine.model.DefaultSiteItem) EmbeddedSiteItem(org.craftercms.engine.model.EmbeddedSiteItem) ItemProcessorPipeline(org.craftercms.core.processors.impl.ItemProcessorPipeline) SiteContext(org.craftercms.engine.service.context.SiteContext) ArrayList(java.util.ArrayList) Predicate(org.apache.commons.collections4.Predicate)

Example 12 with Predicate

use of org.apache.commons.collections4.Predicate in project open-kilda by telstra.

the class BaseResourceAllocationAction method allocatePathPair.

@SneakyThrows
protected GetPathsResult allocatePathPair(Flow flow, PathId newForwardPathId, PathId newReversePathId, boolean forceToIgnoreBandwidth, List<PathId> pathsToReuseBandwidth, FlowPathPair oldPaths, boolean allowOldPaths, String sharedBandwidthGroupId, Predicate<GetPathsResult> whetherCreatePathSegments) throws RecoverableException, UnroutableFlowException, ResourceAllocationException {
    // Lazy initialisable map with reused bandwidth...
    Supplier<Map<IslEndpoints, Long>> reuseBandwidthPerIsl = Suppliers.memoize(() -> {
        Map<IslEndpoints, Long> result = new HashMap<>();
        if (pathsToReuseBandwidth != null && !pathsToReuseBandwidth.isEmpty()) {
            pathsToReuseBandwidth.stream().map(pathId -> flow.getPath(pathId).orElse(flowPathRepository.findById(pathId).orElse(null))).filter(Objects::nonNull).flatMap(path -> path.getSegments().stream()).forEach(segment -> {
                IslEndpoints isl = new IslEndpoints(segment.getSrcSwitchId().toString(), segment.getSrcPort(), segment.getDestSwitchId().toString(), segment.getDestPort());
                result.put(isl, result.getOrDefault(isl, 0L) + segment.getBandwidth());
            });
        }
        return result;
    });
    RetryPolicy<GetPathsResult> pathAllocationRetryPolicy = new RetryPolicy<GetPathsResult>().handle(RecoverableException.class).handle(ResourceAllocationException.class).handle(UnroutableFlowException.class).handle(PersistenceException.class).onRetry(e -> log.warn("Failure in path allocation. Retrying #{}...", e.getAttemptCount(), e.getLastFailure())).onRetriesExceeded(e -> log.warn("Failure in path allocation. No more retries", e.getFailure())).withMaxRetries(pathAllocationRetriesLimit);
    if (pathAllocationRetryDelay > 0) {
        pathAllocationRetryPolicy.withDelay(Duration.ofMillis(pathAllocationRetryDelay));
    }
    try {
        return Failsafe.with(pathAllocationRetryPolicy).get(() -> {
            GetPathsResult potentialPath;
            if (forceToIgnoreBandwidth) {
                boolean originalIgnoreBandwidth = flow.isIgnoreBandwidth();
                flow.setIgnoreBandwidth(true);
                potentialPath = pathComputer.getPath(flow);
                flow.setIgnoreBandwidth(originalIgnoreBandwidth);
            } else {
                potentialPath = pathComputer.getPath(flow, pathsToReuseBandwidth);
            }
            boolean newPathFound = isNotSamePath(potentialPath, oldPaths);
            if (allowOldPaths || newPathFound) {
                if (!newPathFound) {
                    log.debug("Found the same path for flow {}. Proceed with recreating it", flow.getFlowId());
                }
                if (whetherCreatePathSegments.test(potentialPath)) {
                    boolean ignoreBandwidth = forceToIgnoreBandwidth || flow.isIgnoreBandwidth();
                    List<PathSegment> forwardSegments = flowPathBuilder.buildPathSegments(newForwardPathId, potentialPath.getForward(), flow.getBandwidth(), ignoreBandwidth, sharedBandwidthGroupId);
                    List<PathSegment> reverseSegments = flowPathBuilder.buildPathSegments(newReversePathId, potentialPath.getReverse(), flow.getBandwidth(), ignoreBandwidth, sharedBandwidthGroupId);
                    transactionManager.doInTransaction(() -> {
                        createPathSegments(forwardSegments, reuseBandwidthPerIsl);
                        createPathSegments(reverseSegments, reuseBandwidthPerIsl);
                    });
                }
                return potentialPath;
            }
            return null;
        });
    } catch (FailsafeException ex) {
        throw ex.getCause();
    }
}
Also used : FlowPath(org.openkilda.model.FlowPath) HistoryMapper(org.openkilda.wfm.share.mappers.HistoryMapper) SneakyThrows(lombok.SneakyThrows) ResourceAllocationException(org.openkilda.wfm.share.flow.resources.ResourceAllocationException) FlowPathStatus(org.openkilda.model.FlowPathStatus) UnroutableFlowException(org.openkilda.pce.exception.UnroutableFlowException) FlowPathSwappingFsm(org.openkilda.wfm.topology.flowhs.fsm.common.FlowPathSwappingFsm) FailsafeException(net.jodah.failsafe.FailsafeException) Flow(org.openkilda.model.Flow) Duration(java.time.Duration) Map(java.util.Map) FlowPathPair(org.openkilda.wfm.topology.flow.model.FlowPathPair) DumpType(org.openkilda.wfm.share.history.model.FlowDumpData.DumpType) Path(org.openkilda.pce.Path) SwitchProperties(org.openkilda.model.SwitchProperties) IslEndpoints(org.openkilda.persistence.repositories.IslRepository.IslEndpoints) Predicate(java.util.function.Predicate) Collection(java.util.Collection) RetryPolicy(net.jodah.failsafe.RetryPolicy) PersistenceException(org.openkilda.persistence.exceptions.PersistenceException) FlowResources(org.openkilda.wfm.share.flow.resources.FlowResources) String.format(java.lang.String.format) Objects(java.util.Objects) SwitchPropertiesRepository(org.openkilda.persistence.repositories.SwitchPropertiesRepository) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) FlowDumpData(org.openkilda.wfm.share.history.model.FlowDumpData) PathComputer(org.openkilda.pce.PathComputer) Optional(java.util.Optional) ConstraintViolationException(org.openkilda.persistence.exceptions.ConstraintViolationException) SwitchRepository(org.openkilda.persistence.repositories.SwitchRepository) FlowSegmentCookieBuilder(org.openkilda.model.cookie.FlowSegmentCookie.FlowSegmentCookieBuilder) Message(org.openkilda.messaging.Message) PathSegment(org.openkilda.model.PathSegment) KildaConfigurationRepository(org.openkilda.persistence.repositories.KildaConfigurationRepository) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) RecoverableException(org.openkilda.pce.exception.RecoverableException) ArrayList(java.util.ArrayList) FlowPathDirection(org.openkilda.model.FlowPathDirection) PathSegmentRepository(org.openkilda.persistence.repositories.PathSegmentRepository) IslRepository(org.openkilda.persistence.repositories.IslRepository) Suppliers(com.google.common.base.Suppliers) FlowSegmentCookie(org.openkilda.model.cookie.FlowSegmentCookie) PersistenceManager(org.openkilda.persistence.PersistenceManager) PathId(org.openkilda.model.PathId) DetectConnectedDevices(org.openkilda.model.DetectConnectedDevices) FlowOperationsDashboardLogger(org.openkilda.wfm.share.logger.FlowOperationsDashboardLogger) ErrorType(org.openkilda.messaging.error.ErrorType) IslStatus(org.openkilda.model.IslStatus) Failsafe(net.jodah.failsafe.Failsafe) RepositoryFactory(org.openkilda.persistence.repositories.RepositoryFactory) FlowPathBuilder(org.openkilda.wfm.topology.flowhs.service.FlowPathBuilder) SwitchId(org.openkilda.model.SwitchId) FlowResourcesManager(org.openkilda.wfm.share.flow.resources.FlowResourcesManager) GetPathsResult(org.openkilda.pce.GetPathsResult) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Isl(org.openkilda.model.Isl) LazyMap(org.apache.commons.collections4.map.LazyMap) HashMap(java.util.HashMap) FailsafeException(net.jodah.failsafe.FailsafeException) PathSegment(org.openkilda.model.PathSegment) GetPathsResult(org.openkilda.pce.GetPathsResult) IslEndpoints(org.openkilda.persistence.repositories.IslRepository.IslEndpoints) Objects(java.util.Objects) PersistenceException(org.openkilda.persistence.exceptions.PersistenceException) ResourceAllocationException(org.openkilda.wfm.share.flow.resources.ResourceAllocationException) Map(java.util.Map) HashMap(java.util.HashMap) LazyMap(org.apache.commons.collections4.map.LazyMap) SneakyThrows(lombok.SneakyThrows)

Example 13 with Predicate

use of org.apache.commons.collections4.Predicate in project cu-kfs by CU-CommunityApps.

the class GroupServiceImpl method getActiveGroupMembers.

/**
 * This helper method gets the active group members of the specified type
 * (@see {@link KimConstants.KimGroupMemberTypes}). If the optional params are null, it will return all active
 * members for the specified group regardless of type.
 *
 * @param parentId
 * @param childId    optional, but if provided then memberType must be too
 * @param memberType optional, but must be provided if childId is
 * @return a list of group members
 */
private List<GroupMember> getActiveGroupMembers(String parentId, String childId, MemberType memberType) {
    final Date today = new Date(System.currentTimeMillis());
    if (childId != null && memberType == null) {
        throw new RuntimeException("memberType must be non-null if childId is non-null");
    }
    Map<String, Object> criteria = new HashMap<>(4);
    criteria.put(KIMPropertyConstants.GroupMember.GROUP_ID, parentId);
    if (childId != null) {
        criteria.put(KIMPropertyConstants.GroupMember.MEMBER_ID, childId);
        criteria.put(KIMPropertyConstants.GroupMember.MEMBER_TYPE_CODE, memberType.getCode());
    }
    Collection<GroupMember> groupMembers = this.businessObjectService.findMatching(GroupMember.class, criteria);
    CollectionUtils.filter(groupMembers, (Predicate) object -> {
        GroupMember member = (GroupMember) object;
        return member.getActiveToDate() == null || today.before(member.getActiveToDate().toDate());
    });
    return new ArrayList<>(groupMembers);
}
Also used : KimAttributeData(org.kuali.kfs.kim.impl.common.attribute.KimAttributeData) KimApiServiceLocator(org.kuali.kfs.kim.api.services.KimApiServiceLocator) Predicate(org.apache.commons.collections4.Predicate) Cacheable(org.springframework.cache.annotation.Cacheable) GenericQueryResults(org.kuali.kfs.core.api.criteria.GenericQueryResults) CacheEvict(org.springframework.cache.annotation.CacheEvict) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) KIMPropertyConstants(org.kuali.kfs.kim.impl.KIMPropertyConstants) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QueryByCriteria(org.kuali.kfs.core.api.criteria.QueryByCriteria) Map(java.util.Map) GroupService(org.kuali.kfs.kim.api.group.GroupService) AttributeTransform(org.kuali.kfs.kim.impl.common.attribute.AttributeTransform) MemberType(org.kuali.kfs.core.api.membership.MemberType) Role(org.kuali.kfs.kim.impl.role.Role) KimConstants(org.kuali.kfs.kim.api.KimConstants) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) KimImplServiceLocator(org.kuali.kfs.kim.impl.services.KimImplServiceLocator) Set(java.util.Set) LookupCustomizer(org.kuali.kfs.core.api.criteria.LookupCustomizer) Collectors(java.util.stream.Collectors) Date(java.sql.Date) PredicateFactory(org.kuali.kfs.core.api.criteria.PredicateFactory) List(java.util.List) Logger(org.apache.logging.log4j.Logger) BusinessObjectService(org.kuali.kfs.krad.service.BusinessObjectService) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) CriteriaLookupService(org.kuali.kfs.core.api.criteria.CriteriaLookupService) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.sql.Date)

Aggregations

ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)7 List (java.util.List)7 Map (java.util.Map)7 CollectionUtils (org.apache.commons.collections4.CollectionUtils)6 Collections (java.util.Collections)5 Set (java.util.Set)5 Predicate (java.util.function.Predicate)5 Predicate (org.apache.commons.collections4.Predicate)5 HashSet (java.util.HashSet)4 Collectors (java.util.stream.Collectors)4 StringUtils (org.apache.commons.lang3.StringUtils)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3 Supplier (java.util.function.Supplier)3 BigDecimal (java.math.BigDecimal)2 Date (java.util.Date)2 LinkedHashMap (java.util.LinkedHashMap)2