List of usage examples for java.math BigDecimal longValue
@Override public long longValue()
From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java
@Override // startDate is the leave request start date, endDat is leave request end date, usageEndDate is the date before next accrual interval date for leave requst end date // will get leave balance up to the next earn interval for a certain date, including usage up to that next earn interval public BigDecimal getLeaveBalanceForAccrCatUpToDate(String principalId, LocalDate startDate, LocalDate endDate, String accrualCategory, LocalDate usageEndDate) { BigDecimal leaveBalance = BigDecimal.ZERO; if (StringUtils.isEmpty(principalId) || startDate == null || endDate == null || StringUtils.isEmpty(accrualCategory) || usageEndDate == null) { return leaveBalance; }/*from w ww. ja v a2 s . c o m*/ LeaveSummaryRow lsr = new LeaveSummaryRow(); AccrualCategory ac = HrServiceLocator.getAccrualCategoryService().getAccrualCategory(accrualCategory, endDate); if (ac != null) { LeavePlan lp = HrServiceLocator.getLeavePlanService().getLeavePlan(ac.getLeavePlan(), ac.getEffectiveLocalDate()); if (lp == null) { return leaveBalance; } PrincipalHRAttributes pha = getPrincipalHrAttributes(principalId, startDate, endDate); //until we have something that creates carry over, we need to grab everything. // Calculating leave bLocks from Calendar Year start instead of Service Date Map<String, LeaveBlock> carryOverBlocks = getLeaveBlockService().getLastCarryOverBlocks(principalId, startDate); //remove unwanted carry over blocks from map LeaveBlock carryOverBlock = carryOverBlocks.get(accrualCategory); carryOverBlocks = new HashMap<String, LeaveBlock>(1); if (ObjectUtils.isNotNull(carryOverBlock)) carryOverBlocks.put(carryOverBlock.getAccrualCategory(), carryOverBlock); List<LeaveBlock> leaveBlocks = getLeaveBlockService().getLeaveBlocksSinceCarryOver(principalId, carryOverBlocks, endDate, true); List<LeaveBlock> acLeaveBlocks = new ArrayList<LeaveBlock>(); for (LeaveBlock lb : leaveBlocks) { if (StringUtils.equals(lb.getAccrualCategory(), accrualCategory)) { acLeaveBlocks.add(lb); } } // get all leave blocks from the requested date to the usageEndDate List<LeaveBlock> futureLeaveBlocks = getLeaveBlockService() .getLeaveBlocksWithAccrualCategory(principalId, endDate, usageEndDate, accrualCategory); EmployeeOverrideContract maxUsageOverride = LmServiceLocator.getEmployeeOverrideService() .getEmployeeOverride(principalId, lp.getLeavePlan(), accrualCategory, "MU", usageEndDate); //get max balances AccrualCategoryRuleContract acRule = HrServiceLocator.getAccrualCategoryRuleService() .getAccrualCategoryRuleForDate(ac, LocalDate.now(), pha.getServiceLocalDate()); //accrual category rule id set on a leave summary row will be useful in generating a relevant balance transfer //document from the leave calendar display. Could put this id in the request for balance transfer document. lsr.setAccrualCategoryRuleId(acRule == null ? null : acRule.getLmAccrualCategoryRuleId()); if (acRule != null && (acRule.getMaxBalance() != null || acRule.getMaxUsage() != null)) { if (acRule.getMaxUsage() != null) { lsr.setUsageLimit(new BigDecimal(acRule.getMaxUsage()).setScale(2)); } else { lsr.setUsageLimit(null); } } else { lsr.setUsageLimit(null); } if (maxUsageOverride != null) lsr.setUsageLimit(new BigDecimal(maxUsageOverride.getOverrideValue())); //Fetching leaveblocks for accCat with type CarryOver -- This is logic according to the CO blocks creatLed from scheduler job. BigDecimal carryOver = BigDecimal.ZERO.setScale(2); lsr.setCarryOver(carryOver); assignApprovedValuesToRow(lsr, ac.getAccrualCategory(), acLeaveBlocks, lp, startDate, endDate); //merge key sets if (carryOverBlocks.containsKey(lsr.getAccrualCategory())) { carryOver = carryOverBlocks.get(lsr.getAccrualCategory()).getLeaveAmount(); } Set<String> keyset = new HashSet<String>(); keyset.addAll(lsr.getPriorYearsUsage().keySet()); keyset.addAll(lsr.getPriorYearsTotalAccrued().keySet()); for (String key : keyset) { BigDecimal value = lsr.getPriorYearsTotalAccrued().get(key); if (value == null) { value = BigDecimal.ZERO; } carryOver = carryOver.add(value); BigDecimal use = lsr.getPriorYearsUsage().containsKey(key) ? lsr.getPriorYearsUsage().get(key) : BigDecimal.ZERO; carryOver = carryOver.add(use); if (acRule != null && acRule.getMaxCarryOver() != null && acRule.getMaxCarryOver() < carryOver.longValue()) { carryOver = new BigDecimal(acRule.getMaxCarryOver()); } } lsr.setCarryOver(carryOver); //handle future leave blocks assignPendingValuesToRow(lsr, ac.getAccrualCategory(), futureLeaveBlocks); //compute Leave Balance leaveBalance = lsr.getAccruedBalance().subtract(lsr.getPendingLeaveRequests()); if (lsr.getUsageLimit() != null) { //should not set leave balance to usage limit simply because it's not null. BigDecimal availableUsage = lsr.getUsageLimit() .subtract(lsr.getYtdApprovedUsage().add(lsr.getPendingLeaveRequests())); if (leaveBalance.compareTo(availableUsage) > 0) lsr.setLeaveBalance(availableUsage); else lsr.setLeaveBalance(leaveBalance); } else { //no usage limit lsr.setLeaveBalance(leaveBalance); } } leaveBalance = lsr.getLeaveBalance(); return leaveBalance; }
From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java
private long mpsMaterialBreakdown(Bom bom, MpsLine mpsLine, long numberOfJobs, BigDecimal lotQty, long requiredDate) { long reqDate = requiredDate; List<BomRoute> routeList = ormTemplate .findByCriteria(OrmTemplate.createCriteria(BomRoute.class).add(Restrictions.eq("Bom", bom)) .add(Restrictions.le("EffOnDate", MfUtils.tickToDate(requiredDate))) .add(Restrictions.ge("EffOffDate", MfUtils.tickToDate(requiredDate))) .addOrder(Order.desc("OperNum"))); // for (BomRoute bomRoute : routeList) { //?? ? ? long timeOper = numberOfJobs * bomRoute.getSetupTicks() + lotQty.longValue() * numberOfJobs * bomRoute.getRunTicks(); //? ? ? TimeRange timeRange = MfUtils.getTimes(mps.getWeekCal().getId(), reqDate, timeOper, ScheduleDirection.BACKWARD); long operStartDate = timeRange.getStartDateTime(); List<BomMaterial> materialList = ormTemplate.findByCriteria( OrmTemplate.createCriteria(BomMaterial.class).add(Restrictions.eq("BomRoute", bomRoute)) .add(Restrictions.le("EffOnDate", MfUtils.tickToDate(operStartDate))) .add(Restrictions.ge("EffOffDate", MfUtils.tickToDate(operStartDate)))); for (BomMaterial bomMaterial : materialList) { GenericItem planningItem = findPlanningItem(bomMaterial.getCatalog()); if (planningItem == null) continue; BigDecimal MaterialQty = lotQty.multiply(new BigDecimal(numberOfJobs)) .multiply(MfUtils.calculateBOMMaterialQuan(bomMaterial, MfUtils.tickToDate(requiredDate), bom.getPlanningLotQty())); short bucketOffset = MfUtils.determineBucketOffset(mps.getPlanningLevel().getId(), MfUtils.tickToDate(operStartDate)); if (bucketOffset == -1) throw new BusinessException( "? ? ? ? dd/mm/yyyy"); BucketRange bucketRange = MfUtils.determineBucketRange(mps.getPlanningLevel().getId(), bucketOffset);/*from www.j a va 2s. c o m*/ MpsLine mpsl = prepareMPSLine(mps, planningItem, bucketOffset, mpsLine.getMpsSequence()); mpsl.setBucketOffset(bucketOffset); mpsl.setBucketOffsetDate(bucketRange.getBucketStart()); mpsl.setLevelCode(planningItem.getLowLevelCode()); if (bomMaterial.getMeasure().getId() != planningItem.getMeasure().getId()) MaterialQty = getMeasureConversionService().conversion(bomMaterial.getMeasure(), planningItem.getMeasure(), planningItem.getCatalog(), bucketRange.getBucketStart(), MaterialQty); mpsl.setProductionDemandQty(mpsl.getProductionDemandQty().add(MaterialQty)); mpsl.setMeasure(planningItem.getMeasure()); } timeRange = MfUtils.getTimes(mps.getWeekCal().getId(), operStartDate, bomRoute.getMoveTicks() * numberOfJobs, ScheduleDirection.BACKWARD); reqDate = timeRange.getStartDateTime();// ? ? } return reqDate; }
From source file:org.egov.works.web.actions.revisionEstimate.SearchRevisionEstimateAction.java
private void validateARFForRE(final RevisionAbstractEstimate revisionEstimate) { String arfNo = ""; BigDecimal advanceAmount = new BigDecimal(0); final List<WorkOrderEstimate> woeList = persistenceService.findAllBy( " from WorkOrderEstimate woe where woe.workOrder.egwStatus.code = 'APPROVED' and woe.estimate=?", revisionEstimate.getParent()); if (woeList != null && !woeList.isEmpty()) for (final WorkOrderEstimate woe : woeList) for (final ContractorAdvanceRequisition arf : woe.getContractorAdvanceRequisitions()) if (!arf.getStatus().getCode().equalsIgnoreCase( ContractorAdvanceRequisition.ContractorAdvanceRequisitionStatus.CANCELLED.toString())) { advanceAmount = advanceAmount.add(arf.getAdvanceRequisitionAmount()); if (!arfNo.equals("")) arfNo = arfNo.concat(", ").concat(arf.getAdvanceRequisitionNumber()); else arfNo = arfNo.concat(arf.getAdvanceRequisitionNumber()); }/*w w w. ja v a 2s . c om*/ if (!arfNo.equals("")) { final BigDecimal totalEstimateValueIncludingRE = contractorAdvanceService .getTotalEstimateValueIncludingRE(revisionEstimate.getParent()); if (totalEstimateValueIncludingRE.subtract(new BigDecimal(revisionEstimate.getTotalAmount().getValue())) .longValue() < advanceAmount.longValue()) throw new ValidationException(Arrays.asList(new ValidationError("cancelRE.arf.created.message", getText("cancelRE.arf.created.message", new String[] { arfNo })))); } }
From source file:org.openbravo.service.json.AdvancedQueryBuilder.java
private Object getTypeSafeValue(String operator, Property property, Object value) throws JSONException { if (value == null) { return value; }// w w w . java 2 s .c o m if (isLike(operator)) { if (operator.equals(OPERATOR_INOTCONTAINS) || operator.equals(OPERATOR_ICONTAINS) || operator.equals(OPERATOR_CONTAINSFIELD)) { return "%" + escapeLike(value.toString()).replaceAll(" ", "%") + "%"; } else if (operator.equals(OPERATOR_NOTCONTAINS) || operator.equals(OPERATOR_CONTAINS)) { return "%" + escapeLike(value.toString()).replaceAll(" ", "%") + "%"; } else if (operator.equals(OPERATOR_INOTSTARTSWITH) || operator.equals(OPERATOR_ISTARTSWITH) || operator.equals(OPERATOR_STARTSWITHFIELD)) { return escapeLike(value.toString()).replaceAll(" ", "%") + "%"; } else if (operator.equals(OPERATOR_NOTSTARTSWITH) || operator.equals(OPERATOR_STARTSWITH)) { return escapeLike(value.toString()).replaceAll(" ", "%") + "%"; } else { return "%" + escapeLike(value.toString()); } } if (operator.equals(OPERATOR_INSET) || operator.equals(OPERATOR_NOTINSET)) { final List<Object> typedValues = new ArrayList<Object>(); final JSONArray values = (JSONArray) value; for (int i = 0; i < values.length(); i++) { typedValues.add(getTypeSafeValue(OPERATOR_EQUALS, property, values.get(i))); } return typedValues; } if (property.getDomainType() instanceof SearchDomainType) { return value; } // a FK. Old selectors is an special key, though they are not primitive they should be treated // as text if (!property.isPrimitive() && !(property.getDomainType() instanceof SearchDomainType)) { return value; } if (Boolean.class == property.getPrimitiveObjectType()) { return new Boolean(value.toString()); } else if (property.isNumericType()) { try { final BigDecimal bdValue = new BigDecimal(value.toString()); if (Long.class == property.getPrimitiveObjectType()) { return bdValue.longValue(); } else if (Integer.class == property.getPrimitiveObjectType()) { return bdValue.intValue(); } else { return bdValue; } } catch (NumberFormatException e) { throw new IllegalArgumentException(e); } } else if (Date.class.isAssignableFrom(property.getPrimitiveObjectType())) { try { Date date = null; boolean hasComeADateTime = true; if (property.isDatetime() || property.isAbsoluteDateTime()) { try { date = simpleDateTimeFormat.parse(value.toString()); } catch (ParseException e) { // When a DateTime column is filtered, plan Date values are used // See issue https://issues.openbravo.com/view.php?id=23203 hasComeADateTime = false; date = simpleDateFormat.parse(value.toString()); } } if (property.isDate()) { date = simpleDateFormat.parse(value.toString()); } final Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // move the date to the beginning of the day if (isGreaterOperator(operator)) { calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } else if (isLesserOperator(operator)) { // move the data to the end of the day calendar.set(Calendar.HOUR, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); } if (hasComeADateTime || property.isDatetime() || property.isDate()) { // Applies the time zone offset difference of the client // Just in case the date needs to be changed calendar.add(Calendar.MINUTE, -clientUTCMinutesTimeZoneDiff); // Applies the time zone offset difference of the server calendar.add(Calendar.MINUTE, UTCServerMinutesTimeZoneDiff); } return calendar.getTime(); } catch (Exception e) { throw new IllegalArgumentException(e); } } return value; }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.//from w w w. j av a2 s . c o m */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }
From source file:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * @see com.runwaysdk.dataaccess.database.relationship.AbstractDatabase#getChildCountForParent(java.lang.String, java.lang.String) */// w w w . j a va2 s.co m public long getChildCountForParent(String parent_id, String relationshipTableName) { String query = " SELECT COUNT(*) AS CT \n" + " FROM " + relationshipTableName + " \n" + " WHERE " + RelationshipDAOIF.PARENT_ID_COLUMN + " = '" + parent_id + "' \n" + " AND " + RelationshipDAOIF.CHILD_ID_COLUMN + " IN " + " (SELECT DISTINCT " + RelationshipDAOIF.CHILD_ID_COLUMN + " \n" + " FROM " + relationshipTableName + " \n" + " WHERE " + RelationshipDAOIF.PARENT_ID_COLUMN + " = '" + parent_id + "')"; ResultSet resultSet = this.query(query); long returnValue = 0; try { if (resultSet.next()) { BigDecimal number = (BigDecimal) resultSet.getBigDecimal("ct"); returnValue = number.longValue(); } } catch (SQLException sqlEx1) { Database.throwDatabaseException(sqlEx1); } finally { try { java.sql.Statement statement = resultSet.getStatement(); resultSet.close(); statement.close(); } catch (SQLException sqlEx2) { Database.throwDatabaseException(sqlEx2); } } return returnValue; // Heads up: // List<DynaBean> dynaBeanList = this.select(query); // // if (dynaBeanList.size() == 0) // { // return 0; // } // else // { // DynaBean dynaBean = dynaBeanList.get(0); // BigDecimal number = (BigDecimal)dynaBean.get("ct"); // return number.longValue(); // } }
From source file:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * @see com.runwaysdk.dataaccess.database.relationship.AbstractDatabase#getParentCountForChild(java.lang.String, java.lang.String) *//*w w w.j av a2 s . c om*/ public long getParentCountForChild(String child_id, String relationshipTableName) { String query = " SELECT COUNT(*) AS CT \n" + " FROM " + relationshipTableName + " \n" + " WHERE " + RelationshipDAOIF.CHILD_ID_COLUMN + " = '" + child_id + "' \n" + " AND " + RelationshipDAOIF.PARENT_ID_COLUMN + " IN " + " (SELECT DISTINCT " + RelationshipDAOIF.PARENT_ID_COLUMN + " \n" + " FROM " + relationshipTableName + " \n" + " WHERE " + RelationshipDAOIF.CHILD_ID_COLUMN + " = '" + child_id + "')"; ResultSet resultSet = this.query(query); long returnValue = 0; try { if (resultSet.next()) { BigDecimal number = (BigDecimal) resultSet.getBigDecimal("ct"); returnValue = number.longValue(); } } catch (SQLException sqlEx1) { Database.throwDatabaseException(sqlEx1); } finally { try { java.sql.Statement statement = resultSet.getStatement(); resultSet.close(); statement.close(); } catch (SQLException sqlEx2) { Database.throwDatabaseException(sqlEx2); } } return returnValue; // Heads up: // List<DynaBean> dynaBeanList = this.select(query); // // if (dynaBeanList.size() == 0) // { // return 0; // } // else // { // DynaBean dynaBean = dynaBeanList.get(0); // BigDecimal number = (BigDecimal)dynaBean.get("ct"); // return number.longValue(); // } }
From source file:org.egov.egf.commons.EgovCommon.java
/** * @description -This method returns the number of payments, the total payment amount made as on a particular date for a list * of ProjectCode ids that is passed. NOTE - ASSUMPTION IS EJVs don't have partial payments and CJVs have only 1 project code * on debit side.//from ww w.j a va 2 s.c o m * @param entityList - Integer list containing ProjectCode ids. * @param asOnDate - The payments are considered from the beginning to asOnDate (including asOnDate) * @return -A Map containing the total count and total amount. keys are 'count' , 'amount' * @throws ApplicationException - If anyone of the parameters is null or the ProjectCode ids list passed is empty. - If any id * passed is wrong. */ public Map<String, BigDecimal> getPaymentInfoforProjectCode(final List<Long> projectCodeIdList, final Date asOnDate) throws ApplicationException { if (projectCodeIdList == null || projectCodeIdList.size() == 0) throw new ApplicationException("ProjectCode Id list is null or empty"); if (asOnDate == null) throw new ApplicationException("asOnDate is null"); final String strAsOnDate = Constants.DDMMYYYYFORMAT1.format(asOnDate); final Map<String, BigDecimal> result = new HashMap<String, BigDecimal>(); final List<String> commaSeperatedEntitiesList = new ArrayList<String>(); final List<List<Long>> limitedEntityList = new ArrayList<List<Long>>(); String commaSeperatedEntities = ""; List<Long> tempEntityIdList = new ArrayList<Long>(); if (LOGGER.isDebugEnabled()) LOGGER.debug(" Size of entityIdList-" + projectCodeIdList.size() + " asOnDate - " + asOnDate); Long entityId; // In sql query, if in list contains more than 1000 elements, it may // fail. // Hence, we start splitting the list passed into smaller lists of sizes // less than 1000. for (int i = 0; i < projectCodeIdList.size(); i++) { entityId = projectCodeIdList.get(i); commaSeperatedEntities = commaSeperatedEntities + entityId + ","; tempEntityIdList.add(entityId); if (i != 0 && i % 998 == 0 || i == projectCodeIdList.size() - 1) { commaSeperatedEntitiesList .add(commaSeperatedEntities.substring(0, commaSeperatedEntities.length() - 1)); limitedEntityList.add(tempEntityIdList); commaSeperatedEntities = ""; tempEntityIdList = new ArrayList<Long>(); } } final String validationQuery = "SELECT detailkey FROM accountdetailkey WHERE detailtypeid= (SELECT id FROM accountdetailtype " + "WHERE name ='PROJECTCODE' AND description='PROJECTCODE' ) and detailkey in ("; List<BigDecimal> dbEntIdList = new ArrayList<BigDecimal>(); boolean isPresent; final List<Long> incorrectEntityIds = new ArrayList<Long>(); String dbEntIdQuery; if (LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Starts "); for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) { isPresent = false; dbEntIdQuery = validationQuery + commaSeperatedEntitiesList.get(i) + " ) order by detailkey "; if (LOGGER.isDebugEnabled()) LOGGER.debug(i + ":dbEntIdQuery- " + dbEntIdQuery); dbEntIdList = persistenceService.getSession().createSQLQuery(dbEntIdQuery).list(); if (dbEntIdList != null && dbEntIdList.size() != limitedEntityList.get(i).size()) for (final Long entId : limitedEntityList.get(i)) { isPresent = false; for (final BigDecimal dbEntId : dbEntIdList) if (dbEntId.longValue() == entId.longValue()) { isPresent = true; break; } if (!isPresent) incorrectEntityIds.add(entId); } } if (incorrectEntityIds.size() != 0) throw new ApplicationException("Incorrect detail key Ids - " + incorrectEntityIds); if (LOGGER.isDebugEnabled()) LOGGER.debug(" Validation Succeded "); String qryForExpense = ""; String qryForNonExpense = ""; BigDecimal totalExpensePaymentAmount = BigDecimal.ZERO; BigDecimal totalExpensePaymentCount = BigDecimal.ZERO; BigDecimal totalNonExpensePaymentAmount = BigDecimal.ZERO; BigDecimal totalNonExpensePaymentCount = BigDecimal.ZERO; List<Object[]> objForExpense; List<Object[]> objForNonExpense; BigDecimal tempAmountObj = BigDecimal.ZERO; BigDecimal tempCountObj = BigDecimal.ZERO; for (int i = 0; i < commaSeperatedEntitiesList.size(); i++) { qryForExpense = getPaymentInfoQuery(commaSeperatedEntitiesList.get(i), strAsOnDate, true); qryForNonExpense = getPaymentInfoQuery(commaSeperatedEntitiesList.get(i), strAsOnDate, false); if (LOGGER.isDebugEnabled()) LOGGER.debug(i + ": qryForExpense- " + qryForExpense); if (LOGGER.isDebugEnabled()) LOGGER.debug(i + ": qryForNonExpense- " + qryForNonExpense); objForExpense = persistenceService.getSession().createSQLQuery(qryForExpense).list(); objForNonExpense = persistenceService.getSession().createSQLQuery(qryForNonExpense).list(); if (objForExpense != null && objForExpense.size() != 0) { tempAmountObj = new BigDecimal(objForExpense.get(0)[0].toString()); tempCountObj = new BigDecimal(objForExpense.get(0)[1].toString()); totalExpensePaymentAmount = totalExpensePaymentAmount.add(tempAmountObj); totalExpensePaymentCount = totalExpensePaymentCount.add(tempCountObj); } if (objForNonExpense != null && objForNonExpense.size() != 0) { tempAmountObj = new BigDecimal(objForNonExpense.get(0)[0].toString()); tempCountObj = new BigDecimal(objForNonExpense.get(0)[1].toString()); totalNonExpensePaymentAmount = totalNonExpensePaymentAmount.add(tempAmountObj); totalNonExpensePaymentCount = totalNonExpensePaymentCount.add(tempCountObj); } } result.put("count", totalExpensePaymentCount.add(totalNonExpensePaymentCount)); result.put("amount", totalExpensePaymentAmount.add(totalNonExpensePaymentAmount)); return result; }
From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java
/** * Calculates total in home currency for all accounts *//*w w w . j av a 2 s. c o m*/ public Total getAccountsTotal(Currency homeCurrency) { ExchangeRateProvider rates = getLatestRates(); List<Account> accounts = getAllAccountsList(); BigDecimal total = BigDecimal.ZERO; for (Account account : accounts) { if (account.shouldIncludeIntoTotals()) { if (account.currency.id == homeCurrency.id) { total = total.add(BigDecimal.valueOf(account.totalAmount)); } else { ExchangeRate rate = rates.getRate(account.currency, homeCurrency); if (rate == ExchangeRate.NA) { return new Total(homeCurrency, TotalError.lastRateError(account.currency)); } else { total = total.add(BigDecimal.valueOf(rate.rate * account.totalAmount)); } } } } Total result = new Total(homeCurrency); result.balance = total.longValue(); return result; }
From source file:org.egov.pgr.elasticsearch.service.ComplaintIndexService.java
private void prepareMonthlyCallStatCounts(Histogram.Bucket entry, MonthlyFeedbackCounts monthStat) { Terms callStatCountAggr = entry.getAggregations().get(CALL_STATUS_AGGR); BigDecimal nonRespondedCount = ZERO; for (Bucket callStatBucket : callStatCountAggr.getBuckets()) { int callStatus = callStatBucket.getKeyAsNumber().intValue(); if (RESPONDED_WITH_FEEDBACK == callStatus || RESPONDED_WITH_REPEAT_FEEDBACK == callStatus) { monthStat.setRespondedCount(callStatBucket.getDocCount()); prepareMonthlyRatingCount(callStatBucket, monthStat); } else//ww w .j a v a 2 s. c o m nonRespondedCount = nonRespondedCount.add(BigDecimal.valueOf(callStatBucket.getDocCount())); } monthStat.setNonRespondedCount(nonRespondedCount.longValue()); }