List of usage examples for java.math BigDecimal ROUND_CEILING
int ROUND_CEILING
To view the source code for java.math BigDecimal ROUND_CEILING.
Click Source Link
From source file:com.loadsensing.app.Chart.java
private void generaChart(WebView googleChartView, int checkedId, String SensorSelected) { SharedPreferences settings = getSharedPreferences("LoadSensingApp", Context.MODE_PRIVATE); String address = SERVER_HOST + "?session=" + settings.getString("session", "") + "&id=" + SensorSelected + "&TipusGrafic=" + checkedId; ArrayList<HashMap<String, String>> valorsURL = new ArrayList<HashMap<String, String>>(); try {/*ww w. ja va 2 s . c om*/ String jsonString = JsonClient.connectString(address); // Convertim la resposta string a un JSONArray JSONArray ValorsGrafica = new JSONArray(jsonString); // En esta llamada slo hay 1 objeto JSONObject Valors = new JSONObject(); Valors = ValorsGrafica.getJSONObject(0); String grafica = Valors.getString("ValorsGrafica"); // Sobre el string de ValorGrafica, volvemos a parsearlo JSONArray ValorGrafica = new JSONArray(grafica); for (int i = 0; i < ValorGrafica.length(); i++) { JSONObject Valor = new JSONObject(); Valor = ValorGrafica.getJSONObject(i); HashMap<String, String> valorHashMap = new HashMap<String, String>(); valorHashMap.put("date", Valor.getString("date")); valorHashMap.put("value", Valor.getString("value")); valorsURL.add(valorHashMap); } } catch (Exception e) { Log.d(DEB_TAG, "Error rebent xarxes"); } // Montamos URL String mUrl = CHART_URL; // Etiquetas eje X, columna 0 y 1 mUrl = mUrl + "chxl=0:"; for (int i = 3; i < valorsURL.size(); i += 4) { mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date")); } mUrl = mUrl + "|Fecha"; mUrl = mUrl + "|1:"; for (int i = 1; i < valorsURL.size(); i += 4) { mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date")); } // Posicin etiquetas eje Y mUrl = mUrl + "&chxp=0,30,70,110|1,10,50,90"; // Rango x,y // Coger valor mnimo y mximo float max = new Float(valorsURL.get(0).get("value")); float min = new Float(valorsURL.get(0).get("value")); for (int i = 1; i < valorsURL.size(); i++) { Float valueFloat = new Float(valorsURL.get(i).get("value")); max = Math.max(max, valueFloat); min = Math.min(min, valueFloat); } BigDecimal maxRounded = new BigDecimal(max); maxRounded = maxRounded.setScale(1, BigDecimal.ROUND_CEILING); BigDecimal minRounded = new BigDecimal(min); minRounded = minRounded.setScale(1, BigDecimal.ROUND_FLOOR); mUrl = mUrl + "&chxr=0,-5,110|1,-5,110|2," + minRounded + "," + maxRounded; // Ejes visibles mUrl = mUrl + "&chxt=x,x,y"; // Tipo de grfico mUrl = mUrl + "&cht=lxy"; // Medida del grfico Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth() - 170; int height = display.getHeight() - 390; mUrl = mUrl + "&chs=" + width + "x" + height; // Colores mUrl = mUrl + "&chco=3072F3"; // Escala mUrl = mUrl + "&chds=0,9," + minRounded + "," + maxRounded; // Valores mUrl = mUrl + "&chd=t:0"; for (int i = 1; i < valorsURL.size(); i++) { mUrl = mUrl + "," + i; } mUrl = mUrl + "|"; mUrl = mUrl + valorsURL.get(0).get("value"); for (int i = 1; i < valorsURL.size(); i++) { mUrl = mUrl + "," + valorsURL.get(i).get("value"); } // Ttulo eyenda switch (checkedId) { case R.id.radio1: mUrl = mUrl + "&chdl=Sensor+strain+(V)&chdlp=b"; break; case R.id.radio2: mUrl = mUrl + "&chdl=Excitation+power+(V)&chdlp=b"; break; case R.id.radio3: mUrl = mUrl + "&chdl=Counter+(cnts)&chdlp=b"; break; } // Estilo de lineas mUrl = mUrl + "&chls=2"; // Mrgenes mUrl = mUrl + "&chma=0,5,5,25|5"; // Marcador mUrl = mUrl + "&chm=r,FF0000,0,0,0"; Log.d(DEB_TAG, "URL Chart " + mUrl); googleChartView.loadUrl(mUrl); }
From source file:org.egov.utils.BudgetDetailHelper.java
public void populateData(final BudgetAmountView amountDisplay, final Map<String, Object> paramMap, final Date asOnDate, final boolean isRe) { final Date previousYear = subtractYear(asOnDate); final String actualsFor = getActualsFor(paramMap, previousYear); amountDisplay//from w ww .j a v a2 s. co m .setPreviousYearActuals(actualsFor == null ? BigDecimal.ZERO.setScale(0, BigDecimal.ROUND_CEILING) : new BigDecimal(actualsFor).setScale(0, BigDecimal.ROUND_CEILING)); amountDisplay.setOldActuals(getActualsFor(paramMap, subtractYear(previousYear))); final String currentYearActuals = getActualsFor(paramMap, asOnDate); amountDisplay.setCurrentYearBeActuals(currentYearActuals == null ? BigDecimal.ZERO.setScale(2) : new BigDecimal(currentYearActuals).setScale(0, BigDecimal.ROUND_CEILING)); }
From source file:ch.algotrader.service.algo.VariableIncrementalOrderService.java
public void adjustLimit(final VariableIncrementalOrder algoOrder) throws ReflectiveOperationException { Optional<VariableIncrementalOrderStateVO> optional = getAlgoOrderState(algoOrder); if (optional.isPresent()) { VariableIncrementalOrderStateVO orderState = optional.get(); // check limit if (!checkLimit(algoOrder, orderState)) { cancelOrder(algoOrder);//from w w w. j av a 2s. co m return; } SecurityFamily family = algoOrder.getSecurity().getSecurityFamily(); if (algoOrder.getSide().equals(Side.BUY)) { double tickSize = family.getTickSize(null, orderState.getCurrentLimit().doubleValue(), true); double increment = RoundUtil.roundToNextN(orderState.getIncrement(), tickSize, BigDecimal.ROUND_CEILING); BigDecimal roundedIncrement = RoundUtil.getBigDecimal(increment, family.getScale(null)); orderState.setCurrentLimit(orderState.getCurrentLimit().add(roundedIncrement)); } else { double tickSize = family.getTickSize(null, orderState.getCurrentLimit().doubleValue(), false); double increment = RoundUtil.roundToNextN(orderState.getIncrement(), tickSize, BigDecimal.ROUND_CEILING); BigDecimal roundedIncrement = RoundUtil.getBigDecimal(increment, family.getScale(null)); orderState.setCurrentLimit(orderState.getCurrentLimit().subtract(roundedIncrement)); } LimitOrder modifiedOrder = (LimitOrder) BeanUtils.cloneBean(orderState.getLimitOrder()); modifiedOrder.setId(0L); modifiedOrder.setLimit(orderState.getCurrentLimit()); this.simpleOrderService.modifyOrder(modifiedOrder); } }
From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.FiskInfoUtility.java
/** * Truncates a double value to the number of decimals given * * @param number/*w w w. j a v a 2s.c o m*/ * The number to truncate * @param numberofDecimals * Number of decimals of the truncated number * @return * The truncated number. */ @SuppressWarnings("unused") public Double truncateDecimal(double number, int numberofDecimals) { if (number > 0) { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR) .doubleValue(); } else { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING) .doubleValue(); } }
From source file:org.kuali.ole.select.document.web.struts.OlePaymentRequestAction.java
/** * @see org.kuali.ole.module.purap.document.web.struts.AccountsPayableActionBase#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from ww w . j a v a 2s. co m @Override public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { /*ActionForward forward = super.calculate(mapping, form, request, response);*/ /* calculateCurrency(mapping, form, request, response); */ PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems(); for (PurApItem purApItem : purApItems) { List<KualiDecimal> existingAmount = new ArrayList<>(); for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof PaymentRequestAccount) { if (((PaymentRequestAccount) oldSourceAccountingLine).getExistingAmount() != null) { existingAmount.add(((PaymentRequestAccount) oldSourceAccountingLine).getExistingAmount()); } } } int count = 0; for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (account.getAmount() != null && count < existingAmount.size() && existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) { KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount() .multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString()); account.setAccountLinePercent(calculatedPercent.bigDecimalValue() .setScale(OLEConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING)); } else { if (account.getAccountLinePercent().intValue() == 100 && (account.getAmount() == null || account.getAccount() != null)) { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } else { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } } count++; } for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof PaymentRequestAccount) { ((PaymentRequestAccount) oldSourceAccountingLine) .setExistingAmount(oldSourceAccountingLine.getAmount()); } } } OlePaymentRequestForm paymentForm = (OlePaymentRequestForm) form; OlePaymentRequestDocument payDoc = (OlePaymentRequestDocument) paymentForm.getDocument(); Map invMap = new HashMap(); if (payDoc.getInvoiceIdentifier() != null) { invMap.put(PurapConstants.PRQSDocumentsStrings.INV_ID, payDoc.getInvoiceIdentifier()); payDoc.getInvoiceIdentifier(); OleInvoiceDocument oleInvoice = SpringContext .getBean(org.kuali.rice.krad.service.BusinessObjectService.class) .findByPrimaryKey(OleInvoiceDocument.class, invMap); payDoc.setProrateBy(oleInvoice.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : oleInvoice.isProrateManual() ? OLEConstants.MANUAL_PRORATE : oleInvoice.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : oleInvoice.isNoProrate() ? OLEConstants.NO_PRORATE : OLEConstants.DEFAULT_PRORATE_BY_INVOICE); List<OleInvoiceItem> item = oleInvoice.getItems(); for (int i = 0; item.size() > i; i++) { OleInvoiceItem items = (OleInvoiceItem) oleInvoice.getItem(i); if (items.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_FREIGHT_CODE) && LOG.isDebugEnabled()) { LOG.debug("Item Type Code >>>>>>>>>>>" + items.getItemTypeCode()); LOG.debug("items.getItemUnitPrice() >>>>>>>>>" + items.getItemUnitPrice()); LOG.debug("items.getTotalAmount() >>>>>>>>" + items.getTotalAmount()); } } } else { payDoc.setProrateBy(payDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY : payDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE : payDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : payDoc.isNoProrate() ? OLEConstants.NO_PRORATE : null); } boolean manualProrateValidFlag = true; if ((payDoc.getProrateBy() != null) && (payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY) || payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) { if (payDoc.getProrateBy() != null && payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) { // Validates the prorate surchanges if prorate by manual manualProrateValidFlag = getOlePaymentRequestService().validateProratedSurcharge(payDoc); } if (manualProrateValidFlag) { List<OlePaymentRequestItem> item = payDoc.getItems(); if (payDoc.getVendorDetail().getCurrencyType() != null) { if (payDoc.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } if (payDoc.getVendorDetail() == null || (payDoc.getVendorDetail() != null && currencyTypeIndicator)) { for (int i = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) payDoc.getItem(i); if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) { boolean rulePassed = getKualiRuleService() .applyRules(new OleDiscountPaymentRequestEvent(payDoc, items)); if (rulePassed) { items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class) .calculateDiscount(items).setScale(2, BigDecimal.ROUND_HALF_UP)); } } } } else { LOG.debug("###########Foreign Currency Field Calculation###########"); for (int i = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) payDoc.getItem(i); Long id = payDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id); org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext .getBean(org.kuali.rice.krad.service.BusinessObjectService.class); List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate())); payDoc.setForeignVendorInvoiceAmount(payDoc.getVendorInvoiceAmount().bigDecimalValue() .multiply(tempOleExchangeRate.getExchangeRate())); } if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new OleForeignCurrencyPaymentRequestEvent(payDoc, items)); if (rulePassed) { SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items); if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) { items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost() .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP))); items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP)); items.setItemListPrice(items.getItemUnitCostUSD()); //items.setPurchaseOrderItemUnitPrice(items.getItemUnitPrice()); } } } else { if (items.getItemExchangeRate() != null && items.getForeignCurrencyExtendedPrice() != null) { // added for jira - OLE-2203 if (items.isAdditionalChargeUsd()) { items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue() .setScale(2, BigDecimal.ROUND_HALF_UP)); } else { items.setItemUnitPrice( items.getForeignCurrencyExtendedPrice().bigDecimalValue() .divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP) .setScale(2, BigDecimal.ROUND_HALF_UP)); } } } } } getOlePaymentRequestService().calculateProrateItemSurcharge(payDoc); } } if (payDoc.getProrateBy() == null && manualProrateValidFlag) { getOlePaymentRequestService().calculateWithoutProrates(payDoc); } List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) paymentForm.getDocument()).getItems(); for (PurApItem purApItem : newpurApItems) { for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { KualiDecimal calculatedAmount = new KualiDecimal( account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } return super.calculate(mapping, form, request, response); }
From source file:no.barentswatch.implementation.FiskInfoUtility.java
/** * Truncates a double value to the number of decimals given * /*from ww w.j a v a 2 s.c om*/ * @param number * The number to truncate * @param numberofDecimals * Number of decimals of the truncated number * @return */ public Double truncateDecimal(double number, int numberofDecimals) { if (number > 0) { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR) .doubleValue(); } else { return new BigDecimal(String.valueOf(number)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING) .doubleValue(); } }
From source file:science.atlarge.graphalytics.reference.ReferencePlatform.java
@Override public BenchmarkMetrics finalize(RunSpecification runSpecification) { stopPlatformLogging();/* www.java 2s . c om*/ BenchmarkRunSetup benchmarkRunSetup = runSpecification.getBenchmarkRunSetup(); Path path = benchmarkRunSetup.getLogDir().resolve("platform").resolve("driver.logs"); String logs = null; try { logs = new String(readAllBytes(path)); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can't read file at " + path); } Long startTime = null; Long endTime = null; for (String line : logs.split("\n")) { try { if (line.contains("Processing starts at: ")) { String[] lineParts = line.split("\\s+"); startTime = Long.parseLong(lineParts[lineParts.length - 1]); } if (line.contains("Processing ends at: ")) { String[] lineParts = line.split("\\s+"); endTime = Long.parseLong(lineParts[lineParts.length - 1]); } } catch (Exception e) { LOG.error(String.format("Cannot parse line: %s", line, e)); } } if (startTime != null && endTime != null) { BenchmarkMetrics metrics = new BenchmarkMetrics(); Long procTimeMS = new Long(endTime - startTime); BigDecimal procTimeS = (new BigDecimal(procTimeMS)).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_CEILING); metrics.setProcessingTime(new BenchmarkMetric(procTimeS, "s")); return metrics; } else { return new BenchmarkMetrics(); } }
From source file:ch.algotrader.service.algo.VariableIncrementalOrderService.java
private boolean checkLimit(AlgoOrder algoOrder, VariableIncrementalOrderStateVO orderState) { SecurityFamily family = algoOrder.getSecurity().getSecurityFamily(); if (algoOrder.getSide().equals(Side.BUY)) { double tickSize = family.getTickSize(null, orderState.getCurrentLimit().doubleValue(), true); double increment = RoundUtil.roundToNextN(orderState.getIncrement(), tickSize, BigDecimal.ROUND_CEILING); BigDecimal roundedIncrement = RoundUtil.getBigDecimal(increment, family.getScale(null)); return orderState.getCurrentLimit().add(roundedIncrement).compareTo(orderState.getEndLimit()) <= 0; } else {//from w w w. j a v a2 s .c o m double tickSize = family.getTickSize(null, orderState.getCurrentLimit().doubleValue(), false); double increment = RoundUtil.roundToNextN(orderState.getIncrement(), tickSize, BigDecimal.ROUND_CEILING); BigDecimal roundedIncrement = RoundUtil.getBigDecimal(increment, family.getScale(null)); return orderState.getCurrentLimit().subtract(roundedIncrement).compareTo(orderState.getEndLimit()) >= 0; } }
From source file:org.kuali.ole.module.purap.document.web.struts.OleRequisitionAction.java
/** * Calculate the whole document.//from w ww .j av a2 s. c o m * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @return An ActionForward * @throws Exception */ @Override public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside the OleRequisitionAction class Calculate"); PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems(); for (PurApItem purApItem : purApItems) { List<KualiDecimal> existingAmount = new ArrayList<>(); for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OleRequisitionAccount) { if (((OleRequisitionAccount) oldSourceAccountingLine).getExistingAmount() != null) { existingAmount.add(((OleRequisitionAccount) oldSourceAccountingLine).getExistingAmount()); } } } int count = 0; for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (account.getAmount() != null && count < existingAmount.size() && existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) { KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount() .multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString()); account.setAccountLinePercent(calculatedPercent.bigDecimalValue() .setScale(OLEConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING)); } else { if (account.getAccountLinePercent().intValue() == 100 && (account.getAmount() == null || account.getAccount() != null)) { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } else { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } } count++; } for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OleRequisitionAccount) { ((OleRequisitionAccount) oldSourceAccountingLine) .setExistingAmount(oldSourceAccountingLine.getAmount()); } } } ActionForward forward = super.calculate(mapping, form, request, response); purchasingForm = (PurchasingAccountsPayableFormBase) form; PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument(); PurchasingFormBase formBase = (PurchasingFormBase) form; OleRequisitionDocument reqDoc = (OleRequisitionDocument) formBase.getDocument(); boolean foreignCurrencyIndicator = false; List<OleRequisitionItem> item = reqDoc.getItems(); if (purDoc.getVendorDetail() != null) { foreignCurrencyIndicator = isForeignCurrency(purDoc.getVendorDetail().getCurrencyType()); } if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && (!foreignCurrencyIndicator))) { for (int i = 0; purDoc.getItems().size() > i; i++) { OleRequisitionItem items = (OleRequisitionItem) purDoc.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new DiscountRequisitionEvent(reqDoc, items)); if (rulePassed) { items.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(items) .setScale(2, BigDecimal.ROUND_HALF_UP)); } rulePassed = getKualiRuleService().applyRules(new CopiesRequisitionEvent(reqDoc, items)); } } } else { LOG.debug("###########Foreign Currency Field Calculation###########"); for (int i = 0; item.size() > i; i++) { OleRequisitionItem items = (OleRequisitionItem) reqDoc.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new ForeignCurrencyRequisitionEvent(reqDoc, items)); if (rulePassed) { SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items); Long id = reqDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id); BusinessObjectService businessObjectService = SpringContext .getBean(BusinessObjectService.class); List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate())); } if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) { items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost() .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP))); items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP)); items.setItemListPrice(items.getItemUnitCostUSD()); items.setTotalAmount(items.getTotalAmount()); } } } } } purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()) .getItems(); for (PurApItem purApItem : newpurApItems) { for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { KualiDecimal calculatedAmount = new KualiDecimal( account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } forward = super.calculate(mapping, form, request, response); // formBase.setCalculated(true); // Added for jira OLE-964 OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext .getBean("oleRequisitionDocumentService"); List<SourceAccountingLine> sourceAccountingLineList = reqDoc.getSourceAccountingLines(); for (SourceAccountingLine accLine : sourceAccountingLineList) { String notificationOption = null; boolean sufficientFundCheck; Map<String, Object> key = new HashMap<String, Object>(); String chartCode = accLine.getChartOfAccountsCode(); String accNo = accLine.getAccountNumber(); key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode); key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo); OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class) .findByPrimaryKey(OleSufficientFundCheck.class, key); if (account != null) { notificationOption = account.getNotificationOption(); } if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) { sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine); if (sufficientFundCheck) { GlobalVariables.getMessageMap().putError( OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM, OLEConstants.SufficientFundCheck.INSUFF_FUND_REQ + accLine.getAccountNumber()); } } } // End if (LOG.isDebugEnabled()) { LOG.debug("Inside the OleRequisitionAcrion class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice()); } return forward; }
From source file:org.kuali.ole.module.purap.document.web.struts.OlePurchaseOrderAction.java
/** * @see org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from w w w .j av a 2s .c o m*/ @Override public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> purApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems(); for (PurApItem purApItem : purApItems) { List<KualiDecimal> existingAmount = new ArrayList<>(); for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) { if (((OlePurchaseOrderAccount) oldSourceAccountingLine).getExistingAmount() != null) { existingAmount.add(((OlePurchaseOrderAccount) oldSourceAccountingLine).getExistingAmount()); } } } int count = 0; for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (account.getAmount() != null && count < existingAmount.size() && existingAmount.size() != 0 && !existingAmount.get(count).toString().equals(account.getAmount().toString())) { KualiDecimal calculatedPercent = new KualiDecimal(account.getAmount() .multiply(new KualiDecimal(100)).divide(purApItem.getTotalAmount()).toString()); account.setAccountLinePercent(calculatedPercent.bigDecimalValue() .setScale(OLEConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING)); } else { if (account.getAccountLinePercent().intValue() == 100 && (account.getAmount() == null || account.getAccount() != null)) { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } else { KualiDecimal calculatedAmount = new KualiDecimal(account.getAccountLinePercent() .multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } } count++; } for (PurApAccountingLine oldSourceAccountingLine : purApItem.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof OlePurchaseOrderAccount) { ((OlePurchaseOrderAccount) oldSourceAccountingLine) .setExistingAmount(oldSourceAccountingLine.getAmount()); } } } ActionForward forward = super.calculate(mapping, form, request, response); /* calculateCurrency(mapping, form, request, response); */ purchasingForm = (PurchasingAccountsPayableFormBase) form; PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument(); PurchasingFormBase formBase = (PurchasingFormBase) form; PurchaseOrderDocument purchaseDoc = (PurchaseOrderDocument) formBase.getDocument(); List<OlePurchaseOrderItem> purItem = purchaseDoc.getItems(); if (purchaseDoc.getVendorDetail().getCurrencyType() != null) { if (purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } if (purDoc.getVendorDetail() == null || (purDoc.getVendorDetail() != null && currencyTypeIndicator)) { for (int i = 0; purDoc.getItems().size() > i; i++) { OlePurchaseOrderItem item = (OlePurchaseOrderItem) purDoc.getItem(i); if ((item.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new DiscountPurchaseOrderEvent(purchaseDoc, item)); if (rulePassed) { item.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item) .setScale(2, BigDecimal.ROUND_HALF_UP)); } rulePassed = getKualiRuleService().applyRules(new CopiesPurchaseOrderEvent(purDoc, item)); } } } else { LOG.debug("###########Foreign Currency Field Calculation in olepurchaseOrder action###########"); BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class); for (int i = 0; purItem.size() > i; i++) { OlePurchaseOrderItem items = (OlePurchaseOrderItem) purchaseDoc.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { boolean rulePassed = getKualiRuleService() .applyRules(new ForeignCurrencyPOEvent(purchaseDoc, items)); if (rulePassed) { SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items); Long id = purchaseDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map currencyTypeMap = new HashMap(); currencyTypeMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id); List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy( OleExchangeRate.class, currencyTypeMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); String documentNumber = purchaseDoc.getDocumentNumber(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OLEPropertyConstants.DOCUMENT_NUMBER, documentNumber); List<OlePurchaseOrderItem> currenctExchangeRateList = (List) businessObjectService .findMatching(OlePurchaseOrderItem.class, documentNumberMap); Iterator iterate = currenctExchangeRateList.iterator(); if (iterate.hasNext()) { OlePurchaseOrderItem tempCurrentExchangeRate = (OlePurchaseOrderItem) iterate .next(); String poCurrencyType = null; if (tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail() .getCurrencyType() != null) { poCurrencyType = tempCurrentExchangeRate.getPurchaseOrder().getVendorDetail() .getCurrencyType().getCurrencyType(); } String poaCurrencyType = purchaseDoc.getVendorDetail().getCurrencyType() .getCurrencyType(); if (poCurrencyType != null && (poCurrencyType.equalsIgnoreCase(poaCurrencyType)) && !items.isLatestExchangeRate() && !purchaseDoc.getIsPODoc() && ((purchaseDoc instanceof PurchaseOrderAmendmentDocument) || (purchaseDoc instanceof PurchaseOrderSplitDocument) || (purchaseDoc instanceof PurchaseOrderReopenDocument))) { items.setItemExchangeRate(tempCurrentExchangeRate.getItemExchangeRate()); } else { items.setItemExchangeRate( new KualiDecimal(tempOleExchangeRate.getExchangeRate())); } } if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) { items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost() .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP))); items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP)); items.setItemListPrice(items.getItemUnitCostUSD()); } } } } } } purchasingForm = (PurchasingAccountsPayableFormBase) form; List<PurApItem> newpurApItems = ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()) .getItems(); for (PurApItem purApItem : newpurApItems) { for (PurApAccountingLine account : purApItem.getSourceAccountingLines()) { KualiDecimal calculatedAmount = new KualiDecimal( account.getAccountLinePercent().multiply(purApItem.getTotalAmount().bigDecimalValue()) .divide(new BigDecimal(100)).toString()); account.setAmount(calculatedAmount); } } forward = super.calculate(mapping, form, request, response); // setEnumerationToCopies(purItem); // Added for SFC - Start OleRequisitionDocumentService oleRequisitionDocumentService = (OleRequisitionDocumentService) SpringContext .getBean("oleRequisitionDocumentService"); List<SourceAccountingLine> sourceAccountingLineList = purDoc.getSourceAccountingLines(); for (SourceAccountingLine accLine : sourceAccountingLineList) { String notificationOption = null; boolean sufficientFundCheck; Map<String, Object> key = new HashMap<String, Object>(); String chartCode = accLine.getChartOfAccountsCode(); String accNo = accLine.getAccountNumber(); key.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartCode); key.put(OLEPropertyConstants.ACCOUNT_NUMBER, accNo); OleSufficientFundCheck account = SpringContext.getBean(BusinessObjectService.class) .findByPrimaryKey(OleSufficientFundCheck.class, key); if (account != null) { notificationOption = account.getNotificationOption(); } if (notificationOption != null && notificationOption.equals(OLEPropertyConstants.BLOCK_USE)) { sufficientFundCheck = oleRequisitionDocumentService.hasSufficientFundsOnRequisition(accLine); if (sufficientFundCheck) { GlobalVariables.getMessageMap().putError( OLEConstants.SufficientFundCheck.ERROR_MSG_FOR_INSUFF_FUND, RiceKeyConstants.ERROR_CUSTOM, OLEConstants.SufficientFundCheck.INSUFF_FUND_POA + accLine.getAccountNumber()); } } } // End // formBase.setCalculated(true); if (LOG.isDebugEnabled()) { LOG.debug("Inside the OlePurchaseOrderAction class Calculate" + formBase.getNewPurchasingItemLine().getItemUnitPrice()); } return forward; }