List of usage examples for java.math BigDecimal add
public BigDecimal add(BigDecimal augend)
From source file:ch.algotrader.service.PortfolioServiceImpl.java
/** * {@inheritDoc}/*from w w w .jav a2 s .com*/ */ @Override public PortfolioValue getPortfolioValue(final String strategyName, final Date date) { Validate.notEmpty(strategyName, "Strategy name is empty"); Validate.notNull(date, "Date is null"); Strategy strategy = this.strategyDao.findByName(strategyName); BigDecimal cashBalance; BigDecimal marketValue; int positions; if (strategy.isServer()) { cashBalance = getCashBalance(date); marketValue = getMarketValue(date); positions = getOpenPositions(date); } else { cashBalance = getCashBalance(strategyName, date); marketValue = getMarketValue(strategyName, date); positions = getOpenPositions(strategyName, date); } PortfolioValue portfolioValue = PortfolioValue.Factory.newInstance(); portfolioValue.setStrategy(strategy); portfolioValue.setDateTime(date); portfolioValue.setNetLiqValue(marketValue != null ? cashBalance.add(marketValue) : null); portfolioValue.setCashBalance(cashBalance); portfolioValue.setMarketValue(marketValue); portfolioValue.setOpenPositions(positions); return portfolioValue; }
From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRFedNonFedBudgetV1_2Generator.java
private KeyPersons getKeyPersons(BudgetPeriodDto periodInfo) { KeyPersons keyPersons = KeyPersons.Factory.newInstance(); if (periodInfo != null) { if (periodInfo.getKeyPersons() != null) { List<KeyPersonDataType> keyPersonList = new ArrayList<>(); int keyPersonCount = 0; for (KeyPersonDto keyPerson : periodInfo.getKeyPersons()) { if (keyPerson.getRole().equals(NID_PD_PI) || hasPersonnelBudget(keyPerson, periodInfo.getBudgetPeriod())) { KeyPersonDataType keyPersonDataType = KeyPersonDataType.Factory.newInstance(); keyPersonDataType.setName(globLibV20Generator.getHumanNameDataType(keyPerson)); if (keyPerson.getKeyPersonRole() != null) { keyPersonDataType.setProjectRole(keyPerson.getKeyPersonRole()); } else { keyPersonDataType.setProjectRole(keyPerson.getRole()); }//from ww w. ja v a 2 s . c o m keyPersonDataType.setCompensation(getCompensation(keyPerson, periodInfo.getBudgetPeriod())); keyPersonList.add(keyPersonDataType); keyPersonCount++; LOG.info("keyPersonCount:" + keyPersonCount); } } keyPersons.setKeyPersonArray(keyPersonList.toArray(new KeyPersonDataType[0])); } SummaryDataType summary = SummaryDataType.Factory.newInstance(); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setFederalSummary(periodInfo.getTotalFundsKeyPersons().bigDecimalValue()); } if (periodInfo.getTotalNonFundsKeyPersons() != null) { summary.setNonFederalSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setTotalFedNonFedSummary(periodInfo.getTotalFundsKeyPersons() .add(periodInfo.getTotalNonFundsKeyPersons()).bigDecimalValue()); } else { summary.setTotalFedNonFedSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); } } keyPersons.setTotalFundForKeyPersons(summary); SummaryDataType summaryAttachedKey = SummaryDataType.Factory.newInstance(); BigDecimal totalFederalSummary = BigDecimal.ZERO; BigDecimal totalNonFederalSummary = BigDecimal.ZERO; for (KeyPersonDto keyPersonInfo : periodInfo.getExtraKeyPersons()) { totalFederalSummary = totalFederalSummary.add(keyPersonInfo.getFundsRequested().bigDecimalValue()); totalNonFederalSummary = totalNonFederalSummary .add(keyPersonInfo.getNonFundsRequested().bigDecimalValue()); } summaryAttachedKey.setFederalSummary(totalFederalSummary); summaryAttachedKey.setNonFederalSummary(totalNonFederalSummary); summaryAttachedKey.setTotalFedNonFedSummary(totalFederalSummary.add(totalNonFederalSummary)); keyPersons.setTotalFundForAttachedKeyPersons(summaryAttachedKey); } NarrativeContract extraKeyPersonNarr = saveExtraKeyPersons(periodInfo); if (extraKeyPersonNarr != null) { AttachedFileDataType attachedFileDataType = getAttachedFileType(extraKeyPersonNarr); if (attachedFileDataType != null) { keyPersons.setAttachedKeyPersons(attachedFileDataType); } } return keyPersons; }
From source file:com.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils.java
/** * Apply payment charges by category.//from w w w . ja v a 2 s .c o m * * @param opSubscription the op subscription * @param categoryCharge the category charge * @param paymentRequestSet the payment request set * @throws Exception */ private static void applyPaymentChargesByCategory(BillingSubscription.OperatorSubscription opSubscription, CategoryCharge categoryCharge, Set<PaymentRequestDTO> paymentRequestSet) throws Exception { ChargeRate rate = opSubscription.getRate(); TaxDAO taxDAO = new TaxDAO(); List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totalPrice = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; for (PaymentRequestDTO paymentRequest : paymentRequestSet) { totalCharge = totalCharge.add(paymentRequest.getAmount()); BigDecimal price = BigDecimal.ZERO; CategoryEntity rateCategories = new CategoryEntity(); if (rateCategories == null) { throw new APIManagementException( "Payment Categoreis required for QUOTA charging are not specified in rate-card.xml"); } BigDecimal catpercent = rate.getValue().divide(new BigDecimal(100)); Date date = new Date(paymentRequest.getDate().getTime()); for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { // totalTax += taxFraction x paymentAmount totalTax = totalTax.add(tax.getValue().multiply(price)); } } } // Get the percentage from the rate value // apply category wise charge percentage }
From source file:net.sourceforge.fenixedu.domain.reports.TutorshipProgramReportFile.java
@Override public void renderReport(final Spreadsheet spreadsheet) throws Exception { spreadsheet.setHeader("Nmero"); spreadsheet.setHeader("Sexo"); spreadsheet.setHeader("Mdia"); spreadsheet.setHeader("Mdia Anual"); spreadsheet.setHeader("Nmero Inscries"); spreadsheet.setHeader("Nmero Aprovaes"); spreadsheet.setHeader("Nota de Seriao"); spreadsheet.setHeader("Local de Origem"); final ExecutionYear executionYear = getExecutionYear(); for (final Degree degree : Degree.readNotEmptyDegrees()) { if (checkDegreeType(getDegreeType(), degree)) { if (isActive(degree)) { for (final Registration registration : degree.getRegistrationsSet()) { if (registration.isRegistered(getExecutionYear())) { int enrolmentCounter = 0; int aprovalCounter = 0; BigDecimal bigDecimal = null; double totalCredits = 0; for (final Registration otherRegistration : registration.getStudent() .getRegistrationsSet()) { if (otherRegistration.getDegree() == registration.getDegree()) { for (final StudentCurricularPlan studentCurricularPlan : otherRegistration .getStudentCurricularPlansSet()) { for (final Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) { final ExecutionSemester executionSemester = enrolment .getExecutionPeriod(); if (executionSemester.getExecutionYear() == executionYear) { enrolmentCounter++; if (enrolment.isApproved()) { aprovalCounter++; final Grade grade = enrolment.getGrade(); if (grade.isNumeric()) { final double credits = enrolment .getEctsCreditsForCurriculum().doubleValue(); totalCredits += credits; bigDecimal = bigDecimal == null ? grade.getNumericValue() .multiply(new BigDecimal(credits)) : bigDecimal.add(grade.getNumericValue() .multiply(new BigDecimal(credits))); } } } }//from w w w . ja v a2 s .c o m } } } final Row row = spreadsheet.addRow(); row.setCell(registration.getNumber().toString()); row.setCell(registration.getPerson().getGender().toLocalizedString()); row.setCell(registration.getAverage(executionYear)); if (bigDecimal == null) { row.setCell(""); } else { row.setCell( bigDecimal.divide(new BigDecimal(totalCredits), 5, RoundingMode.HALF_UP)); } row.setCell(Integer.toString(enrolmentCounter)); row.setCell(Integer.toString(aprovalCounter)); row.setCell( registration.getEntryGrade() != null ? registration.getEntryGrade().toString() : StringUtils.EMPTY); Boolean dislocated = null; if (registration.getStudentCandidacy() != null) { dislocated = registration.getStudentCandidacy() .getDislocatedFromPermanentResidence(); } final String dislocatedString = dislocated == null ? "" : (dislocated.booleanValue() ? "Deslocado" : "No Deslocado"); row.setCell(dislocatedString); } } } } } }
From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRFedNonFedBudget10V1_1Generator.java
/** * This method gets KeyPersons details such as Name,ProjectRole,Compensation,TotalFundForAttachedKeyPersons * TotalFundForKeyPersons and AttachedKeyPersons based on BudgetPeriodInfo for the RRFedNonFedBudget. * //from w ww.ja v a 2 s . c o m * @param periodInfo (BudgetPeriodInfo) budget period entry. * @return KeyPersons details corresponding to the BudgetPeriodInfo object. */ private KeyPersons getKeyPersons(BudgetPeriodDto periodInfo) { KeyPersons keyPersons = KeyPersons.Factory.newInstance(); if (periodInfo != null) { if (periodInfo.getKeyPersons() != null) { List<KeyPersonDataType> keyPersonList = new ArrayList<>(); int keyPersonCount = 0; for (KeyPersonDto keyPerson : periodInfo.getKeyPersons()) { if (keyPerson.getRole().equals(NID_PD_PI) || hasPersonnelBudget(keyPerson, periodInfo.getBudgetPeriod())) { KeyPersonDataType keyPersonDataType = KeyPersonDataType.Factory.newInstance(); keyPersonDataType.setName(globLibV20Generator.getHumanNameDataType(keyPerson)); if (keyPerson.getKeyPersonRole() != null) { keyPersonDataType.setProjectRole(keyPerson.getKeyPersonRole()); } else { keyPersonDataType.setProjectRole(keyPerson.getRole()); } keyPersonDataType.setCompensation(getCompensation(keyPerson, periodInfo.getBudgetPeriod())); keyPersonList.add(keyPersonDataType); keyPersonCount++; LOG.info("keyPersonCount:" + keyPersonCount); } } keyPersons.setKeyPersonArray(keyPersonList.toArray(new KeyPersonDataType[0])); } SummaryDataType summary = SummaryDataType.Factory.newInstance(); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setFederalSummary(periodInfo.getTotalFundsKeyPersons().bigDecimalValue()); } if (periodInfo.getTotalNonFundsKeyPersons() != null) { summary.setNonFederalSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setTotalFedNonFedSummary(periodInfo.getTotalFundsKeyPersons() .add(periodInfo.getTotalNonFundsKeyPersons()).bigDecimalValue()); } else { summary.setTotalFedNonFedSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); } } keyPersons.setTotalFundForKeyPersons(summary); SummaryDataType summaryAttachedKey = SummaryDataType.Factory.newInstance(); BigDecimal totalFederalSummary = BigDecimal.ZERO; BigDecimal totalNonFederalSummary = BigDecimal.ZERO; for (KeyPersonDto keyPersonInfo : periodInfo.getExtraKeyPersons()) { totalFederalSummary = totalFederalSummary.add(keyPersonInfo.getFundsRequested().bigDecimalValue()); totalNonFederalSummary = totalNonFederalSummary .add(keyPersonInfo.getNonFundsRequested().bigDecimalValue()); } summaryAttachedKey.setFederalSummary(totalFederalSummary); summaryAttachedKey.setNonFederalSummary(totalNonFederalSummary); summaryAttachedKey.setTotalFedNonFedSummary(totalFederalSummary.add(totalNonFederalSummary)); keyPersons.setTotalFundForAttachedKeyPersons(summaryAttachedKey); } NarrativeContract extraKeyPersonNarr = saveExtraKeyPersons(periodInfo); AttachedFileDataType attachedFileDataType = null; if (extraKeyPersonNarr != null) { attachedFileDataType = getAttachedFileType(extraKeyPersonNarr); if (attachedFileDataType != null) { keyPersons.setAttachedKeyPersons(attachedFileDataType); } } return keyPersons; }
From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeDate.java
@Override public EBusDateTime decodeInt(byte[] data) throws EBusTypeException { if (data == null) { // TODO replace value return null; }/*from w w w.j av a2s. c o m*/ IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD); IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD); IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR); Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); BigDecimal day = null; BigDecimal month = null; BigDecimal year = null; if (data.length != getTypeLength()) { throw new EBusTypeException( String.format("Input byte array must have a length of %d bytes!", getTypeLength())); } if (StringUtils.equals(variant, SHORT)) { day = bcdType.decode(new byte[] { data[0] }); month = bcdType.decode(new byte[] { data[1] }); year = bcdType.decode(new byte[] { data[2] }); } else if (StringUtils.equals(variant, DEFAULT)) { day = bcdType.decode(new byte[] { data[0] }); month = bcdType.decode(new byte[] { data[1] }); year = bcdType.decode(new byte[] { data[3] }); } else if (StringUtils.equals(variant, HEX_SHORT)) { day = charType.decode(new byte[] { data[0] }); month = charType.decode(new byte[] { data[1] }); year = charType.decode(new byte[] { data[2] }); } else if (StringUtils.equals(variant, HEX)) { day = charType.decode(new byte[] { data[0] }); month = charType.decode(new byte[] { data[1] }); year = charType.decode(new byte[] { data[3] }); } else if (StringUtils.equals(variant, DAYS)) { BigDecimal daysSince1900 = wordType.decode(data); calendar.set(1900, 0, 1, 0, 0); calendar.add(Calendar.DAY_OF_YEAR, daysSince1900.intValue()); } if (day != null && month != null && year != null) { if (day.intValue() < 1 || day.intValue() > 31) { throw new EBusTypeException("A valid day must be in a range between 1-31 !"); } if (month.intValue() < 1 || month.intValue() > 12) { throw new EBusTypeException("A valid day must be in a range between 1-12 !"); } } if (year != null) { if (year.intValue() < 70) { year = year.add(new BigDecimal(2000)); } else { year = year.add(new BigDecimal(1900)); } calendar.set(Calendar.YEAR, year.intValue()); } if (month != null) { calendar.set(Calendar.MONTH, month.intValue() - 1); } if (day != null && day.intValue() > 0 && day.intValue() < 32) { calendar.set(Calendar.DAY_OF_MONTH, day.intValue()); } return new EBusDateTime(calendar, false, true); }
From source file:com.topsec.tsm.sim.report.util.ReportUiUtil.java
public synchronized static Object sumValue(Object sumValue, Object value) { if (sumValue == null) { sumValue = 0;//from www . j a v a2 s . c om } if (value == null) { return sumValue; } if (sumValue instanceof String) { sumValue = Integer.valueOf((String) sumValue); } if (value instanceof String) { value = Integer.valueOf((String) value); } if (value instanceof Integer) { Integer valueInteger = (Integer) value; Integer sumValueInteger = 0; if (sumValue instanceof Integer) { sumValueInteger = (Integer) sumValue; } else if (sumValue instanceof Long) { sumValueInteger = ((Long) sumValue).intValue(); } else if (sumValue instanceof Float) { sumValueInteger = ((Float) sumValue).intValue(); } else if (sumValue instanceof Double) { sumValueInteger = ((Double) sumValue).intValue(); } sumValueInteger += valueInteger; return sumValueInteger; } else if (value instanceof Long) { Long valueLong = (Long) value; Long sumValueLong = 0L; if (sumValue instanceof Integer) { sumValueLong = ((Integer) sumValue).longValue(); } else if (sumValue instanceof Long) { sumValueLong = (Long) sumValue; } else if (sumValue instanceof Float) { sumValueLong = ((Float) sumValue).longValue(); } else if (sumValue instanceof Double) { sumValueLong = ((Double) sumValue).longValue(); } sumValueLong += valueLong; return sumValueLong; } else if (value instanceof Float) { Float valueFloat = (Float) value; Float sumValueFloat = 0f; if (sumValue instanceof Integer) { sumValueFloat = ((Integer) sumValue).floatValue(); } else if (sumValue instanceof Long) { sumValueFloat = ((Long) sumValue).floatValue(); } else if (sumValue instanceof Float) { sumValueFloat = (Float) sumValue; } else if (sumValue instanceof Double) { sumValueFloat = ((Double) sumValue).floatValue(); } sumValueFloat += valueFloat; return sumValueFloat; } else if (value instanceof Double) { Double valueDouble = (Double) value; Double sumValueDouble = 0D; if (sumValue instanceof Integer) { sumValueDouble = ((Integer) sumValue).doubleValue(); } else if (sumValue instanceof Long) { sumValueDouble = ((Long) sumValue).doubleValue(); } else if (sumValue instanceof Float) { sumValueDouble = ((Float) sumValue).doubleValue(); } else if (sumValue instanceof Double) { sumValueDouble = (Double) sumValue; } sumValueDouble += valueDouble; return sumValueDouble; } else if (value instanceof BigDecimal) { BigDecimal valueDouble = (BigDecimal) value; BigDecimal sumValueBigDecimal = new BigDecimal(0); if (sumValue instanceof Integer) { sumValueBigDecimal = new BigDecimal((Integer) sumValue); } else if (sumValue instanceof Long) { sumValueBigDecimal = new BigDecimal((Long) sumValue); } else if (sumValue instanceof Float) { sumValueBigDecimal = new BigDecimal((Float) sumValue); } else if (sumValue instanceof Double) { sumValueBigDecimal = new BigDecimal((Double) sumValue); } else if (sumValue instanceof BigDecimal) { sumValueBigDecimal = (BigDecimal) sumValue; } sumValueBigDecimal = sumValueBigDecimal.add(valueDouble); return sumValueBigDecimal; } return 0; }
From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRFedNonFedBudgetV1_1Generator.java
/** * This method gets KeyPersons details such as Name,ProjectRole,Compensation,TotalFundForAttachedKeyPersons * TotalFundForKeyPersons and AttachedKeyPersons based on BudgetPeriodInfo for the RRFedNonFedBudget. * /*from ww w . ja v a 2 s. c o m*/ * @param periodInfo (BudgetPeriodInfo) budget period entry. * @return KeyPersons details corresponding to the BudgetPeriodInfo object. */ private KeyPersons getKeyPersons(BudgetPeriodDto periodInfo) { KeyPersons keyPersons = KeyPersons.Factory.newInstance(); if (periodInfo != null) { if (periodInfo.getKeyPersons() != null) { List<KeyPersonDataType> keyPersonList = new ArrayList<>(); int keyPersonCount = 0; for (KeyPersonDto keyPerson : periodInfo.getKeyPersons()) { if (keyPerson.getRole().equals(NID_PD_PI) || hasPersonnelBudget(keyPerson, periodInfo.getBudgetPeriod())) { KeyPersonDataType keyPersonDataType = KeyPersonDataType.Factory.newInstance(); keyPersonDataType.setName(globLibV20Generator.getHumanNameDataType(keyPerson)); if (keyPerson.getKeyPersonRole() != null) { keyPersonDataType.setProjectRole(keyPerson.getKeyPersonRole()); } else { keyPersonDataType.setProjectRole(keyPerson.getRole()); } keyPersonDataType.setCompensation(getCompensation(keyPerson, periodInfo.getBudgetPeriod())); keyPersonList.add(keyPersonDataType); keyPersonCount++; LOG.info("keyPersonCount:" + keyPersonCount); } } keyPersons.setKeyPersonArray(keyPersonList.toArray(new KeyPersonDataType[0])); } SummaryDataType summary = SummaryDataType.Factory.newInstance(); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setFederalSummary(periodInfo.getTotalFundsKeyPersons().bigDecimalValue()); } if (periodInfo.getTotalNonFundsKeyPersons() != null) { summary.setNonFederalSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); if (periodInfo.getTotalFundsKeyPersons() != null) { summary.setTotalFedNonFedSummary(periodInfo.getTotalFundsKeyPersons() .add(periodInfo.getTotalNonFundsKeyPersons()).bigDecimalValue()); } else { summary.setTotalFedNonFedSummary(periodInfo.getTotalNonFundsKeyPersons().bigDecimalValue()); } } keyPersons.setTotalFundForKeyPersons(summary); SummaryDataType summaryAttachedKey = SummaryDataType.Factory.newInstance(); BigDecimal totalFederalSummary = BigDecimal.ZERO; BigDecimal totalNonFederalSummary = BigDecimal.ZERO; for (KeyPersonDto keyPersonInfo : periodInfo.getExtraKeyPersons()) { totalFederalSummary = totalFederalSummary.add(keyPersonInfo.getFundsRequested().bigDecimalValue()); totalNonFederalSummary = totalNonFederalSummary .add(keyPersonInfo.getNonFundsRequested().bigDecimalValue()); } summaryAttachedKey.setFederalSummary(totalFederalSummary); summaryAttachedKey.setNonFederalSummary(totalNonFederalSummary); summaryAttachedKey.setTotalFedNonFedSummary(totalFederalSummary.add(totalNonFederalSummary)); keyPersons.setTotalFundForAttachedKeyPersons(summaryAttachedKey); } NarrativeContract extraKeyPersonNarr = saveExtraKeyPersons(periodInfo); AttachedFileDataType attachedFileDataType = null; if (extraKeyPersonNarr != null) { attachedFileDataType = getAttachedFileType(extraKeyPersonNarr); if (attachedFileDataType != null) { keyPersons.setAttachedKeyPersons(attachedFileDataType); } } return keyPersons; }
From source file:com.osafe.events.CheckOutEvents.java
public static String setShipGroups(HttpServletRequest request, HttpServletResponse response) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); Delegator delegator = (Delegator) request.getAttribute("delegator"); Locale locale = UtilHttp.getLocale(request); ShoppingCart shoppingCart = ShoppingCartEvents.getCartObject(request); String sItemTotalQty = request.getParameter("itemTotalQuantity"); String sNumberOfItems = request.getParameter("numberOfItems"); int iNumberOfItems = Integer.valueOf(sNumberOfItems); int iItemTotalQty = 0; BigDecimal bcartItemTotalQty = shoppingCart.getTotalQuantity(); Map shippingContactMechMap = FastMap.newInstance(); Map cartLineShippingContactMechQtyMap = FastMap.newInstance(); Map cartLineShippingContactMechGiftMsgMap = FastMap.newInstance(); Map cartLineQtyMap = FastMap.newInstance(); Map cartLineProductInfoMap = FastMap.newInstance(); Map cartItemQtyMap = FastMap.newInstance(); List<MessageString> error_list = new ArrayList<MessageString>(); MessageString messageString = null;/*from w w w. j av a2s .co m*/ String message = null; if (UtilValidate.isNotEmpty(sItemTotalQty)) { iItemTotalQty = Integer.valueOf(sItemTotalQty).intValue(); } /* Build quantity-product maps based on items on page */ for (int i = 0; i < iItemTotalQty; i++) { String shippingContactMechId = request.getParameter("shippingContactMechId_" + i); String sCartLineIndex = request.getParameter("cartLineIndex_" + i); int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue(); String qtyInCart = request.getParameter("qtyInCart_" + i); String productName = request.getParameter("productName_" + i); String productId = request.getParameter("productId_" + i); String productCategoryId = request.getParameter("productCategoryId_" + i); String prodCatalogId = request.getParameter("prodCatelogId_" + i); String unitPrice = request.getParameter("unitPrice_" + i); Map productInfoMap = FastMap.newInstance(); productInfoMap.put("productName", productName); productInfoMap.put("productId", productId); productInfoMap.put("productCategoryId", productCategoryId); productInfoMap.put("prodCatalogId", prodCatalogId); productInfoMap.put("unitPrice", unitPrice); String giftMsgFrom = request.getParameter("lineItemGiftFrom_" + i); String giftMsgTo = request.getParameter("lineItemGiftTo_" + i); String giftMsg = request.getParameter("lineItemGiftMsg_" + i); Map giftMessageInfoMap = FastMap.newInstance(); if (UtilValidate.isNotEmpty(giftMsgFrom)) { giftMessageInfoMap.put("from", giftMsgFrom); } if (UtilValidate.isNotEmpty(giftMsgTo)) { giftMessageInfoMap.put("to", giftMsgTo); } if (UtilValidate.isNotEmpty(giftMsg)) { giftMessageInfoMap.put("msg", giftMsg); } BigDecimal bLineQty = BigDecimal.ZERO; BigDecimal bShipQty = BigDecimal.ZERO; BigDecimal bCartQty = BigDecimal.ZERO; try { if (UtilValidate.isNotEmpty(qtyInCart)) { Double dQty = Double.valueOf(qtyInCart); if (UtilValidate.isInteger(qtyInCart) && dQty >= 0) { bLineQty = BigDecimal.valueOf(dQty.doubleValue()); } else { bLineQty = BigDecimal.ZERO; message = OSAFE_UI_LABELS.getString("PDPQtyDecimalNumberError"); message = StringUtil.replaceString(message, "_PRODUCT_NAME_", productName); messageString = new MessageString(message, "qtyInCart_" + i, true); error_list.add(messageString); } } } catch (Exception e) { bLineQty = BigDecimal.ZERO; message = OSAFE_UI_LABELS.getString("PDPQtyDecimalNumberError"); message = StringUtil.replaceString(message, "_PRODUCT_NAME_", productName); messageString = new MessageString(message, "qtyInCart_" + i, true); error_list.add(messageString); } shippingContactMechMap.put(shippingContactMechId, shippingContactMechId); if (cartLineShippingContactMechQtyMap.containsKey(sCartLineIndex + "_" + shippingContactMechId)) { BigDecimal bTempQty = (BigDecimal) cartLineShippingContactMechQtyMap .get(sCartLineIndex + "_" + shippingContactMechId); bShipQty = bShipQty.add(bTempQty); } bShipQty = bShipQty.add(bLineQty); cartLineShippingContactMechQtyMap.put(sCartLineIndex + "_" + shippingContactMechId, bShipQty); if (UtilValidate.isNotEmpty(giftMessageInfoMap)) { List lGiftMsg = null; if (cartLineShippingContactMechGiftMsgMap .containsKey(sCartLineIndex + "_" + shippingContactMechId)) { lGiftMsg = (List) cartLineShippingContactMechGiftMsgMap .get(sCartLineIndex + "_" + shippingContactMechId); } else { lGiftMsg = FastList.newInstance(); } lGiftMsg.add(giftMessageInfoMap); cartLineShippingContactMechGiftMsgMap.put(sCartLineIndex + "_" + shippingContactMechId, lGiftMsg); } if (cartLineQtyMap.containsKey(sCartLineIndex)) { BigDecimal bTempQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex); bCartQty = bCartQty.add(bTempQty); } bCartQty = bCartQty.add(bLineQty); cartLineQtyMap.put(sCartLineIndex, bCartQty); cartLineProductInfoMap.put(sCartLineIndex, productInfoMap); } /* Validate Quantities entered */ if (UtilValidate.isNotEmpty(cartLineQtyMap)) { try { String pdpQtyMin = Util.getProductStoreParm(request, "PDP_QTY_MIN"); if (UtilValidate.isEmpty(pdpQtyMin)) { pdpQtyMin = "1"; } String pdpQtyMax = Util.getProductStoreParm(request, "PDP_QTY_MAX"); if (UtilValidate.isEmpty(pdpQtyMax)) { pdpQtyMax = "99"; } BigDecimal bPdpQtyMin = BigDecimal.valueOf(Double.valueOf(pdpQtyMin).doubleValue()); BigDecimal bPdpQtyMax = BigDecimal.valueOf(Double.valueOf(pdpQtyMax).doubleValue()); Iterator<String> cartItemIter = cartLineQtyMap.keySet().iterator(); while (cartItemIter.hasNext()) { String sCartLineIndex = cartItemIter.next(); BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex); if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) { continue; } int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue(); Map productInfoMap = (Map) cartLineProductInfoMap.get(sCartLineIndex); GenericValue prodPdpQtyMin = delegator.findOne("ProductAttribute", UtilMisc.toMap("productId", productInfoMap.get("productId"), "attrName", "PDP_QTY_MIN"), true); GenericValue prodPdpQtyMax = delegator.findOne("ProductAttribute", UtilMisc.toMap("productId", productInfoMap.get("productId"), "attrName", "PDP_QTY_MAX"), true); if (UtilValidate.isNotEmpty(prodPdpQtyMin) && UtilValidate.isNotEmpty(prodPdpQtyMax)) { bPdpQtyMin = BigDecimal .valueOf(Double.valueOf(prodPdpQtyMin.getString("attrValue")).doubleValue()); bPdpQtyMax = BigDecimal .valueOf(Double.valueOf(prodPdpQtyMax.getString("attrValue")).doubleValue()); } if (bChangeQty.compareTo(bPdpQtyMin) < 0) { message = OSAFE_UI_LABELS.getString("PDPMinQtyError"); message = StringUtil.replaceString(message, "_PRODUCT_NAME_", "" + productInfoMap.get("productName")); message = StringUtil.replaceString(message, "_PDP_QTY_MIN_", "" + bPdpQtyMin.intValue()); messageString = new MessageString(message, "qtyInCart_" + sCartLineIndex, true); error_list.add(messageString); } if (bChangeQty.compareTo(bPdpQtyMax) > 0) { message = OSAFE_UI_LABELS.getString("PDPMaxQtyError"); message = StringUtil.replaceString(message, "_PRODUCT_NAME_", "" + productInfoMap.get("productName")); message = StringUtil.replaceString(message, "_PDP_QTY_MAX_", "" + bPdpQtyMax.intValue()); messageString = new MessageString(message, "qtyInCart_" + sCartLineIndex, true); error_list.add(messageString); } } } catch (Exception e) { Debug.logError(e, "Error: updating cart quantity", module); } } if (error_list.size() != 0) { request.setAttribute("_ERROR_MESSAGE_LIST_", error_list); return "error"; } /* Check the number of items passed from the screen matches the number of items in the cart. * If the number of items has changed remove all products from the cart and add back. * If the number of items have not changed remove zero quantities and set changed item quantities * The number of item check is essentially protecting against the usage of the back button. */ if (UtilValidate.isNotEmpty(cartLineQtyMap)) { if (shoppingCart.items().size() != iNumberOfItems) { ShoppingCartItem shoppingCartItem = null; try { Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator(); while (cartItemIter.hasNext()) { shoppingCartItem = (ShoppingCartItem) cartItemIter.next(); shoppingCart.removeCartItem(shoppingCartItem, dispatcher); } Iterator<String> cartLineItemIter = cartLineQtyMap.keySet().iterator(); while (cartLineItemIter.hasNext()) { String sCartLineIndex = cartLineItemIter.next(); BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex); if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) { continue; } Map productInfoMap = (Map) cartLineProductInfoMap.get(sCartLineIndex); String unitPrice = (String) productInfoMap.get("unitPrice"); BigDecimal bUnitPrice = null; if (UtilValidate.isNotEmpty(unitPrice)) { bUnitPrice = BigDecimal.valueOf(Double.valueOf(unitPrice).doubleValue()); } if (UtilValidate.isEmpty(bUnitPrice)) { message = OSAFE_UI_LABELS.getString("PDPMaxQtyError"); error_list.add(messageString); request.setAttribute("_ERROR_MESSAGE_LIST_", error_list); return "error"; } ShoppingCartItem item = ShoppingCartItem.makeItem(null, "" + productInfoMap.get("productId"), null, bChangeQty, bUnitPrice, null, null, null, null, null, null, null, null, null, "" + productInfoMap.get("prodCatelogId"), null, null, null, dispatcher, shoppingCart, Boolean.TRUE, Boolean.FALSE, "" + productInfoMap.get("parentProductId"), Boolean.TRUE, Boolean.TRUE); shoppingCart.addItemToEnd(item); com.osafe.events.ShoppingCartEvents.setProductFeaturesOnCart(shoppingCart, "" + productInfoMap.get("productId")); } } catch (Exception e) { Debug.logError("Error: removing cart item" + shoppingCartItem, module); } } else { try { Iterator<String> cartItemIter = cartLineQtyMap.keySet().iterator(); while (cartItemIter.hasNext()) { String sCartLineIndex = cartItemIter.next(); BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex); int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue(); ShoppingCartItem shoppingCartItem = shoppingCart.findCartItem(iCartLineIndex); if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) { shoppingCart.removeCartItem(shoppingCartItem, dispatcher); continue; } if (bChangeQty.compareTo(shoppingCartItem.getQuantity()) != 0) { shoppingCartItem.setQuantity(bChangeQty, dispatcher, shoppingCart); } } } catch (Exception e) { Debug.logError("Error: updating cart quantity", module); } } } if (UtilValidate.isNotEmpty(shoppingCart.items())) { Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator(); int iItemIndex = 0; while (cartItemIter.hasNext()) { ShoppingCartItem shoppingCartItem = (ShoppingCartItem) cartItemIter.next(); BigDecimal itemQuantity = shoppingCartItem.getQuantity(); cartItemQtyMap.put("" + iItemIndex, itemQuantity); iItemIndex++; /* Clear Gift Messages per item. Will be Reset * */ Map<String, String> orderItemAttributesMap = shoppingCartItem.getOrderItemAttributes(); if (UtilValidate.isNotEmpty(orderItemAttributesMap)) { for (Entry<String, String> itemAttr : orderItemAttributesMap.entrySet()) { String sAttrName = (String) itemAttr.getKey(); if (sAttrName.startsWith("GIFT_MSG_FROM_")) { shoppingCartItem.removeOrderItemAttribute(sAttrName); } if (sAttrName.startsWith("GIFT_MSG_TO_")) { shoppingCartItem.removeOrderItemAttribute(sAttrName); } if (sAttrName.startsWith("GIFT_MSG_TEXT_")) { shoppingCartItem.removeOrderItemAttribute(sAttrName); } } } } } else { return "emptyCart"; } /* Clear item Ship Groups and create new ones */ if (UtilValidate.isNotEmpty(shippingContactMechMap)) { Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator(); while (cartItemIter.hasNext()) { shoppingCart.clearItemShipInfo(cartItemIter.next()); } shoppingCart.cleanUpShipGroups(); Iterator<String> shipGroupIter = shippingContactMechMap.keySet().iterator(); while (shipGroupIter.hasNext()) { int shipGroupIndex = shoppingCart.addShipInfo(); String shippingContactMechId = shipGroupIter.next(); shoppingCart.setShippingContactMechId(shipGroupIndex, shippingContactMechId); shippingContactMechMap.put(shippingContactMechId, Integer.valueOf(shipGroupIndex)); } } if (UtilValidate.isNotEmpty(cartLineShippingContactMechQtyMap)) { Map<ShoppingCartItem, String> cartItemMessageCount = FastMap.newInstance(); Iterator<String> cartLineShippingQtyIter = cartLineShippingContactMechQtyMap.keySet().iterator(); while (cartLineShippingQtyIter.hasNext()) { String cartLineShippingContactMechKey = cartLineShippingQtyIter.next(); int iKeySeparator = cartLineShippingContactMechKey.indexOf('_'); String sCartLineIndex = cartLineShippingContactMechKey.substring(0, iKeySeparator); int iCartLineIndex = Integer.valueOf(sCartLineIndex); int iItemGiftMsgCount = 0; String shippingContactMechId = cartLineShippingContactMechKey.substring(iKeySeparator + 1); BigDecimal bShipQty = (BigDecimal) cartLineShippingContactMechQtyMap .get(cartLineShippingContactMechKey); BigDecimal bCartItemQty = (BigDecimal) cartItemQtyMap.get(sCartLineIndex); BigDecimal bCartQty = BigDecimal.ZERO; if (UtilValidate.isNotEmpty(bCartItemQty)) { bCartQty = bCartItemQty; } BigDecimal bTotalShipGroupQty = BigDecimal.ZERO; BigDecimal bAddShipQty = BigDecimal.ZERO; if (bShipQty.compareTo(BigDecimal.ZERO) > 0) { Map shipGroupQtyMap = shoppingCart.getShipGroups(iCartLineIndex); Iterator shipGroupQtyIter = shipGroupQtyMap.keySet().iterator(); while (shipGroupQtyIter.hasNext()) { BigDecimal bShipGroupQty = (BigDecimal) shipGroupQtyMap.get(shipGroupQtyIter.next()); bTotalShipGroupQty = bTotalShipGroupQty.add(bShipGroupQty); } /* Total quantity designated to Ship has already been met */ if (bTotalShipGroupQty.compareTo(bCartQty) == 0) { continue; } /* If the ship quantity is greater than the quantity in the cart, set the ship quantity equal to cart quantity. */ if (bShipQty.compareTo(bCartQty) > 0) { bShipQty = bCartQty; } /* Add the Ship quantity to total ship quantity, If greater set the ship quantity to the quantity left that can be shipped * (cart quantity minus total ship quantity) */ bAddShipQty = bShipQty.add(bTotalShipGroupQty); if (bAddShipQty.compareTo(bCartQty) > 0) { bShipQty = bCartQty.subtract(bTotalShipGroupQty); } if (bShipQty.compareTo(BigDecimal.ZERO) > 0) { int shipGroupIndex = ((Integer) shippingContactMechMap.get(shippingContactMechId)) .intValue(); shoppingCart.setItemShipGroupQty(iCartLineIndex, bShipQty, shipGroupIndex); /* Check Cart item Gift Messages going to this Ship Group (Address) * */ List lGiftMsg = (List) cartLineShippingContactMechGiftMsgMap .get(cartLineShippingContactMechKey); if (UtilValidate.isNotEmpty(lGiftMsg)) { ShoppingCartItem cartItem = shoppingCart.findCartItem(iCartLineIndex); for (int i = 0; i < lGiftMsg.size(); i++) { if (i > bShipQty.intValue()) { break; } String sItemGiftMsgCount = (String) cartItemMessageCount.get(cartItem); if (UtilValidate.isEmpty(sItemGiftMsgCount)) { iItemGiftMsgCount = 1; } else { iItemGiftMsgCount = Integer.valueOf(sItemGiftMsgCount); iItemGiftMsgCount++; } sItemGiftMsgCount = "" + iItemGiftMsgCount; cartItemMessageCount.put(cartItem, sItemGiftMsgCount); Map giftMsgMap = (Map) lGiftMsg.get(i); String msgFrom = (String) giftMsgMap.get("from"); if (UtilValidate.isNotEmpty(msgFrom)) { cartItem.setOrderItemAttribute( "GIFT_MSG_FROM_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1), msgFrom); } String msgTo = (String) giftMsgMap.get("to"); if (UtilValidate.isNotEmpty(msgTo)) { cartItem.setOrderItemAttribute( "GIFT_MSG_TO_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1), msgTo); } String msg = (String) giftMsgMap.get("msg"); if (UtilValidate.isNotEmpty(msg)) { cartItem.setOrderItemAttribute( "GIFT_MSG_TEXT_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1), msg); } } } } } } /* Now check all quantities of each cart items have been assigned to a ship group * If not calculate and add the missing quantity to the last ship group defined for the item * */ Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator(); while (cartItemIter.hasNext()) { ShoppingCartItem shoppingCartItem = (ShoppingCartItem) cartItemIter.next(); BigDecimal bTotalShipGroupQty = BigDecimal.ZERO; BigDecimal bCartQty = shoppingCartItem.getQuantity(); BigDecimal bShipGroupQty = BigDecimal.ZERO; int iShipGroupIndex = 0; Map shipGroupQtyMap = shoppingCart.getShipGroups(shoppingCartItem); Iterator shipGroupQtyIter = shipGroupQtyMap.keySet().iterator(); while (shipGroupQtyIter.hasNext()) { iShipGroupIndex = Integer.valueOf(shipGroupQtyIter.next().toString()); bShipGroupQty = (BigDecimal) shipGroupQtyMap.get(iShipGroupIndex); bTotalShipGroupQty = bTotalShipGroupQty.add(bShipGroupQty); } if (bTotalShipGroupQty.compareTo(bCartQty) < 0) { BigDecimal bAddShipQty = bCartQty.subtract(bTotalShipGroupQty); bAddShipQty = bAddShipQty.add(bShipGroupQty); shoppingCart.setItemShipGroupQty(shoppingCartItem, bAddShipQty, iShipGroupIndex); } } /* Clean up ship groups, if no quantities in group the group is removed. * If not calculate and add the missing quantity to the last ship group defined for the item * */ shoppingCart.cleanUpShipGroups(); /* Check ship group with multiple items, if more than one item in the group check * the shipping options available for each item,; if different count the group is split. * */ splitShipGroupByShipOptions(request, response); } return "success"; }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply charges for payment api./*from w w w . j a va 2 s.c o m*/ * * @param opSubscription the op subscription * @param paymentRequestSet the payment request set * @param categoryEntry the category entry * @param appId the app id * @param apiId the api id * @param subId the sub id * @throws Exception */ private static void applyChargesForPaymentApi(BillingSubscription.OperatorSubscription opSubscription, Set<PaymentRequestDTO> paymentRequestSet, Map.Entry<CategoryCharge, BilledCharge> categoryEntry, int appId, int apiId, String subId) throws Exception { ChargeRate rate = opSubscription.getRate(); String billCategory = categoryEntry.getKey().getCategory(); String billSubCategory = categoryEntry.getKey().getSubcategory(); BigDecimal billRate = rate.getValue(); boolean CategoryBased = rate.getCategoryBasedVal(); TaxDAO taxDAO = new TaxDAO(); List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); Map<String, CommissionPercentagesDTO> commisionMap = null; BillingDAO billingDAO = new BillingDAO(); if (!CategoryBased) { commisionMap = billingDAO.getCommissionPercentages(subId, appId); } BigDecimal totalspcom = BigDecimal.ZERO; BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totaladscom = BigDecimal.ZERO; BigDecimal totalopcom = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; // get this flag from rate card for (PaymentRequestDTO paymentRequest : paymentRequestSet) { totalCharge = totalCharge.add(paymentRequest.getAmount()); BigDecimal spcom = BigDecimal.ZERO; BigDecimal adscom = BigDecimal.ZERO; BigDecimal opcom = BigDecimal.ZERO; String category = paymentRequest.getCategory(); String subcategory = paymentRequest.getSubcategory(); String merchant = paymentRequest.getMerchant(); BigDecimal adscomPercnt = rate.getCommission().getAdsCommission().divide(new BigDecimal(100)); BigDecimal spcomPercnt = rate.getCommission().getSpCommission().divide(new BigDecimal(100)); BigDecimal opcomPercnt = rate.getCommission().getOpcoCommission().divide(new BigDecimal(100)); if (CategoryBased) { Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory); if (SubsRate != null) { RateCommission commisionRates = (RateCommission) SubsRate; adscomPercnt = commisionRates.getAdsCommission().divide(new BigDecimal(100)); spcomPercnt = commisionRates.getSpCommission().divide(new BigDecimal(100)); opcomPercnt = commisionRates.getOpcoCommission().divide(new BigDecimal(100)); } } else { if (commisionMap.containsKey(merchant)) { adscomPercnt = commisionMap.get(merchant).getAdsCommission().divide(new BigDecimal(100)); spcomPercnt = commisionMap.get(merchant).getSpCommission().divide(new BigDecimal(100)); opcomPercnt = commisionMap.get(merchant).getOpcoCommission().divide(new BigDecimal(100)); } else { throw new APIManagementException( "Payment Categoreis required for MERCHANT based charging are not specified in rate-card.xml"); } } spcom = paymentRequest.getAmount().multiply(spcomPercnt); totalspcom = totalspcom.add(spcom); opcom = paymentRequest.getAmount().multiply(opcomPercnt); totalopcom = totalopcom.add(opcom); adscom = paymentRequest.getAmount().multiply(adscomPercnt); totaladscom = totaladscom.add(adscom); Date date = new Date(paymentRequest.getDate().getTime()); BigDecimal totalReqTax = BigDecimal.ZERO; for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { // totalTax += taxFraction x paymentAmount totalReqTax = totalReqTax.add(tax.getValue().multiply(paymentRequest.getAmount())); } } totalTax = totalTax.add(totalReqTax); if (!CategoryBased) { if (opSubscription.getMerchantCharges().containsKey(merchant)) { opSubscription.getMerchantCharges().get(merchant).addAdscom(adscom); opSubscription.getMerchantCharges().get(merchant).addOpcom(opcom); opSubscription.getMerchantCharges().get(merchant).addSpcom(spcom); opSubscription.getMerchantCharges().get(merchant).addPrice(spcom); opSubscription.getMerchantCharges().get(merchant).addTax(totalReqTax); opSubscription.getMerchantCharges().get(merchant).addCount(1); } else { BilledCharge billedCharge = new BilledCharge(0); billedCharge.addAdscom(adscom); billedCharge.addOpcom(opcom); billedCharge.addSpcom(spcom); billedCharge.addPrice(spcom); billedCharge.addTax(totalReqTax); billedCharge.addCount(1); opSubscription.getMerchantCharges().put(merchant, billedCharge); } } } // Get the percentage from the rate value // BigDecimal percentage = rate.getValue().divide(new BigDecimal(100)); // apply category wise charge percentage // BigDecimal price = totalCharge.multiply(percentage); // if (CategoryBased) { categoryEntry.getValue().addAdscom(totaladscom); categoryEntry.getValue().addOpcom(totalopcom); categoryEntry.getValue().addSpcom(totalspcom); categoryEntry.getValue().addPrice(totalspcom); categoryEntry.getValue().setTax(totalTax); // } }