Example usage for org.apache.commons.lang3.math NumberUtils isParsable

List of usage examples for org.apache.commons.lang3.math NumberUtils isParsable

Introduction

In this page you can find the example usage for org.apache.commons.lang3.math NumberUtils isParsable.

Prototype

public static boolean isParsable(final String str) 

Source Link

Document

Checks whether the given String is a parsable number.

Parsable numbers include those Strings understood by Integer#parseInt(String) , Long#parseLong(String) , Float#parseFloat(String) or Double#parseDouble(String) .

Usage

From source file:org.apache.nifi.csv.CSVSchemaInference.java

private DataType getDataType(final String value) {
    if (value == null || value.isEmpty()) {
        return null;
    }/*  w w w  . j  ava 2 s  . com*/

    if (NumberUtils.isParsable(value)) {
        if (value.contains(".")) {
            try {
                final double doubleValue = Double.parseDouble(value);
                if (doubleValue > Float.MAX_VALUE || doubleValue < Float.MIN_VALUE) {
                    return RecordFieldType.DOUBLE.getDataType();
                }

                return RecordFieldType.FLOAT.getDataType();
            } catch (final NumberFormatException nfe) {
                return RecordFieldType.STRING.getDataType();
            }
        }

        try {
            final long longValue = Long.parseLong(value);
            if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) {
                return RecordFieldType.LONG.getDataType();
            }

            return RecordFieldType.INT.getDataType();
        } catch (final NumberFormatException nfe) {
            return RecordFieldType.STRING.getDataType();
        }
    }

    if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
        return RecordFieldType.BOOLEAN.getDataType();
    }

    final Optional<DataType> timeDataType = timeValueInference.getDataType(value);
    return timeDataType.orElse(RecordFieldType.STRING.getDataType());
}

From source file:org.apache.nifi.xml.inference.XmlSchemaInference.java

private DataType inferTextualDataType(final String text) {
    if (text == null || text.isEmpty()) {
        return null;
    }/*w ww. j ava2  s . c o  m*/

    if (NumberUtils.isParsable(text)) {
        if (text.contains(".")) {
            try {
                final double doubleValue = Double.parseDouble(text);
                if (doubleValue > Float.MAX_VALUE || doubleValue < Float.MIN_VALUE) {
                    return RecordFieldType.DOUBLE.getDataType();
                }

                return RecordFieldType.FLOAT.getDataType();
            } catch (final NumberFormatException nfe) {
                return RecordFieldType.STRING.getDataType();
            }
        }

        try {
            final long longValue = Long.parseLong(text);
            if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) {
                return RecordFieldType.LONG.getDataType();
            }

            return RecordFieldType.INT.getDataType();
        } catch (final NumberFormatException nfe) {
            return RecordFieldType.STRING.getDataType();
        }
    }

    if (text.equalsIgnoreCase("true") || text.equalsIgnoreCase("false")) {
        return RecordFieldType.BOOLEAN.getDataType();
    }

    final Optional<DataType> timeDataType = timeValueInference.getDataType(text);
    return timeDataType.orElse(RecordFieldType.STRING.getDataType());
}

From source file:org.opencb.opencga.storage.mongodb.variant.adaptors.VariantMongoDBAdaptor.java

/**
 * Accepts a list of filters separated with "," or ";" with the expression: {SOURCE}{OPERATION}{VALUE}.
 *
 * @param value         Value to parse/*  w w w. j  a v  a 2s.c  o m*/
 * @param builder       QueryBuilder
 * @param scoreParam    Score VariantQueryParam
 * @param defaultSource Default source value. If null, must be present in the filter. If not, must not be present.
 * @param allowDescriptionFilter Use string values as filters for the score description
 * @return QueryBuilder
 */
private QueryBuilder addScoreFilter(String value, QueryBuilder builder, VariantQueryParams scoreParam,
        final String defaultSource, boolean allowDescriptionFilter) {
    final List<String> list;
    QueryOperation operation = checkOperator(value);
    list = splitValue(value, operation);
    List<DBObject> dbObjects = new ArrayList<>();
    for (String elem : list) {
        String[] score = VariantDBAdaptorUtils.splitOperator(elem);
        String source;
        String op;
        String scoreValue;
        // No given score
        if (StringUtils.isEmpty(score[0])) {
            if (defaultSource == null) {
                logger.error("Bad score filter: " + elem);
                throw VariantQueryException.malformedParam(scoreParam, value);
            }
            source = defaultSource;
            op = score[1];
            scoreValue = score[2];
        } else {
            if (defaultSource != null) {
                logger.error("Bad score filter: " + elem);
                throw VariantQueryException.malformedParam(scoreParam, value);
            }
            source = score[0];
            op = score[1];
            scoreValue = score[2];
        }

        String key = DocumentToVariantAnnotationConverter.SCORE_FIELD_MAP.get(source);
        if (key == null) {
            // Unknown score
            throw VariantQueryException.malformedParam(scoreParam, value);
        }

        QueryBuilder scoreBuilder = new QueryBuilder();
        if (NumberUtils.isParsable(scoreValue)) {
            // Query by score
            key += '.' + DocumentToVariantAnnotationConverter.SCORE_SCORE_FIELD;
            addCompQueryFilter(key, scoreValue, scoreBuilder, op);
        } else if (allowDescriptionFilter) {
            // Query by description
            key += '.' + DocumentToVariantAnnotationConverter.SCORE_DESCRIPTION_FIELD;
            addStringCompQueryFilter(key, scoreValue, scoreBuilder);
        } else {
            throw VariantQueryException.malformedParam(scoreParam, value);
        }
        dbObjects.add(scoreBuilder.get());
    }

    if (!dbObjects.isEmpty()) {
        if (operation == null || operation == QueryOperation.AND) {
            builder.and(dbObjects.toArray(new DBObject[dbObjects.size()]));
        } else {
            builder.and(new BasicDBObject("$or", dbObjects));
        }
    }
    return builder;
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
public boolean canSubmit(Assignment a, String userId) {
    if (a == null)
        return false;
    // submissions are never allowed to non-electronic assignments
    if (a.getTypeOfSubmission() == Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
        return false;
    }// ww w  . j a v  a 2s .co  m

    // return false only if the user is not allowed to submit and not allowed to add to the assignment
    if (!allowAddSubmissionCheckGroups(a) && !allowAddAssignment(a.getContext()))
        return false;

    //If userId is not defined look it up
    if (userId == null) {
        userId = sessionManager.getCurrentSessionUserId();
    }

    try {
        // if user the user can access this assignment
        checkAssignmentAccessibleForUser(a, userId);

        // get user
        User u = userDirectoryService.getUser(userId);

        Instant currentTime = Instant.now();

        // return false if the assignment is draft or is not open yet
        Instant openTime = a.getOpenDate();
        if (a.getDraft() || openTime.isAfter(currentTime)) {
            return false;
        }

        // whether the current time is after the assignment close date inclusive
        boolean isBeforeAssignmentCloseDate = !currentTime.isAfter(a.getCloseDate());

        // get user's submission
        AssignmentSubmission submission = getSubmission(
                AssignmentReferenceReckoner.reckoner().assignment(a).reckon().getId(), u);

        if (submission != null) {
            // check for allow resubmission or not first
            // return true if resubmission is allowed and current time is before resubmission close time
            // get the resubmit settings from submission object first
            String allowResubmitNumString = submission.getProperties()
                    .get(AssignmentConstants.ALLOW_RESUBMIT_NUMBER);
            if (NumberUtils.isParsable(allowResubmitNumString) && submission.getSubmitted()
                    && submission.getDateSubmitted() != null) {
                String allowResubmitCloseTime = submission.getProperties()
                        .get(AssignmentConstants.ALLOW_RESUBMIT_CLOSETIME);
                try {
                    int allowResubmitNumber = Integer.parseInt(allowResubmitNumString);

                    Instant resubmitCloseTime;
                    if (NumberUtils.isParsable(allowResubmitCloseTime)) {
                        // see if a resubmission close time is set on submission level
                        resubmitCloseTime = Instant.ofEpochMilli(Long.parseLong(allowResubmitCloseTime));
                    } else {
                        // otherwise, use assignment close time as the resubmission close time
                        resubmitCloseTime = a.getCloseDate();
                    }
                    return (allowResubmitNumber > 0 || allowResubmitNumber == -1)
                            && !currentTime.isAfter(resubmitCloseTime);
                } catch (NumberFormatException e) {
                    log.warn("allowResubmitNumString = {}, allowResubmitCloseTime = {}", allowResubmitNumString,
                            allowResubmitCloseTime, e);
                }
            }

            if (isBeforeAssignmentCloseDate
                    && (submission.getDateSubmitted() == null || !submission.getSubmitted())) {
                // before the assignment close date
                // and if no date then a submission was never never submitted
                // or if there is a submitted date and its a not submitted then it is considered a draft
                return true;
            }
        } else {
            // there is no submission yet so only check if before assignment close date
            return isBeforeAssignmentCloseDate;
        }
    } catch (UserNotDefinedException e) {
        log.warn("The user {} could not be found while checking if they can submit to assignment {}, {}",
                userId, a.getId(), e.getMessage());
    } catch (PermissionException e) {
        log.warn("The user {} cannot submit to assignment {}, {}", userId, a.getId(), e.getMessage());
    }
    return false;
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject) {
    List<KeyValueProto> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
                    } catch (RuntimeException th) {
                        result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                                .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                    }//from ww  w .j  av  a2 s. c  o  m
                } else {
                    result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                            .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                }
            } else if (value.isBoolean()) {
                result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                        .setType(KeyValueType.BOOLEAN_V).setBoolV(value.getAsBoolean()).build());
            } else if (value.isNumber()) {
                result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

private static List<KvEntry> parseValues(JsonObject valuesObject) {
    List<KvEntry> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        parseNumericValue(result, valueEntry, value);
                    } catch (RuntimeException th) {
                        result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                    }/*w  ww  . j a v  a2  s . c om*/
                } else {
                    result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                }
            } else if (value.isBoolean()) {
                result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean()));
            } else if (value.isNumber()) {
                parseNumericValue(result, valueEntry, value);
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}