Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

In this page you can find the example usage for java.math BigDecimal toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce an XML message for an instance of the BigDecimal.
 * <br>//w  w  w.j  av  a  2s  . co  m
 * @param object the instance for which the message is to be produced.
 * @param parent the XML element that is to be the parent of the produced XML message.
 * @return the root element of the XML segment that was produced.
 * @exception JDOMException if there is an error producing the message.
 */
private Element produceMsg(BigDecimal object, Element parent) throws JDOMException {

    // ----------------------
    // Create the BigDecimal element ...
    // ----------------------
    Element bigDecimalElement = new Element(TagNames.Elements.BIGDECIMAL);
    bigDecimalElement.setText(object.toString());
    if (parent != null) {
        bigDecimalElement = parent.addContent(bigDecimalElement);
    }

    return bigDecimalElement;
}

From source file:org.egov.ptis.domain.service.demolition.PropertyDemolitionService.java

private void buildSms(final Property property, final User user, final String workFlowAction) {
    final String assessmentNo = property.getBasicProperty().getUpicNo();
    final String mobileNumber = user.getMobileNumber();
    final String applicantName = user.getName();
    String smsMsg = "";
    if (workFlowAction.equals(WFLOW_ACTION_STEP_FORWARD)) {
        // to be enabled once acknowledgement feature is developed
        /*/*from  w w  w.j av a 2s .c o  m*/
         * smsMsg = messageSource.getMessage("demolition.ack.sms", new String[] { applicantName, assessmentNo }, null);
         */
    } else if (workFlowAction.equals(WFLOW_ACTION_STEP_REJECT))
        smsMsg = ptisMessageSource.getMessage("demolition.rejection.sms",
                new String[] { applicantName, assessmentNo, ApplicationThreadLocals.getMunicipalityName() },
                null);
    else if (workFlowAction.equals(WFLOW_ACTION_STEP_APPROVE)) {
        Installment effectiveInstallment = null;
        final Map<String, Installment> yearwiseInstMap = propertyTaxUtil.getInstallmentsForCurrYear(new Date());
        final Installment installmentFirstHalf = yearwiseInstMap.get(CURRENTYEAR_FIRST_HALF);
        final Installment installmentSecondHalf = yearwiseInstMap.get(CURRENTYEAR_SECOND_HALF);
        Date effectiveDate;
        Map<String, BigDecimal> demandMap = null;
        BigDecimal totalTax;

        /*
         * If demolition is done in 1st half, then fetch the total tax amount for the 2nd half, else fetch the total tax for
         * next installment 1st half and display in the SMS.
         */
        if (DateUtils.between(new Date(), installmentFirstHalf.getFromDate(), installmentFirstHalf.getToDate()))
            effectiveInstallment = installmentSecondHalf;
        else {
            final Module module = moduleDao.getModuleByName(PTMODULENAME);
            effectiveDate = org.apache.commons.lang3.time.DateUtils.addDays(installmentSecondHalf.getToDate(),
                    1);
            effectiveInstallment = installmentDao.getInsatllmentByModuleForGivenDate(module, effectiveDate);
        }
        demandMap = propertyTaxUtil.getTaxDetailsForInstallment(property, effectiveInstallment,
                installmentFirstHalf);
        totalTax = demandMap.get(DEMANDRSN_STR_VACANT_TAX) == null ? BigDecimal.ZERO
                : demandMap.get(DEMANDRSN_STR_VACANT_TAX)
                        .add(demandMap.get(DEMANDRSN_STR_LIBRARY_CESS) == null ? BigDecimal.ZERO
                                : demandMap.get(DEMANDRSN_STR_LIBRARY_CESS));
        smsMsg = ptisMessageSource.getMessage("demolition.approval.sms",
                new String[] { applicantName, assessmentNo, totalTax.toString(),
                        new SimpleDateFormat("dd/MM/yyyy").format(effectiveInstallment.getFromDate()),
                        ApplicationThreadLocals.getMunicipalityName() },
                null);
    }

    if (StringUtils.isNotBlank(mobileNumber))
        notificationService.sendSMS(mobileNumber, smsMsg);

}

From source file:org.openbravo.erpCommon.utility.CashVATUtil.java

/**
 * Create the accounting fact lines related to Cash VAT for payments, transactions and
 * reconciliations that come from a cash VAT invoice
 * //w ww .jav  a  2  s.co  m
 */
public static String createFactCashVAT(AcctSchema as, ConnectionProvider conn, Fact fact,
        String Fact_Acct_Group_ID, DocLineCashVATReady_PaymentTransactionReconciliation line, Invoice invoice,
        final String documentType, final String cCurrencyID, final String SeqNo) {
    try {
        if (invoice.isCashVAT() && !line.getInvoiceTaxCashVAT_V().isEmpty()) {
            FactLine factLine2 = null;
            for (final InvoiceTaxCashVAT_V itcv : line.getInvoiceTaxCashVAT_V()) {
                final TaxRate tax = itcv.getInvoiceTax().getTax();
                Invoice inv = itcv.getInvoiceTax().getInvoice();
                if (tax.isCashVAT() && inv.equals(invoice)) {
                    final BigDecimal taxAmt = itcv.getTaxAmount();
                    if (taxAmt.compareTo(BigDecimal.ZERO) != 0) {
                        final DocTax m_tax = new DocTax(tax.getId(), tax.getName(), tax.getRate().toString(),
                                itcv.getInvoiceTax().getTaxableAmount().toString(),
                                itcv.getTaxAmount().toString(), tax.isNotTaxdeductable(),
                                tax.isTaxdeductable());
                        final String invoicedocumentType = invoice.getDocumentType().getDocumentCategory();
                        final boolean isReversal = invoice.getDocumentType().isReversal();
                        String dateFormatString = OBPropertiesProvider.getInstance().getOpenbravoProperties()
                                .getProperty("dateFormat.java");
                        SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
                        String taxAmountConverted = fact.getM_doc().convertAmount(taxAmt,
                                invoice.isSalesTransaction(), dateFormat.format(invoice.getAccountingDate()),
                                AcctServer.TABLEID_Invoice, invoice.getId(), invoice.getCurrency().getId(),
                                as.m_C_Currency_ID, line, as, fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn)
                                .toString();
                        // ARI, ARF, ARI_RM
                        if (invoicedocumentType.equals(AcctServer.DOCTYPE_ARInvoice)
                                || invoicedocumentType.equals(AcctServer.DOCTYPE_ARProForma)
                                || invoicedocumentType.equals(AcctServer.DOCTYPE_RMSalesInvoice)) {
                            if (isReversal) {
                                final FactLine factLine1 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                                        invoice.getCurrency().getId(), "", taxAmountConverted,
                                        Fact_Acct_Group_ID, nextSeqNo(SeqNo), documentType, conn);
                                factLine2 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxDue, as, conn),
                                        invoice.getCurrency().getId(), taxAmt.toString(), "",
                                        Fact_Acct_Group_ID, nextSeqNo(factLine1.m_SeqNo), documentType, conn);
                            } else {
                                final FactLine factLine1 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                                        invoice.getCurrency().getId(), taxAmountConverted, "",
                                        Fact_Acct_Group_ID, nextSeqNo(SeqNo), documentType, conn);
                                factLine2 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxDue, as, conn),
                                        invoice.getCurrency().getId(), "", taxAmt.toString(),
                                        Fact_Acct_Group_ID, nextSeqNo(factLine1.m_SeqNo), documentType, conn);
                            }
                        } // ARC
                        else if (invoicedocumentType.equals(AcctServer.DOCTYPE_ARCredit)) {
                            final FactLine factLine1 = fact.createLine(line,
                                    m_tax.getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                                    invoice.getCurrency().getId(), "", taxAmountConverted, Fact_Acct_Group_ID,
                                    nextSeqNo(SeqNo), documentType, conn);
                            factLine2 = fact.createLine(line,
                                    m_tax.getAccount(DocTax.ACCTTYPE_TaxDue, as, conn),
                                    invoice.getCurrency().getId(), taxAmt.toString(), "", Fact_Acct_Group_ID,
                                    nextSeqNo(factLine1.m_SeqNo), documentType, conn);
                        }
                        // API
                        else if (invoicedocumentType.equals(AcctServer.DOCTYPE_APInvoice)) {
                            if (isReversal) {
                                final FactLine factLine1 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                                        invoice.getCurrency().getId(), taxAmountConverted, "",
                                        Fact_Acct_Group_ID, nextSeqNo(SeqNo), documentType, conn);
                                factLine2 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn),
                                        invoice.getCurrency().getId(), "", taxAmt.toString(),
                                        Fact_Acct_Group_ID, nextSeqNo(factLine1.m_SeqNo), documentType, conn);
                            } else {
                                final FactLine factLine1 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                                        cCurrencyID, "", taxAmountConverted, Fact_Acct_Group_ID,
                                        nextSeqNo(SeqNo), documentType, conn);
                                factLine2 = fact.createLine(line,
                                        m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn), cCurrencyID,
                                        taxAmt.toString(), "", Fact_Acct_Group_ID, nextSeqNo(factLine1.m_SeqNo),
                                        documentType, conn);
                            }
                        }
                        // APC
                        else if (invoicedocumentType.equals(AcctServer.DOCTYPE_APCredit)) {
                            final FactLine factLine1 = fact.createLine(line,
                                    m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                                    invoice.getCurrency().getId(), taxAmountConverted, "", Fact_Acct_Group_ID,
                                    nextSeqNo(SeqNo), documentType, conn);
                            factLine2 = fact.createLine(line,
                                    m_tax.getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn),
                                    invoice.getCurrency().getId(), "", taxAmt.toString(), Fact_Acct_Group_ID,
                                    nextSeqNo(factLine1.m_SeqNo), documentType, conn);
                        }
                    }
                }
            }
            if (factLine2 != null) {
                return factLine2.m_SeqNo;
            }
        }
    } catch (ServletException e) {
        log4j.error("Error ocurring posting cashVAT", e);
    }
    return SeqNo;
}

From source file:it.govpay.web.rs.dars.monitoraggio.pagamenti.PagamentiHandler.java

@Override
public String getTitolo(Pagamento entry, BasicBD bd) {
    Date dataPagamento = entry.getDataPagamento();
    BigDecimal importoPagato = entry.getImportoPagato();
    StringBuilder sb = new StringBuilder();

    String pagamentoString = Utils.getInstance(this.getLanguage()).getMessageWithParamsFromResourceBundle(
            this.nomeServizio + ".label.titolo", (importoPagato.toString() + ""),
            this.sdf.format(dataPagamento));
    sb.append(pagamentoString);//from  w  ww.j  av  a 2s  .com
    return sb.toString();
}

From source file:it.geosolutions.geobatch.destination.vulnerability.VulnerabilityComputation.java

private void calculateCell(RenderedImage currentImage, Map<Integer, TargetInfo> currentBPT, String targetID,
        String outFeatureName, int trace, VulnerabilityStatsEngine vse, OutputObject vulnerabilityObj,
        VulnerabilityOperation concreteOperation, VulnerabilityMonitor monitor, List<Double> allDistances,
        int reportingLoopStep, String geoName, Filter baseFilter, ConcurrentSkipListSet<BigDecimal> arcIdsSet,
        SimpleFeature currentCell) {/*w  w  w.j  a v  a2  s.co m*/

    // Selection of the id associated to the feature.
    BigDecimal cellId = ((BigDecimal) currentCell.getAttribute(ID_GEO_ARCO));

    // Check if the feature has been already taken
    boolean newCell = arcIdsSet.add(cellId);
    if (newCell) {

        Map<Double, ResultStatsMap> statList = new TreeMap<Double, ResultStatsMap>();

        // For level 3, get all the arcs that intersect with
        // the current grid cell
        FeatureIterator<SimpleFeature> iterator = null;

        try {
            iterator = getArcsForCell(geoName, baseFilter, currentCell);

            while (iterator.hasNext()) {
                calculateBetchOfArcsForCell(currentImage, currentBPT, vse, allDistances, statList, iterator,
                        cellId.toString(), MAX_TEMP_CALC, monitor, targetID);
            }
        } catch (Exception e) {
            monitor.incrementErrors();
            monitor.newMessage(new VulnerabilityMonitor.Message(TYPE.ERROR,
                    "Raster=" + targetID + ", Error reading arcs for cell " + cellId, e));
            LOGGER.error("Raster=" + targetID + ", Error reading arcs for cell " + cellId, e);
        } finally {
            if (iterator != null) {
                iterator.close();
            }
        }

        // write cell stats
        for (Double processedDistance : allDistances) {
            try {
                // Writing of the result for the
                // selected distance and Id
                concreteOperation.writeOutputObjects(trace, vulnerabilityObj, monitor.getTotal(),
                        outFeatureName, currentCell, buildFid(cellId.toString(), processedDistance),
                        statList.get(processedDistance).getStatsMap(), partner);
            } catch (Exception e) {
                monitor.incrementErrors();
                monitor.newMessage(new VulnerabilityMonitor.Message(TYPE.ERROR,
                        "Raster=" + targetID + ", Error writing cell " + cellId + " on " + geoName, e));

                LOGGER.error("Raster=" + targetID + ", Error writing objects on " + geoName, e);
            }
        }

        // Update of the LoopCounter
        monitor.incrementCounter();
        monitor.newMessage(
                new VulnerabilityMonitor.Message(TYPE.PROGRESS, "Calculating vulnerability for " + targetID));

        // DEBUG: indication of which arc is calculated
        if (LOGGER.isDebugEnabled() && currentCell != null) {
            LOGGER.debug("Raster=" + targetID + ", Computed cell " + cellId);
        }
    }
}

From source file:org.apache.cloudstack.quota.QuotaAlertManagerImpl.java

public void sendQuotaAlert(DeferredQuotaEmail emailToBeSent) {
    final AccountVO account = emailToBeSent.getAccount();
    final BigDecimal balance = emailToBeSent.getQuotaBalance();
    final BigDecimal usage = emailToBeSent.getQuotaUsage();
    final QuotaConfig.QuotaEmailTemplateTypes emailType = emailToBeSent.getEmailTemplateType();

    final List<QuotaEmailTemplatesVO> emailTemplates = _quotaEmailTemplateDao
            .listAllQuotaEmailTemplates(emailType.toString());
    if (emailTemplates != null && emailTemplates.get(0) != null) {
        final QuotaEmailTemplatesVO emailTemplate = emailTemplates.get(0);

        final DomainVO accountDomain = _domainDao.findByIdIncludingRemoved(account.getDomainId());
        final List<UserVO> usersInAccount = _userDao.listByAccount(account.getId());

        String userNames = "";
        final List<String> emailRecipients = new ArrayList<String>();
        for (UserVO user : usersInAccount) {
            userNames += String.format("%s <%s>,", user.getUsername(), user.getEmail());
            emailRecipients.add(user.getEmail());
        }// w w w .  j  a  v a 2 s. c o  m
        if (userNames.endsWith(",")) {
            userNames = userNames.substring(0, userNames.length() - 1);
        }

        final Map<String, String> optionMap = new HashMap<String, String>();
        optionMap.put("accountName", account.getAccountName());
        optionMap.put("accountID", account.getUuid());
        optionMap.put("accountUsers", userNames);
        optionMap.put("domainName", accountDomain.getName());
        optionMap.put("domainID", accountDomain.getUuid());
        optionMap.put("quotaBalance", QuotaConfig.QuotaCurrencySymbol.value() + " " + balance.toString());
        if (emailType == QuotaEmailTemplateTypes.QUOTA_STATEMENT) {
            optionMap.put("quotaUsage", QuotaConfig.QuotaCurrencySymbol.value() + " " + usage.toString());
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("accountName" + account.getAccountName() + "accountID" + account.getUuid()
                    + "accountUsers" + userNames + "domainName" + accountDomain.getName() + "domainID"
                    + accountDomain.getUuid());
        }

        final StrSubstitutor templateEngine = new StrSubstitutor(optionMap);
        final String subject = templateEngine.replace(emailTemplate.getTemplateSubject());
        final String body = templateEngine.replace(emailTemplate.getTemplateBody());
        try {
            _emailQuotaAlert.sendQuotaAlert(emailRecipients, subject, body);
            emailToBeSent.sentSuccessfully(_quotaAcc);
        } catch (Exception e) {
            s_logger.error(String.format(
                    "Unable to send quota alert email (subject=%s; body=%s) to account %s (%s) recipients (%s) due to error (%s)",
                    subject, body, account.getAccountName(), account.getUuid(), emailRecipients, e));
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Exception", e);
            }
        }
    } else {
        s_logger.error(String.format(
                "No quota email template found for type %s, cannot send quota alert email to account %s(%s)",
                emailType, account.getAccountName(), account.getUuid()));
    }
}

From source file:ca.uhn.fhir.parser.JsonParser.java

private void encodeChildElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource,
        JsonLikeWriter theEventWriter, IBase theNextValue, BaseRuntimeElementDefinition<?> theChildDef,
        String theChildName, boolean theContainedResource, CompositeChildElement theChildElem,
        boolean theForceEmpty) throws IOException {

    switch (theChildDef.getChildType()) {
    case ID_DATATYPE: {
        IIdType value = (IIdType) theNextValue;
        String encodedValue = "id".equals(theChildName) ? value.getIdPart() : value.getValue();
        if (isBlank(encodedValue)) {
            break;
        }//from w  w  w. ja v  a2 s. c o  m
        if (theChildName != null) {
            write(theEventWriter, theChildName, encodedValue);
        } else {
            theEventWriter.write(encodedValue);
        }
        break;
    }
    case PRIMITIVE_DATATYPE: {
        final IPrimitiveType<?> value = (IPrimitiveType<?>) theNextValue;
        if (isBlank(value.getValueAsString())) {
            if (theForceEmpty) {
                theEventWriter.writeNull();
            }
            break;
        }

        if (value instanceof IBaseIntegerDatatype) {
            if (theChildName != null) {
                write(theEventWriter, theChildName, ((IBaseIntegerDatatype) value).getValue());
            } else {
                theEventWriter.write(((IBaseIntegerDatatype) value).getValue());
            }
        } else if (value instanceof IBaseDecimalDatatype) {
            BigDecimal decimalValue = ((IBaseDecimalDatatype) value).getValue();
            decimalValue = new BigDecimal(decimalValue.toString()) {
                private static final long serialVersionUID = 1L;

                @Override
                public String toString() {
                    return value.getValueAsString();
                }
            };
            if (theChildName != null) {
                write(theEventWriter, theChildName, decimalValue);
            } else {
                theEventWriter.write(decimalValue);
            }
        } else if (value instanceof IBaseBooleanDatatype) {
            if (theChildName != null) {
                write(theEventWriter, theChildName, ((IBaseBooleanDatatype) value).getValue());
            } else {
                Boolean booleanValue = ((IBaseBooleanDatatype) value).getValue();
                if (booleanValue != null) {
                    theEventWriter.write(booleanValue.booleanValue());
                }
            }
        } else {
            String valueStr = value.getValueAsString();
            if (theChildName != null) {
                write(theEventWriter, theChildName, valueStr);
            } else {
                theEventWriter.write(valueStr);
            }
        }
        break;
    }
    case RESOURCE_BLOCK:
    case COMPOSITE_DATATYPE: {
        if (theChildName != null) {
            theEventWriter.beginObject(theChildName);
        } else {
            theEventWriter.beginObject();
        }
        encodeCompositeElementToStreamWriter(theResDef, theResource, theNextValue, theEventWriter,
                theContainedResource, theChildElem);
        theEventWriter.endObject();
        break;
    }
    case CONTAINED_RESOURCE_LIST:
    case CONTAINED_RESOURCES: {
        /*
         * Disabled per #103 ContainedDt value = (ContainedDt) theNextValue; for (IResource next :
         * value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) { continue; }
         * encodeResourceToJsonStreamWriter(theResDef, next, theWriter, null, true,
         * fixContainedResourceId(next.getId().getValue())); }
         */
        List<IBaseResource> containedResources = getContainedResources().getContainedResources();
        if (containedResources.size() > 0) {
            beginArray(theEventWriter, theChildName);

            for (IBaseResource next : containedResources) {
                IIdType resourceId = getContainedResources().getResourceId(next);
                encodeResourceToJsonStreamWriter(theResDef, next, theEventWriter, null, true,
                        fixContainedResourceId(resourceId.getValue()));
            }

            theEventWriter.endArray();
        }
        break;
    }
    case PRIMITIVE_XHTML_HL7ORG:
    case PRIMITIVE_XHTML: {
        if (!isSuppressNarratives()) {
            IPrimitiveType<?> dt = (IPrimitiveType<?>) theNextValue;
            if (theChildName != null) {
                write(theEventWriter, theChildName, dt.getValueAsString());
            } else {
                theEventWriter.write(dt.getValueAsString());
            }
        } else {
            if (theChildName != null) {
                // do nothing
            } else {
                theEventWriter.writeNull();
            }
        }
        break;
    }
    case RESOURCE:
        IBaseResource resource = (IBaseResource) theNextValue;
        RuntimeResourceDefinition def = myContext.getResourceDefinition(resource);
        encodeResourceToJsonStreamWriter(def, resource, theEventWriter, theChildName, false, true);
        break;
    case UNDECL_EXT:
    default:
        throw new IllegalStateException(
                "Should not have this state here: " + theChildDef.getChildType().name());
    }

}

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

@Deprecated
public static String getConvertedAmt(String Amt, String CurFrom_ID, String CurTo_ID, String ConvDate,
        String RateType, String client, String org, String recordId, String docType, ConnectionProvider conn) {
    boolean useSystemConversionRate = true;
    if (log4j.isDebugEnabled())
        log4j.debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt + " - CurFrom_ID : "
                + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: " + ConvDate + " - RateType:"
                + RateType + " - client:" + client + "- org:" + org);

    if (Amt.equals(""))
        throw new IllegalArgumentException("AcctServer - getConvertedAmt - required parameter missing - Amt");
    if ((CurFrom_ID.equals(CurTo_ID) && !docType.equals(EXCHANGE_DOCTYPE_Transaction)) || Amt.equals("0"))
        return Amt;
    AcctServerData[] data = null;/*from   w  w  w  .j  a  va 2 s  . com*/
    OBContext.setAdminMode();
    try {
        if (ConvDate != null && ConvDate.equals(""))
            ConvDate = DateTimeData.today(conn);
        // ConvDate IN DATE
        if (RateType == null || RateType.equals(""))
            RateType = "S";
        data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType, client, org);
        // Search if exists any conversion rate at document level

        OBCriteria<ConversionRateDoc> docRateCriteria = OBDal.getInstance()
                .createCriteria(ConversionRateDoc.class);
        if (docType.equals(EXCHANGE_DOCTYPE_Invoice) && recordId != null) {
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY,
                    OBDal.getInstance().get(Currency.class, CurTo_ID)));
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY,
                    OBDal.getInstance().get(Currency.class, CurFrom_ID)));
            // get reversed invoice id if exist.
            OBCriteria<ReversedInvoice> reversedCriteria = OBDal.getInstance()
                    .createCriteria(ReversedInvoice.class);
            reversedCriteria.add(Restrictions.eq(ReversedInvoice.PROPERTY_INVOICE,
                    OBDal.getInstance().get(Invoice.class, recordId)));
            if (!reversedCriteria.list().isEmpty()) {
                String strDateFormat;
                strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
                        .getProperty("dateFormat.java");
                final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
                ConvDate = dateFormat
                        .format(reversedCriteria.list().get(0).getReversedInvoice().getAccountingDate());
                data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType,
                        client, org);
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE, OBDal.getInstance()
                        .get(Invoice.class, reversedCriteria.list().get(0).getReversedInvoice().getId())));
            } else {
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE,
                        OBDal.getInstance().get(Invoice.class, recordId)));
            }
            useSystemConversionRate = false;
        } else if (docType.equals(EXCHANGE_DOCTYPE_Payment)) {
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY,
                    OBDal.getInstance().get(Currency.class, CurTo_ID)));
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY,
                    OBDal.getInstance().get(Currency.class, CurFrom_ID)));
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_PAYMENT,
                    OBDal.getInstance().get(FIN_Payment.class, recordId)));
            useSystemConversionRate = false;
        } else if (docType.equals(EXCHANGE_DOCTYPE_Transaction)) {
            APRM_FinaccTransactionV a = OBDal.getInstance().get(APRM_FinaccTransactionV.class, recordId);
            if (a.getForeignCurrency() != null) { // && !a.getForeignCurrency().getId().equals(CurTo_ID)
                String strDateFormat;
                strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
                        .getProperty("dateFormat.java");
                final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
                Amt = a.getForeignAmount().toString();
                data = AcctServerData.currencyConvert(conn, Amt, a.getForeignCurrency().getId(), CurTo_ID,
                        ConvDate, RateType, client, org);
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY,
                        OBDal.getInstance().get(Currency.class, CurTo_ID)));
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY,
                        OBDal.getInstance().get(Currency.class, a.getForeignCurrency().getId())));
            } else {
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY,
                        OBDal.getInstance().get(Currency.class, CurTo_ID)));
                docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY,
                        OBDal.getInstance().get(Currency.class, CurFrom_ID)));
            }
            docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_FINANCIALACCOUNTTRANSACTION,
                    OBDal.getInstance().get(APRM_FinaccTransactionV.class, recordId)));
            useSystemConversionRate = false;
        }
        if (docType.equals(EXCHANGE_DOCTYPE_Invoice) || docType.equals(EXCHANGE_DOCTYPE_Payment)
                || docType.equals(EXCHANGE_DOCTYPE_Transaction)) {
            List<ConversionRateDoc> conversionRates = docRateCriteria.list();
            if (!conversionRates.isEmpty() && !useSystemConversionRate) {
                BigDecimal Amount = new BigDecimal(Amt);
                BigDecimal AmountConverted = Amount.multiply(conversionRates.get(0).getRate()).setScale(2,
                        BigDecimal.ROUND_HALF_UP);
                return AmountConverted.toString();
            }
        }
    } catch (ServletException e) {
        log4j.warn(e);
        e.printStackTrace();
    } finally {
        OBContext.restorePreviousMode();
    }
    if (data == null || data.length == 0) {
        /*
         * log4j.error("No conversion ratio"); throw new
         * ServletException("No conversion ratio defined!");
         */
        return "";
    } else {
        if (log4j.isDebugEnabled())
            log4j.debug("getConvertedAmount - converted:" + data[0].converted);
        return data[0].converted;
    }
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Create and convert Fact Line using a specified conversion date. Used to create a DR and/or CR
 * entry/*  ww  w  .j  a  va2s. com*/
 * 
 * @param docLine
 *          the document line or null
 * @param account
 *          if null, line is not created
 * @param C_Currency_ID
 *          the currency
 * @param debitAmt
 *          debit amount, can be null
 * @param creditAmt
 *          credit amount, can be null
 * @param Fact_Acct_Group_ID
 * 
 * @param SeqNo
 * 
 * @param DocBaseType
 * 
 * @param conversionDate
 *          Date to convert currencies if required
 * @param conversionRate
 *          The rate to use to convert from source amount to account amount. May be null
 * @return Fact Line
 */
public FactLine createLine(DocLine docLine, Account account, String C_Currency_ID, String debitAmt,
        String creditAmt, String Fact_Acct_Group_ID, String SeqNo, String DocBaseType, String conversionDate,
        BigDecimal conversionRate, ConnectionProvider conn) {

    String strNegate = "";
    try {
        strNegate = AcctServerData.selectNegate(conn, m_acctSchema.m_C_AcctSchema_ID, DocBaseType);
        if (strNegate.equals(""))
            strNegate = AcctServerData.selectDefaultNegate(conn, m_acctSchema.m_C_AcctSchema_ID);
    } catch (ServletException e) {
    }
    if (strNegate.equals(""))
        strNegate = "Y";
    BigDecimal DebitAmt = new BigDecimal(debitAmt.equals("") ? "0.00" : debitAmt);
    BigDecimal CreditAmt = new BigDecimal(creditAmt.equals("") ? "0.00" : creditAmt);
    if (DebitAmt.compareTo(BigDecimal.ZERO) == 0 && CreditAmt.compareTo(BigDecimal.ZERO) == 0) {
        return null;
    }
    if (strNegate.equals("N") && (DebitAmt.compareTo(ZERO) < 0 || CreditAmt.compareTo(ZERO) < 0)) {
        BigDecimal convertedDebitAmt = StringUtils.isBlank(docLine.m_AmtAcctDr) ? ZERO
                : new BigDecimal(docLine.m_AmtAcctDr);
        BigDecimal convertedCreditAmt = StringUtils.isBlank(docLine.m_AmtAcctCr) ? ZERO
                : new BigDecimal(docLine.m_AmtAcctCr);

        if (DebitAmt.compareTo(ZERO) < 0) {
            CreditAmt = CreditAmt.add(DebitAmt.abs());
            creditAmt = CreditAmt.toString();
            DebitAmt = BigDecimal.ZERO;
            debitAmt = DebitAmt.toString();
            convertedCreditAmt = convertedCreditAmt.add(convertedDebitAmt.abs());
            convertedDebitAmt = BigDecimal.ZERO;
        }
        if (CreditAmt.compareTo(ZERO) < 0) {
            DebitAmt = DebitAmt.add(CreditAmt.abs());
            debitAmt = DebitAmt.toString();
            CreditAmt = BigDecimal.ZERO;
            creditAmt = CreditAmt.toString();
            convertedDebitAmt = convertedDebitAmt.add(convertedCreditAmt.abs());
            convertedCreditAmt = BigDecimal.ZERO;
        }

        // If this is a manual entry then we need to recompute Amounts which were set in loadLines for
        // GL Journal Document
        if ("GLJ".equals(DocBaseType)) {
            docLine.setConvertedAmt(docLine.m_C_AcctSchema_ID, convertedDebitAmt.toString(),
                    convertedCreditAmt.toString());
        }

        if (strNegate.equals("N") && (DebitAmt.compareTo(ZERO) < 0 || CreditAmt.compareTo(ZERO) < 0)) {
            return createLine(docLine, account, C_Currency_ID, CreditAmt.abs().toString(),
                    DebitAmt.abs().toString(), Fact_Acct_Group_ID, SeqNo, DocBaseType, conn);
        }
    }

    log4jFact.debug("createLine - " + account + " - Dr=" + debitAmt + ", Cr=" + creditAmt);
    log4jFact.debug("Starting createline");
    // Data Check
    if (account == null) {
        log4jFact.debug("end of create line");
        m_doc.setStatus(AcctServer.STATUS_InvalidAccount);
        return null;
    }
    //
    log4jFact.debug("createLine - Fact_Acct_Group_ID = " + Fact_Acct_Group_ID);
    FactLine line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID,
            docLine == null ? "" : docLine.m_TrxLine_ID, Fact_Acct_Group_ID, SeqNo, DocBaseType);
    log4jFact.debug("createLine - line.m_Fact_Acct_Group_ID = " + line.m_Fact_Acct_Group_ID);
    log4jFact.debug("Object created");
    line.setDocumentInfo(m_doc, docLine);
    line.setAD_Org_ID(m_doc.AD_Org_ID);
    // if (docLine!=null) line.setAD_Org_ID(docLine.m_AD_Org_ID);
    log4jFact.debug("document info set");
    line.setAccount(m_acctSchema, account);
    log4jFact.debug("account set");

    log4jFact.debug(
            "C_Currency_ID: " + C_Currency_ID + " - debitAmt: " + debitAmt + " - creditAmt: " + creditAmt);
    // Amounts - one needs to be both not zero
    if (!line.setAmtSource(C_Currency_ID, debitAmt, creditAmt))
        return null;
    if (conversionDate == null || conversionDate.isEmpty()) {
        conversionDate = m_doc.DateAcct;
    }
    log4jFact.debug("C_Currency_ID: " + m_acctSchema.getC_Currency_ID() + " - ConversionDate: " + conversionDate
            + " - CurrencyRateType: " + m_acctSchema.getCurrencyRateType());
    // Convert
    if (conversionRate != null) {
        line.convertByRate(m_acctSchema.getC_Currency_ID(), conversionRate);
    } else {
        line.convert(m_acctSchema.getC_Currency_ID(), conversionDate, m_acctSchema.getCurrencyRateType(), conn);
    }
    // Optionally overwrite Acct Amount
    if (docLine != null && !docLine.m_AmtAcctDr.equals("") && !docLine.m_AmtAcctCr.equals(""))
        line.setAmtAcct(docLine.m_AmtAcctDr, docLine.m_AmtAcctCr);
    // Info
    line.setJournalInfo(m_doc.GL_Category_ID);
    line.setPostingType(m_postingType);
    // Set Info
    line.setDocumentInfo(m_doc, docLine);
    //
    log4jFact.debug("createLine - " + m_doc.DocumentNo);
    log4jFact.debug("********************* Fact - createLine - DocumentNo - " + m_doc.DocumentNo
            + " -  m_lines.size() - " + m_lines.size());

    line.roundToCurrencyPrecision();

    m_lines.add(line);
    return line;
}

From source file:org.openhab.binding.km200.internal.KM200Comm.java

/**
 * This function sets the state of a service on the device
 *
 *///from w  w  w  .j av  a  2s  .c o  m
public byte[] sendProvidersState(KM200BindingProvider provider, String item, Command command) {
    synchronized (device) {
        String type = null;
        String dataToSend = null;
        KM200CommObject object = null;
        Class<? extends Item> itemType = provider.getItemType(item);
        String service = checkParameterReplacement(provider, item);

        logger.debug("Prepare item for send: {} type: {} item: {}", service, type, itemType.getName());
        if (device.blacklistMap.contains(service)) {
            logger.debug("Service on blacklist: {}", service);
            return null;
        }
        if (device.serviceMap.containsKey(service)) {
            if (device.serviceMap.get(service).getWriteable() == 0) {
                logger.error("Service is listed as read-only: {}", service);
                return null;
            }
            object = device.serviceMap.get(service);
            type = object.getServiceType();
        } else {
            logger.error("Service is not in the determined device service list: {}", service);
            return null;
        }
        /* The service is availible, set now the values depeding on the item and binding type */
        logger.debug("state of: {} type: {}", command, type);
        /* Binding is a NumberItem */
        if (itemType.isAssignableFrom(NumberItem.class)) {
            BigDecimal bdVal = ((DecimalType) command).toBigDecimal();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked")
                List<BigDecimal> valParas = (List<BigDecimal>) object.getValueParameter();
                BigDecimal minVal = valParas.get(0);
                BigDecimal maxVal = valParas.get(1);
                if (bdVal.compareTo(minVal) < 0) {
                    bdVal = minVal;
                }
                if (bdVal.compareTo(maxVal) > 0) {
                    bdVal = maxVal;
                }
            }
            if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", bdVal).toString();
            } else if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", bdVal.toString()).toString();
            } else if (type.equals("switchProgram") && object.getVirtual() == 1) {
                /* A switchProgram as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else if (type.equals("errorList") && object.getVirtual() == 1) {
                /* A errorList as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for numberItem: {}", type);
            }
            /* Binding is a StringItem */
        } else if (itemType.isAssignableFrom(StringItem.class)) {
            String val = ((StringType) command).toString();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked")
                List<String> valParas = (List<String>) object.getValueParameter();
                if (!valParas.contains(val)) {
                    logger.warn("Parameter is not in the service parameterlist: {}", val);
                    return null;
                }
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", Float.parseFloat(val)).toString();
            } else if (type.equals("switchProgram")) {
                if (object.getVirtual() == 1) {
                    dataToSend = sendVirtualState(object, itemType, service, command);
                } else {
                    /* The JSONArray of switch items can be sended directly */
                    try {
                        /* Check whether ths input string is a valid JSONArray */
                        JSONArray userArray = new JSONArray(val);
                        dataToSend = userArray.toString();
                    } catch (Exception e) {
                        logger.warn("The input for the switchProgram is not a valid JSONArray : {}",
                                e.getMessage());
                        return null;
                    }
                }
            } else {
                logger.warn("Not supported type for stringItem: {}", type);
            }

            /* Binding is a DateTimeItem */
        } else if (itemType.isAssignableFrom(DateTimeItem.class)) {
            String val = ((DateTimeType) command).toString();
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("switchProgram")) {
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for dateTimeItem: {}", type);
            }

            /* Binding is a SwitchItem */
        } else if (itemType.isAssignableFrom(SwitchItem.class)) {
            String val = null;
            if (provider.getParameter(item).containsKey("on")) {
                if (command == OnOffType.OFF) {
                    val = provider.getParameter(item).get("off");
                } else if (command == OnOffType.ON) {
                    val = provider.getParameter(item).get("on");
                }
            } else {
                logger.warn("Switch-Item only on configured on/off string values {}", command);
                return null;
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else {
                logger.warn("Not supported type for SwitchItem:{}", type);
            }

        } else {
            logger.warn("Bindingtype not supported: {}", itemType.getClass());
            return null;
        }
        /* If some data is availible then we have to send it to device */
        if (dataToSend != null) {
            /* base64 + encoding */
            logger.debug("Encoding: {}", dataToSend);
            byte[] encData = encodeMessage(dataToSend);
            if (encData == null) {
                logger.error("Couldn't encrypt data");
                return null;
            }
            return encData;
        } else {
            return null;
        }
    }
}