Example usage for com.google.common.collect Iterables all

List of usage examples for com.google.common.collect Iterables all

Introduction

In this page you can find the example usage for com.google.common.collect Iterables all.

Prototype

public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if every element in iterable satisfies the predicate.

Usage

From source file:nextmethod.web.razor.parser.TokenizerBackedParser.java

@SafeVarargs
protected final void acceptUntil(@Nonnull final TSymbolType... types) {
    final List<TSymbolType> symbolTypeList = Arrays.asList(types);
    acceptWhile(tSymbol -> tSymbol == null || Iterables.all(symbolTypeList,
            tSymbolType -> tSymbolType == null || tSymbolType != tSymbol.getType()));
}

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

/**
 * Remove launch permissions./*from w w  w.  j  a  va2 s . c om*/
 * 
 * @param accountIds
 */
public void removePermissions(final List<String> accountIds) {

    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {
        final ImageInfo entity = Entities.merge(this);
        Iterables.all(accountIds, new Predicate<String>() {

            @Override
            public boolean apply(final String input) {
                ImageInfo.this.getPermissions().remove(input);
                return true;
            }
        });

        db.commit();
    } catch (final Exception ex) {
        Logs.exhaust().error(ex, ex);
        db.rollback();
    }
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.alarms.AlarmManager.java

private static boolean modifySelectedAlarms(final String accountId, final Collection<String> alarmNames,
        final Predicate<CloudWatchMetadata.AlarmMetadata> filter, final Predicate<AlarmEntity> update) {
    final Map<String, Collection<String>> accountToNamesMap = buildAccountIdToAlarmNamesMap(accountId,
            alarmNames);//from  www  .ja  v  a 2  s  .co  m
    try (final TransactionResource db = Entities.transactionFor(AlarmEntity.class)) {
        final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
        final Junction disjunction = Restrictions.disjunction();
        for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) {
            final Junction conjunction = Restrictions.conjunction();
            conjunction.add(Restrictions.eq("accountId", entry.getKey()));
            conjunction.add(Restrictions.in("alarmName", entry.getValue()));
            disjunction.add(conjunction);
        }
        criteria.add(disjunction);
        criteria.addOrder(Order.asc("creationTimestamp"));
        criteria.addOrder(Order.asc("naturalId"));
        final Collection<AlarmEntity> alarmEntities = (Collection<AlarmEntity>) criteria.list();
        if (!Iterables.all(alarmEntities, filter)) {
            return false;
        }
        CollectionUtils.each(alarmEntities, update);
        db.commit();
        return true;
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java

@Override
public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) {
    try {/*from  w  ww  .j a va  2 s  . com*/
        long firstTs = timestampByCell.values().iterator().next();
        if (Iterables.all(timestampByCell.values(), Predicates.equalTo(firstTs))) {
            StartTsResultsCollector collector = new StartTsResultsCollector(firstTs);
            loadWithTs(tableName, timestampByCell.keySet(), firstTs, false, collector, readConsistency);
            return collector.collectedResults;
        }

        SetMultimap<Long, Cell> cellsByTs = HashMultimap.create();
        Multimaps.invertFrom(Multimaps.forMap(timestampByCell), cellsByTs);
        Builder<Cell, Value> builder = ImmutableMap.builder();
        for (long ts : cellsByTs.keySet()) {
            StartTsResultsCollector collector = new StartTsResultsCollector(ts);
            loadWithTs(tableName, cellsByTs.get(ts), ts, false, collector, readConsistency);
            builder.putAll(collector.collectedResults);
        }
        return builder.build();
    } catch (Throwable t) {
        throw Throwables.throwUncheckedException(t);
    }
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.validation.EMFPatternLanguageValidator.java

private void checkParameterTypes(final Variable variable) {
    Set<Variable> parameterReferences = PatternLanguageHelper.getLocalReferencesOfParameter(variable).stream()
            .filter(Objects::nonNull).collect(Collectors.toSet());

    final IInputKey inferredType = typeInferrer.getType(variable);
    if (variable.getType() == null) {
        // Missing type validation
        Set<IInputKey> possibleTypes = Sets.newHashSet();

        for (Variable bodyVar : parameterReferences) {
            possibleTypes.addAll(typeInferrer.getAllPossibleTypes(bodyVar));
        }//from   ww w.ja  v  a 2 s.co  m
        reportMissingParameterTypeDeclaration(variable, possibleTypes, typeInferrer.getInferredType(variable));

        if (possibleTypes.isEmpty()) {
            return;
        } else if (possibleTypes.size() > 1
                && Iterables.all(possibleTypes, EClassTransitiveInstancesKey.class::isInstance)) {
            Set<EClass> eClasses = typeSystem.getCompatibleSupertypes(possibleTypes).stream()
                    .filter(EClassTransitiveInstancesKey.class::isInstance)
                    .map(EClassTransitiveInstancesKey.class::cast).map(EClassTransitiveInstancesKey::getEmfKey)
                    .filter(input -> input != null && !input.eIsProxy()).collect(Collectors.toSet());

            final EClass erroneous = EcoreFactory.eINSTANCE.createEClass();
            Optional<EClass> reduced = eClasses.stream().filter(Objects::nonNull).filter(obj -> !obj.eIsProxy())
                    .reduce((t1, t2) -> {
                        if (t1 == EcorePackage.Literals.EOBJECT) {
                            return t2;
                        } else {
                            final EClass compatibleType = (EClass) EcoreUtil2.getCompatibleType(t1, t2, null);
                            return compatibleType == null ? erroneous : compatibleType;
                        }
                    });
            if (Objects.equals(reduced.orElse(erroneous), erroneous)) {
                String[] issueData = Stream.concat(eClasses.stream().map(EClass::getName), Stream.of("EObject"))
                        .toArray(String[]::new);
                error("Variable type cannot be calculated unambiguously, the types ["
                        + Joiner.on(", ").join(Iterables.transform(possibleTypes, typeSystem::typeString))
                        + "] have no _unique_ common supertype. The list of possible supertypes found are ["
                        + Joiner.on(", ").join(issueData) + "], specify one as the intended supertype.",
                        variable, null, IssueCodes.PARAMETER_TYPE_AMBIGUOUS, issueData);
            }
        }
    } else {
        // Check for more specific type inferrable for bodies
        Set<IInputKey> referenceTypes = parameterReferences.stream().map(typeInferrer::getInferredType)
                .filter(Objects::nonNull).collect(Collectors.toSet());
        boolean allTypesMoreSpecific = referenceTypes.stream()
                .allMatch(aggregatedType -> !Objects.equals(inferredType, aggregatedType)
                        && Objects.equals(inferredType.getClass(), aggregatedType.getClass())
                        && typeSystem.isConformant(inferredType, aggregatedType));
        Iterator<IInputKey> it = referenceTypes.iterator();
        if (it.hasNext() && allTypesMoreSpecific) {
            Set<IInputKey> aggregatedTypes = typeSystem.minimizeTypeInformation(Sets.newHashSet(referenceTypes),
                    true);
            if (aggregatedTypes.size() == 1 && inferredType != null) {
                IInputKey aggregatedType = aggregatedTypes.iterator().next();
                if (!Objects.equals(inferredType, aggregatedType)
                        && Objects.equals(inferredType.getClass(), aggregatedType.getClass())
                        && typeSystem.isConformant(inferredType, aggregatedType)) {
                    warning("Declared type " + typeSystem.typeString(inferredType)
                            + " is less specific then the type " + typeSystem.typeString(aggregatedType)
                            + " inferred from bodies", variable, null, IssueCodes.PARAMETER_TYPE_INVALID);
                }
            }
        }
    }
}

From source file:com.isotrol.impe3.pms.core.impl.PortalsServiceImpl.java

/**
 * @see com.isotrol.impe3.pms.api.portal.PortalsService#save(com.isotrol.impe3.pms.api.portal.PortalDTO)
 *//*from w  ww  . j a v  a 2s. co m*/
@Transactional(rollbackFor = Throwable.class)
@Authorized(global = GlobalAuthority.PORTAL_SET, portal = PortalAuthority.SET)
public void save(PortalDTO dto) throws PMSException {
    checkNotNull(dto);
    checkNotNull(MoreLocales.VALID.apply(dto.getDefaultLocale()));
    checkArgument(dto.getLocales() == null || Iterables.all(dto.getLocales().keySet(), MoreLocales.VALID));
    final String id = dto.getId();
    final PortalEntity entity = load(id);
    final PortalDfn dfn = portalManager.touchOffline(entity);
    fill(loadContextGlobal(), dfn, dto);
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.BasicDifferenceGroupImpl.java

/**
 * @param match/*from w w w  .  j  a v  a 2 s  . co m*/
 * @return
 */
private boolean isMatchWithOnlyResourceAttachmentChanges(Match match) {
    boolean ret = false;
    Iterable<Diff> allDifferences = match.getAllDifferences();
    if (Iterables.isEmpty(allDifferences)) {
        ret = false;
    } else if (Iterables.all(allDifferences, instanceOf(ResourceAttachmentChange.class))) {
        if (match.getSubmatches() == null || match.getSubmatches().isEmpty()) {
            ret = true;
        }
    }
    return ret;
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.provider.BorderItemAwareLayoutProvider.java

/**
 * Layout this list of selected objects, using the specified layout hint.
 * The selected objects all reside within the same parent container. Other
 * elements that are part of the container but not specified in the list of
 * objects, are ignored.//from w w  w .j a  va2s. co  m
 * 
 * @param selectedObjects
 *            <code>List</code> of <code>EditPart</code> objects that are to
 *            be layed out.
 * @param layoutHint
 *            <code>IAdaptable</code> hint to the provider to determine the
 *            layout kind.
 * @param normalArrangeMustBeCalled
 *            Tell if the normal arrange process must be called before the
 *            border item arrange
 * @return <code>Command</code> that when executed will layout the edit
 *         parts in the container
 */
public Command layoutEditParts(final List selectedObjects, final IAdaptable layoutHint,
        final boolean normalArrangeMustBeCalled) {
    this.launchNormalArrange = normalArrangeMustBeCalled;

    if (selectedObjects.isEmpty()) {
        return UnexecutableCommand.INSTANCE;
    }

    CompoundCommand result = new CompoundCommand();

    if (launchNormalArrange) {
        // Create a request recorder to record all ChangeBounds requests by
        // editparts.
        final EditPartViewer root = ((EditPart) selectedObjects.get(0)).getViewer();
        if (root instanceof SiriusDiagramGraphicalViewer) {
            final ChangeBoundRequestRecorder recorder = ((SiriusDiagramGraphicalViewer) root)
                    .getChangeBoundRequestRecorder();
            recorder.startRecording();
            result.add(lauchPrimaryArrangeAll(selectedObjects, layoutHint));
            recorder.stopRecording();
            registerChangeBoundsCommand(recorder);
            recorder.dispose();
        }
    }

    // Finds if there are unpinned diagram elements to keep fixed stored in
    // the LayoutHint as a Collection
    ArrayList<IDiagramElementEditPart> elementsToKeepFixed = Lists.newArrayList();
    if (layoutHint.getAdapter(Collection.class) instanceof ArrayList<?>
            && Iterables.all((ArrayList<?>) layoutHint.getAdapter(Collection.class),
                    validateAllElementInArrayListAreIDiagramElementEditPart)) {
        elementsToKeepFixed = (ArrayList<IDiagramElementEditPart>) layoutHint.getAdapter(Collection.class);
    }

    // Create the specific command to layout the border items.
    final Command layoutBorderItems = layoutBorderItems(selectedObjects, 1, elementsToKeepFixed);
    if (layoutBorderItems != null && layoutBorderItems.canExecute()) {
        result.add(layoutBorderItems);
    }

    resetBoundsOfPinnedElements(selectedObjects, result, elementsToKeepFixed);
    this.getViewsToChangeBoundsRequest().clear();
    if (result.size() == 0) {
        result = null; // removeCommandsForPinnedElements(result);
    }
    return result;
}

From source file:com.b2international.snowowl.snomed.importer.rf2.util.ImportUtil.java

private SnomedImportResult doImportInternal(final SnomedImportContext context, final String requestingUserId,
        final ImportConfiguration configuration, final IProgressMonitor monitor) {
    final SubMonitor subMonitor = SubMonitor.convert(monitor, "Importing release files...", 17);
    final SnomedImportResult result = new SnomedImportResult();

    CodeSystemEntry codeSystem = CodeSystemRequests.prepareGetCodeSystem(configuration.getCodeSystemShortName())
            .build(SnomedDatastoreActivator.REPOSITORY_UUID).execute(getEventBus()).getSync();

    IBranchPath codeSystemPath = BranchPathUtils.createPath(codeSystem.getBranchPath());
    String importPath = configuration.getBranchPath();
    final IBranchPath branchPath;

    if (importPath.startsWith(IBranchPath.MAIN_BRANCH)) {
        IBranchPath candidate = BranchPathUtils.createPath(importPath);
        Iterator<IBranchPath> iterator = BranchPathUtils.bottomToTopIterator(candidate);
        boolean found = false;

        while (iterator.hasNext()) {
            candidate = iterator.next();
            if (codeSystemPath.equals(candidate)) {
                found = true;//from   w w w.  ja  va2s  .c  om
                break;
            }
        }

        if (!found) {
            throw new ImportException("Import path %s is not valid for code system %s.", importPath,
                    configuration.getCodeSystemShortName());
        }

        branchPath = BranchPathUtils.createPath(importPath); // importPath is absolute
    } else {
        branchPath = BranchPathUtils.createPath(codeSystemPath, importPath); // importPath is relative to the code system's work branch
    }

    LogUtils.logImportActivity(IMPORT_LOGGER, requestingUserId, branchPath,
            "SNOMED CT import started from RF2 release format.");

    final RepositoryState repositoryState = getIndex().read(configuration.getBranchPath(),
            new RevisionIndexRead<RepositoryState>() {
                @Override
                public RepositoryState execute(RevisionSearcher searcher) throws IOException {
                    return loadRepositoryState(searcher);
                }
            });

    if (!isContentValid(repositoryState, result, requestingUserId, configuration, branchPath, subMonitor)) {
        LogUtils.logImportActivity(IMPORT_LOGGER, requestingUserId, branchPath,
                "SNOMED CT import failed due to invalid RF2 release file(s).");
        return result;
    }

    final Set<URL> patchedRefSetURLs = Sets.newHashSet(configuration.getRefSetUrls());
    final Set<String> patchedExcludedRefSetIDs = Sets.newHashSet(configuration.getExcludedRefSetIds());
    final List<Importer> importers = Lists.newArrayList();

    final File stagingDirectoryRoot = new File(System.getProperty("java.io.tmpdir"));

    context.setVersionCreationEnabled(configuration.isCreateVersions());
    context.setLogger(IMPORT_LOGGER);
    context.setStagingDirectory(stagingDirectoryRoot);
    context.setContentSubType(configuration.getContentSubType());
    context.setIgnoredRefSetIds(patchedExcludedRefSetIDs);
    context.setReleasePatch(configuration.isReleasePatch());
    context.setPatchReleaseVersion(configuration.getPatchReleaseVersion());
    context.setCodeSystemShortName(configuration.getCodeSystemShortName());

    try {

        if (configuration.isValidReleaseFile(configuration.getConceptFile())) {
            final URL url = configuration.toURL(configuration.getConceptFile());
            importers.add(new SnomedConceptImporter(context, url.openStream(),
                    configuration.getMappedName(url.getPath())));
        }

        for (File descriptionFile : configuration.getDescriptionFiles()) {
            if (configuration.isValidReleaseFile(descriptionFile)) {
                final URL url = configuration.toURL(descriptionFile);
                importers.add(new SnomedDescriptionImporter(context, url.openStream(),
                        configuration.getMappedName(url.getPath()), ComponentImportType.DESCRIPTION));
            }
        }

        for (File textFile : configuration.getTextDefinitionFiles()) {
            if (configuration.isValidReleaseFile(textFile)) {
                final URL url = configuration.toURL(textFile);
                importers.add(new SnomedDescriptionImporter(context, url.openStream(),
                        configuration.getMappedName(url.getPath()), ComponentImportType.TEXT_DEFINITION));
            }

        }

        if (configuration.isValidReleaseFile(configuration.getRelationshipFile())) {
            final URL url = configuration.toURL(configuration.getRelationshipFile());
            importers.add(new SnomedRelationshipImporter(context, url.openStream(),
                    configuration.getMappedName(url.getPath()), ComponentImportType.RELATIONSHIP));
        }

        if (configuration.isValidReleaseFile(configuration.getStatedRelationshipFile())) {
            final URL url = configuration.toURL(configuration.getStatedRelationshipFile());
            importers.add(new SnomedRelationshipImporter(context, url.openStream(),
                    configuration.getMappedName(url.getPath()), ComponentImportType.STATED_RELATIONSHIP));
        }

    } catch (final IOException e) {
        final String reason = null != e.getMessage() ? " Reason: '" + e.getMessage() + "'" : "";
        LogUtils.logImportActivity(IMPORT_LOGGER, requestingUserId, branchPath,
                "SNOMED CT import failed due to invalid RF2 release file URL." + reason);
        throw new ImportException("Invalid release file URL(s).", e);
    }

    for (final URL url : patchedRefSetURLs) {

        try {

            final AbstractSnomedRefSetImporter<?, ?> createRefSetImporter = SnomedRefSetImporterFactory
                    .createRefSetImporter(url, context, configuration.getMappedName(url.getPath()));

            if (createRefSetImporter == null) {
                final String message = MessageFormat
                        .format("Skipping unsupported reference set with URL ''{0}''.", url);
                LogUtils.logImportActivity(IMPORT_LOGGER, requestingUserId, branchPath, message);
                IMPORT_LOGGER.info(message);
            } else {
                importers.add(createRefSetImporter);
            }

        } catch (final IOException e) {
            final String reason = null != e.getMessage() ? " Reason: '" + e.getMessage() + "'" : "";
            LogUtils.logImportActivity(IMPORT_LOGGER, requestingUserId, branchPath,
                    "SNOMED CT import failed due to I/O error while creating reference set importer." + reason);
            throw new ImportException("I/O error occurred while creating reference set importer.", e);
        }
    }

    final boolean terminologyExistsBeforeImport = getIndex().read(BranchPathUtils.createMainPath().getPath(),
            new RevisionIndexRead<Boolean>() {
                @Override
                public Boolean execute(RevisionSearcher index) throws IOException {
                    return index.search(Query.select(SnomedConceptDocument.class)
                            .where(SnomedConceptDocument.Expressions.id(Concepts.ROOT_CONCEPT)).limit(0)
                            .build()).getTotal() > 0;
                }
            });
    final boolean onlyRefSetImportersRegistered = Iterables.all(importers,
            Predicates.instanceOf(AbstractSnomedRefSetImporter.class));

    /*
     * Commit notifications for changes made by the import should only be sent if the terminology already exists,
     * and only changes for reference sets are coming in from the import files. 
     */
    context.setCommitNotificationEnabled(terminologyExistsBeforeImport && onlyRefSetImportersRegistered);
    context.setUserId(requestingUserId);

    final ICDOConnectionManager connectionManager = ApplicationContext.getInstance()
            .getService(ICDOConnectionManager.class);
    final CDOBranch branch = connectionManager.get(SnomedPackage.eINSTANCE).getBranch(branchPath);

    if (null == branch) {
        throw new ImportException("Branch does not exist. [" + branchPath + "]");
    }

    final SnomedEditingContext editingContext = new SnomedEditingContext(branchPath);
    context.setEditingContext(editingContext);
    context.setAggregatorSupplier(
            new EffectiveTimeBaseTransactionAggregatorSupplier(editingContext.getTransaction()));

    final IOperationLockTarget lockTarget = new SingleRepositoryAndBranchLockTarget(
            editingContext.getTransaction().getSession().getRepositoryInfo().getUUID(), branchPath);
    final DatastoreLockContext lockContext = new DatastoreLockContext(requestingUserId,
            DatastoreLockContextDescriptions.IMPORT);
    final SnomedImportResult[] resultHolder = new SnomedImportResult[1];
    final IDatastoreOperationLockManager lockManager = ApplicationContext.getInstance()
            .getServiceChecked(IDatastoreOperationLockManager.class);

    final FeatureToggles features = ApplicationContext.getServiceForClass(FeatureToggles.class);
    final String importFeatureToggle = Features.getImportFeatureToggle(SnomedDatastoreActivator.REPOSITORY_UUID,
            branchPath.getPath(), configuration.getContentSubType().getLowerCaseName());
    try {
        features.enable(importFeatureToggle);
        OperationLockRunner.with(lockManager).run(new Runnable() {
            @Override
            public void run() {
                resultHolder[0] = doImportLocked(requestingUserId, configuration, result, branchPath, context,
                        subMonitor, importers, editingContext, branch, repositoryState);
            }
        }, lockContext, IOperationLockManager.NO_TIMEOUT, lockTarget);
    } catch (final OperationLockException | InterruptedException e) {
        throw new ImportException("Caught exception while locking repository for import.", e);
    } catch (final InvocationTargetException e) {
        throw new ImportException("Failed to import RF2 release.", e.getCause());
    } finally {
        features.disable(importFeatureToggle);
    }

    return resultHolder[0];
}

From source file:org.eclipse.sirius.diagram.business.internal.experimental.sync.DDiagramSynchronizer.java

/**
 * Order and process edge mappings refresh to have both end of the edge
 * refreshed before its own refresh./*from w w w  .  ja v a 2  s. c  o  m*/
 * 
 * @param edgeMappings
 *            list of EdgeMapping to refresh
 * @param mappingsToEdgeTargets
 *            map of refreshed EdgeMapping
 * @param edgeToMappingBasedDecoration
 * @param edgeToSemanticBasedDecoration
 * @param monitor
 *            the current Monitor
 */
private void processEdgeMappingsRefresh(List<EdgeMapping> edgeMappings,
        final Map<DiagramElementMapping, Collection<EdgeTarget>> mappingsToEdgeTargets,
        Map<EdgeMapping, Collection<MappingBasedDecoration>> edgeToMappingBasedDecoration,
        Map<String, Collection<SemanticBasedDecoration>> edgeToSemanticBasedDecoration,
        final IProgressMonitor monitor) {

    final IsMappingOfCurrentDiagramDescription isMappingOfCurrentDiagramDescription = new IsMappingOfCurrentDiagramDescription(
            description);

    Predicate<EdgeMapping> edgeMappingWithoutEdgeAsSourceOrTarget = new Predicate<EdgeMapping>() {
        public boolean apply(EdgeMapping input) {
            // Valid if source mapping and target mapping are not
            // EdgeMappings
            Iterable<EdgeMapping> edgeSourceMappings = Iterables.filter(
                    Iterables.filter(input.getSourceMapping(), EdgeMapping.class),
                    isMappingOfCurrentDiagramDescription);
            Iterable<EdgeMapping> edgeTargetMappings = Iterables.filter(
                    Iterables.filter(input.getTargetMapping(), EdgeMapping.class),
                    isMappingOfCurrentDiagramDescription);
            return Iterables.isEmpty(edgeSourceMappings) && Iterables.isEmpty(edgeTargetMappings);
        }
    };

    final Predicate<EdgeMapping> refreshedEdgeMapping = new Predicate<EdgeMapping>() {
        public boolean apply(EdgeMapping input) {
            // Valid if edge mapping has been refreshed or is not in the
            // activated layers
            return mappingsToEdgeTargets.keySet().contains(input)
                    || !getDiagram().getActivatedLayers().contains(new EObjectQuery(input)
                            .getFirstAncestorOfType(DescriptionPackage.eINSTANCE.getLayer()));
        }
    };

    Predicate<EdgeMapping> unrefreshedEdgeMappingWithRefreshedEdgeAsSourceOrTarget = new Predicate<EdgeMapping>() {
        public boolean apply(EdgeMapping input) {
            // Valid if the EdgeMapping is not refresh and the source or
            // target EdgeMapping has been refreshed
            boolean result = !mappingsToEdgeTargets.keySet().contains(input);
            Iterable<EdgeMapping> edgeSourceMappings = Iterables.filter(
                    Iterables.filter(input.getSourceMapping(), EdgeMapping.class),
                    isMappingOfCurrentDiagramDescription);
            Iterable<EdgeMapping> edgeTargetMappings = Iterables.filter(
                    Iterables.filter(input.getTargetMapping(), EdgeMapping.class),
                    isMappingOfCurrentDiagramDescription);
            return result && Iterables.all(edgeSourceMappings, refreshedEdgeMapping)
                    && Iterables.all(edgeTargetMappings, refreshedEdgeMapping);
        }
    };

    // Firstly, we need to refresh the EdgeMapping having no other
    // EdgeMapping as source neither as target
    for (final EdgeMapping mapping : Iterables.filter(edgeMappings, edgeMappingWithoutEdgeAsSourceOrTarget)) {
        refreshEdgeMapping(diagramMappingsManager, mappingsToEdgeTargets, mapping, edgeToMappingBasedDecoration,
                edgeToSemanticBasedDecoration, new SubProgressMonitor(monitor, 1));
        mappingsToEdgeTargets.put(mapping, (Collection) diagram.getEdgesFromMapping(mapping));
    }

    // The list of EdgeMappings that have not been processed.
    ArrayList<EdgeMapping> remaingEdgeMappingsToRefresh = Lists.newArrayList(edgeMappings);
    remaingEdgeMappingsToRefresh.removeAll(mappingsToEdgeTargets.keySet());

    boolean noRefreshImpliesCycleDetected = true;

    // Then, we will refresh the other EdgeMapping. An EdgeMapping with
    // another EdgeMapping as source or target can be refreshed only if this
    // other EdgeMapping has been refreshed (therefore is included in the
    // mappingsToEdgeTargets map).
    while (!mappingsToEdgeTargets.keySet().containsAll(edgeMappings)) {
        for (final EdgeMapping mapping : Iterables.filter(remaingEdgeMappingsToRefresh,
                unrefreshedEdgeMappingWithRefreshedEdgeAsSourceOrTarget)) {
            refreshEdgeMapping(diagramMappingsManager, mappingsToEdgeTargets, mapping,
                    edgeToMappingBasedDecoration, edgeToSemanticBasedDecoration,
                    new SubProgressMonitor(monitor, 1));
            mappingsToEdgeTargets.put(mapping, (Collection) diagram.getEdgesFromMapping(mapping));
            noRefreshImpliesCycleDetected = false;
        }

        remaingEdgeMappingsToRefresh = Lists.newArrayList(edgeMappings);
        remaingEdgeMappingsToRefresh.removeAll(mappingsToEdgeTargets.keySet());
        if (noRefreshImpliesCycleDetected) {
            // No refresh has been done. That means that there are
            // EdgeMapping that need refresh but have as source or target an
            // EdgeMapping that is not refreshed because of a cycle between
            // EdgeMappings. Therefore, we stop the refresh here in order to
            // avoid a dead lock.
            return;
        }
        noRefreshImpliesCycleDetected = true;
    }

}