Example usage for org.apache.commons.lang StringUtils isNumeric

List of usage examples for org.apache.commons.lang StringUtils isNumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils isNumeric.

Prototype

public static boolean isNumeric(String str) 

Source Link

Document

Checks if the String contains only unicode digits.

Usage

From source file:com.hmsinc.epicenter.webapp.remoting.GeographyService.java

/**
 * Automagically completes a Geography name.
 * /*from   ww w.  j  a  va  2  s  .  co m*/
 * If entity is null, the current user's visible region is used as bounds.
 * 
 * @param query
 * @return
 */
@Secured("ROLE_USER")
@Transactional(readOnly = true)
@RemoteMethod
public Collection<GeographyDTO> autocompleteGeography(final Long orgId, String query) {

    logger.debug(query);

    Organization entity = null;
    if (orgId != null) {
        entity = permissionRepository.load(orgId, Organization.class);
        Validate.notNull(entity, "Invalid organization id: " + orgId);
        SpatialSecurity.checkPermission(getPrincipal(), entity);
    }

    final Set<Geography> geolist = new LinkedHashSet<Geography>();

    if (query.equals("ALL")) {

        geolist.addAll(getVisibleRegions(entity));

    } else {

        final String q = StringUtils.trimToNull(StringUtils.trimToEmpty(query).replaceAll(",+$", ""));

        if (q != null) {

            if (q.matches("^\\w\\w$")) {

                // match single state by abbreviatation
                final State state = geographyRepository.getStateByAbbreviation(q);
                if (state != null) {
                    geolist.add(state);
                }
            } else if (q.matches("^\\w\\w,.*")) {

                // match something starting with state abbreviation
                final String[] fragments = q.split(",");
                final State state = geographyRepository.getStateByAbbreviation(fragments[0]);
                if (state != null) {
                    if (fragments.length > 1 && StringUtils.trimToNull(fragments[1]) != null) {
                        geolist.addAll(getGeographiesInState(state, fragments[1]));
                    } else {
                        geolist.add(state);
                    }
                }
            } else if (q.matches("^\\w.*,\\s*\\w\\w$")) {

                // match something comma state abbreviation
                final String[] fragments = q.split(",");
                final String first = StringUtils.trimToNull(fragments[0]);
                if (first != null && fragments.length > 1) {
                    final String second = StringUtils.trimToNull(fragments[1]);
                    if (second != null) {
                        final State state = geographyRepository.getStateByAbbreviation(second);
                        if (state != null) {
                            geolist.addAll(getGeographiesInState(state, first));
                        }
                    }
                }

            } else if (q.matches("^\\w\\w\\w.*,\\s*\\w\\w\\w.*")) {

                // match something comma something, each part being > 2
                // characters
                final String[] fragments = q.split(",");
                final String first = StringUtils.trimToNull(fragments[0]);
                if (first != null && fragments.length > 1) {
                    final String second = StringUtils.trimToNull(fragments[1]);
                    if (second != null) {

                        String other = null;
                        State state = null;

                        // Find out which one is a state
                        State s = geographyRepository.getGeography(first, State.class);
                        if (s != null) {
                            state = s;
                            other = second;
                        } else {
                            s = geographyRepository.getGeography(second, State.class);
                            if (s != null) {
                                state = s;
                                other = first;
                            }
                        }

                        if (other != null && state != null) {
                            geolist.addAll(getGeographiesInState(state, other));
                        }
                    }
                }
            } else {

                // Match anything
                final List<Geography> g = new ArrayList<Geography>();

                // Search region, state, county, zipcode
                if (StringUtils.isNumeric(q)) {
                    g.addAll(geographyRepository.searchGeographies(q, Zipcode.class));
                } else {
                    g.addAll(geographyRepository.searchGeographies(q, Region.class));
                    if (g.size() != 1) {
                        final List<State> states = geographyRepository.searchGeographies(q, State.class);
                        if (states.size() == 1) {
                            g.clear();
                        }
                        g.addAll(states);
                    }
                    if (g.size() != 1) {
                        g.addAll(geographyRepository.searchGeographies(stripCountyFromQuery(q), County.class));
                    }
                }

                geolist.addAll(g);
            }

            // If we have a single match, find the objects contained inside
            // it.
            if (geolist.size() == 1) {
                geolist.addAll(getContainedGeographies(geolist.iterator().next()));
            }

            if (entity == null) {
                for (Organization org : getPrincipal().getOrganizations()) {
                    geolist.addAll(getVisibleRegions(org));
                }
            } else {
                geolist.addAll(getVisibleRegions(entity));
            }
        }

    }

    // Filter the list to the user's permissions
    // TODO: Unwind the collection and drill down if limited visibility.
    return entity == null ? filterSpatialCollection(getPrincipal(), geolist, true)
            : filterSpatialCollection(entity, geolist, true);
}

From source file:fr.paris.lutece.plugins.appointment.modules.resource.web.workflow.SetAppointmentResourceTaskComponent.java

/**
 * {@inheritDoc}/*from   www .  j a  va  2 s.co  m*/
 */
@Override
public String doSaveConfig(HttpServletRequest request, Locale locale, ITask task) {
    boolean bRefresh = Boolean.parseBoolean(request.getParameter(PARAMETER_REFRESH_APPOINTMENT_FORM));

    if (bRefresh) {
        String strIdAppointmentForm = request.getParameter(PARAMETER_ID_APPOINTMENT_FORM);

        return getUrlModifyTask(request, task.getId(), strIdAppointmentForm);
    }

    String strResourceType = request.getParameter(PARAMETER_ID_FORM_RESOURCE_TYPE);

    if (StringUtils.isEmpty(strResourceType) || !StringUtils.isNumeric(strResourceType)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_NO_RESOURCE_TYPE, AdminMessage.TYPE_STOP);
    }

    TaskSetAppointmentResourceConfig config = _taskSetAppointmentResourceConfigService
            .findByPrimaryKey(task.getId());
    boolean bCreate = false;

    if (config == null) {
        bCreate = true;
        config = new TaskSetAppointmentResourceConfig();
        config.setIdTask(task.getId());
    }

    boolean bIsMandatory = request.getParameter(PARAMETER_IS_MANDATORY) != null;
    config.setIsMandatory(bIsMandatory);

    config.setIdFormResourceType(Integer.parseInt(strResourceType));

    if (bCreate) {
        _taskSetAppointmentResourceConfigService.create(config);
    } else {
        _taskSetAppointmentResourceConfigService.update(config);
    }

    return null;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java

public int readFile(BufferedReader csvReader, DataTable dataTable, PrintWriter finalOut) throws IOException {

    List<DataVariable> variableList = new ArrayList<>();
    CSVParser parser = new CSVParser(csvReader, inFormat.withHeader());
    Map<String, Integer> headers = parser.getHeaderMap();

    int i = 0;/*from   w  w w.j  a  v a 2s . com*/
    for (String varName : headers.keySet()) {
        if (varName == null || varName.isEmpty()) {
            // TODO:
            // Add a sensible variable name validation algorithm.
            // -- L.A. 4.0 alpha 1
            throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.invalidHeader"));
        }

        DataVariable dv = new DataVariable();
        dv.setName(varName);
        dv.setLabel(varName);
        dv.setInvalidRanges(new ArrayList<>());
        dv.setSummaryStatistics(new ArrayList<>());
        dv.setUnf("UNF:6:NOTCALCULATED");
        dv.setCategories(new ArrayList<>());
        variableList.add(dv);

        dv.setTypeCharacter();
        dv.setIntervalDiscrete();
        dv.setFileOrder(i);
        dv.setDataTable(dataTable);
        i++;
    }

    dataTable.setVarQuantity((long) variableList.size());
    dataTable.setDataVariables(variableList);

    boolean[] isNumericVariable = new boolean[headers.size()];
    boolean[] isIntegerVariable = new boolean[headers.size()];
    boolean[] isTimeVariable = new boolean[headers.size()];
    boolean[] isDateVariable = new boolean[headers.size()];

    for (i = 0; i < headers.size(); i++) {
        // OK, let's assume that every variable is numeric;
        // but we'll go through the file and examine every value; the
        // moment we find a value that's not a legit numeric one, we'll
        // assume that it is in fact a String.
        isNumericVariable[i] = true;
        isIntegerVariable[i] = true;
        isDateVariable[i] = true;
        isTimeVariable[i] = true;
    }

    // First, "learning" pass.
    // (we'll save the incoming stream in another temp file:)
    SimpleDateFormat[] selectedDateTimeFormat = new SimpleDateFormat[headers.size()];
    SimpleDateFormat[] selectedDateFormat = new SimpleDateFormat[headers.size()];

    File firstPassTempFile = File.createTempFile("firstpass-", ".csv");

    try (CSVPrinter csvFilePrinter = new CSVPrinter(
            // TODO allow other parsers of tabular data to use this parser by changin inFormat
            new FileWriter(firstPassTempFile.getAbsolutePath()), inFormat)) {
        //Write  headers
        csvFilePrinter.printRecord(headers.keySet());
        for (CSVRecord record : parser.getRecords()) {
            // Checks if #records = #columns in header
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                isIntegerVariable[i] = isIntegerVariable[i] && varString != null
                        && (varString.isEmpty() || varString.equals("null")
                                || (firstNumCharSet.contains(varString.charAt(0))
                                        && StringUtils.isNumeric(varString.substring(1))));
                if (isNumericVariable[i]) {
                    // If variable might be "numeric" test to see if this value is a parsable number:
                    if (varString != null && !varString.isEmpty()) {

                        boolean isNumeric = false;
                        boolean isInteger = false;

                        if (varString.equalsIgnoreCase("NaN") || varString.equalsIgnoreCase("NA")
                                || varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")
                                || varString.equalsIgnoreCase("-Inf") || varString.equalsIgnoreCase("null")) {
                            continue;
                        } else {
                            try {
                                Double testDoubleValue = new Double(varString);
                                continue;
                            } catch (NumberFormatException ex) {
                                // the token failed to parse as a double
                                // so the column is a string variable.
                            }
                        }
                        isNumericVariable[i] = false;
                    }
                }

                // If this is not a numeric column, see if it is a date collumn
                // by parsing the cell as a date or date-time value:
                if (!isNumericVariable[i]) {

                    Date dateResult = null;

                    if (isTimeVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isTime = false;

                            if (selectedDateTimeFormat[i] != null) {
                                ParsePosition pos = new ParsePosition(0);
                                dateResult = selectedDateTimeFormat[i].parse(varString, pos);

                                if (dateResult != null && pos.getIndex() == varString.length()) {
                                    // OK, successfully parsed a value!
                                    isTime = true;
                                }
                            } else {
                                for (SimpleDateFormat format : TIME_FORMATS) {
                                    ParsePosition pos = new ParsePosition(0);
                                    dateResult = format.parse(varString, pos);
                                    if (dateResult != null && pos.getIndex() == varString.length()) {
                                        // OK, successfully parsed a value!
                                        isTime = true;
                                        selectedDateTimeFormat[i] = format;
                                        break;
                                    }
                                }
                            }
                            if (!isTime) {
                                isTimeVariable[i] = false;
                                // if the token didn't parse as a time value,
                                // we will still try to parse it as a date, below.
                                // unless this column is NOT a date.
                            } else {
                                // And if it is a time value, we are going to assume it's
                                // NOT a date.
                                isDateVariable[i] = false;
                            }
                        }
                    }

                    if (isDateVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isDate = false;

                            // TODO:
                            // Strictly speaking, we should be doing the same thing
                            // here as with the time formats above; select the
                            // first one that works, then insist that all the
                            // other values in this column match it... but we
                            // only have one, as of now, so it should be ok.
                            // -- L.A. 4.0 beta
                            for (SimpleDateFormat format : DATE_FORMATS) {
                                // Strict parsing - it will throw an
                                // exception if it doesn't parse!
                                format.setLenient(false);
                                try {
                                    format.parse(varString);
                                    isDate = true;
                                    selectedDateFormat[i] = format;
                                    break;
                                } catch (ParseException ex) {
                                    //Do nothing
                                }
                            }
                            isDateVariable[i] = isDate;
                        }
                    }
                }
            }

            csvFilePrinter.printRecord(record);
        }
    }
    dataTable.setCaseQuantity(parser.getRecordNumber());
    parser.close();
    csvReader.close();

    // Re-type the variables that we've determined are numerics:
    for (i = 0; i < headers.size(); i++) {
        if (isNumericVariable[i]) {
            dataTable.getDataVariables().get(i).setTypeNumeric();

            if (isIntegerVariable[i]) {
                dataTable.getDataVariables().get(i).setIntervalDiscrete();
            } else {
                dataTable.getDataVariables().get(i).setIntervalContinuous();
            }
        } else if (isDateVariable[i] && selectedDateFormat[i] != null) {
            // Dates are still Strings, i.e., they are "character" and "discrete";
            // But we add special format values for them:
            dataTable.getDataVariables().get(i).setFormat(DATE_FORMATS[0].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("date");
        } else if (isTimeVariable[i] && selectedDateTimeFormat[i] != null) {
            // Same for time values:
            dataTable.getDataVariables().get(i).setFormat(selectedDateTimeFormat[i].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("time");
        }
    }
    // Second, final pass.
    try (BufferedReader secondPassReader = new BufferedReader(new FileReader(firstPassTempFile))) {
        parser = new CSVParser(secondPassReader, inFormat.withHeader());
        String[] caseRow = new String[headers.size()];

        for (CSVRecord record : parser) {
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                if (isNumericVariable[i]) {
                    if (varString == null || varString.isEmpty() || varString.equalsIgnoreCase("NA")) {
                        // Missing value - represented as an empty string in
                        // the final tab file
                        caseRow[i] = "";
                    } else if (varString.equalsIgnoreCase("NaN")) {
                        // "Not a Number" special value:
                        caseRow[i] = "NaN";
                    } else if (varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")) {
                        // Positive infinity:
                        caseRow[i] = "Inf";
                    } else if (varString.equalsIgnoreCase("-Inf")) {
                        // Negative infinity:
                        caseRow[i] = "-Inf";
                    } else if (varString.equalsIgnoreCase("null")) {
                        // By request from Gus - "NULL" is recognized as a
                        // numeric zero:
                        caseRow[i] = isIntegerVariable[i] ? "0" : "0.0";
                    } else {
                        /* No re-formatting is done on any other numeric values.
                         * We'll save them as they were, for archival purposes.
                         * The alternative solution - formatting in sci. notation
                         * is commented-out below.
                         */
                        caseRow[i] = varString;
                        /*
                         if (isIntegerVariable[i]) {
                        try {
                            Integer testIntegerValue = new Integer(varString);
                            caseRow[i] = testIntegerValue.toString();
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as an integer in the first pass! (?)");
                        }
                        } else {
                        try {
                            Double testDoubleValue = new Double(varString);
                            if (testDoubleValue.equals(0.0)) {
                                caseRow[i] = "0.0";
                            } else {
                                                                    // One possible implementation:
                                //
                                // Round our fractional values to 15 digits
                                // (minimum number of digits of precision guaranteed by
                                // type Double) and format the resulting representations
                                // in a IEEE 754-like "scientific notation" - for ex.,
                                // 753.24 will be encoded as 7.5324e2
                                BigDecimal testBigDecimal = new BigDecimal(varString, doubleMathContext);
                                caseRow[i] = String.format(FORMAT_IEEE754, testBigDecimal);
                                
                                // Strip meaningless zeros and extra + signs:
                                caseRow[i] = caseRow[i].replaceFirst("00*e", "e");
                                caseRow[i] = caseRow[i].replaceFirst("\\.e", ".0e");
                                caseRow[i] = caseRow[i].replaceFirst("e\\+00", "");
                                caseRow[i] = caseRow[i].replaceFirst("^\\+", "");
                            }
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as numeric in the first pass! (?)");
                        }
                        }
                         */
                    }
                } else if (isTimeVariable[i] || isDateVariable[i]) {
                    // Time and Dates are stored NOT quoted (don't ask).
                    if (varString != null) {
                        // Dealing with quotes:
                        // remove the leading and trailing quotes, if present:
                        varString = varString.replaceFirst("^\"*", "");
                        varString = varString.replaceFirst("\"*$", "");
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "";
                    }
                } else {
                    // Treat as a String:
                    // Strings are stored in tab files quoted;
                    // Missing values are stored as an empty string
                    // between two tabs (or one tab and the new line);
                    // Empty strings stored as "" (quoted empty string).
                    // For the purposes  of this CSV ingest reader, we are going
                    // to assume that all the empty strings in the file are
                    // indeed empty strings, and NOT missing values:
                    if (varString != null) {
                        // escape the quotes, newlines, and tabs:
                        varString = varString.replace("\"", "\\\"");
                        varString = varString.replace("\n", "\\n");
                        varString = varString.replace("\t", "\\t");
                        // final pair of quotes:
                        varString = "\"" + varString + "\"";
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "\"\"";
                    }
                }
            }
            finalOut.println(StringUtils.join(caseRow, "\t"));
        }
    }
    long linecount = parser.getRecordNumber();
    finalOut.close();
    parser.close();
    dbglog.fine("Tmp File: " + firstPassTempFile);
    // Firstpass file is deleted to prevent tmp from filling up.
    firstPassTempFile.delete();
    if (dataTable.getCaseQuantity().intValue() != linecount) {
        List<String> args = Arrays
                .asList(new String[] { "" + dataTable.getCaseQuantity().intValue(), "" + linecount });
        throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.line_mismatch", args));
    }
    return (int) linecount;
}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString/*from  w w  w.j  a  v  a  2  s.c  om*/
 * @param q
 */
public static void setQueryParameters(String queryString, HashMap<String, String> paramsMap, Query q) {
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);

        if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    if (paramName.equalsIgnoreCase("firstResult")) {
                        q.setFirstResult(Integer.parseInt((String) paramValue));
                    } else if (paramName.equalsIgnoreCase("maxResult")) {
                        q.setMaxResults(Integer.parseInt((String) paramValue));
                    } else {
                        q.setParameter(paramName, paramValue);
                    }
                    break;
                }
            }

        }
    }
}

From source file:fr.paris.lutece.plugins.workflow.modules.mappings.web.CodeMappingJspBean.java

/**
 * Get modify a code mapping/*from   ww  w . j  ava 2  s.co  m*/
 * @param request the HTTP request
 * @return the HTML code
 */
public String getModifyCodeMapping(HttpServletRequest request) {
    setPageTitleProperty(PROPERTY_CREATE_MAPPING_PAGE_TITLE);

    String strIdCode = request.getParameter(PARAMETER_ID_CODE);

    if (StringUtils.isNotBlank(strIdCode) && StringUtils.isNumeric(strIdCode)) {
        int nIdCode = Integer.parseInt(strIdCode);
        ICodeMapping codeMapping = _codeMappingService.getCodeMapping(nIdCode);

        if (codeMapping != null) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put(MARK_CODE_MAPPING, codeMapping);
            model.put(MARK_LOCALE, getLocale());

            IMappingTypeComponent mappingTypeComponent = _codeMappingFactory
                    .getMappingTypeComponent(codeMapping.getMappingType().getKey());

            if (mappingTypeComponent != null) {
                model.put(MARK_REFERENCE_CODE_FORM,
                        mappingTypeComponent.getModifyCodeMappingHtml(codeMapping, request, getLocale()));
            } else {
                AppLogService.error("CodeMappingJspBean - MappingTypeComponent is null for key '"
                        + codeMapping.getMappingType().getKey() + "'");

                String strErrorMessage = I18nService.getLocalizedString(
                        MESSAGE_ERROR_MAPPING_TYPE_COMPONENT_NOT_FOUND, request.getLocale());

                return getError(request, strErrorMessage);
            }

            HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MODIFY_CODE_MAPPING, getLocale(),
                    model);

            return getAdminPage(template.getHtml());
        }

        AppLogService.debug("CodeMappingJspBean - CodeMapping is null for id code '" + strIdCode + "'");

        String strErrorMessage = I18nService.getLocalizedString(MESSAGE_ERROR_CODE_MAPPING_NOT_FOUND,
                request.getLocale());

        return getError(request, strErrorMessage);
    }

    String strErrorMessage = I18nService.getLocalizedString(Messages.MANDATORY_FIELDS, request.getLocale());

    return getError(request, strErrorMessage);
}

From source file:com.egt.core.util.STP.java

public static Object getObjeto(String string) {
    Object objeto = null;//from  w  w w  .jav a 2 s. c om
    String cadena = StringUtils.trimToNull(string);
    if (cadena == null) {
        return null;
    }
    if (StringUtils.isNumeric(cadena)) {
        objeto = getObjeto(cadena, EnumTipoDatoPar.ENTERO);
    }
    if (objeto == null && StringUtils.isNumeric(cadena)) {
        objeto = getObjeto(cadena, EnumTipoDatoPar.ENTERO_GRANDE);
    }
    if (objeto == null && cadena.startsWith(Global.PREFIJO_STRING_ID_RECURSO)) {
        String substr = cadena.substring(1);
        if (StringUtils.isNumeric(substr)) {
            objeto = getObjeto(substr, EnumTipoDatoPar.ENTERO_GRANDE);
        }
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, EnumTipoDatoPar.NUMERICO);
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, EnumTipoDatoPar.FECHA_HORA);
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, EnumTipoDatoPar.ALFANUMERICO);
    }
    return objeto;
}

From source file:ips1ap101.lib.core.util.STP.java

public static Object getObjeto(String string) {
    Object objeto = null;/*from www .  j  a v a2 s  .c  o  m*/
    String cadena = StringUtils.trimToNull(string);
    if (cadena == null) {
        return null;
    }
    if (StringUtils.isNumeric(cadena)) {
        objeto = getObjeto(cadena, TipoDatoParEnumeration.ENTERO);
    }
    if (objeto == null && StringUtils.isNumeric(cadena)) {
        objeto = getObjeto(cadena, TipoDatoParEnumeration.ENTERO_GRANDE);
    }
    if (objeto == null && cadena.startsWith(Global.PREFIJO_STRING_ID_RECURSO)) {
        String substr = cadena.substring(1);
        if (StringUtils.isNumeric(substr)) {
            objeto = getObjeto(substr, TipoDatoParEnumeration.ENTERO_GRANDE);
        }
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, TipoDatoParEnumeration.NUMERICO);
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, TipoDatoParEnumeration.FECHA_HORA);
    }
    if (objeto == null) {
        objeto = getObjeto(cadena, TipoDatoParEnumeration.ALFANUMERICO);
    }
    return objeto;
}

From source file:br.com.nordestefomento.jrimum.bopepo.exemplo.CampoLivreSicredi.java

InnerCooperativaDeCredito loadCooperativaDeCredito(Agencia agencia) {

    InnerCooperativaDeCredito cooperativa = null;

    if (isNotNull(agencia.getCodigo(), "Nmero da Agncia Sicredi")) {
        if (agencia.getCodigo() > 0) {
            if (String.valueOf(agencia.getCodigo()).length() <= 4) {

                cooperativa = new InnerCooperativaDeCredito();

                cooperativa.codigo = "" + agencia.getCodigo();

            } else
                new IllegalArgumentException(
                        "Nmero da Agncia Sicredi deve conter no mximo 4 dgitos (SEM O DIGITO VERIFICADOR) e no: "
                                + agencia.getCodigo());
        } else/*  w  ww . ja  v a2s  . c  om*/
            new IllegalArgumentException(
                    "Nmero da Agncia Sicredi com valor invlido: " + agencia.getCodigo());
    }

    if (isNotNull(agencia.getDigitoVerificador(), "Dgito da Agncia Sicredi")) {
        if (StringUtils.isNumeric(agencia.getDigitoVerificador())) {

            if (String.valueOf(agencia.getDigitoVerificador()).length() <= 2) {

                Integer digitoDaAgencia = Integer.valueOf(agencia.getDigitoVerificador());

                if (digitoDaAgencia >= 0)
                    cooperativa.posto = digitoDaAgencia.toString();
                else
                    new IllegalArgumentException(
                            "O dgito da Agncia Sicredi deve ser um nmero natural no-negativo, e no: ["
                                    + agencia.getDigitoVerificador() + "]");

            } else
                new IllegalArgumentException(
                        "Dgito da Agncia Sicredi deve conter no mximo 2 dgitos e no: "
                                + agencia.getCodigo());
        } else
            new IllegalArgumentException("O dgito da Agncia Sicredi deve ser numrico, e no: ["
                    + agencia.getDigitoVerificador() + "]");
    }

    return cooperativa;
}

From source file:fr.paris.lutece.plugins.crm.web.category.CategoryJspBean.java

/**
 * Returns the form to update info about a category
 * @param request The Http request/*from w  w w .  j av a 2s .c  om*/
 * @return The HTML form to update info
 */
public String getModifyCategory(HttpServletRequest request) {
    setPageTitleProperty(CRMConstants.PROPERTY_PAGE_TITLE_MODIFY_CATEGORY);

    String strUrl = StringUtils.EMPTY;
    String strCategoryId = request.getParameter(CRMConstants.PARAMETER_CATEGORY_ID_CATEGORY);

    if (StringUtils.isNotBlank(strCategoryId) && StringUtils.isNumeric(strCategoryId)) {
        int nId = Integer.parseInt(strCategoryId);
        Category category = _categoryService.findByPrimaryKey(nId);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put(CRMConstants.MARK_CATEGORY, category);

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MODIFY_CATEGORY, getLocale(), model);

        strUrl = getAdminPage(template.getHtml());
    } else {
        throw new AppException(I18nService.getLocalizedString(CRMConstants.MESSAGE_ERROR, request.getLocale()));
    }

    return strUrl;
}

From source file:edu.ku.brc.af.core.UsageTracker.java

/**
 * Gets the usage count of the given feature.  If the given feature name is not
 * present in the usage statistics, 0 is returned.
 * /*from w  w  w.ja  v  a  2  s .com*/
 * @param featureName the feature to retrieve the count for
 * @return the usage count
 */
public synchronized static int getUsageCount(final String featureName) {
    if (featureName.startsWith(USAGE_PREFIX)) {
        AppPreferences appPrefs = AppPreferences.getLocalPrefs();
        return appPrefs.getInt(featureName, 0);
    }

    String valStr = usageProps.getProperty(featureName);
    if (StringUtils.isNumeric(valStr)) {
        return Integer.parseInt(valStr);
    }
    return 0;
}