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

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

Introduction

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

Prototype

public static boolean isInt(String value) 

Source Link

Document

Checks if the value can safely be converted to a int primitive.

Usage

From source file:jp.terasoluna.fw.web.struts.form.FieldChecksEx.java

/**
 * wtB?[h?l`FbN?B//from ww w  .  j  av  a 2s.c om
 * 
 * ?Ap?A<code>BigDecimal</code> ^??
 * ??s\G?[pActionMessage???A<code>false</code> p?B
 * 
 * ???w???A?mF?s?B <code>validation.xml</code> 
 * <code>isAccordedInteger()</code>  <code>"true"</code> w??
 * ???`FbN?s?B `FbN???AG?[pActionMessage???Afalsep?B
 * 
 * ????w???A?mF?s?B
 * validation.xmlisAccordedScale"true"?? ???`FbN?s?B
 * 
 * <p>
 * G?[???AG?[????A wG?[?Xg?B G?[?bZ?[WtH?[}bg?A<code>validation-rules.xml</code>
 * L?q?B<br>
 * L?A??3?A??2?l??B
 * </p>
 * 
 * <h5>validation.xmlL?q</h5>
 * <code><pre>
 * &lt;form name=&quot;/sample&quot;&gt;
 *  ?E?E?E
 *  &lt;field property=&quot;escape&quot;
 *      depends=&quot;number&quot;&gt;
 *    &lt;arg0 key=&quot;sample.escape&quot;/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;integerLength&lt;/var-name&gt;
 *      &lt;var-value&gt;3&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;scale&lt;/var-name&gt;
 *      &lt;var-value&gt;2&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedInteger&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedScale&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  ?E?E?E
 * &lt;/form&gt;
 * </pre></code>
 * <h5>validation.xml?v&lt;var&gt;vf</h5>
 * <table border="1">
 * <tr>
 * <td><center><b><code>var-name</code></b></center></td>
 * <td><center><b><code>var-value</code></b></center></td>
 * <td><center><b>K?{?</b></center></td>
 * <td><center><b>Tv</b></center></td>
 * </tr>
 * <tr>
 * <td> <code>integerLength</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>?????A<code>isAccordedInteger</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>scale</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>??l???A<code>isAccordedScale</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedInteger</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedScale</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * </table>
 * 
 * @param bean
 *            ??IuWFNg
 * @param va
 *            StrutspValidatorAction
 * @param field
 *            tB?[hIuWFNg
 * @param errors
 *            ActionMessages ANVG?[
 * @param validator
 *            ValidatorCX^X
 * @param request
 *            HTTPNGXg
 * @return l? <code>true</code>
 */
public static boolean validateNumber(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {

    // beannull?AG?[?O?o?Atruep?B
    if (bean == null) {
        log.error("bean is null.");
        return true;
    }
    // ???
    String integerLength = field.getVarValue("integerLength");
    // ???
    String scaleStr = field.getVarValue("scale");
    // ???v`FbN
    String isAccordedInteger = field.getVarValue("isAccordedInteger");
    // ???v`FbN
    String isAccordedScale = field.getVarValue("isAccordedScale");

    String value = null;
    if (isString(bean)) {
        value = (String) bean;
    } else {
        value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }
    // ?lnull?Atruep
    if (GenericValidator.isBlankOrNull(value)) {
        return true;
    }
    char[] chars = value.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (!isHankaku(chars[i])) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }
    // ???w???A??`FbN?s
    if (GenericValidator.isInt(integerLength)) {
        try {
            BigDecimal bd = new BigDecimal(value);
            // ???l?o
            BigInteger bi = bd.toBigInteger().abs();
            // ???
            int length = bi.toString().length();
            // validation.xmlw?
            int checkLength = Integer.valueOf(integerLength).intValue();
            // ?I?[o?Afalsep
            if (length > checkLength) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
            // vw
            if (isAccordedInteger != null && "true".equals(isAccordedInteger)) {
                // ?sv?Afalsep
                if (length != checkLength) {
                    errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                    return false;
                }
            }
        } catch (NumberFormatException nfe) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }

    // ???w???A??`FbN?s
    if (GenericValidator.isInt(scaleStr)) {
        int scale = 0;
        int checkScale = 0;
        try {
            BigDecimal bd = new BigDecimal(value);
            scale = bd.scale();
            // validation.xmlw?
            checkScale = Integer.valueOf(scaleStr).intValue();
        } catch (NumberFormatException e) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // ?I?[o?Afalsep
        if (scale > checkScale) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // vw
        if (isAccordedScale != null && "true".equals(isAccordedScale)) {
            // ?sv?Afalsep
            if (scale != checkScale) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
        }
    }
    return true;
}

From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java

private void setPreparedStatmentForCurrentColumn(PreparedStatement ps, int index, CSVColumnState column,
        ProfileRecipientFields bean, ImportProfile importProfile, ValidatorResults validatorResults)
        throws SQLException {
    String value = Toolkit.getValueFromBean(bean, column.getColName());
    if (column.getType() == CSVColumnState.TYPE_NUMERIC && column.getColName().equals("gender")) {
        if (StringUtils.isEmpty(value) || value == null) {
            ps.setInt(index, 2);/*from  www  .j av a2  s .  c  om*/
        } else {
            if (GenericValidator.isInt(value) && Integer.valueOf(value) <= 5 && Integer.valueOf(value) >= 0) {
                ps.setInt(index, Integer.valueOf(value));
            } else {
                final Integer intValue = importProfile.getGenderMapping().get(value);
                ps.setInt(index, intValue);
            }
        }

    } else if (column.getType() == CSVColumnState.TYPE_CHAR) {
        if (value == null) {
            ps.setNull(index, Types.VARCHAR);
        } else {
            String columnName = column.getColName();
            if (columnName.equals("email")) {
                value = value.toLowerCase();
                if (validatorResults != null
                        && !ImportUtils.checkIsCurrentFieldValid(validatorResults, "email", "checkRange")) {
                    throw new ImportRecipientsToolongValueException(value);
                }
            } else if (importProfile.getKeyColumns().contains(columnName)
                    || (importProfile.getKeyColumns().isEmpty()
                            && columnName.equals(importProfile.getKeyColumn()))) {
                // range validation for keyColumn
                if (validatorResults != null
                        && !ImportUtils.checkIsCurrentFieldValid(validatorResults, columnName, "checkRange")) {
                    throw new ImportRecipientsToolongValueException(value);
                }
            }
            if (AgnUtils.isOracleDB()) {
                ps.setString(index, value);
            } else if (AgnUtils.isMySQLDB()) {
                if (column.isNullable() && value.isEmpty()) {
                    ps.setNull(index, Types.VARCHAR);
                } else {
                    ps.setString(index, value);
                }
            }

        }
    } else if (column.getType() == CSVColumnState.TYPE_NUMERIC) {
        if (StringUtils.isEmpty(value) || value == null) {
            ps.setNull(index, Types.NUMERIC);
        } else {
            ps.setDouble(index, Double.valueOf(value));
        }
    } else if (column.getType() == CSVColumnState.TYPE_DATE) {
        if (StringUtils.isEmpty(value) || value == null) {
            ps.setNull(index, Types.DATE);
        } else {
            Date date = ImportUtils.getDateAsString(value, importProfile.getDateFormat());

            ps.setTimestamp(index, new Timestamp(date.getTime()));
        }
    }
}

From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java

@Override
public void updateExistRecipients(final Collection<ProfileRecipientFields> recipientsForUpdate,
        final ImportProfile importProfile, final CSVColumnState[] columns, Integer adminId) {
    if (recipientsForUpdate.isEmpty()) {
        return;//from   w  w  w  . j  a v  a 2 s . c  o  m
    }

    final JdbcTemplate template = createJdbcTemplate();
    final ProfileRecipientFields[] recipientsBean = recipientsForUpdate
            .toArray(new ProfileRecipientFields[recipientsForUpdate.size()]);
    final String[] querys = new String[recipientsForUpdate.size()];
    for (int i = 0; i < querys.length; i++) {
        String query = "UPDATE  customer_" + importProfile.getCompanyId() + "_tbl SET ";
        if (recipientsBean[i].getMailtypeDefined().equals(ImportUtils.MAIL_TYPE_DEFINED))
            query = query + "mailtype=" + recipientsBean[i].getMailtype() + ", ";
        for (CSVColumnState column : columns) {
            if (column.getImportedColumn() && !column.getColName().equals("mailtype")) {
                String value = Toolkit.getValueFromBean(recipientsBean[i], column.getColName());

                // @todo: agn: value == null
                if (StringUtils.isEmpty(value)
                        && importProfile.getNullValuesAction() == NullValuesAction.OVERWRITE.getIntValue()
                        && !column.getColName().equals("gender")) {
                    query = query + column.getColName() + "=NULL, ";
                } else if (!StringUtils.isEmpty(value)) {
                    if (column.getColName().equals("gender")) {
                        if (StringUtils.isEmpty(value)) {
                            query = query + column.getColName() + "=2, ";
                        } else {
                            if (GenericValidator.isInt(value)) {
                                query = query + column.getColName() + "=" + value + ", ";
                            } else {
                                final Integer intValue = importProfile.getGenderMapping().get(value);
                                query = query + column.getColName() + "=" + intValue + ", ";
                            }
                        }
                    } else {
                        switch (column.getType()) {
                        case CSVColumnState.TYPE_CHAR:
                            if (column.getColName().equals("email")) {
                                value = value.toLowerCase();
                            }
                            if (AgnUtils.isOracleDB()) {
                                query = query + column.getColName() + "='" + value.replace("'", "''") + "', ";
                            } else if (AgnUtils.isMySQLDB()) {
                                query = query + column.getColName() + "='"
                                        + value.replace("\\", "\\\\").replace("'", "\\'") + "', ";
                            }
                            break;
                        case CSVColumnState.TYPE_NUMERIC:
                            query = query + column.getColName() + "=" + value + ", ";
                            break;
                        case CSVColumnState.TYPE_DATE:
                            if (StringUtils.isEmpty(value) || value == null) {
                                query = query + column.getColName() + "=null, ";
                            } else {
                                final int format = importProfile.getDateFormat();
                                Date date = ImportUtils.getDateAsString(value, format);
                                if (AgnUtils.isMySQLDB()) {
                                    String temTimestamp = new Timestamp(date.getTime()).toString();
                                    query = query + column.getColName() + "='"
                                            + temTimestamp.substring(0, temTimestamp.indexOf(" ")) + "', ";
                                }
                                if (AgnUtils.isOracleDB()) {
                                    final String dateAsFormatedString = DB_DATE_FORMAT.format(date);
                                    query = query + column.getColName() + "=to_date('" + dateAsFormatedString
                                            + "', 'dd.MM.YYYY HH24:MI:SS'), ";
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }

        query = query.substring(0, query.length() - 2);
        String value = Toolkit.getValueFromBean(recipientsBean[i], importProfile.getKeyColumn());
        value = value.toLowerCase();
        if (!importProfile.getUpdateAllDuplicates()) {
            query = query + " WHERE customer_id = " + recipientsBean[i].getUpdatedIds().get(0);
        } else {
            query = query + " WHERE customer_id IN(";
            final int countUpdatedRecipients = recipientsBean[i].getUpdatedIds().size();
            for (int index = 0; index < countUpdatedRecipients; index++) {
                query = query + recipientsBean[i].getUpdatedIds().get(index)
                        + ((index + 1) != countUpdatedRecipients ? "," : "");
            }
            query = query + ")";

        }

        if (logger.isInfoEnabled()) {
            logger.info("Import ID: " + importProfile.getImportId() + " Updating recipient in recipient-table: "
                    + Toolkit.getValueFromBean(recipientsBean[i], importProfile.getKeyColumn()));
        }

        querys[i] = query;
    }
    template.batchUpdate(querys);
}

From source file:org.agnitas.service.csv.validator.FieldsValidator.java

private static boolean genderMappingValidation(String value, ImportProfile profile, Integer maxGenderValue) {
    final Map<String, Integer> genderMap = profile.getGenderMapping();
    return GenericValidator.isInt(value) && Integer.valueOf(value) <= maxGenderValue
            && Integer.valueOf(value) >= 0 || genderMap.keySet().contains(value);
}

From source file:org.agnitas.service.csv.validator.FieldsValidator.java

/**
 * Checks if the field can be successfully converted to a <code>int</code>.
 *
 * @param value The value validation is being performed on.
 * @return boolean If the field can be successfully converted
 *         to a <code>int</code> <code>true</code> is returned.
 *         Otherwise <code>false</code>.
 *///w  ww .j  av  a  2 s .  c  o  m
public static boolean validateInt(Object bean, Field field, Validator validator) {
    String value = getValueAsString(bean, field);
    final ImportProfile profile = (ImportProfile) validator
            .getParameterValue("org.agnitas.beans.ImportProfile");
    final ColumnMapping currentColumn = getColumnMappingForCurentField(field, profile);
    if (currentColumn != null && currentColumn.getMandatory()) {
        return !GenericValidator.isBlankOrNull(value) && GenericValidator.isInt(value);
    } else {
        return currentColumn == null || GenericValidator.isInt(value);
    }
}

From source file:org.agnitas.service.csv.validator.FieldsValidator.java

/**
* Checks the mailtype value//  www . j  a v a 2 s  .c o  m
*
* @param mailtype the mailtype value
* @return true if mailtype is a number from 0 to 2 or mailtype is one
* of the strings: "txt", "text", "html" (the letter case is not important). False otherwise
*/
private static boolean isValidMailTypeValue(String mailtype) {
    if (GenericValidator.isInt(mailtype)) {
        int mailTypeInt = Integer.valueOf(mailtype);
        return mailTypeInt == Recipient.MAILTYPE_TEXT || mailTypeInt == Recipient.MAILTYPE_HTML
                || mailTypeInt == Recipient.MAILTYPE_HTML_OFFLINE || mailTypeInt == Recipient.MAILTYPE_MHTML;
    } else {
        String mailtypeLower = mailtype.toLowerCase();
        return (mailtypeLower.equals(ImportUtils.MAIL_TYPE_HTML)
                || mailtypeLower.equals(ImportUtils.MAIL_TYPE_TEXT)
                || mailtypeLower.equals(ImportUtils.MAIL_TYPE_TEXT_ALT));
    }
}

From source file:org.apache.commons.validator.TestValidator.java

/**
 * Checks if the field can be successfully converted to a <code>int</code>.
 *
 * @param    value       The value validation is being performed on.
 * @return   boolean      If the field can be successfully converted 
 *                           to a <code>int</code> <code>true</code> is returned.  
 *                           Otherwise <code>false</code>.
 *///from  www . ja  va  2s .  c om
public static boolean validateInt(Object bean, Field field) {
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

    return GenericValidator.isInt(value);
}

From source file:org.mule.transport.comm.CommMessageReceiver.java

protected void doConnect() throws ConnectException {
    disposing.set(false);//from  w w  w. jav a2 s .  c om
    URI uri = endpoint.getEndpointURI().getUri();

    try {
        int baudrate = 9600;
        int databits = 8;
        int stopbits = 1;
        int parity = 0;
        int delay = 150;
        String host = "";

        if (GenericValidator.isInt((String) endpoint.getProperties().get("baudrate"))) {
            baudrate = Integer.valueOf((String) endpoint.getProperties().get("baudrate"));
        }
        if (GenericValidator.isInt((String) endpoint.getProperties().get("databits"))) {
            databits = Integer.valueOf((String) endpoint.getProperties().get("databits"));
        }
        if (GenericValidator.isInt((String) endpoint.getProperties().get("stopbits"))) {
            stopbits = Integer.valueOf((String) endpoint.getProperties().get("stopbits"));
        }
        if (GenericValidator.isInt((String) endpoint.getProperties().get("parity"))) {
            parity = Integer.valueOf((String) endpoint.getProperties().get("parity"));
        }
        host = uri.getHost();

        commPort = ((CommConnector) connector).getCommPort(host, baudrate, databits, stopbits, parity, delay);
    } catch (Exception e) {
        throw new org.mule.transport.ConnectException(CommMessages.failedToBindToUri(uri), e, this);
    }

    try {
        getWorkManager().scheduleWork(this, WorkManager.INDEFINITE, null, connector);
    } catch (WorkException e) {
        throw new ConnectException(CoreMessages.failedToScheduleWork(), e, this);
    }
}

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

private boolean validatePositive(String field, String fieldName, ActionErrors errs) {
    if (GenericValidator.isBlankOrNull(field)) {
        errs.add(fieldName, new ActionMessage("alert.config.error.DampeningFieldRequired"));
        return false;
    }/* ww  w.j  ava2 s.  co m*/

    if ((GenericValidator.isInt(field) == false) || (Integer.parseInt(field) < 1)) {
        errs.add(fieldName, new ActionMessage("alert.config.error.InvalidDampeningField"));
        return false;
    }

    return true;
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.EctValidation.java

public boolean isInteger(String inputValue) {

    boolean validation = true;
    org.apache.commons.validator.GenericValidator gValidator = new org.apache.commons.validator.GenericValidator();

    if (!GenericValidator.isInt(inputValue)) {
        validation = false;/*w w  w. j  a v  a2 s  .  c o  m*/
    }

    return validation;
}