List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:org.efaps.esjp.accounting.transaction.TransInfo_Base.java
/** * Gets the rel pos infos./*from w ww.j ava 2s. c o m*/ * * @param _parameter Parameter as passed by the eFaps API * @param _accInfo the acc info * @param _type the type * @return the rel pos infos * @throws EFapsException on error */ protected static List<PositionInfo> getRelPosInfos(final Parameter _parameter, final AccountInfo _accInfo, final Type _type) throws EFapsException { final List<PositionInfo> ret = new ArrayList<>(); final boolean isDebitTrans = _type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid); final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, _accInfo.getInstance()); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selAcc = SelectBuilder.get().linkto(CIAccounting.Account2AccountAbstract.ToAccountLink) .instance(); multi.addSelect(selAcc); multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator, CIAccounting.Account2AccountAbstract.Denominator, CIAccounting.Account2AccountAbstract.Config); multi.execute(); int y = 1; while (multi.next()) { final Instance instance = multi.getCurrentInstance(); final PositionInfo connPos = new PositionInfo(); connPos.setPosType(TransPosType.CONNECTION); final BigDecimal numerator = new BigDecimal( multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator)); final BigDecimal denominator = new BigDecimal( multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)); final Collection<Accounting.Account2AccountConfig> configs = multi .getAttribute(CIAccounting.Account2AccountAbstract.Config); final boolean confCheck = isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT) || !isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT); if (confCheck) { BigDecimal amount = _accInfo.getAmountRate(_parameter).multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); BigDecimal rateAmount = _accInfo.getAmount().multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); if (isDebitTrans) { amount = amount.negate(); rateAmount = rateAmount.negate(); } if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCosting.uuid)) { connPos.setType(_type); } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCostingInverse.uuid)) { if (_type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid)) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); } amount = amount.negate(); } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCredit.uuid)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount = amount.negate(); rateAmount = rateAmount.negate(); } } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountDebit.uuid)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount = amount.negate(); rateAmount = rateAmount.negate(); } else { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } } if (connPos.getType() == null) { LOG.error("Missing definition"); } else { connPos.setConnOrder(y).setAccInst(multi.<Instance>getSelect(selAcc)).setAmount(amount) .setRateAmount(rateAmount); ret.add(connPos); } y++; } } return ret; }
From source file:org.egov.adtax.service.AdvertisementDemandService.java
/** * Update demand details of current or latest year data on renewal. Assumption: There is no partial payment collected for * selected year./*from w w w . j a v a 2 s. c o m*/ * * @param advertisementPermitDetail * @param demand * @return */ public EgDemand updateDemandOnRenewal(final AdvertisementPermitDetail advertisementPermitDetail, final EgDemand demand) { if (demand != null) { final List<EgDemandDetails> removableDemandDetailList = new ArrayList<>(); final Installment installment = demand.getEgInstallmentMaster(); BigDecimal totalDemandAmount = BigDecimal.ZERO; Boolean enchroachmentFeeAlreadyExistInDemand = false; /* * EgDemandReason pendingTaxReason = getDemandReasonByCodeAndInstallment( * AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment); */ final EgDemandReason encroachmentFeeReason = getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment); final EgDemandReason taxReason = getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX, installment); for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails()) { // Assumption: tax amount is mandatory. if (dmdDtl.getEgDemandReason().getId() == taxReason.getId() && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) >= 0) { totalDemandAmount = totalDemandAmount .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount())); dmdDtl.setAmount( advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP)); } /* * if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId() && * advertisementPermitDetail.getAdvertisement().getPendingTax()!=null && * advertisementPermitDetail.getAdvertisement().getPendingTax().compareTo(BigDecimal.ZERO) > 0) { // TODO: Also * check whether fully collected ? totalDemandAmount = * totalDemandAmount.add(advertisementPermitDetail.getAdvertisement().getPendingTax().subtract(dmdDtl.getAmount()) * ); dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0, * BigDecimal.ROUND_HALF_UP)); } */ // Encroachment fee may not mandatory. If already part of demand if (dmdDtl.getEgDemandReason().getId() == encroachmentFeeReason.getId()) { enchroachmentFeeAlreadyExistInDemand = true; if (advertisementPermitDetail.getEncroachmentFee() != null && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) { totalDemandAmount = totalDemandAmount .add(advertisementPermitDetail.getEncroachmentFee().subtract(dmdDtl.getAmount())); dmdDtl.setAmount(advertisementPermitDetail.getEncroachmentFee().setScale(0, BigDecimal.ROUND_HALF_UP)); // update encroachment fee.. } else { totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount()); // demand.removeEgDemandDetails(dmdDtl); removableDemandDetailList.add(dmdDtl); // delete demand detail } } } if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) { demand.addEgDemandDetails( createDemandDetails(advertisementPermitDetail.getEncroachmentFee(), getDemandReasonByCodeAndInstallment( AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment), BigDecimal.ZERO)); totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee()); } for (final EgDemandDetails removableDmdDtl : removableDemandDetailList) demand.removeEgDemandDetails(removableDmdDtl); demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP)); } return demand; }
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 ww . j a va 2s . 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:net.sourceforge.fenixedu.domain.Teacher.java
public BigDecimal getMasterDegreeThesesCredits(ExecutionYear executionYear) { double totalThesisValue = 0.0; if (!executionYear.getYear().equals("2011/2012")) { for (ThesisEvaluationParticipant participant : getPerson().getThesisEvaluationParticipantsSet()) { Thesis thesis = participant.getThesis(); if (thesis.isEvaluated() && thesis.hasFinalEnrolmentEvaluation() && thesis.getEvaluation().getYear() == executionYear.getBeginCivilYear() && (participant.getType() == ThesisParticipationType.ORIENTATOR || participant.getType() == ThesisParticipationType.COORIENTATOR)) { totalThesisValue = totalThesisValue + participant.getParticipationCredits(); }//from www. ja v a 2 s . co m } } return (BigDecimal.valueOf(5).min(new BigDecimal(totalThesisValue * 0.5))).setScale(2, BigDecimal.ROUND_HALF_UP); }
From source file:org.egov.ptis.domain.service.revisionPetition.RevisionPetitionService.java
public void setNoticeInfo(final PropertyImpl property, final PropertyNoticeInfo propertyNotice, final BasicPropertyImpl basicProperty, final RevisionPetition objection) { final PropertyAckNoticeInfo infoBean = new PropertyAckNoticeInfo(); final Address ownerAddress = basicProperty.getAddress(); BigDecimal totalTax = BigDecimal.ZERO; BigDecimal propertyTax = BigDecimal.ZERO; if (basicProperty.getPropertyOwnerInfo().size() > 1) infoBean.setOwnerName(basicProperty.getFullOwnerName().concat(" and others")); else/*from w ww .ja v a2 s .c om*/ infoBean.setOwnerName(basicProperty.getFullOwnerName()); infoBean.setOwnerAddress(basicProperty.getAddress().toString()); infoBean.setApplicationNo(property.getApplicationNo()); infoBean.setDoorNo(ownerAddress.getHouseNoBldgApt()); if (isNotBlank(ownerAddress.getLandmark())) infoBean.setStreetName(ownerAddress.getLandmark()); else infoBean.setStreetName("N/A"); final SimpleDateFormat formatNowYear = new SimpleDateFormat("yyyy"); final String occupancyYear = formatNowYear.format(basicProperty.getPropOccupationDate()); infoBean.setInstallmentYear(occupancyYear); infoBean.setAssessmentNo(basicProperty.getUpicNo()); final SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy"); infoBean.setAssessmentDate(dateformat.format(basicProperty.getAssessmentdate())); final Ptdemand currDemand = ptDemandDAO.getNonHistoryCurrDmdForProperty(property); // Sets data for the current property prepareTaxInfoForProperty(infoBean, totalTax, propertyTax, currDemand, CURRENT); if (currDemand.getDmdCalculations() != null && currDemand.getDmdCalculations().getAlv() != null) infoBean.setNew_rev_ARV(currDemand.getDmdCalculations().getAlv()); // Sets data for the latest history property final PropertyImpl historyProperty = propertyService.getLatestHistoryProperty(basicProperty.getUpicNo()); final Ptdemand historyDemand = ptDemandDAO.getNonHistoryCurrDmdForProperty(historyProperty); if (historyProperty != null && historyDemand != null) { totalTax = BigDecimal.ZERO; propertyTax = BigDecimal.ZERO; prepareTaxInfoForProperty(infoBean, totalTax, propertyTax, historyDemand, HISTORY); if (historyDemand.getDmdCalculations() != null && historyDemand.getDmdCalculations().getAlv() != null) infoBean.setExistingARV(historyDemand.getDmdCalculations().getAlv()); } final PropertyID boundaryDetails = basicProperty.getPropertyID(); infoBean.setZoneName(boundaryDetails.getZone().getName()); infoBean.setWardName(boundaryDetails.getWard().getName()); infoBean.setAreaName(boundaryDetails.getArea().getName()); infoBean.setLocalityName(boundaryDetails.getLocality().getName()); infoBean.setNoticeDate(new Date()); infoBean.setApplicationDate(DateUtils.getFormattedDate(objection.getCreatedDate(), DATE_FORMAT_DDMMYYY)); infoBean.setHearingDate(DateUtils.getFormattedDate(objection.getHearings().get(0).getPlannedHearingDt(), DATE_FORMAT_DDMMYYY)); infoBean.setActualHearingDate(DateUtils .getFormattedDate(objection.getHearings().get(0).getActualHearingDt(), DATE_FORMAT_DDMMYYY)); final User approver = userService.getUserById(ApplicationThreadLocals.getUserId()); infoBean.setApproverName(approver.getName()); final BigDecimal revTax = currDemand.getBaseDemand(); infoBean.setNewTotalTax(revTax.setScale(0, BigDecimal.ROUND_HALF_UP)); if (property.getSource().equals(SOURCE_MEESEVA)) infoBean.setMeesevaNo(property.getApplicationNo()); propertyNotice.setOwnerInfo(infoBean); }
From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java
/** * Provides collection and demand results * * @param collectionDashBoardRequest/*from w w w . j a va2s . co m*/ * @param fromDate * @param toDate * @param indexName * @param fieldName * @param ulbCodeField * @param aggregationField * @return Map */ public Map<String, BigDecimal> getCollectionAndDemandValues( final CollectionDashBoardRequest collectionDashBoardRequest, final Date fromDate, final Date toDate, final String fieldName, final String aggregationField, final List<String> serviceDetails) { BoolQueryBuilder boolQuery = prepareWhereClause(collectionDashBoardRequest); if (!serviceDetails.isEmpty()) boolQuery = boolQuery.filter(QueryBuilders.termsQuery(BILLING_SERVICE, serviceDetails)); boolQuery = boolQuery .filter(QueryBuilders.rangeQuery(RECEIPT_DATE).gte(DATEFORMATTER_YYYY_MM_DD.format(fromDate)) .lte(DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false)) .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED)); final AggregationBuilder aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120) .subAggregation(AggregationBuilders.sum("total").field(fieldName)); final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(COLLECTION_INDEX_NAME) .withQuery(boolQuery).addAggregation(aggregation).build(); final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); final StringTerms cityAggr = collAggr.get(BY_CITY); final Map<String, BigDecimal> cytdCollMap = new HashMap<>(); for (final Terms.Bucket entry : cityAggr.getBuckets()) { final Sum aggr = entry.getAggregations().get("total"); cytdCollMap.put(String.valueOf(entry.getKey()), BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)); } return cytdCollMap; }
From source file:org.egov.ptis.actions.common.AjaxCommonAction.java
/** * API to calculate Mutation Fee dynamically * * @return/*from w ww. j a va 2 s . c o m*/ */ @Action(value = "/ajaxCommon-calculateMutationFee") public String calculateMutationFee() { // Maximum among partyValue and departmentValue will be considered as // the documentValue final BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue; if (documentValue.compareTo(ZERO) > 0) { BigDecimal excessDocValue; BigDecimal multiplicationFactor; final MutationFeeDetails mutationFeeDetails = (MutationFeeDetails) getPersistenceService().find( "from MutationFeeDetails where lowLimit <= ? and (highLimit is null OR highLimit >= ?) and toDate > now()", documentValue, documentValue); if (mutationFeeDetails != null) { if (mutationFeeDetails.getFlatAmount() != null && mutationFeeDetails.getFlatAmount().compareTo(ZERO) > 0) if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N)) mutationFee = mutationFeeDetails.getFlatAmount(); else { excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit()) .add(BigDecimal.ONE); multiplicationFactor = excessDocValue.divide(mutationFeeDetails.getRecursiveAmount(), BigDecimal.ROUND_CEILING); mutationFee = mutationFeeDetails.getFlatAmount() .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveFactor())); } if (mutationFeeDetails.getPercentage() != null && mutationFeeDetails.getPercentage().compareTo(ZERO) > 0) if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N)) mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage()) .divide(PropertyTaxConstants.BIGDECIMAL_100); mutationFee = mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP); } } return RESULT_MUTATION_FEE; }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
/** * Returns the consolidated collections for single day and between the 2 * dates/*from w w w .j ava 2s. c o m*/ * * @param collectionDetailsRequest * @param fromDate * @param toDate * @param cityName * @return BigDecimal */ public BigDecimal getCollectionBetweenDates(final WaterChargeDashBoardRequest collectionDetailsRequest, final Date fromDate, final Date toDate, final String cityName) { final Long startTime = System.currentTimeMillis(); BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, WaterTaxConstants.COLLECTION_INDEX_NAME); boolQuery = boolQuery .filter(QueryBuilders.rangeQuery(RECEIPT_DATEINDEX) .gte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(fromDate)) .lte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false)) .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED)); if (StringUtils.isNotBlank(cityName)) boolQuery = boolQuery .filter(QueryBuilders.matchQuery(WaterTaxConstants.CITYNAMEAGGREGATIONFIELD, cityName)); final SearchQuery searchQueryColl = new NativeSearchQueryBuilder() .withIndices(WaterTaxConstants.COLLECTION_INDEX_NAME).withQuery(boolQuery) .addAggregation(AggregationBuilders.sum(COLLECTION_TOTAL).field(TOTAL_AMOUNT)).build(); final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); final Sum aggr = collAggr.get(COLLECTION_TOTAL); final Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getCollectionBetweenDates() is (millisecs) : " + timeTaken); return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP); }
From source file:net.sourceforge.fenixedu.domain.Teacher.java
public BigDecimal getPhdDegreeThesesCredits(ExecutionYear executionYear) { ExecutionYear previousExecutionYear = executionYear.getPreviousExecutionYear(); int guidedThesesNumber = 0; double assistantGuidedTheses = 0.0; if (!executionYear.getYear().equals("2011/2012")) { for (InternalPhdParticipant internalPhdParticipant : getPerson().getInternalParticipantsSet()) { ExecutionYear conclusionYear = internalPhdParticipant.getIndividualProcess().getConclusionYear(); if (conclusionYear != null && conclusionYear.equals(previousExecutionYear)) { if (internalPhdParticipant.getProcessForGuiding() != null) { guidedThesesNumber++; } else if (internalPhdParticipant.getProcessForAssistantGuiding() != null) { assistantGuidedTheses = assistantGuidedTheses + (0.5 / internalPhdParticipant .getProcessForAssistantGuiding().getAssistantGuidingsSet().size()); }// w w w . j a v a 2 s . c om } } } return BigDecimal.valueOf(2 * (guidedThesesNumber + assistantGuidedTheses)).setScale(2, BigDecimal.ROUND_HALF_UP); }
From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java
private void addInvestorByMonthInterest(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) { int monthes = trade.getTimeLimit(); double investAmount = 0; long tradeId = trade.getId(); long detailId = detail.getId(); BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount()); investAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue(); double monthMoney = investAmount / monthes; // investAmount = Math.floor(investAmount); monthMoney = Math.floor(monthMoney); for (int i = 0; i < monthes; i++) { TradeDetail tradeDetail = new TradeDetail(detail.getUserId(), tradeId, (long) monthMoney, 12, divsionRuleRole.getPhase(), String.valueOf(detailId)); tradeDetail.setRepayPeriodNo(i + 1); tradeDetail.setRepayPeriodCount(monthes); tradeDetailDao.addTradeDetail(tradeDetail); }//from w w w . j av a 2s.co m }