List of usage examples for java.math BigDecimal scale
int scale
To view the source code for java.math BigDecimal scale.
Click Source Link
From source file:org.apache.nifi.avro.AvroTypeUtil.java
@SuppressWarnings("unchecked") private static Object convertToAvroObject(final Object rawValue, final Schema fieldSchema, final String fieldName, final Charset charset) { if (rawValue == null) { return null; }/*w w w .j ava 2 s.c o m*/ switch (fieldSchema.getType()) { case INT: { final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType == null) { return DataTypeUtils.toInteger(rawValue, fieldName); } if (LOGICAL_TYPE_DATE.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); final Date date = DataTypeUtils.toDate(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); final Duration duration = Duration.between(new Date(0L).toInstant(), new Date(date.getTime()).toInstant()); final long days = duration.toDays(); return (int) days; } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); final Time time = DataTypeUtils.toTime(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); final Date date = new Date(time.getTime()); final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS), date.toInstant()); final long millisSinceMidnight = duration.toMillis(); return (int) millisSinceMidnight; } return DataTypeUtils.toInteger(rawValue, fieldName); } case LONG: { final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType == null) { return DataTypeUtils.toLong(rawValue, fieldName); } if (LOGICAL_TYPE_TIME_MICROS.equals(logicalType.getName())) { final long longValue = getLongFromTimestamp(rawValue, fieldSchema, fieldName); final Date date = new Date(longValue); final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS), date.toInstant()); return duration.toMillis() * 1000L; } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); Timestamp t = DataTypeUtils.toTimestamp(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); return getLongFromTimestamp(rawValue, fieldSchema, fieldName); } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalType.getName())) { return getLongFromTimestamp(rawValue, fieldSchema, fieldName) * 1000L; } return DataTypeUtils.toLong(rawValue, fieldName); } case BYTES: case FIXED: final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) { final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType; final BigDecimal rawDecimal; if (rawValue instanceof BigDecimal) { rawDecimal = (BigDecimal) rawValue; } else if (rawValue instanceof Double) { rawDecimal = BigDecimal.valueOf((Double) rawValue); } else if (rawValue instanceof String) { rawDecimal = new BigDecimal((String) rawValue); } else if (rawValue instanceof Integer) { rawDecimal = new BigDecimal((Integer) rawValue); } else if (rawValue instanceof Long) { rawDecimal = new BigDecimal((Long) rawValue); } else { throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a logical decimal"); } // If the desired scale is different than this value's coerce scale. final int desiredScale = decimalType.getScale(); final BigDecimal decimal = rawDecimal.scale() == desiredScale ? rawDecimal : rawDecimal.setScale(desiredScale, BigDecimal.ROUND_HALF_UP); return new Conversions.DecimalConversion().toBytes(decimal, fieldSchema, logicalType); } if (rawValue instanceof byte[]) { return ByteBuffer.wrap((byte[]) rawValue); } if (rawValue instanceof String) { return ByteBuffer.wrap(((String) rawValue).getBytes(charset)); } if (rawValue instanceof Object[]) { return AvroTypeUtil.convertByteArray((Object[]) rawValue); } else { throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a ByteBuffer"); } case MAP: if (rawValue instanceof Record) { final Record recordValue = (Record) rawValue; final Map<String, Object> map = new HashMap<>(); for (final RecordField recordField : recordValue.getSchema().getFields()) { final Object v = recordValue.getValue(recordField); if (v != null) { map.put(recordField.getFieldName(), v); } } return map; } else if (rawValue instanceof Map) { final Map<String, Object> objectMap = (Map<String, Object>) rawValue; final Map<String, Object> map = new HashMap<>(objectMap.size()); for (final String s : objectMap.keySet()) { final Object converted = convertToAvroObject(objectMap.get(s), fieldSchema.getValueType(), fieldName + "[" + s + "]", charset); map.put(s, converted); } return map; } else { throw new IllegalTypeConversionException( "Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a Map"); } case RECORD: final GenericData.Record avroRecord = new GenericData.Record(fieldSchema); final Record record = (Record) rawValue; for (final RecordField recordField : record.getSchema().getFields()) { final Object recordFieldValue = record.getValue(recordField); final String recordFieldName = recordField.getFieldName(); final Field field = fieldSchema.getField(recordFieldName); if (field == null) { continue; } final Object converted = convertToAvroObject(recordFieldValue, field.schema(), fieldName + "/" + recordFieldName, charset); avroRecord.put(recordFieldName, converted); } return avroRecord; case UNION: return convertUnionFieldValue(rawValue, fieldSchema, schema -> convertToAvroObject(rawValue, schema, fieldName, charset), fieldName); case ARRAY: final Object[] objectArray = (Object[]) rawValue; final List<Object> list = new ArrayList<>(objectArray.length); int i = 0; for (final Object o : objectArray) { final Object converted = convertToAvroObject(o, fieldSchema.getElementType(), fieldName + "[" + i + "]", charset); list.add(converted); i++; } return list; case BOOLEAN: return DataTypeUtils.toBoolean(rawValue, fieldName); case DOUBLE: return DataTypeUtils.toDouble(rawValue, fieldName); case FLOAT: return DataTypeUtils.toFloat(rawValue, fieldName); case NULL: return null; case ENUM: return new GenericData.EnumSymbol(fieldSchema, rawValue); case STRING: return DataTypeUtils.toString(rawValue, (String) null, charset); } return rawValue; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Append decimal zeros to the value. This returns a value which appears to have * a higher precision than the input./* w ww .j a v a2s .c om*/ * * @param x The input value * @param d The (positive) value of zeros to be added as least significant digits. * @return The same value as the input but with increased (pseudo) precision. */ static public BigDecimal scalePrec(final BigDecimal x, int d) { return x.setScale(d + x.scale()); }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.BasicFieldPersistenceProvider.java
@Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; }// w w w. j a va 2s . co m try { if (extractValueRequest.getRequestedValue() != null) { String val = null; if (extractValueRequest.getMetadata().getForeignKeyCollection()) { ((BasicFieldMetadata) property.getMetadata()) .setFieldType(extractValueRequest.getMetadata().getFieldType()); } else if (extractValueRequest.getMetadata().getFieldType().equals(SupportedFieldType.BOOLEAN) && extractValueRequest.getRequestedValue() instanceof Character) { val = (extractValueRequest.getRequestedValue().equals('Y')) ? "true" : "false"; } else if (Date.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter() .format((Date) extractValueRequest.getRequestedValue()); } else if (Timestamp.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter() .format(new Date(((Timestamp) extractValueRequest.getRequestedValue()).getTime())); } else if (Calendar.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter() .format(((Calendar) extractValueRequest.getRequestedValue()).getTime()); } else if (Double.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getDecimalFormatter() .format(extractValueRequest.getRequestedValue()); } else if (BigDecimal.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { BigDecimal decimal = (BigDecimal) extractValueRequest.getRequestedValue(); DecimalFormat format = extractValueRequest.getDataFormatProvider().getDecimalFormatter(); //track all the decimal places in the scale of the BigDecimal - even if they're all zeros StringBuilder sb = new StringBuilder(); sb.append("0"); if (decimal.scale() > 0) { sb.append("."); for (int j = 0; j < decimal.scale(); j++) { sb.append("0"); } } format.applyPattern(sb.toString()); val = format.format(extractValueRequest.getRequestedValue()); } else if (extractValueRequest.getMetadata().getForeignKeyClass() != null) { try { val = extractValueRequest.getFieldManager() .getFieldValue(extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getForeignKeyProperty()) .toString(); if (extensionManager != null) { ExtensionResultHolder<Serializable> resultHolder = new ExtensionResultHolder<Serializable>(); ExtensionResultStatusType result = extensionManager.getProxy() .transformForeignKey(extractValueRequest, property, resultHolder); if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) { val = String.valueOf(resultHolder.getResult()); } } //see if there's a name property and use it for the display value String entityName = null; if (extractValueRequest.getRequestedValue() instanceof AdminMainEntity) { entityName = ((AdminMainEntity) extractValueRequest.getRequestedValue()) .getMainEntityName(); } Object temp = null; if (!StringUtils .isEmpty(extractValueRequest.getMetadata().getForeignKeyDisplayValueProperty())) { String nameProperty = extractValueRequest.getMetadata() .getForeignKeyDisplayValueProperty(); try { temp = extractValueRequest.getFieldManager() .getFieldValue(extractValueRequest.getRequestedValue(), nameProperty); } catch (FieldNotAvailableException e) { //do nothing } } if (temp == null && StringUtils.isEmpty(entityName)) { try { temp = extractValueRequest.getFieldManager() .getFieldValue(extractValueRequest.getRequestedValue(), "name"); } catch (FieldNotAvailableException e) { //do nothing } } if (temp != null) { extractValueRequest.setDisplayVal(temp.toString()); } else if (!StringUtils.isEmpty(entityName)) { extractValueRequest.setDisplayVal(entityName); } } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } } else if (SupportedFieldType.ID == extractValueRequest.getMetadata().getFieldType()) { val = extractValueRequest.getRequestedValue().toString(); if (extensionManager != null) { ExtensionResultHolder<Serializable> resultHolder = new ExtensionResultHolder<Serializable>(); ExtensionResultStatusType result = extensionManager.getProxy() .transformId(extractValueRequest, property, resultHolder); if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) { val = String.valueOf(resultHolder.getResult()); } } } else { val = extractValueRequest.getRequestedValue().toString(); } property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } } catch (IllegalAccessException e) { throw new PersistenceException(e); } return FieldProviderResponse.HANDLED; }
From source file:com.qcadoo.mes.productionScheduling.listeners.OrderTimePredictionListeners.java
@Transactional public void changeRealizationTime(final ViewDefinitionState view, final ComponentState state, final String[] args) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent technologyLookup = (FieldComponent) view.getComponentByReference(OrderFields.TECHNOLOGY); FieldComponent plannedQuantityField = (FieldComponent) view .getComponentByReference(OrderFields.PLANNED_QUANTITY); FieldComponent dateFromField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_FROM); FieldComponent dateToField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_TO); FieldComponent productionLineLookup = (FieldComponent) view .getComponentByReference(OrderFields.PRODUCTION_LINE); boolean isGenerated = false; if (technologyLookup.getFieldValue() == null) { technologyLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return;/*from w ww . ja va2 s. c om*/ } if (!StringUtils.hasText((String) dateFromField.getFieldValue())) { dateFromField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } if (!StringUtils.hasText((String) plannedQuantityField.getFieldValue())) { plannedQuantityField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } if (productionLineLookup.getFieldValue() == null) { productionLineLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } BigDecimal quantity = null; Object value = plannedQuantityField.getFieldValue(); if (value instanceof BigDecimal) { quantity = (BigDecimal) value; } else { try { ParsePosition parsePosition = new ParsePosition(0); String trimedValue = value.toString().replaceAll(" ", ""); DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(view.getLocale()); formatter.setParseBigDecimal(true); quantity = new BigDecimal(String.valueOf(formatter.parseObject(trimedValue, parsePosition))); } catch (NumberFormatException e) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidNumericFormat", MessageType.FAILURE); return; } } int scale = quantity.scale(); if (MAX != null && scale > MAX) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidScale.max", MessageType.FAILURE, MAX.toString()); return; } int presicion = quantity.precision() - scale; if (MAX != null && presicion > MAX) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidPrecision.max", MessageType.FAILURE, MAX.toString()); return; } if (BigDecimal.ZERO.compareTo(quantity) >= 0) { plannedQuantityField.addMessage("qcadooView.validate.field.error.outOfRange.toSmall", MessageType.FAILURE); return; } int maxPathTime = 0; Entity technology = dataDefinitionService .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY) .get((Long) technologyLookup.getFieldValue()); Validate.notNull(technology, "technology is null"); if (technology.getStringField(TechnologyFields.STATE).equals(TechnologyState.DRAFT.getStringValue()) || technology.getStringField(TechnologyFields.STATE) .equals(TechnologyState.OUTDATED.getStringValue())) { technologyLookup.addMessage("productionScheduling.technology.incorrectState", MessageType.FAILURE); return; } FieldComponent laborWorkTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.LABOR_WORK_TIME); FieldComponent machineWorkTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.MACHINE_WORK_TIME); FieldComponent includeTpzField = (FieldComponent) view.getComponentByReference(OrderFieldsPS.INCLUDE_TPZ); FieldComponent includeAdditionalTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.INCLUDE_ADDITIONAL_TIME); Boolean includeTpz = "1".equals(includeTpzField.getFieldValue()); Boolean includeAdditionalTime = "1".equals(includeAdditionalTimeField.getFieldValue()); Entity productionLine = dataDefinitionService .get(ProductionLinesConstants.PLUGIN_IDENTIFIER, ProductionLinesConstants.MODEL_PRODUCTION_LINE) .get((Long) productionLineLookup.getFieldValue()); final Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getProductComponentQuantities(technology, quantity, operationRuns); OperationWorkTime workTime = operationWorkTimeService.estimateTotalWorkTimeForTechnology(technology, operationRuns, includeTpz, includeAdditionalTime, productionLine, true); laborWorkTimeField.setFieldValue(workTime.getLaborWorkTime()); machineWorkTimeField.setFieldValue(workTime.getMachineWorkTime()); maxPathTime = orderRealizationTimeService.estimateOperationTimeConsumption( technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS).getRoot(), quantity, includeTpz, includeAdditionalTime, productionLine); if (maxPathTime > OrderRealizationTimeService.MAX_REALIZATION_TIME) { state.addMessage("orders.validate.global.error.RealizationTimeIsToLong", MessageType.FAILURE); dateToField.setFieldValue(null); } else { Date startTime = DateUtils.parseDate(dateFromField.getFieldValue()); if (startTime == null) { dateFromField.addMessage("orders.validate.global.error.dateFromIsNull", MessageType.FAILURE); } else { Date stopTime = shiftsService.findDateToForOrder(startTime, maxPathTime); if (stopTime == null) { orderForm.addMessage("productionScheduling.timenorms.isZero", MessageType.FAILURE, false); dateToField.setFieldValue(null); } else { dateToField.setFieldValue(orderRealizationTimeService.setDateToField(stopTime)); startTime = shiftsService.findDateFromForOrder(stopTime, maxPathTime); scheduleOperationComponents(technology.getId(), startTime); isGenerated = true; } if (startTime != null) { orderForm.addMessage("orders.dateFrom.info.dateFromSetToFirstPossible", MessageType.INFO, false); } } } laborWorkTimeField.requestComponentUpdateState(); machineWorkTimeField.requestComponentUpdateState(); dateFromField.requestComponentUpdateState(); dateToField.requestComponentUpdateState(); orderForm.setEntity(orderForm.getEntity()); state.performEvent(view, "refresh", new String[0]); if (isGenerated) { orderForm.addMessage("productionScheduling.info.calculationGenerated", MessageType.SUCCESS); } }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
private void validateAdministrativeAndAdditionalFees(Errors errors) { Set<Integer> feeSet = new HashSet<Integer>(); if (this.selectedFeeId != null) { boolean noDuplicateExists = true; for (Number feeId : this.selectedFeeId) { if (feeId != null) { noDuplicateExists = feeSet.add(feeId.intValue()); if (!noDuplicateExists) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.invalid", "Multiple instances of the same fee are not allowed."); break; }//from w w w . j a va2 s . c o m } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { Number amountOrRate = this.defaultFeeAmountOrRate[defaultFeeIndex]; if (amountOrRate == null) { errors.rejectValue("defaultFeeId", "loanAccountFormBean.defaultfees.amountOrRate.invalid", "Please specify fee amount for administrative fee " + Integer.valueOf(defaultFeeIndex + 1).toString()); } else { FeeDto selectedFee = findDefaultFee(feeId.intValue()); if (selectedFee.isRateBasedFee()) { // maybe check based on 'interest rate' decimals? } else { BigDecimal feeAmountAsDecimal = new BigDecimal(amountOrRate.toString()) .stripTrailingZeros(); int places = feeAmountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.amountOrRate.digits.after.decimal.invalid", new Object[] { Integer.valueOf(defaultFeeIndex + 1), this.digitsAfterDecimalForMonetaryAmounts }, "Please specify fee amount for additional fee " + Integer.valueOf(defaultFeeIndex + 1).toString()); } int digitsBefore = feeAmountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.amountOrRate.digits.before.decimal.invalid", new Object[] { Integer.valueOf(defaultFeeIndex + 1), this.digitsAfterDecimalForMonetaryAmounts }, "Please specify fee amount for additional fee " + Integer.valueOf(defaultFeeIndex + 1).toString()); } } } } } defaultFeeIndex++; } } int additionalFeeIndex = 0; if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { Number amountOrRate = this.selectedFeeAmount[additionalFeeIndex]; if (amountOrRate == null) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.amountOrRate.invalid", "Please specify fee amount for additional fee " + Integer.valueOf(additionalFeeIndex + 1).toString()); } else { int digitsAllowedBefore, digitsAllowedAfter; if (findAdditionalFee(feeId.intValue()).isRateBasedFee()) { digitsAllowedBefore = this.digitsBeforeDecimalForInterest; digitsAllowedAfter = this.digitsAfterDecimalForInterest; } else { digitsAllowedBefore = this.digitsBeforeDecimalForMonetaryAmounts; digitsAllowedAfter = this.digitsAfterDecimalForMonetaryAmounts; } BigDecimal feeAmountAsDecimal = new BigDecimal(amountOrRate.toString()) .stripTrailingZeros(); int places = feeAmountAsDecimal.scale(); if (places > digitsAllowedAfter) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.amountOrRate.digits.after.decimal.invalid", new Object[] { Integer.valueOf(additionalFeeIndex + 1), digitsAllowedAfter }, "Please specify fee amount for additional fee " + Integer.valueOf(additionalFeeIndex + 1).toString()); } int digitsBefore = feeAmountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > digitsAllowedBefore) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.amountOrRate.digits.before.decimal.invalid", new Object[] { Integer.valueOf(additionalFeeIndex + 1), digitsAllowedBefore }, "Please specify fee amount for additional fee " + Integer.valueOf(additionalFeeIndex + 1).toString()); } } } additionalFeeIndex++; } } }
From source file:net.pms.util.Rational.java
/** * Returns an instance that represents the value of {@code value}. * * @param value the value.//from w w w . j a va 2 s . co m * @return An instance that represents the value of {@code value}. */ @Nullable public static Rational valueOf(@Nullable BigDecimal value) { if (value == null) { return null; } BigInteger numerator; BigInteger denominator; if (value.signum() == 0) { return ZERO; } if (BigDecimal.ONE.equals(value)) { return ONE; } if (value.scale() > 0) { BigInteger unscaled = value.unscaledValue(); BigInteger tmpDenominator = BigInteger.TEN.pow(value.scale()); BigInteger tmpGreatestCommonDivisor = unscaled.gcd(tmpDenominator); numerator = unscaled.divide(tmpGreatestCommonDivisor); denominator = tmpDenominator.divide(tmpGreatestCommonDivisor); } else { numerator = value.toBigIntegerExact(); denominator = BigInteger.ONE; } return new Rational(numerator, denominator, BigInteger.ONE, numerator, denominator); }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "") public void validateEnterAccountDetailsStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); Errors errors = validator.checkConstraints(this); // handle data binding errors that may of occurred if (messageContext.hasErrorMessages()) { Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() { @Override//from ww w. java 2s. c o m public boolean test(@SuppressWarnings("unused") Message message) { return true; } }); messageContext.clearMessages(); for (Message message : errorMessages) { handleDataMappingError(errors, message); } } if (this.glimApplicable) { int index = 0; int selectedCount = 0; for (Boolean clientSelected : this.clientSelectForGroup) { if (clientSelected != null && clientSelected.booleanValue()) { Number clientAmount = this.clientAmount[index]; if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage); } if (clientAmount != null) { BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts }); } } // check error message of loan purpose for each client when its mandatory.. Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) { errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose."); this.clientLoanPurposeId[index] = 0; } else { // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over. if (clientLoanPurposeId == null) { this.clientLoanPurposeId[index] = 0; } } selectedCount++; } else { Number clientAmount = this.clientAmount[index]; Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (clientAmount != null || clientLoanPurposeId != null) { String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan."; rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage); } } index++; } if (selectedCount < 2) { String defaultErrorMessage = "Not enough clients for group loan."; rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage); } } if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; if (glimApplicable) { defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product."; rejectGlimTotalAmountField(errors, defaultErrorMessage); } else { rejectAmountField(errors, defaultErrorMessage); } } if (this.amount != null) { BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts }); } } if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) { String defaultErrorMessage = "Please specify valid Interest rate."; rejectInterestRateField(errors, defaultErrorMessage); } if (this.interestRate != null) { BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros(); int places = interestRateAsDecimal.scale(); if (places > this.digitsAfterDecimalForInterest) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest }); } int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForInterest) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest }); } } if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) { String defaultErrorMessage = "Please specify valid number of installments."; rejectNumberOfInstallmentsField(errors, defaultErrorMessage); } if (this.graceDuration == null || this.graceDuration.intValue() < 0) { if (!errors.hasFieldErrors("graceDuration")) { String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + "."; rejectGraceDurationField(errors, defaultErrorMessage); } } else { if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) { String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage); } if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) { String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage); } } if (dateValidator == null) { dateValidator = new DateValidator(); } if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) { String defaultErrorMessage = "Please specify valid disbursal date."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", ""); } else { LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate(); org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors(); if (this.redoLoanAccount) { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId); } else { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanDisbursementDate(validDate, customerId, productId); } for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) { String defaultErrorMessage = "The disbursal date is invalid."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0)); } } if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) { errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds."); } if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) { errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id."); } if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) { errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose."); } validateAdministrativeAndAdditionalFees(errors); if (this.repaymentScheduleIndependentOfCustomerMeeting) { if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) { errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day."); } if (this.weekly) { if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } else if (this.monthly) { if (this.monthlyDayOfMonthOptionSelected) { if (isInvalidDayOfMonthEntered()) { errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day."); } } else if (this.monthlyWeekOfMonthOptionSelected) { if (isInvalidWeekOfMonthSelection()) { errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day."); } if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } } if (this.variableInstallmentsAllowed) { if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } defaultFeeIndex++; } } } } if (errors.hasErrors()) { for (FieldError fieldError : errors.getFieldErrors()) { MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()) .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()) .args(fieldError.getArguments()); messageContext.addMessage(builder.build()); } } }
From source file:com.aimluck.eip.project.ProjectTaskFormData.java
/** * ????//from ww w .j ava 2s . c o m * * @param rundata * RunData * @param context * Context * @param msgList * * @return TRUE ? FALSE */ @Override protected boolean setFormData(RunData rundata, Context context, List<String> msgList) throws ALPageNotFoundException, ALDBErrorException { boolean res = super.setFormData(rundata, context, msgList); try { if (res) { String members[] = rundata.getParameters().getStrings("task_member"); String workload[] = rundata.getParameters().getStrings("workload"); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i] == null || members[i].length() == 0) { continue; } // ALEipUser user = ALEipUtils.getALEipUser(Integer.valueOf(members[i])); // BigDecimal w = BigDecimal.valueOf(0); try { if (workload[i] != null && workload[i].length() > 0) { w = new BigDecimal(workload[i]); } if (w.compareTo(BigDecimal.valueOf(0)) < 0) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD")); } else if (w.precision() - w.scale() > 5) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_RATIONAL_INTEGER")); } else if (w.scale() > 3) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_DECIMAL")); } } catch (Exception e) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_INTEGER")); } ProjectTaskMemberResultData member = new ProjectTaskMemberResultData(); member.initField(); member.setUserId(user.getUserId().getValue()); member.setUserName(user.getAliasName().getValue()); member.setWorkload(w); taskMembers.add(member); } } planWorkloadString = rundata.getParameters().getString("plan_workload"); // fileuploadList = pfile.getFileuploadList(rundata); if (ALEipConstants.MODE_NEW_FORM.equals(getMode())) { String nullStr = null; start_date_check.setValue("TRUE"); start_date.setValue(nullStr); end_date_check.setValue("TRUE"); end_date.setValue(nullStr); } } } catch (RuntimeException ex) { logger.error("RuntimeException", ex); res = false; } catch (Exception ex) { logger.error("Exception", ex); res = false; } return res; }
From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java
private boolean isIntegerValue(BigDecimal bigDecimal) { if (bigDecimal == null) { return false; }/* w w w .j ava 2s . co m*/ if (bigDecimal.signum() == 0 || bigDecimal.scale() <= 0 || bigDecimal.stripTrailingZeros().scale() <= 0) { return true; } else { return false; } }
From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java
public int numberOfDecimals(BigDecimal value) { if (value == null) { return -1; }//from ww w.j a v a 2s. c om int i = value.subtract(value.setScale(0, RoundingMode.FLOOR)).movePointRight(value.scale()).intValue(); return Integer.toString(i).length(); }