Example usage for org.apache.commons.validator GenericValidator matchRegexp

List of usage examples for org.apache.commons.validator GenericValidator matchRegexp

Introduction

In this page you can find the example usage for org.apache.commons.validator GenericValidator matchRegexp.

Prototype

public static boolean matchRegexp(String value, String regexp) 

Source Link

Document

Checks if the value matches the regular expression.

Usage

From source file:org.apache.archiva.admin.repository.DefaultRepositoryCommonValidator.java

/**
 * validate cronExpression and location format
 *
 * @param managedRepository//ww w. j a v  a2 s. c o m
 * @since 1.4-M2
 */
@Override
public void validateManagedRepository(ManagedRepository managedRepository) throws RepositoryAdminException {
    String cronExpression = managedRepository.getCronExpression();
    // FIXME : olamy can be empty to avoid scheduled scan ?
    if (StringUtils.isNotBlank(cronExpression)) {
        CronExpressionValidator validator = new CronExpressionValidator();

        if (!validator.validate(cronExpression)) {
            throw new RepositoryAdminException("Invalid cron expression.", "cronExpression");
        }
    } else {
        throw new RepositoryAdminException("Cron expression cannot be empty.");
    }

    String repoLocation = removeExpressions(managedRepository.getLocation());

    if (!GenericValidator.matchRegexp(repoLocation,
            ManagedRepositoryAdmin.REPOSITORY_LOCATION_VALID_EXPRESSION)) {
        throw new RepositoryAdminException(
                "Invalid repository location. Directory must only contain alphanumeric characters, equals(=), question-marks(?), "
                        + "exclamation-points(!), ampersands(&), forward-slashes(/), back-slashes(\\), underscores(_), dots(.), colons(:), tildes(~), and dashes(-).",
                "location");
    }
}

From source file:org.apache.archiva.admin.repository.ValidatorTest.java

@Test
public void testGenericValidator() {
    // Be sure M/*  w  w w. j  a  va  2 s  . c o m*/
    assertFalse("A repo location cannot contains space", GenericValidator.matchRegexp("/opt/ testme/",
            ManagedRepositoryAdmin.REPOSITORY_LOCATION_VALID_EXPRESSION));

}

From source file:org.apache.myfaces.custom.regexprvalidator.AbstractRegExprValidator.java

public void validate(FacesContext facesContext, UIComponent uiComponent, Object value)
        throws ValidatorException {

    if (facesContext == null)
        throw new NullPointerException("facesContext");
    if (uiComponent == null)
        throw new NullPointerException("uiComponent");

    if (value == null) {
        return;//from w  ww  .j a v a2  s. co  m
    }
    Object[] args = { value.toString() };
    if (!GenericValidator.matchRegexp(value.toString(), "^" + getPattern() + "$")) {
        throw new ValidatorException(getFacesMessage(REGEXPR_MESSAGE_ID, args));
    }
}

From source file:org.apache.struts.validator.FieldChecks.java

/**
 * Checks if the field matches the regular expression in the field's mask
 * attribute./*  w w w.j a  v a 2  s .co m*/
 *
 * @param bean      The bean validation is being performed on.
 * @param va        The <code>ValidatorAction</code> that is currently
 *                  being performed.
 * @param field     The <code>Field</code> object associated with the
 *                  current field being validated.
 * @param errors    The <code>ActionMessages</code> object to add errors
 *                  to if any validation errors occur.
 * @param validator The <code>Validator</code> instance, used to access
 *                  other field values.
 * @param request   Current request object.
 * @return true if field matches mask, false otherwise.
 */
public static boolean validateMask(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {
    String value = null;

    value = evaluateBean(bean, field);

    try {
        String mask = Resources.getVarValue("mask", field, validator, request, true);

        if (value != null && value.length() > 0 && !GenericValidator.matchRegexp(value, mask)) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));

            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        processFailure(errors, field, "mask", e);

        return false;
    }
}

From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.config.ConditionBean.java

public boolean validate(HttpServletRequest request, ActionErrors errs, int idx) {
    boolean valid = true;
    if (trigger.equals("onMetric")) {
        if (getMetricId().intValue() <= 0) {
            // user didn't select a metric
            ActionMessage err = new ActionMessage("alert.config.error.NoMetricSelected");
            errs.add("condition[" + idx + "].metricId", err);
            valid = false;/*from   ww  w  .j a v a2s. c o  m*/
        }
        if (thresholdType.equals(TYPE_ABS)) {
            if (!GenericValidator.matchRegexp(getAbsoluteValue(), DOUBLE_REGEX)) {
                String fieldName = RequestUtils.message(request, "alert.config.props.CB.AbsoluteValue");
                ActionMessage err = new ActionMessage("errors.double", fieldName);
                errs.add("condition[" + idx + "].absoluteValue", err);
                valid = false;
            } else { // double
                // do nothing
            }
        } else if (thresholdType.equals(TYPE_PERC)) { // percentage
            if (!GenericValidator.matchRegexp(getPercentage(), DOUBLE_REGEX)) {
                String fieldName = RequestUtils.message(request, "alert.config.props.CB.Percentage");
                ActionMessage err = new ActionMessage("errors.double", fieldName);
                errs.add("condition[" + idx + "].percentage", err);
                valid = false;
            } else { // double
                // 0-100 range
                double percentage = NumberUtil.stringAsNumber(getPercentage()).doubleValue();
                if (!GenericValidator.isInRange(percentage, 0d, 1000d)) {
                    ActionMessage err = new ActionMessage("errors.range", String.valueOf(percentage),
                            String.valueOf(0d), String.valueOf(1000d));
                    errs.add("condition[" + idx + "].percentage", err);
                    valid = false;
                }
            }
            if (null == getBaselineOption() || getBaselineOption().length() == 0) {
                log.debug("!!! NO BASELINE OPTION!");
                ActionMessage err = new ActionMessage("alert.config.error.NoBaselineOptionSelected");
                errs.add("condition[" + idx + "].baselineOption", err);
                valid = false;
            } else {
                log.debug("*** BASELINE OPTION!");
            }
        }
    } else if (trigger.equals("onCustProp")) {
        if (0 == getCustomProperty().length()) {
            ActionMessage err = new ActionMessage("alert.config.error.NoCustomPropertySelected");
            errs.add("condition[" + idx + "].customProperty", err);
            valid = false;
        }
    } else if (trigger.equals("onLog") || trigger.equals("onCfgChg")) {
        // Nothing is required
    } else { // on control action
        if (0 == getControlAction().length()) {
            ActionMessage err = new ActionMessage("alert.config.error.NoControlActionSelected");
            errs.add("condition[" + idx + "].controlAction", err);
            valid = false;
        }
        if (0 == getControlActionStatus().length()) {
            ActionMessage err = new ActionMessage("alert.config.error.NoControlActionStatusSelected");
            errs.add("condition[" + idx + "].controlActionStatus", err);
            valid = false;
        }
    }

    return valid;
}

From source file:org.hyperic.util.validator.common.CommonValidatorUtil.java

/**
 * Validates the principal (Username) field based on default regular
 * expression./*from  ww  w .  j a v  a2  s . co m*/
 *
 * @param    bean       The bean containing the field to validate.
 * @param    field       The Field property info from the mapping file.
 * @return   boolean      If the field contains valid data <code>true</code>
 *                       is returned, otherwise <code>false</code>.
*/
// note to-do: accept non-default regexp (as property arg?)
public static boolean validatePrincipal(Object bean, Field field) {
    boolean valid = false;
    // validate the length and characters.
    String userName = ValidatorUtils.getValueAsString(bean, field.getProperty());
    if ((userName != null) && (GenericValidator.matchRegexp(userName, USERNAME_VALID_REGEXP)))
        valid = true;
    return valid;
}

From source file:org.megatome.frame2.validator.CommonsFieldValidator.java

/**
 * Validate that a value matches a regular expression value. The regular
 * expression is declared in the validator rules file.
 * /*from   w ww .  j  a  va  2s.c om*/
 * @param value
 *            The value to validate
 * @param va
 *            The validator action
 * @param errors
 *            Errors object to populate
 * @param field
 *            The field to validate
 * @return True if the value matches the mask expression.
 */
public static boolean mask(String value, ValidatorAction va, Errors errors, Field field) {
    if (value == null) {
        return true;
    }
    String mask = field.getVarValue("mask"); //$NON-NLS-1$
    if (mask == null) {
        return true;
    }
    try {
        if (!GenericValidator.matchRegexp(value, mask)) {
            addError(va, errors, field);
            return false;
        }
        return true;
    } catch (Exception e) {
        LOGGER.info("mask = " + mask + " caused an exception:" + e); //$NON-NLS-1$ //$NON-NLS-2$
    }
    return true;
}

From source file:org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.java

/**
 * Fails if a field's value does not match the given mask.
 *///from   w  w  w.j  a v a2 s  .  c  om
public static boolean validateMask(CheckResultSourceInterface source, String propertyName, int levelOnFail,
        List<CheckResultInterface> remarks, String mask) {
    final String VALIDATOR_NAME = "matches";
    String value = null;

    value = ValidatorUtils.getValueAsString(source, propertyName);

    try {
        if (null == mask) {
            addGeneralRemark(source, propertyName, VALIDATOR_NAME, remarks, "errors.missingVar",
                    CheckResultInterface.TYPE_RESULT_ERROR);
            return false;
        }

        if (StringUtils.isNotBlank(value) && !GenericValidator.matchRegexp(value, mask)) {
            addFailureRemark(source, propertyName, VALIDATOR_NAME, remarks, levelOnFail);
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        addExceptionRemark(source, propertyName, VALIDATOR_NAME, remarks, e);
        return false;
    }
}

From source file:org.rhq.enterprise.gui.legacy.action.resource.common.monitor.alerts.config.condition.MeasurementConverterValidator.java

public boolean validate(ConditionBean bean, ActionErrors errors, int index) {
    if (bean.getMetricId() <= 0) {
        // user didn't select a metric
        ActionMessage err = new ActionMessage("alert.config.error.NoMetricSelected");
        errors.add("condition[" + index + "].metricId", err);
        return false;
    }/*from ww w . j av  a 2  s. com*/

    if (bean.getThresholdType().equals(TYPE_ABS)) {
        if (!GenericValidator.matchRegexp(bean.getAbsoluteValue(), DOUBLE_REGEX)) {
            ActionMessage err = new ActionMessage("errors.double", "AbsoluteValue");
            errors.add("condition[" + index + "].absoluteValue", err);
            return false;
        } else // double
        {
            // do nothing
        }
    } else if (bean.getThresholdType().equals(TYPE_PERC)) // percentage
    {
        if (!GenericValidator.matchRegexp(bean.getPercentage(), DOUBLE_REGEX)) {
            ActionMessage err = new ActionMessage("errors.double", "Percentage");
            errors.add("condition[" + index + "].percentage", err);
            return false;
        } else // double
        {
            // 0-100 range
            double percentage = NumberUtil.stringAsNumber(bean.getPercentage()).doubleValue();
            if (!GenericValidator.isInRange(percentage, 0d, 1000d)) {
                ActionMessage err = new ActionMessage("errors.range", String.valueOf(percentage),
                        String.valueOf(0d), String.valueOf(1000d));
                errors.add("condition[" + index + "].percentage", err);
                return false;
            }
        }

        if ((null == bean.getBaselineOption()) || (bean.getBaselineOption().length() == 0)) {
            ActionMessage err = new ActionMessage("alert.config.error.NoBaselineOptionSelected");
            errors.add("condition[" + index + "].baselineOption", err);
            return false;
        } else {
            // some sort of error handling here?
        }
    }

    return true;
}

From source file:org.sgrp.singer.validator.ArrayFieldChecks.java

/**
 * Checks for each value if it matches the regular expression in the field's mask attribute.
 *
 * @param bean The bean validation is being performed on.
 * @param va The <code>ValidatorAction</code> that is currently being
 * performed.//  w  ww.j a  v  a 2s .c  o m
 * @param field The <code>Field</code> object associated with the current
 * field being validated.
 * @param errors   The <code>ActionMessages</code> object to add errors to if
 * any validation errors occur.
 * @param request Current request object.
 * @return true if field matches mask, false otherwise.
 */
public static boolean validateMask(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        HttpServletRequest request) {

    String mask = field.getVarValue("mask");
    String[] value = null;
    if (isStringArray(bean)) {
        value = (String[]) bean;
    } else {
        value = new String[0];
    }

    try {
        for (int i = 0; i < value.length; i++) {
            if (!GenericValidator.isBlankOrNull(value[i]) && !GenericValidator.matchRegexp(value[i], mask)) {

                errors.add(field.getKey(), Resources.getActionMessage(request, va, field));

                return false;
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return true;
}