All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.mf.checks.atts.text.AbstractTextMustMatchPattern Maven / Gradle / Ivy

The newest version!
package cdc.mf.checks.atts.text;

import java.util.regex.Pattern;

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.mf.checks.IssueDescription;
import cdc.mf.checks.MfAbstractRuleChecker;
import cdc.util.strings.StringUtils;

/**
 * Checker that checks that a particular text property of an item matches a pattern.
 *
 * @author Damien Carbonne
 *
 * @param  The item type.
 */
public abstract class AbstractTextMustMatchPattern extends MfAbstractRuleChecker {
    public static final IssueSeverity SEVERITY = IssueSeverity.MAJOR;

    protected static final String MUST_MATCH_THIS_PATTERN = " must match this pattern: ";

    protected static final String UPPER_CAMEL_CASE_REGEX = "^[A-Z][a-zA-Z0-9]*$";
    protected static final String LOWER_CAMEL_CASE_REGEX = "^[a-z][a-zA-Z0-9]*$";
    protected static final String LOWER_CASE_REGEX = "^[a-z]+$";
    protected static final String CAPITAL_CASE_REGEX = "^[A-Z][A-Za-z0-9]*( [A-Z][A-Za-z0-9]*)*$";
    protected static final String NO_SPACES_REGEX = "^[\\S]+$";

    private final Pattern pattern;

    protected AbstractTextMustMatchPattern(SnapshotManager manager,
                                           Class objectClass,
                                           Rule rule,
                                           String regex) {
        super(manager,
              objectClass,
              rule);
        this.pattern = Pattern.compile(regex);
    }

    /**
     * Retrieve the text property to check.
     *
     * @param object The item.
     * @return The text property to check.
     */
    protected abstract String getText(O object);

    @Override
    public CheckResult check(CheckContext context,
                             O object,
                             Location location) {
        final String text = getText(object);
        if (!StringUtils.isNullOrEmpty(text)) {
            final boolean matches = pattern.matcher(text).matches();
            if (!matches) {
                final IssueDescription.Builder description = IssueDescription.builder();

                description.header(getHeader(object))
                           .value(text)
                           .violation("does not match " + pattern.pattern());

                add(issue().description(description)
                           .location(location)
                           .build());
                return CheckResult.FAILURE;
            } else {
                return CheckResult.SUCCESS;
            }
        } else {
            return CheckResult.SUCCESS;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy