List of usage examples for java.math BigDecimal toString
@Override
public String toString()
From source file:org.plasma.sdo.helper.DataConverter.java
public Object fromDecimal(Type targetType, BigDecimal value) { DataType targetDataType = DataType.valueOf(targetType.getName()); switch (targetDataType) { case Decimal: return value; case Double: return new Double(value.doubleValue()); case Float: return new Float(value.floatValue()); case Int:/*from ww w . j a v a 2s .com*/ return new Integer(value.intValue()); case Long: return new Long(value.longValue()); case Integer: return value.toBigInteger(); case String: // as per spec: ('+'|'-')? [0-9]* ('.'[0-9]*)? (('E'|'e') ('+'|'-')? [0-9]+)? /* * [123,0] "123" * [-123,0] "-123" * [123,-1] "1.23E+3" * [123,-3] "1.23E+5" * [123,1] "12.3" * [123,5] "0.00123" * [123,10] "1.23E-8" * [-123,12] "-1.23E-10" */ return value.toString(); default: throw new InvalidDataConversionException(targetDataType, DataType.Decimal, value); } }
From source file:pe.gob.mef.gescon.web.ui.PreguntaMB.java
public void saveResp(ActionEvent event) throws Exception { try {/* w ww . j a v a 2 s . co m*/ if (CollectionUtils.isEmpty(this.getListaPregunta())) { this.setListaPregunta(Collections.EMPTY_LIST); } LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB"); User user = loginMB.getUser(); BigDecimal cat2; PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService"); this.getSelectedPregunta().setVrespuesta(this.getSelectedPregunta().getVrespuesta().toUpperCase()); this.getSelectedPregunta().setNcategoriaid(this.getSelectedPregunta().getNcategoriaid()); cat2 = this.getSelectedPregunta().getNcategoriaid(); if (Integer.parseInt(getCat1().toString()) != Integer.parseInt(cat2.toString())) { this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf(Long.parseLong("3"))); } else { this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf(Long.parseLong("6"))); } service.saveOrUpdate(this.getSelectedPregunta()); if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaTargetVinculos())) { VinculoPreguntaService vinculopreguntaService = (VinculoPreguntaService) ServiceFinder .findBean("VinculoPreguntaService"); service.delete(this.getSelectedPregunta().getNpreguntaid()); for (Consulta consulta : this.getListaTargetVinculos()) { VinculoPregunta vinculopregunta = new VinculoPregunta(); vinculopregunta.setNvinculoid(vinculopreguntaService.getNextPK()); vinculopregunta.setNpreguntaid(this.getSelectedPregunta().getNpreguntaid()); vinculopregunta.setNconocimientovinc(consulta.getIdconocimiento()); vinculopregunta.setNtipoconocimientovinc(consulta.getIdTipoConocimiento()); vinculopregunta.setDfechacreacion(new Date()); vinculopregunta.setVusuariocreacion(user.getVlogin()); vinculopreguntaService.saveOrUpdate(vinculopregunta); } } this.setListaPregunta(service.getPreguntas()); RequestContext.getCurrentInstance().execute("PF('respDialog').hide();"); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } }
From source file:org.egov.ptis.web.controller.reports.BaseRegisterVLTResultAdaptor.java
@Override public JsonElement serialize(final DataTable<PropertyMVInfo> baseRegisterResponse, final Type type, final JsonSerializationContext jsc) { final List<PropertyMVInfo> baseRegisterResult = baseRegisterResponse.getData(); final JsonArray baseRegisterResultData = new JsonArray(); baseRegisterResult.forEach(baseRegisterResultObj -> { final JsonObject jsonObject = new JsonObject(); final BigDecimal taxRate = propertyTaxUtil.getTaxRates(); final Map<String, BigDecimal> valuesMap = getTaxDetails(baseRegisterResultObj); final BigDecimal marketValue = baseRegisterResultObj.getMarketValue() == null ? BigDecimal.ZERO : baseRegisterResultObj.getMarketValue(); final BigDecimal capitalValue = baseRegisterResultObj.getCapitalValue() == null ? BigDecimal.ZERO : baseRegisterResultObj.getCapitalValue(); final BigDecimal higherValueForImposedTax = marketValue.compareTo(capitalValue) > 0 ? marketValue.setScale(2, BigDecimal.ROUND_HALF_UP) : capitalValue.setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal currPenaltyFine = BigDecimal.ZERO; if (baseRegisterResultObj.getAggrCurrFirstHalfPenaly() != null) currPenaltyFine = currPenaltyFine.add(baseRegisterResultObj.getAggrCurrFirstHalfPenaly()); if (baseRegisterResultObj.getAggrCurrSecondHalfPenaly() != null) currPenaltyFine = currPenaltyFine.add(baseRegisterResultObj.getAggrCurrSecondHalfPenaly()); final BigDecimal currentColl = baseRegisterResultObj.getAggrCurrFirstHalfColl() == null ? BigDecimal.ZERO .add(baseRegisterResultObj.getAggrCurrSecondHalfColl() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrCurrSecondHalfColl()) : baseRegisterResultObj.getAggrCurrFirstHalfColl(); final BigDecimal arrColl = baseRegisterResultObj.getAggrArrColl() != null ? baseRegisterResultObj.getAggrArrColl() : BigDecimal.ZERO; final BigDecimal totalColl = arrColl.add(currentColl); final BigDecimal currTotal = baseRegisterResultObj.getAggrCurrFirstHalfDmd() == null ? BigDecimal.ZERO.add(baseRegisterResultObj.getAggrCurrSecondHalfDmd() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrCurrSecondHalfDmd()) : baseRegisterResultObj.getAggrCurrFirstHalfDmd(); jsonObject.addProperty("assessmentNo", baseRegisterResultObj.getPropertyId()); jsonObject.addProperty("oldAssessmentNo", StringUtils.isNotBlank(baseRegisterResultObj.getOldMuncipalNum()) ? baseRegisterResultObj.getOldMuncipalNum() : "NA"); jsonObject.addProperty("sitalArea", baseRegisterResultObj.getSitalArea().setScale(2, BigDecimal.ROUND_HALF_UP)); jsonObject.addProperty("ward", baseRegisterResultObj.getWard().getBoundaryNum()); jsonObject.addProperty("ownerName", baseRegisterResultObj.getOwnerName()); jsonObject.addProperty("surveyNo", StringUtils.isNotBlank(baseRegisterResultObj.getSurveyNo()) ? baseRegisterResultObj.getSurveyNo() : "NA"); jsonObject.addProperty("taxationRate", taxRate); jsonObject.addProperty("marketValue", marketValue.toString()); jsonObject.addProperty("documentValue", capitalValue.toString()); jsonObject.addProperty("higherValueForImposedtax", higherValueForImposedTax.toString()); jsonObject.addProperty("isExempted", baseRegisterResultObj.getIsExempted() ? "Yes" : "No"); jsonObject.addProperty("propertyTaxFirstHlf", baseRegisterResultObj.getAggrCurrFirstHalfDmd() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrCurrFirstHalfDmd()); if (!valuesMap.isEmpty()) { jsonObject.addProperty("libraryCessTaxFirstHlf", valuesMap.get(CURR_FIRST_HALF_LIB_CESS) == null ? BigDecimal.ZERO : valuesMap.get(CURR_FIRST_HALF_LIB_CESS)); jsonObject.addProperty("libraryCessTaxSecondHlf", valuesMap.get(CURR_SECOND_HALF_LIB_CESS) == null ? BigDecimal.ZERO : valuesMap.get(CURR_SECOND_HALF_LIB_CESS)); jsonObject.addProperty("arrearLibraryTax", valuesMap.get(ARR_LIB_CESS) == null ? BigDecimal.ZERO : valuesMap.get(ARR_LIB_CESS)); }//from w w w .ja v a 2 s. c o m jsonObject.addProperty("propertyTaxSecondHlf", baseRegisterResultObj.getAggrCurrSecondHalfDmd() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrCurrSecondHalfDmd()); jsonObject.addProperty("currTotal", currTotal); jsonObject.addProperty("penaltyFines", currPenaltyFine); jsonObject.addProperty("arrearPeriod", baseRegisterResultObj.getDuePeriod() != null && org.apache.commons.lang.StringUtils.isNotBlank(baseRegisterResultObj.getDuePeriod()) ? baseRegisterResultObj.getDuePeriod() : "NA"); jsonObject.addProperty("arrearPropertyTax", baseRegisterResultObj.getAggrArrDmd() != null && baseRegisterResultObj.getAggrArrDmd().compareTo(BigDecimal.ZERO) >= 1 ? baseRegisterResultObj.getAggrArrDmd().subtract( valuesMap == null ? BigDecimal.ZERO : valuesMap.get(ARR_LIB_CESS)) : BigDecimal.ZERO); jsonObject.addProperty("arrearPenaltyFines", baseRegisterResultObj.getAggrArrearPenaly() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrArrearPenaly()); jsonObject.addProperty("arrearTotal", baseRegisterResultObj.getAggrArrDmd() == null ? BigDecimal.ZERO : baseRegisterResultObj.getAggrArrDmd()); jsonObject.addProperty("arrearColl", arrColl); jsonObject.addProperty("currentColl", currentColl); jsonObject.addProperty("totalColl", totalColl); baseRegisterResultData.add(jsonObject); }); return enhance(baseRegisterResultData, baseRegisterResponse); }
From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java
public String createAccDefExpenseFact(Fact fact, DocLine_Invoice line, Account prodExpAccount, Account prodDefExpAccount, String lineAmount, String strCurrencyId, ConnectionProvider conn) { BigDecimal amount = new BigDecimal(lineAmount); String Fact_Acct_Group_ID = SequenceIdData.getUUID(); ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>(); Period startingPeriod = OBDal.getInstance().get(Period.class, line.getStartingPeriodId()); plan = calculateAccDefPlan(startingPeriod, line.getPeriodNumber(), amount, strCurrencyId); for (HashMap<String, String> planLine : plan) { DocLine planDocLine = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID); planDocLine.copyInfo(line);/* w w w . j av a 2s . c o m*/ planDocLine.m_DateAcct = planLine.get("date"); if (IsReversal.equals("Y")) { // Expense Account fact.createLine(planDocLine, prodExpAccount, strCurrencyId, "", planLine.get("amount"), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); // Deferred Expense Account fact.createLine(planDocLine, prodDefExpAccount, strCurrencyId, planLine.get("amount"), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); } else { // Deferred Expense Account fact.createLine(planDocLine, prodDefExpAccount, strCurrencyId, "", planLine.get("amount"), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); // Expense Account fact.createLine(planDocLine, prodExpAccount, strCurrencyId, planLine.get("amount"), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); } amount = amount.subtract(new BigDecimal(planLine.get("amount"))); Fact_Acct_Group_ID = SequenceIdData.getUUID(); } return amount.toString(); }
From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java
String createAccDefRevenueFact(Fact fact, DocLine_Invoice line, Account prodRevAccount, Account prodDefRevAccount, String lineAmount, String strCurrencyId, ConnectionProvider conn) { BigDecimal amount = new BigDecimal(lineAmount); String Fact_Acct_Group_ID = SequenceIdData.getUUID(); ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>(); Period startingPeriod = OBDal.getInstance().get(Period.class, line.getStartingPeriodId()); plan = calculateAccDefPlan(startingPeriod, line.getPeriodNumber(), amount, strCurrencyId); for (HashMap<String, String> planLine : plan) { DocLine planDocLine = new DocLine(DocumentType, Record_ID, line.m_TrxLine_ID); planDocLine.copyInfo(line);//from ww w .ja v a 2 s .co m planDocLine.m_DateAcct = planLine.get("date"); if (IsReversal.equals("Y")) { // Revenue Account fact.createLine(planDocLine, prodRevAccount, strCurrencyId, planLine.get("amount"), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); // Deferred Revenue Account fact.createLine(planDocLine, prodDefRevAccount, strCurrencyId, "", planLine.get("amount"), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); } else { // Deferred Revenue Account fact.createLine(planDocLine, prodDefRevAccount, strCurrencyId, planLine.get("amount"), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); // Revenue Account fact.createLine(planDocLine, prodRevAccount, strCurrencyId, "", planLine.get("amount"), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn); } amount = amount.subtract(new BigDecimal(planLine.get("amount"))); Fact_Acct_Group_ID = SequenceIdData.getUUID(); } return amount.toString(); }
From source file:org.mifosplatform.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override/* w w w. j a v a2 s .co m*/ public CommandProcessingResult makeLoanRepayment(final Long loanId, final JsonCommand command) { this.context.authenticatedUser(); this.loanEventApiJsonValidator.validateNewRepaymentTransaction(command.json()); final LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate"); final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed("transactionAmount"); final String txnExternalId = command.stringValueOfParameterNamedAllowingNull("externalId"); final Map<String, Object> changes = new LinkedHashMap<String, Object>(); changes.put("transactionDate", command.stringValueOfParameterNamed("transactionDate")); changes.put("transactionAmount", command.stringValueOfParameterNamed("transactionAmount")); changes.put("locale", command.locale()); changes.put("dateFormat", command.dateFormat()); changes.put("paymentTypeId", command.stringValueOfParameterNamed("paymentTypeId")); final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { changes.put("note", noteText); } final Loan loan = this.loanAssembler.assembleFrom(loanId); final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService .createAndPersistPaymentDetail(command, changes); final CommandProcessingResultBuilder commandProcessingResultBuilder = new CommandProcessingResultBuilder(); this.loanAccountDomainService.makeRepayment(loan, commandProcessingResultBuilder, transactionDate, transactionAmount, paymentDetail, noteText, txnExternalId); String mailId = loanReadPlatformService.getEmailForClient(loan.getClientId()); String content = "paid on:" + transactionDate.toString().concat("Amount:" + transactionAmount.toString()); String type = "Lease Repayment Details"; if (mailId != null) { gmailSendingNotificationToClients.sendToUserAccount(mailId, content, type, null); } return commandProcessingResultBuilder.withCommandId(command.commandId()) // .withLoanId(loanId) // .with(changes) // .build(); }
From source file:org.openbravo.erpCommon.ad_forms.Fact.java
/** * Balance Accounting Currency. If the accounting currency is not balanced, if Currency balancing * is enabled create a new line using the currency balancing account with zero source balance or * adjust the line with the largest balance sheet account or if no balance sheet account exist, * the line with the largest amount/*from w w w .ja v a2s . com*/ * * @return FactLine */ public FactLine balanceAccounting(ConnectionProvider conn) { BigDecimal diff = getAcctBalance(); log4jFact.debug("balanceAccounting - Balance=" + diff); FactLine line = null; // Create Currency Entry if (m_acctSchema.isCurrencyBalancing()) { if (m_lines.size() == 0) { log4jFact.error("balanceAccounting failed."); return null; } FactLine fl = (FactLine) m_lines.get(0); line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID, "", fl.m_Fact_Acct_Group_ID, fl.m_SeqNo, fl.m_DocBaseType); line.setDocumentInfo(m_doc, null); line.setJournalInfo(m_doc.GL_Category_ID); line.setPostingType(m_postingType); // Amount line.setAmtSource(m_doc.C_Currency_ID, ZERO.toString(), ZERO.toString()); line.convert(m_acctSchema.getC_Currency_ID(), m_doc.DateAcct, m_acctSchema.getCurrencyRateType(), conn); if (diff.compareTo(ZERO) < 0) line.setAmtAcct(diff.abs().toString(), ZERO.toString()); else line.setAmtAcct(ZERO.toString(), diff.abs().toString()); line.setAccount(m_acctSchema, m_acctSchema.getCurrencyBalancing_Acct()); log4jFact.debug("balanceAccounting - " + line.toString()); log4jFact.debug("************* fact - balanceAccounting - m_lines.size() - " + m_lines.size()); m_lines.add(line); } else { // Adjust biggest (Balance Sheet) line amount BigDecimal BSamount = ZERO; FactLine BSline = null; BigDecimal PLamount = ZERO; FactLine PLline = null; int signum = diff.signum(); // Find line for (int i = 0; i < m_lines.size(); i++) { FactLine l = (FactLine) m_lines.get(i); BigDecimal amt = l.getAccountingBalance(); // amt = amt.abs(); if (l.isBalanceSheet() && ((amt.compareTo(BSamount) > 0 && signum != 1)) || ((amt.compareTo(BSamount) < 0 && signum == 1))) { BSamount = amt; BSline = l; } else if (!l.isBalanceSheet() && ((amt.compareTo(BSamount) > 0 && signum != 1)) || ((amt.compareTo(BSamount) < 0 && signum == 1))) { PLamount = amt; PLline = l; } } if (BSline != null) line = BSline; else line = PLline; if (line == null) log4jFact.error("balanceAccounting - No Line found"); else { log4jFact.debug("Adjusting Amt=" + diff.toString() + "; Line=" + line.toString()); line.currencyCorrect(diff); log4jFact.debug("balanceAccounting - " + line.toString()); } } // correct biggest amount // Debug info only this.isAcctBalanced(); return line; }
From source file:eu.europa.ec.fisheries.uvms.rules.service.mapper.fact.ActivityFactMapper.java
public FaFishingOperationFact generateFactsForFishingOperation(FishingActivity fishingActivity, FAReportDocument faReportDocument) { if (fishingActivity == null && faReportDocument == null) { return null; }/*from w w w . j a va 2 s .co m*/ FaFishingOperationFact faFishingOperationFact = new FaFishingOperationFact(); String partialXpath = xPathUtil.getValue(); if (fishingActivity != null) { faFishingOperationFact.setFishingActivityTypeCode(mapToCodeType(fishingActivity.getTypeCode())); xPathUtil.appendWithoutWrapping(partialXpath).append(TYPE_CODE).storeInRepo(faFishingOperationFact, FISHING_ACTIVITY_TYPE_CODE_PROP); if (fishingActivity.getRelatedFLUXLocations() != null) { faFishingOperationFact .setRelatedFLUXLocations(new ArrayList<>(fishingActivity.getRelatedFLUXLocations())); } xPathUtil.appendWithoutWrapping(partialXpath).append(RELATED_FLUX_LOCATION) .storeInRepo(faFishingOperationFact, RELATED_FLUX_LOCATIONS_PROP); BigDecimal operatQuantity = fishingActivityOperationsQuantityValue(fishingActivity); faFishingOperationFact.setOperationsQuantity(operatQuantity == null ? null : operatQuantity.toString()); xPathUtil.appendWithoutWrapping(partialXpath).append(OPERATIONS_QUANTITY) .storeInRepo(faFishingOperationFact, "operationsQuantity"); faFishingOperationFact .setVesselRelatedActivityCode(mapToCodeType(fishingActivity.getVesselRelatedActivityCode())); xPathUtil.appendWithoutWrapping(partialXpath).append(VESSEL_RELATED_ACTIVITY_CODE) .storeInRepo(faFishingOperationFact, VESSEL_RELATED_ACTIVITY_CODE_PROP); List<VesselTransportMeans> vesselTransportMeans = fishingActivity.getRelatedVesselTransportMeans(); if (CollectionUtils.isNotEmpty(vesselTransportMeans)) { faFishingOperationFact.setVesselTransportMeansContactParties( getContactPartiesFromVesselTransportMeans(vesselTransportMeans)); } xPathUtil.appendWithoutWrapping(partialXpath) .append(RELATED_VESSEL_TRANSPORT_MEANS, SPECIFIED_CONTACT_PARTY) .storeInRepo(faFishingOperationFact, "vesselTransportMeansContactParties"); faFishingOperationFact .setFishingGearRoleCodes(getFishingGearRoleCodes(fishingActivity.getSpecifiedFishingGears())); xPathUtil.appendWithoutWrapping(partialXpath) .append(SPECIFIED_FISHING_ACTIVITY, VESSEL_RELATED_ACTIVITY_CODE) .storeInRepo(faFishingOperationFact, FISHING_GEAR_ROLE_CODES_PROP); List<FishingActivity> relatedFishingActivities = fishingActivity.getRelatedFishingActivities(); if (CollectionUtils.isNotEmpty(relatedFishingActivities)) { faFishingOperationFact.setRelatedFishingActivityTypeCodes( getFishingActivityTypeCodeList(relatedFishingActivities)); xPathUtil.appendWithoutWrapping(partialXpath).append(RELATED_FISHING_ACTIVITY, TYPE_CODE) .storeInRepo(faFishingOperationFact, "relatedFishingActivityTypeCodes"); faFishingOperationFact.setRelatedFishingActivities(relatedFishingActivities); xPathUtil.appendWithoutWrapping(partialXpath).append(RELATED_FISHING_ACTIVITY) .storeInRepo(faFishingOperationFact, "relatedFishingActivities"); int activityIndex = 1; for (FishingActivity activity : relatedFishingActivities) { faFishingOperationFact .setFishingGearRoleCodes(getFishingGearRoleCodes(activity.getSpecifiedFishingGears())); xPathUtil.appendWithoutWrapping(partialXpath).append(RELATED_FISHING_ACTIVITY) .appendWithIndex(VESSEL_RELATED_ACTIVITY_CODE, activityIndex) .storeInRepo(faFishingOperationFact, FISHING_GEAR_ROLE_CODES_PROP); } } } if (faReportDocument != null) { faFishingOperationFact.setFaReportDocumentTypeCode(mapToCodeType(faReportDocument.getTypeCode())); xPathUtil.append(FLUXFA_REPORT_MESSAGE, FA_REPORT_DOCUMENT, TYPE_CODE) .storeInRepo(faFishingOperationFact, FA_REPORT_DOCUMENT_TYPE_CODE_PROP); } return faFishingOperationFact; }
From source file:fr.paris.lutece.plugins.suggest.web.SuggestJspBean.java
/** * Gets the form statistics page//from ww w . j a v a 2 s .c o m * * @param request * the http request * @return the form test page */ public String getStatistics(HttpServletRequest request) { Plugin plugin = getPlugin(); Locale locale = getLocale(); Timestamp tFirstDateFilter = null; Timestamp tLastDateFilter = null; SuggestFilter suggestFilter = new SuggestFilter(); suggestFilter.setIdState(Suggest.STATE_ENABLE); List<Suggest> listSuggest = SuggestHome.getSuggestList(suggestFilter, plugin); String strIdSuggest = request.getParameter(PARAMETER_ID_SUGGEST); String strFirstDateFilter = request.getParameter(PARAMETER_FIRST_DATE_FILTER); String strLastDateFilter = request.getParameter(PARAMETER_LAST_DATE_FILTER); String strIdCategory = request.getParameter(PARAMETER_ID_CATEGORY_FILTER); String strIdType = request.getParameter(PARAMETER_ID_TYPE_SUGGEST); int nIdCategory = SuggestUtils.getIntegerParameter(strIdCategory); int nIdType = SuggestUtils.getIntegerParameter(strIdType); if ((strIdSuggest != null) && !strIdSuggest.equals(EMPTY_STRING)) { _nIdSuggest = SuggestUtils.getIntegerParameter(strIdSuggest); } else if (listSuggest.size() > 0) { _nIdSuggest = listSuggest.get(0).getIdSuggest(); } Suggest suggest = SuggestHome.findByPrimaryKey(_nIdSuggest, plugin); if ((strFirstDateFilter != null) && !strFirstDateFilter.equals("")) { try { tFirstDateFilter = new Timestamp(DateUtil.formatDate(strFirstDateFilter, locale).getTime()); } catch (Exception e) { tFirstDateFilter = null; } } if ((strLastDateFilter != null) && !strLastDateFilter.equals("")) { try { tLastDateFilter = new Timestamp(DateUtil.formatDate(strLastDateFilter, locale).getTime()); } catch (Exception e) { tLastDateFilter = null; } } // build Filter SubmitFilter filter = new SubmitFilter(); filter.setIdSuggest(_nIdSuggest); filter.setDateFirst(tFirstDateFilter); filter.setDateLast(tLastDateFilter); filter.setIdCategory(nIdCategory); filter.setIdType(nIdType); // number of comments filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH); int nNbComments = _commentSubmitService.getCountCommentSubmit(filter, plugin); // number of votes filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH); int nNbVotes = 0; List<SuggestSubmit> listSuggestSubmit = _suggestSubmitService.getSuggestSubmitList(filter, plugin); List<String> listUsersKey = new ArrayList<String>(); for (SuggestSubmit d : listSuggestSubmit) { nNbVotes += d.getNumberVote(); if (!listUsersKey.contains(d.getLuteceUserKey())) { listUsersKey.add(d.getLuteceUserKey()); } } // number of suggest submit filter.setIdSuggestSubmitState(SuggestSubmit.STATE_DISABLE); int nNbSuggestSubmitDisabled = _suggestSubmitService.getCountSuggestSubmit(filter, plugin); filter.setIdSuggestSubmitState(SuggestSubmit.STATE_WAITING_FOR_PUBLISH); int nNbSuggestSubmitWaiting = _suggestSubmitService.getCountSuggestSubmit(filter, plugin); filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH); int nNbSuggestSubmitPublished = _suggestSubmitService.getCountSuggestSubmit(filter, plugin); // high scores SuggestUtils.initSubmitFilterBySort(filter, SubmitFilter.SORT_BY_SCORE_DESC); int nNumberMaxSuggestSubmit = AppPropertiesService.getPropertyInt(PROPERTY_SUGGESTSUBMIT_HIGHSCORES, 10); listSuggestSubmit = _suggestSubmitService.getSuggestSubmitList(filter, plugin, nNumberMaxSuggestSubmit); ReferenceList refSuggestList = SuggestUtils.getRefListSuggest(listSuggest, false); Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_FIRST_DATE_FILTER, (tFirstDateFilter == null) ? null : new Date(tFirstDateFilter.getTime())); model.put(MARK_LAST_DATE_FILTER, (tLastDateFilter == null) ? null : new Date(tLastDateFilter.getTime())); model.put(MARK_SUGGEST, suggest); if (nNbSuggestSubmitPublished != 0) { float fV = (float) nNbVotes / nNbSuggestSubmitPublished; float fC = (float) nNbComments / nNbSuggestSubmitPublished; BigDecimal bd = new BigDecimal(fV); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal bd2 = new BigDecimal(fC); bd2 = bd2.setScale(2, BigDecimal.ROUND_HALF_UP); model.put(MARK_NUMBER_VOTES, bd.toString()); model.put(MARK_NUMBER_COMMENTS, bd2.toString()); } if ((suggest.getCategories() != null) && !suggest.getCategories().isEmpty()) { ReferenceList refCategoryList = SuggestUtils.getRefListCategory(suggest.getCategories()); SuggestUtils.addEmptyItem(refCategoryList); model.put(MARK_CATEGORY_LIST, refCategoryList); model.put(MARK_SUGGEST_SUBMIT_CATEGORY_SELECTED, nIdCategory); if (nIdCategory != SuggestUtils.CONSTANT_ID_NULL) { model.put(MARK_CATEGORY_FILTER, CategoryHome.findByPrimaryKey(nIdCategory, plugin)); } } if ((suggest.getSuggestSubmitTypes() != null) && !suggest.getSuggestSubmitTypes().isEmpty()) { ReferenceList refSuggestSubmitTypes = SuggestUtils.getRefListType(suggest.getSuggestSubmitTypes()); SuggestUtils.addEmptyItem(refSuggestSubmitTypes); model.put(MARK_SUGGEST_SUBMIT_TYPE_LIST, refSuggestSubmitTypes); model.put(MARK_SUGGEST_SUBMIT_TYPE_SELECTED, nIdType); if (nIdType != SuggestUtils.CONSTANT_ID_NULL) { model.put(MARK_TYPE_FILTER, SuggestSubmitTypeHome.findByPrimaryKey(nIdType, plugin)); } } model.put(MARK_NUMBER_SUGGESTSUBMIT_DISABLED, nNbSuggestSubmitDisabled); model.put(MARK_NUMBER_SUGGESTSUBMIT_WAITING, nNbSuggestSubmitWaiting); model.put(MARK_NUMBER_SUGGESTSUBMIT_PUBLISHED, nNbSuggestSubmitPublished); model.put(MARK_NUMBER_USERS, listUsersKey.size()); model.put(MARK_HIGH_SCORES, listSuggestSubmit); model.put(MARK_SUGGEST_LIST, refSuggestList); model.put(MARK_URL, AppPathService.getBaseUrl(request) + JSP_MANAGE_COMMENT_SUBMIT + "?id_suggest_submit="); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_STATISTICS_SUGGEST, locale, model); return getAdminPage(template.getHtml()); }
From source file:org.sakaiproject.tool.assessment.services.GradingService.java
/** * CALCULATED_QUESTION// w w w .j ava2 s . c om * applyPrecisionToNumberString() takes a string representation of a number and returns * a string representation of that number, rounded to the specified number of * decimal places, including trimming decimal places if needed. * Will also throw away the extra trailing zeros as well as removing a trailing decimal point. * @param numberStr * @param decimalPlaces * @return processed number string (will never be null or empty string) */ public String applyPrecisionToNumberString(String numberStr, int decimalPlaces) { // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(numberStr); bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); String decimal = "."; // TODO handle localized decimal separator? //DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale); //char dec = dfs.getDecimalFormatSymbols().getDecimalSeparator(); String displayAnswer = bd.toString(); if (displayAnswer.length() > 2 && displayAnswer.contains(decimal)) { if (decimalPlaces == 0) { // Remove ".0" if decimalPlaces == 0 displayAnswer = displayAnswer.replace(decimal + "0", ""); } else { // trim away all the extra 0s from the end of the number if (displayAnswer.endsWith("0")) { displayAnswer = StringUtils.stripEnd(displayAnswer, "0"); } if (displayAnswer.endsWith(decimal)) { displayAnswer = displayAnswer.substring(0, displayAnswer.length() - 1); } } } return displayAnswer; }