cdc.mf.checks.atts.name.AbstractSiblingsMustHaveDifferentNames Maven / Gradle / Ivy
The newest version!
package cdc.mf.checks.atts.name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cdc.issues.IssueSeverity;
import cdc.issues.checks.CheckContext;
import cdc.issues.checks.CheckResult;
import cdc.issues.checks.SnapshotManager;
import cdc.issues.locations.Location;
import cdc.issues.rules.Rule;
import cdc.issues.rules.RuleDescription;
import cdc.mf.checks.IssueDescription;
import cdc.mf.checks.MfAbstractRuleChecker;
import cdc.mf.model.MfElement;
import cdc.mf.model.MfNameItem;
import cdc.mf.model.MfUtils;
import cdc.util.strings.StringUtils;
public abstract class AbstractSiblingsMustHaveDifferentNames extends MfAbstractRuleChecker {
public static final IssueSeverity SEVERITY = IssueSeverity.CRITICAL;
protected static String describe() {
return RuleDescription.format("Some {%wrap} must have different {%wrap}.",
N_SIBLING + S,
N_NAME + S);
}
protected AbstractSiblingsMustHaveDifferentNames(SnapshotManager manager,
Rule rule) {
super(manager,
MfElement.class,
rule);
}
@Override
protected final String getHeader(MfElement object) {
return getTheItemHeader(object);
}
@Override
public CheckResult check(CheckContext context,
MfElement object,
Location location) {
// The children that can have a name
final List children = object.getChildren(MfNameItem.class);
// Map from name to list of items with that name
final Map> map = new HashMap<>();
// Set to true if siblings with same name are found
boolean hasDuplicates = false;
for (final MfNameItem child : children) {
if (MfUtils.getFeatures(child.getClass()).nameUniqueness()) {
final String name = child.getName();
if (!StringUtils.isNullOrEmpty(name)) {
final List list = map.computeIfAbsent(name, k -> new ArrayList<>());
list.add(child);
if (list.size() > 1) {
hasDuplicates = true;
}
}
}
}
if (hasDuplicates) {
final IssueDescription.Builder description = IssueDescription.builder();
// Select the items that have duplicate names
final List duplicates = new ArrayList<>();
for (final List list : map.values()) {
if (list.size() >= 2) {
duplicates.addAll(list);
}
}
Collections.sort(duplicates, MfNameItem.NAME_COMPARATOR);
description.header(getHeader(object))
.violation("has siblings with same name")
.elements(duplicates);
add(issue().description(description)
.location(location)
.build());
return CheckResult.FAILURE;
} else {
return CheckResult.SUCCESS;
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy