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:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des fichiers dtails
 * @param mlr/*w ww  .j  a  v  a 2s .co m*/
 * @param fileName
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public void exportMoveLineAllTypeSelectFILE2(MoveLineReport moveLineReport, String fileName)
        throws AxelorException, IOException {

    log.info("In export service FILE 2 :");

    Company company = moveLineReport.getCompany();

    String companyCode = "";
    String moveLineQueryStr = "";

    int typeSelect = moveLineReport.getTypeSelect();

    if (company != null) {
        companyCode = company.getCode();
        moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    }
    if (moveLineReport.getJournal() != null) {
        moveLineQueryStr += String.format(" AND self.move.journal = %s", moveLineReport.getJournal().getId());
    } else {
        moveLineQueryStr += String.format(" AND self.move.journal.type = %s",
                moveLineReportService.getJournalType(moveLineReport).getId());
    }

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }

    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (typeSelect != 8) {
        moveLineQueryStr += String.format(" AND self.account.reconcileOk = false ");
    }
    moveLineQueryStr += String.format(
            "AND self.move.accountingOk = true AND self.move.ignoreInAccountingOk = false AND self.move.moveLineReport = %s",
            moveLineReport.getId());
    moveLineQueryStr += String.format(" AND self.move.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    Query queryDate = JPA.em().createQuery(
            "SELECT self.date from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                    + moveLineQueryStr + " group by self.date ORDER BY self.date");

    List<LocalDate> dates = new ArrayList<LocalDate>();
    dates = queryDate.getResultList();

    log.debug("dates : {}", dates);

    List<String[]> allMoveLineData = new ArrayList<String[]>();

    for (LocalDate localDate : dates) {

        Query queryExportAgressoRef = JPA.em().createQuery(
                "SELECT DISTINCT self.move.exportNumber from MoveLine self where self.account != null "
                        + "AND (self.debit > 0 OR self.credit > 0) AND self.date = '" + localDate.toString()
                        + "'" + moveLineQueryStr);
        List<String> exportAgressoRefs = new ArrayList<String>();
        exportAgressoRefs = queryExportAgressoRef.getResultList();
        for (String exportAgressoRef : exportAgressoRefs) {

            if (exportAgressoRef != null && !exportAgressoRef.isEmpty()) {

                int sequence = 1;

                Query query = JPA.em().createQuery(
                        "SELECT self.account.id from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                                + "AND self.date = '" + localDate.toString()
                                + "' AND self.move.exportNumber = '" + exportAgressoRef + "'" + moveLineQueryStr
                                + " group by self.account.id");

                List<Long> accountIds = new ArrayList<Long>();
                accountIds = query.getResultList();

                log.debug("accountIds : {}", accountIds);

                for (Long accountId : accountIds) {
                    if (accountId != null) {
                        String accountCode = accountRepo.find(accountId).getCode();
                        List<MoveLine> moveLines = moveLineRepo.all().filter(
                                "self.account.id = ?1 AND (self.debit > 0 OR self.credit > 0) AND self.date = '"
                                        + localDate.toString() + "' AND self.move.exportNumber = '"
                                        + exportAgressoRef + "'" + moveLineQueryStr,
                                accountId).fetch();

                        log.debug("movelines  : {} ", moveLines);

                        if (moveLines.size() > 0) {

                            List<MoveLine> moveLineList = moveLineService.consolidateMoveLines(moveLines);

                            List<MoveLine> sortMoveLineList = this.sortMoveLineByDebitCredit(moveLineList);

                            for (MoveLine moveLine3 : sortMoveLineList) {

                                Journal journal = moveLine3.getMove().getJournal();
                                LocalDate date = moveLine3.getDate();
                                String items[] = null;

                                if (typeSelect == 9) {
                                    items = new String[13];
                                } else {
                                    items = new String[12];
                                }

                                items[0] = companyCode;
                                items[1] = journal.getExportCode();
                                items[2] = moveLine3.getMove().getExportNumber();
                                items[3] = String.format("%s", sequence);
                                sequence++;
                                items[4] = accountCode;

                                BigDecimal totAmt = moveLine3.getCredit().subtract(moveLine3.getDebit());
                                String moveLineSign = "C";
                                if (totAmt.compareTo(BigDecimal.ZERO) == -1) {
                                    moveLineSign = "D";
                                    totAmt = totAmt.negate();
                                }
                                items[5] = moveLineSign;
                                items[6] = totAmt.toString();

                                String analyticAccounts = "";
                                for (AnalyticMoveLine analyticDistributionLine : moveLine3
                                        .getAnalyticMoveLineList()) {
                                    analyticAccounts = analyticAccounts
                                            + analyticDistributionLine.getAnalyticAccount().getCode() + "/";
                                }

                                if (typeSelect == 9) {
                                    items[7] = "";
                                    items[8] = analyticAccounts;
                                    items[9] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                } else {
                                    items[7] = analyticAccounts;
                                    items[8] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                }

                                allMoveLineData.add(items);

                            }
                        }
                    }
                }
            }
        }
    }

    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|',  this.createHeaderForDetailFile(typeSelect), allMoveLineData);
}

From source file:org.ethereum.rpc.Web3Impl.java

public String eth_hashrate() {
    BigDecimal hashesPerSecond = BigDecimal.ZERO;
    if (RskSystemProperties.RSKCONFIG.minerServerEnabled()) {
        BigInteger hashesPerHour = this.worldManager.getHashRateCalculator().calculateNodeHashRate(1L,
                TimeUnit.HOURS);// w  w w .  ja  va2s .  c  om
        hashesPerSecond = new BigDecimal(hashesPerHour).divide(new BigDecimal(TimeUnit.HOURS.toSeconds(1)), 3,
                RoundingMode.HALF_UP);
    }

    String result = hashesPerSecond.toString();

    if (logger.isDebugEnabled())
        logger.debug("eth_hashrate(): " + result);

    return result;
}

From source file:org.apache.ofbiz.accounting.thirdparty.verisign.PayflowPro.java

public static Map<String, Object> ccRefund(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal amount = (BigDecimal) context.get("refundAmount");
    String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
    String configString = (String) context.get("paymentConfig");
    Locale locale = (Locale) context.get("locale");
    if (configString == null) {
        configString = "payment.properties";
    }//from  w  w  w.j a va2s.c om

    GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(paymentPref);

    if (captureTrans == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                "AccountingPaymentTransactionAuthorizationNotFoundCannotRefund", locale));
    }

    boolean isPayPal = false;
    // Are we doing a cc or a paypal payment?
    if ("EXT_PAYPAL".equals(paymentPref.getString("paymentMethodTypeId"))) {
        isPayPal = true;
    }

    // auth ref number
    String refNum = captureTrans.getString("referenceNum");
    Map<String, String> data = UtilMisc.toMap("ORIGID", refNum);

    // tx type (Credit)
    data.put("TRXTYPE", "C");

    // get the orderID
    String orderId = paymentPref.getString("orderId");

    if (isPayPal) {
        data.put("TENDER", "P");

        data.put("MEMO", orderId);
        // PayPal won't allow us to refund more than the capture amount
        BigDecimal captureAmount = captureTrans.getBigDecimal("amount");
        amount = amount.min(captureAmount);
    } else {
        // credit card tender
        data.put("TENDER", "C");

        data.put("COMMENT1", orderId);
    }

    // amount to capture
    data.put("AMT", amount.toString());

    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, configString, context);

    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, configString);

    // parse the context parameters
    params.append("&").append(parseContext(data));

    // transmit the request
    if (Debug.verboseOn())
        Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString,
            "payment.verisign.enable_transmit", "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }

    if (Debug.verboseOn())
        Debug.logVerbose("Response from Verisign: " + resp, module);

    // check the response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    parseRefundResponse(resp, result);
    result.put("refundAmount", amount);
    return result;
}

From source file:org.openvpms.hl7.impl.TestPharmacyService.java

/**
 * Creates an RDS^O13 message from an RDE^O11 order.
 *
 * @param order    the order//from   w  ww  . j  av a2  s  .  com
 * @param quantity the quantity to dispense
 * @return a new message
 * @throws HL7Exception for any HL7 exception
 * @throws IOException  for any I/O exception
 */
private RDS_O13 createRDS(RDE_O11 order, BigDecimal quantity) throws HL7Exception, IOException {
    RDS_O13 message = new RDS_O13(sendContext.getModelClassFactory());
    message.setParser(sendContext.getGenericParser());
    message.initQuickstart("RDS", "O13", "P");
    MSH msh = message.getMSH();
    MSH orderMSH = order.getMSH();
    RXD rxd = message.getORDER().getRXD();
    RXE rxe = message.getORDER().getENCODING().getRXE();
    FT1 ft1 = message.getORDER().getFT1();
    RXO rxo = order.getORDER().getORDER_DETAIL().getRXO();

    // populate header
    DeepCopy.copy(orderMSH.getReceivingApplication(), msh.getSendingApplication());
    DeepCopy.copy(orderMSH.getReceivingFacility(), msh.getSendingFacility());
    DeepCopy.copy(orderMSH.getSendingApplication(), msh.getReceivingApplication());
    DeepCopy.copy(orderMSH.getSendingFacility(), msh.getReceivingFacility());

    // populate PID
    DeepCopy.copy(order.getPATIENT().getPID(), message.getPATIENT().getPID());

    // populate PV1
    DeepCopy.copy(order.getPATIENT().getPATIENT_VISIT().getPV1(),
            message.getPATIENT().getPATIENT_VISIT().getPV1());

    // populate ORC
    DeepCopy.copy(order.getORDER().getORC(), message.getORDER().getORC());
    message.getORDER().getORC().getOrderControl().setValue("RE");

    // populate RXE
    DeepCopy.copy(rxo.getRequestedGiveCode(), rxe.getGiveCode());
    DeepCopy.copy(rxo.getRequestedDispenseUnits(), rxe.getGiveUnits());
    DeepCopy.copy(rxo.getProviderSAdministrationInstructions(0), rxe.getProviderSAdministrationInstructions(0));
    rxe.getDispenseAmount().setValue(quantity.toString());
    DeepCopy.copy(rxo.getRequestedDispenseUnits(), rxe.getDispenseUnits());

    // populate RXD
    DeepCopy.copy(rxo.getRequestedGiveCode(), rxd.getDispenseGiveCode());
    rxd.getActualDispenseAmount().setValue(quantity.toString());
    DeepCopy.copy(rxo.getRequestedDispenseUnits(), rxd.getActualDispenseUnits());

    // populate FT1
    ft1.getSetIDFT1().setValue("1");
    ft1.getTransactionType().setValue("CG");
    ft1.getTransactionQuantity().setValue(quantity.toString());
    DeepCopy.copy(rxe.getGiveCode(), ft1.getTransactionCode());
    return message;
}

From source file:org.egov.works.web.controller.lineestimate.CreateSpillOverLineEstimateController.java

private void validateBudgetAmount(final LineEstimate lineEstimate, final BindingResult errors) {
    final List<Long> budgetheadid = new ArrayList<Long>();
    budgetheadid.add(lineEstimate.getBudgetHead().getId());

    try {//from  w w w  .  j  ava 2  s . co  m
        final BigDecimal budgetAvailable = budgetDetailsDAO.getPlanningBudgetAvailable(
                lineEstimateService.getCurrentFinancialYear(new Date()).getId(),
                Integer.parseInt(lineEstimate.getExecutingDepartment().getId().toString()),
                lineEstimate.getFunction().getId(), null,
                lineEstimate.getScheme() == null ? null
                        : Integer.parseInt(lineEstimate.getScheme().getId().toString()),
                lineEstimate.getSubScheme() == null ? null
                        : Integer.parseInt(lineEstimate.getSubScheme().getId().toString()),
                null, budgetheadid, Integer.parseInt(lineEstimate.getFund().getId().toString()));

        BigDecimal totalAppropriationAmount = BigDecimal.ZERO;

        for (final LineEstimateDetails led : lineEstimate.getLineEstimateDetails())
            if (lineEstimate.isBillsCreated() && led.getGrossAmountBilled() != null)
                totalAppropriationAmount = totalAppropriationAmount
                        .add(led.getEstimateAmount().subtract(led.getGrossAmountBilled()));
            else
                totalAppropriationAmount = totalAppropriationAmount.add(led.getEstimateAmount());
        if (BudgetControlType.BudgetCheckOption.MANDATORY.toString()
                .equalsIgnoreCase(budgetControlTypeService.getConfigValue())
                && budgetAvailable.compareTo(totalAppropriationAmount) == -1)
            errors.reject("error.budgetappropriation.amount",
                    new String[] { budgetAvailable.toString(), totalAppropriationAmount.toString() }, null);
    } catch (final ValidationException e) {
        // TODO: Used ApplicationRuntimeException for time being since there is issue in session after
        // budgetDetailsDAO.getPlanningBudgetAvailable API call
        // TODO: needs to replace with errors.reject
        for (final ValidationError error : e.getErrors())
            throw new ApplicationRuntimeException(error.getKey());
        /*
         * for (final ValidationError error : e.getErrors()) errors.reject(error.getMessage());
         */
    }
}

From source file:org.kuali.ole.select.service.OLEAddTitlesToInvoiceService.java

private void updateForeignCurrencyDetails(OleInvoiceDocument oleInvoiceDocument) {
    String currencyType = null;// ww w  . j av a 2s  .c  o  m
    BigDecimal exchangeRate = null;
    oleInvoiceDocument.setInvoiceCurrencyType(
            oleInvoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId().toString());
    if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
        currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
        if (StringUtils.isNotBlank(currencyType)) {
            // local vendor
            if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
                oleInvoiceDocument.setForeignCurrencyFlag(true);
                oleInvoiceDocument
                        .setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
                exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType())
                        .getExchangeRate();
                oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
                if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceAmount())) {
                    oleInvoiceDocument.setForeignVendorInvoiceAmount(
                            new BigDecimal(oleInvoiceDocument.getInvoiceAmount()).multiply(exchangeRate));
                    oleInvoiceDocument.setForeignInvoiceAmount(
                            new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
                    oleInvoiceDocument.setForeignVendorAmount(
                            new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
                }
            }
        }
    }

}

From source file:org.globus.exec.client.HackedGramJob.java

private EndpointReferenceType createJobEndpoint(final ManagedJobFactoryPortType factoryPort,
        final boolean batch) throws Exception {
    // Create a service instance base on creation info
    logger.debug("creating ManagedJob instance");

    if (logger.isDebugEnabled()) {
        long millis = System.currentTimeMillis();
        BigDecimal seconds = new BigDecimal(((double) millis) / 1000);
        seconds = seconds.setScale(3, BigDecimal.ROUND_HALF_DOWN);
        logger.debug("submission time, in seconds from the Epoch:" + "\nbefore: " + seconds.toString());
        logger.debug("\nbefore, in milliseconds: " + millis);
    }// w  w w . j  ava 2s.co  m

    ((org.apache.axis.client.Stub) factoryPort).setTimeout(this.axisStubTimeOut);

    CreateManagedJobInputType jobInput = new CreateManagedJobInputType();
    jobInput.setInitialTerminationTime(getTerminationTime());
    if (this.id != null) {
        jobInput.setJobID(new AttributedURI(this.id));
    }
    if (this.jobDescription instanceof MultiJobDescriptionType) {
        jobInput.setMultiJob((MultiJobDescriptionType) this.getDescription());
    } else {
        jobInput.setJob(this.getDescription());
    }

    if (!batch) {
        if (this.useDefaultNotificationConsumer) {
            setupNotificationConsumerManager();
        }

        try {
            if (this.useDefaultNotificationConsumer) {
                setupNotificationConsumer();
            }

            Subscribe subscriptionRequest = new Subscribe();
            subscriptionRequest.setConsumerReference(this.notificationConsumerEPR);
            TopicExpressionType topicExpression = new TopicExpressionType(WSNConstants.SIMPLE_TOPIC_DIALECT,
                    ManagedJobConstants.RP_STATE);
            subscriptionRequest.setTopicExpression(topicExpression);
            jobInput.setSubscribe(subscriptionRequest);
        } catch (Exception e) {
            // may happen...? Let's not fail.
            logger.error(e);
            try {
                unbind();
            } catch (Exception unbindEx) {
                // let's not fail the unbinding
                logger.error(unbindEx);
            }
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("<startTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</startTime>");
    }
    CreateManagedJobOutputType response = factoryPort.createManagedJob(jobInput);
    if (logger.isInfoEnabled()) {
        logger.info("<endTime name=\"createManagedJob\">" + System.currentTimeMillis() + "</endTime");
    }
    EndpointReferenceType jobEPR = (EndpointReferenceType) ObjectSerializer
            .clone(response.getManagedJobEndpoint());

    // This doesn't work with GRAM.NET for some reason...
    /*
    if(logger.isDebugEnabled()) {
       * logger.debug("Job Handle: " + AuditUtil.eprToGridId(jobEPR)); Element jobEndpointElement = null; try { jobEndpointElement = ObjectSerializer.toElement( jobEPR, new QName( "http://schemas.xmlsoap.org/ws/2004/03/addressing", "EndpointReferenceType")); } catch (Exception e)
       * { throw new RuntimeException(e); } logger.debug("Job EPR: " + XmlUtils.toString(jobEndpointElement));
    }
       */

    EndpointReferenceType subscriptionEPR = response.getSubscriptionEndpoint();

    if (subscriptionEPR != null) {
        this.notificationProducerEPR = (EndpointReferenceType) ObjectSerializer.clone(subscriptionEPR);
    }

    if (logger.isDebugEnabled()) {
        Calendar terminationTime = response.getNewTerminationTime();
        Calendar serviceCurrentTime = response.getCurrentTime();
        logger.debug(
                "Termination time granted by the factory to the job resource: " + terminationTime.getTime());
        logger.debug("Current time seen by the factory service on creation: " + serviceCurrentTime.getTime());
    }

    return jobEPR;
}

From source file:org.egov.works.web.actions.estimate.FinancialDetailAction.java

public void search(final String src) {
    if (APP.equalsIgnoreCase(src) && abstractEstimate != null
            && abstractEstimate.getFinancialDetails().get(0) != null)
        financialDetail = abstractEstimate.getFinancialDetails().get(0);

    if (financialDetail != null && financialDetail.getFund() != null
            && financialDetail.getFund().getId() != null && financialDetail.getFund().getId() != -1)
        queryParamMap.put("fundid", financialDetail.getFund().getId());

    if (financialDetail != null && financialDetail.getFunction() != null
            && financialDetail.getFunction().getId() != null && financialDetail.getFunction().getId() != -1)
        queryParamMap.put("functionid", financialDetail.getFunction().getId());
    if (financialDetail != null && financialDetail.getBudgetGroup() != null
            && financialDetail.getBudgetGroup().getId() != null
            && financialDetail.getBudgetGroup().getId() != -1) {
        final List<BudgetGroup> budgetheadid = new ArrayList<BudgetGroup>();
        budgetheadid.add(financialDetail.getBudgetGroup());
        queryParamMap.put("budgetheadid", budgetheadid);
    }/*  ww w.  j av a 2 s .c o  m*/

    if (APP.equalsIgnoreCase(src) && financialDetail != null
            && financialDetail.getAbstractEstimate().getUserDepartment() != null)
        queryParamMap.put("deptid", financialDetail.getAbstractEstimate().getUserDepartment().getId());
    else if (getUserDepartment() != null && getUserDepartment() != -1)
        queryParamMap.put("deptid", getUserDepartment());

    if (APP.equalsIgnoreCase(src) && abstractEstimate != null
            && abstractEstimate.getLeastFinancialYearForEstimate() != null
            && abstractEstimate.getLeastFinancialYearForEstimate().getId() != null) {
        queryParamMap.put("financialyearid",
                financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getId());
        queryParamMap.put("fromDate",
                financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getStartingDate());
        queryParamMap.put("toDate", new Date());
    } else if (getReportDate() != null) {
        if (!DateUtils.compareDates(new Date(), getReportDate()))
            throw new ValidationException(Arrays.asList(new ValidationError(
                    "greaterthan.currentDate.reportDate", getText("greaterthan.currentDate.reportDate"))));
        CFinancialYear finyear = null;
        try {
            finyear = abstractEstimateService.getCurrentFinancialYear(getReportDate());
        } catch (final ApplicationRuntimeException noFinYearExp) {
            if (noFinYearExp.getMessage().equals("Financial Year Id does not exist."))
                throw new ValidationException(Arrays
                        .asList(new ValidationError(noFinYearExp.getMessage(), noFinYearExp.getMessage())));
            else
                throw noFinYearExp;

        }
        if (finyear != null && finyear.getId() != null)
            queryParamMap.put("financialyearid", finyear.getId());
        queryParamMap.put("toDate", getReportDate());
    }

    if (!queryParamMap.isEmpty() && getFieldErrors().isEmpty()) {
        BigDecimal planningBudgetPerc = new BigDecimal(0);
        try {
            totalGrant = budgetDetailsDAO.getBudgetedAmtForYear(queryParamMap);
            planningBudgetPerc = getPlanningBudgetPercentage(queryParamMap);
        } catch (final ValidationException valEx) {
            logger.error(valEx);
        }
        // String appValue =
        // worksService.getWorksConfigValue(PERCENTAGE_GRANT);

        if (planningBudgetPerc != null && !planningBudgetPerc.equals(0)) {
            setAppValueLabel(planningBudgetPerc.toString());
            totalGrantPerc = totalGrant.multiply(planningBudgetPerc.divide(new BigDecimal(100)));
            queryParamMap.put("totalGrantPerc", totalGrantPerc);
        }
        final Map<String, List> approvedBudgetFolioDetailsMap = abstractEstimateService
                .getApprovedAppropriationDetailsForBugetHead(queryParamMap);
        approvedBudgetFolioDetails = new ArrayList<BudgetFolioDetail>();
        if (approvedBudgetFolioDetailsMap != null && !approvedBudgetFolioDetailsMap.isEmpty()) {
            approvedBudgetFolioDetails = approvedBudgetFolioDetailsMap.get("budgetFolioList");
            setReportLatestValues(approvedBudgetFolioDetailsMap);
        }
    }
}

From source file:org.opentaps.amazon.product.AmazonProductServices.java

/**
 * Service looks over AmzonProduct and collect new products (and those which aren't posted due error as well),
 * creates XML document for Product Feed and post it to Amazon.com.
 * @param dctx a <code>DispatchContext</code> value
 * @param context the service context <code>Map</code>
 * @return the service response <code>Map</code>
 *//*www  .j a v  a  2 s  .  co m*/
public static Map<String, Object> publishProductsToAmazon(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    String prodId = (String) context.get("productId");

    try {
        List<EntityCondition> conditions = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition(
                "statusId", EntityOperator.IN, Arrays.asList(AmazonConstants.statusProductCreated,
                        AmazonConstants.statusProductError, AmazonConstants.statusProductChanged)));
        if (UtilValidate.isNotEmpty(prodId)) {
            conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, prodId));
        }

        EntityListIterator amazonProductsIt = delegator.findListIteratorByCondition("ViewAmazonProducts",
                EntityCondition.makeCondition(conditions, EntityOperator.AND), null,
                Arrays.asList("productId"));

        // Prepare Product Feed document
        Document productFeed = AmazonConstants.soapClient
                .createDocumentHeader(AmazonConstants.messageTypeProduct);
        Element root = productFeed.getDocumentElement();
        GenericValue viewAmazonProduct = null;
        long messageId = 1;
        Map<GenericValue, String> invalidAmazonProducts = new HashMap<GenericValue, String>();
        List<GenericValue> validAmazonProducts = new ArrayList<GenericValue>();
        while ((viewAmazonProduct = amazonProductsIt.next()) != null) {

            GenericValue amazonProduct = delegator.findByPrimaryKey("AmazonProduct",
                    UtilMisc.toMap("productId", viewAmazonProduct.get("productId")));

            if ((viewAmazonProduct.get("postFailures") != null)
                    && (AmazonConstants.productPostRetryThreshold <= viewAmazonProduct.getLong("postFailures")
                            .intValue())) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostProductAttemptsOverThreshold",
                        UtilMisc.<String, Object>toMap("productId", viewAmazonProduct.getString("productId"),
                                "threshold", AmazonConstants.productPostRetryThreshold),
                        locale);
                Debug.logInfo(errorLog, MODULE);
                continue;
            }

            String errMessage = null;

            /*
             * Some elements are required. So, we get it first and go to next iteration
             * if some of these is absent.
             */
            String title = AmazonUtil.Strings.LONG_STR_N_NULL
                    .normalize(viewAmazonProduct.getString("productName"), locale);
            if (UtilValidate.isEmpty(title)) {
                Debug.logWarning(
                        UtilProperties.getMessage(AmazonConstants.errorResource,
                                "AmazonError_NoRequiredParameter", UtilMisc.toMap("parameterName", "Title",
                                        "productName", viewAmazonProduct.getString("productId")),
                                locale),
                        MODULE);
            }

            List<GenericValue> goodIdents = viewAmazonProduct.getRelated("GoodIdentification",
                    Arrays.asList("lastUpdatedStamp DESC"));
            goodIdents = EntityUtil.filterOutByCondition(goodIdents,
                    EntityCondition.makeCondition(EntityOperator.OR,
                            EntityCondition.makeCondition("idValue", EntityOperator.EQUALS, ""),
                            EntityCondition.makeCondition("idValue", EntityOperator.EQUALS, null)));

            String upc = null;
            if (AmazonConstants.requireUpcCodes || AmazonConstants.useUPCAsSKU) {

                // Establish and validate the UPC
                upc = getProductUPC(delegator, viewAmazonProduct.getString("productId"), locale);
                if (UtilValidate.isEmpty(upc) && AmazonConstants.requireUpcCodes) {
                    errMessage = AmazonUtil.compoundError(errMessage, UtilProperties.getMessage(
                            AmazonConstants.errorResource, "AmazonError_MissingCodeUPC",
                            UtilMisc.toMap("productId", viewAmazonProduct.getString("productId")), locale));
                } else if (UtilValidate.isNotEmpty(upc) && !UtilProduct.isValidUPC(upc)) {
                    errMessage = AmazonUtil.compoundError(errMessage, UtilProperties.getMessage(
                            AmazonConstants.errorResource, "AmazonError_InvalidCodeUPC",
                            UtilMisc.toMap("productId", viewAmazonProduct.getString("productId")), locale));
                }
            }

            // Establish and validate the SKU
            String sku = getProductSKU(delegator, viewAmazonProduct, upc);

            // Establish the manufacturer name and ID #
            String manufacturerName = AmazonUtil.Strings.STR_N_NULL.normalize(PartyHelper.getPartyName(
                    delegator, viewAmazonProduct.getString("manufacturerPartyId"), false), locale);
            String manufacturerId = null;
            GenericValue manufacturerIdValue = EntityUtil.getFirst(EntityUtil.filterByAnd(goodIdents,
                    UtilMisc.toMap("goodIdentificationTypeId", "MANUFACTURER_ID_NO")));
            if (UtilValidate.isNotEmpty(manufacturerIdValue)) {
                manufacturerId = AmazonUtil.Strings.FOURTY_STR_N_NULL
                        .normalize(manufacturerIdValue.getString("idValue"), locale);
            }
            if (UtilValidate.isEmpty(manufacturerId)) {
                manufacturerId = AmazonUtil.Strings.FOURTY_STR_N_NULL.normalize(upc, locale);
            }

            // Limit the remaining goodIdentifications to EAN, ISBN and GTIN
            goodIdents = EntityUtil.filterByCondition(goodIdents, EntityCondition.makeCondition(
                    "goodIdentificationTypeId", EntityOperator.IN, AmazonConstants.goodIdentTypeIds.keySet()));

            // Add errors if some required elements are missing.
            if (UtilValidate.isEmpty(sku) && !AmazonConstants.useUPCAsSKU) {
                errMessage = AmazonUtil.compoundError(errMessage,
                        UtilProperties.getMessage(AmazonConstants.errorResource,
                                "AmazonError_NoRequiredParameter",
                                UtilMisc.toMap("parameterName", "SKU", "productName", title), locale));
            }
            String productTaxCode = viewAmazonProduct.getString("productTaxCode");
            if (UtilValidate.isEmpty(productTaxCode)) {
                errMessage = AmazonUtil.compoundError(errMessage, UtilProperties.getMessage(
                        AmazonConstants.errorResource, "AmazonError_NoRequiredParameter",
                        UtilMisc.toMap("parameterName", "ProductTaxCode", "productName", title), locale));
            }

            // Check for errors
            if (UtilValidate.isNotEmpty(errMessage)) {
                invalidAmazonProducts.put(amazonProduct, errMessage);
                continue;
            }

            /*
             * Create and add elements and values to XML document
             */
            Element message = productFeed.createElement("Message");
            root.appendChild(message);
            UtilXml.addChildElementValue(message, "MessageID", "" + messageId, productFeed);
            UtilXml.addChildElementValue(message, "OperationType", "Update", productFeed);
            Element product = productFeed.createElement("Product");
            message.appendChild(product);
            UtilXml.addChildElementValue(product, "SKU", sku, productFeed);
            if (UtilValidate.isNotEmpty(upc)) {
                Element upcEl = UtilXml.addChildElement(product, "StandardProductID", productFeed);
                UtilXml.addChildElementValue(upcEl, "Type", "UPC", productFeed);
                UtilXml.addChildElementValue(upcEl, "Value", upc, productFeed);
            }
            GenericValue goodIdent = EntityUtil.getFirst(goodIdents);
            if (UtilValidate.isNotEmpty(goodIdent)) {
                Element standardProductId = productFeed.createElement("StandardProductID");
                product.appendChild(standardProductId);
                UtilXml.addChildElementValue(standardProductId, "Type",
                        AmazonConstants.goodIdentTypeIds.get(goodIdent.getString("goodIdentificationType")),
                        productFeed);
                UtilXml.addChildElementValue(standardProductId, "Value", goodIdent.getString("idValue"),
                        productFeed);
            }
            UtilXml.addChildElementValue(product, "ProductTaxCode", productTaxCode, productFeed);
            if (UtilValidate.isNotEmpty(viewAmazonProduct.get("introductionDate"))) {
                UtilXml.addChildElementValue(product, "LaunchDate", AmazonUtil.convertTimestampToXSDate(
                        (Timestamp) viewAmazonProduct.get("introductionDate")), productFeed);
            }
            if (UtilValidate.isNotEmpty(viewAmazonProduct.get("salesDiscontinuationDate"))) {
                UtilXml.addChildElementValue(product, "DiscontinueDate", AmazonUtil.convertTimestampToXSDate(
                        (Timestamp) viewAmazonProduct.get("salesDiscontinuationDate")), productFeed);
            }
            if (UtilValidate.isNotEmpty(viewAmazonProduct.get("releaseDate"))) {
                UtilXml.addChildElementValue(product, "ReleaseDate",
                        AmazonUtil.convertTimestampToXSDate((Timestamp) viewAmazonProduct.get("releaseDate")),
                        productFeed);
            }
            Element conditionInfo = productFeed.createElement("Condition");
            product.appendChild(conditionInfo);
            UtilXml.addChildElementValue(conditionInfo, "ConditionType", AmazonConstants.productConditionType,
                    productFeed);
            Element descriptionData = productFeed.createElement("DescriptionData");
            product.appendChild(descriptionData);
            UtilXml.addChildElementValue(descriptionData, "Title", UtilValidate.isNotEmpty(title) ? title : sku,
                    productFeed);
            String brandName = AmazonUtil.Strings.STR_N_NULL.normalize(viewAmazonProduct.getString("brandName"),
                    locale);
            if (UtilValidate.isEmpty(brandName)) {
                EntityCondition cond = EntityCondition.makeCondition(EntityOperator.AND,
                        EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                                viewAmazonProduct.getString("productId")),
                        EntityCondition.makeCondition("productFeatureTypeId", EntityOperator.EQUALS, "BRAND"),
                        EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS,
                                "STANDARD_FEATURE"),
                        EntityUtil.getFilterByDateExpr());
                GenericValue pf = EntityUtil.getFirst(delegator.findByCondition("ProductFeatureAndAppl", cond,
                        null, Arrays.asList("fromDate DESC")));
                if (UtilValidate.isNotEmpty(pf)) {
                    brandName = AmazonUtil.Strings.STR_N_NULL.normalize(pf.getString("description"), locale);
                }
            }
            if (UtilValidate.isNotEmpty(brandName)) {
                UtilXml.addChildElementValue(descriptionData, "Brand", brandName, productFeed);
            }

            String description = viewAmazonProduct.getString(AmazonConstants.productDescriptionField);
            description = UtilValidate.isEmpty(description) ? null : description.replaceAll("<[^ ].*?>", "");
            description = StringEscapeUtils.escapeHtml(description);
            if (UtilValidate.isNotEmpty(description)) {

                // Put the XML reserved characters back, since the parser will escape them again and we get things like &amp;amp;
                description = description.replaceAll("&amp;", "&").replaceAll("&gt;", ">")
                        .replaceAll("&lt;", "<").replaceAll("&quot;", "\"");
                UtilXml.addChildElementValue(descriptionData, "Description",
                        AmazonUtil.Strings.DESCRIPTION.normalize(description, locale), productFeed);
            }
            List<GenericValue> bulletPoints = viewAmazonProduct.getRelated("AmazonProductBulletPoint");
            if (bulletPoints != null) {
                if (bulletPoints.size() > AmazonConstants.productFeedMaxBulletPoints) {
                    String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_TooMuchElementsInFeed",
                            UtilMisc.<String, Object>toMap("max", AmazonConstants.productFeedMaxBulletPoints,
                                    "elementName", "Bullet Points", "elementsCount", bulletPoints.size(),
                                    "productId", viewAmazonProduct.getString("productId")),
                            locale);
                    Debug.logInfo(infoMessage, MODULE);
                }
                int index = 0;
                for (GenericValue bulletPoint : bulletPoints) {
                    UtilXml.addChildElementValue(descriptionData, "BulletPoint",
                            AmazonUtil.Strings.LONG_STR_N_NULL.normalize(bulletPoint.getString("description"),
                                    locale),
                            productFeed);
                    index++;
                    if (index == AmazonConstants.productFeedMaxBulletPoints) {
                        break;
                    }
                }
            }

            Double lengthValue = viewAmazonProduct.getDouble("productDepth");
            Double widthValue = viewAmazonProduct.getDouble("productWidth");
            Double heightValue = viewAmazonProduct.getDouble("productHeight");
            Double weightValue = viewAmazonProduct.getDouble("weight");
            String currentUomId = null;
            if (lengthValue != null || widthValue != null || heightValue != null || weightValue != null) {
                Element itemDimensions = productFeed.createElement("ItemDimensions");
                descriptionData.appendChild(itemDimensions);
                if (lengthValue != null) {
                    Element itemLength = UtilXml.addChildElementValue(itemDimensions, "Length",
                            lengthValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("depthUomId"));
                    itemLength.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultLengthUom);
                }
                if (widthValue != null) {
                    Element itemWidth = UtilXml.addChildElementValue(itemDimensions, "Width",
                            widthValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("widthUomId"));
                    itemWidth.setAttribute("unitOfMeasure", UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                            : AmazonConstants.defaultLengthUom);
                }
                if (heightValue != null) {
                    Element itemHeight = UtilXml.addChildElementValue(itemDimensions, "Height",
                            heightValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("heightUomId"));
                    itemHeight.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultLengthUom);
                }
                if (weightValue != null) {
                    Element itemWeight = UtilXml.addChildElementValue(itemDimensions, "Weight",
                            weightValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("weightUomId"));
                    itemWeight.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultWeightUom);
                }
            }

            lengthValue = viewAmazonProduct.getDouble("shippingDepth");
            widthValue = viewAmazonProduct.getDouble("shippingWidth");
            heightValue = viewAmazonProduct.getDouble("shippingHeight");
            if (lengthValue != null || widthValue != null || heightValue != null || weightValue != null) {
                Element packageDimensions = productFeed.createElement("PackageDimensions");
                descriptionData.appendChild(packageDimensions);
                if (lengthValue != null) {
                    Element packageLength = UtilXml.addChildElementValue(packageDimensions, "Length",
                            lengthValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("depthUomId"));
                    packageLength.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultLengthUom);
                }
                if (widthValue != null) {
                    Element packageWidth = UtilXml.addChildElementValue(packageDimensions, "Width",
                            widthValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("widthUomId"));
                    packageWidth.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultLengthUom);
                }
                if (heightValue != null) {
                    Element packageHeight = UtilXml.addChildElementValue(packageDimensions, "Height",
                            heightValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("heightUomId"));
                    packageHeight.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultLengthUom);
                }
                if (weightValue != null) {
                    Element packageWeight = UtilXml.addChildElementValue(packageDimensions, "Weight",
                            weightValue.toString(), productFeed);
                    currentUomId = AmazonConstants.units.get(viewAmazonProduct.getString("weightUomId"));
                    packageWeight.setAttribute("unitOfMeasure",
                            UtilValidate.isNotEmpty(currentUomId) ? currentUomId
                                    : AmazonConstants.defaultWeightUom);
                }
            }

            UtilXml.addChildElementValue(descriptionData, "MerchantCatalogNumber",
                    AmazonUtil.Strings.FOURTY_STR_N_NULL.normalize(viewAmazonProduct.getString("productId"),
                            locale),
                    productFeed);

            // Try to find a price for the Amazon productStoreGroup first
            EntityCondition cond = EntityCondition.makeCondition(EntityOperator.AND,
                    EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                            amazonProduct.getString("productId")),
                    EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS,
                            AmazonConstants.priceStandard),
                    EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS,
                            AmazonConstants.priceProductStoreGroup),
                    EntityUtil.getFilterByDateExpr());
            GenericValue msrpValue = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null,
                    Arrays.asList("lastUpdatedStamp DESC")));
            if (UtilValidate.isEmpty(msrpValue)) {

                // If there's no price for the Amazon productStoreGroup, try _NA_
                cond = EntityCondition.makeCondition(EntityOperator.AND,
                        EntityCondition.makeCondition("productId", EntityOperator.EQUALS,
                                amazonProduct.getString("productId")),
                        EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS,
                                AmazonConstants.priceStandard),
                        EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, "_NA_"),
                        EntityUtil.getFilterByDateExpr());
                msrpValue = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null,
                        Arrays.asList("lastUpdatedStamp DESC")));
            }
            BigDecimal msrp = null;
            String msrpCurrency = null;
            if (UtilValidate.isNotEmpty(msrpValue)) {
                msrp = msrpValue.getBigDecimal("price").setScale(AmazonConstants.decimals,
                        AmazonConstants.rounding);
                msrpCurrency = msrpValue.getString("currencyUomId");
            }

            if (UtilValidate.isNotEmpty(msrp)) {
                Element msrpEl = UtilXml.addChildElementValue(descriptionData, "MSRP", msrp.toString(),
                        productFeed);
                msrpEl.setAttribute("currency", UtilValidate.isNotEmpty(msrpCurrency) ? msrpCurrency
                        : UtilProperties.getPropertyValue("opentaps.properties", "defaultCurrencyUomId"));
            }

            if (UtilValidate.isEmpty(manufacturerName) && UtilValidate.isNotEmpty(brandName)) {
                manufacturerName = brandName;
            }
            if (UtilValidate.isNotEmpty(manufacturerName)) {
                UtilXml.addChildElementValue(descriptionData, "Manufacturer", manufacturerName, productFeed);
            }
            if (UtilValidate.isNotEmpty(manufacturerId)) {
                UtilXml.addChildElementValue(descriptionData, "MfrPartNumber", manufacturerId, productFeed);
            }

            // Add a search term for the product name.  Amazon does not like null <SearchTerms/> tag so make sure it is not empty
            if (UtilValidate.isNotEmpty(title)) {
                UtilXml.addChildElementValue(descriptionData, "SearchTerms",
                        AmazonUtil.Strings.STR_N_NULL.normalize(title, locale), productFeed);
            }

            // Add any other search terms
            List<GenericValue> searchTerms = viewAmazonProduct.getRelated("AmazonProductSearchTerms");
            if (searchTerms != null) {
                if (searchTerms.size() > AmazonConstants.productFeedMaxSearchTerms) {
                    String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_TooMuchElementsInFeed",
                            UtilMisc.<String, Object>toMap("max", AmazonConstants.productFeedMaxSearchTerms,
                                    "elementName", "Search Terms", "elementsCount", searchTerms.size(),
                                    "productId", viewAmazonProduct.getString("productId")),
                            locale);
                    Debug.logInfo(infoMessage, MODULE);
                }
                int index = 0;
                for (GenericValue searchTerm : searchTerms) {
                    UtilXml.addChildElementValue(descriptionData, "SearchTerms", AmazonUtil.Strings.STR_N_NULL
                            .normalize(searchTerm.getString("description"), locale), productFeed);
                    index++;
                    if (index == AmazonConstants.productFeedMaxSearchTerms) {
                        break;
                    }
                }
            }

            List<GenericValue> usedForList = viewAmazonProduct.getRelated("AmazonUsedForValue");
            if (usedForList != null) {
                if (usedForList.size() > AmazonConstants.productFeedMaxUsedFor) {
                    String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_TooMuchElementsInFeed",
                            UtilMisc.<String, Object>toMap("max", AmazonConstants.productFeedMaxUsedFor,
                                    "elementName", "Used For", "elementsCount", searchTerms.size(), "productId",
                                    viewAmazonProduct.getString("productId")),
                            locale);
                    Debug.logInfo(infoMessage, MODULE);
                }
                int index = 0;
                for (GenericValue usedFor : usedForList) {
                    UtilXml.addChildElementValue(descriptionData, "UsedFor",
                            AmazonUtil.Strings.STR_N_NULL.normalize(usedFor.getString("usedForId"), locale),
                            productFeed);
                    index++;
                    if (index == AmazonConstants.productFeedMaxUsedFor) {
                        break;
                    }
                }
            }

            String itemType = viewAmazonProduct.getString("itemTypeId");
            if (UtilValidate.isNotEmpty(itemType)) {
                UtilXml.addChildElementValue(descriptionData, "ItemType", itemType, productFeed);
            }

            List<GenericValue> otherItemAttributes = viewAmazonProduct.getRelated("AmazonOtherItemAttrValue");
            if (otherItemAttributes != null) {
                if (otherItemAttributes.size() > AmazonConstants.productFeedMaxOtherItemAttributes) {
                    String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_TooMuchElementsInFeed",
                            UtilMisc.<String, Object>toMap("max",
                                    AmazonConstants.productFeedMaxOtherItemAttributes, "elementName",
                                    "Other Item Attribute", "elementsCount", searchTerms.size(), "productId",
                                    viewAmazonProduct.getString("productId")),
                            locale);
                    Debug.logInfo(infoMessage, MODULE);
                }
                int index = 0;
                for (GenericValue attribute : otherItemAttributes) {
                    UtilXml.addChildElementValue(descriptionData, "OtherItemAttributes",
                            AmazonUtil.Strings.LONG_STR_N_NULL.normalize(attribute.getString("otherItemAttrId"),
                                    locale),
                            productFeed);
                    index++;
                    if (index == AmazonConstants.productFeedMaxOtherItemAttributes) {
                        break;
                    }
                }
            }

            List<GenericValue> targetAudience = viewAmazonProduct.getRelated("AmazonTargetAudienceValue");
            if (targetAudience != null) {
                if (targetAudience.size() > AmazonConstants.productFeedMaxTargetAudience) {
                    String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_TooMuchElementsInFeed",
                            UtilMisc.<String, Object>toMap("max", AmazonConstants.productFeedMaxTargetAudience,
                                    "elementName", "Target Audience", "elementsCount", searchTerms.size(),
                                    "productId", viewAmazonProduct.getString("productId")),
                            locale);
                    Debug.logInfo(infoMessage, MODULE);
                }
                int index = 0;
                for (GenericValue audience : targetAudience) {
                    UtilXml.addChildElementValue(descriptionData, "TargetAudience",
                            AmazonUtil.Strings.STR_N_NULL.normalize(audience.getString("targetAudienceId"),
                                    locale),
                            productFeed);
                    index++;
                    if (index == AmazonConstants.productFeedMaxTargetAudience) {
                        break;
                    }
                }
            }

            amazonProduct.set("acknowledgeMessageId", "" + messageId);
            validAmazonProducts.add(amazonProduct);
            messageId++;
            if (messageId % 500 == 0) {
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_Processed_Records_Product", UtilMisc.toMap("count", messageId), locale),
                        MODULE);
            }
        }
        amazonProductsIt.close();

        LinkedHashMap<GenericValue, String> emailErrorMessages = new LinkedHashMap<GenericValue, String>();

        if (UtilValidate.isEmpty(validAmazonProducts)) {
            String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                    "AmazonError_PostNoNewProducts", locale);
            Debug.logInfo(infoMessage, MODULE);
        } else {

            /*
             * Post product document and get transaction ID. Store ID with product for later use.
             */
            boolean success = true;
            String postErrorMessage = null;
            long processingDocumentId = -1;
            try {
                String xml = UtilXml.writeXmlDocument(productFeed);
                Debug.logVerbose(xml, MODULE);
                Writer writer = new OutputStreamWriter(
                        new FileOutputStream(AmazonConstants.xmlOutputLocation + "AmazonProductFeed_"
                                + AmazonConstants.xmlOutputDateFormat.format(new Date()) + ".xml"),
                        "UTF-8");
                writer.write(xml);
                writer.close();
                processingDocumentId = AmazonConstants.soapClient.postProducts(xml);
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_ProcessingDocumentId_Product",
                        UtilMisc.toMap("processingDocumentId", processingDocumentId), locale), MODULE);
            } catch (RemoteException e) {
                success = false;
                postErrorMessage = e.getMessage();
                List<String> productIds = EntityUtil.getFieldListFromEntityList(validAmazonProducts,
                        "productId", true);
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostProductError",
                        UtilMisc.toMap("productIds", productIds, "errorMessage", postErrorMessage), locale);
                Debug.logError(errorLog, MODULE);
            }

            // Store operational data of the post attempt
            for (GenericValue validAmazonProduct : validAmazonProducts) {
                validAmazonProduct.set("statusId",
                        success ? AmazonConstants.statusProductPosted : AmazonConstants.statusProductError);
                validAmazonProduct.set("postTimestamp", UtilDateTime.nowTimestamp());
                validAmazonProduct.set("postErrorMessage", success ? null : postErrorMessage);
                long postFailures = 0;
                if (validAmazonProduct.getLong("postFailures") != null) {
                    postFailures = validAmazonProduct.getLong("postFailures");
                }
                if (!success) {
                    validAmazonProduct.set("postFailures", postFailures + 1);
                }
                validAmazonProduct.set("processingDocumentId", success ? processingDocumentId : null);
                validAmazonProduct.set("ackStatusId", AmazonConstants.statusProductNotAcked);
                validAmazonProduct.set("acknowledgeTimestamp", null);
                validAmazonProduct.set("acknowledgeErrorMessage", null);
                validAmazonProduct.store();
                if (AmazonConstants.sendErrorEmails && !success) {
                    emailErrorMessages.put(validAmazonProduct, postErrorMessage);
                }
            }
        }

        for (GenericValue invalidAmazonProduct : invalidAmazonProducts.keySet()) {
            String errorMessage = invalidAmazonProducts.get(invalidAmazonProduct);
            invalidAmazonProduct.set("statusId", AmazonConstants.statusProductError);
            invalidAmazonProduct.set("postTimestamp", UtilDateTime.nowTimestamp());
            invalidAmazonProduct.set("postErrorMessage", errorMessage);
            invalidAmazonProduct.set("postFailures", invalidAmazonProduct.getLong("postFailures") + 1);
            invalidAmazonProduct.set("processingDocumentId", null);
            invalidAmazonProduct.set("ackStatusId", AmazonConstants.statusProductNotAcked);
            invalidAmazonProduct.set("acknowledgeTimestamp", null);
            invalidAmazonProduct.set("acknowledgeErrorMessage", null);
            invalidAmazonProduct.store();
            if (AmazonConstants.sendErrorEmails) {
                emailErrorMessages.put(invalidAmazonProduct, errorMessage);
            }
        }

        if (AmazonConstants.sendErrorEmails && UtilValidate.isNotEmpty(emailErrorMessages)) {
            AmazonUtil.sendBulkErrorEmail(dispatcher, userLogin, emailErrorMessages,
                    UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_ErrorEmailSubject_PostProduct", AmazonConstants.errorEmailLocale),
                    AmazonConstants.errorEmailScreenUriProducts);
        }

    } catch (GenericEntityException gee) {
        UtilMessage.createAndLogServiceError(gee, locale, MODULE);
    } catch (IOException ioe) {
        UtilMessage.createAndLogServiceError(ioe, locale, MODULE);
    } catch (GenericServiceException gse) {
        UtilMessage.createAndLogServiceError(gse, locale, MODULE);
    }

    return ServiceUtil.returnSuccess();
}

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

private ArrayList<HashMap<String, String>> calculateAccDefPlan(Period startingPeriod, int periodNumber,
        BigDecimal amount, String strCurrencyId) {
    Period period = startingPeriod;
    Date date = period.getEndingDate();
    ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>();
    int i = 1;/*from w w  w .  ja  v a 2  s  .  c om*/
    BigDecimal total = BigDecimal.ZERO;
    int stdPrecision = 0;
    OBContext.setAdminMode(true);
    try {
        stdPrecision = OBDal.getInstance().get(Currency.class, this.C_Currency_ID).getStandardPrecision()
                .intValue();
    } finally {
        OBContext.restorePreviousMode();
    }
    BigDecimal periodAmount = amount
            .divide(new BigDecimal(periodNumber), new MathContext(32, RoundingMode.HALF_UP))
            .setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);

    while (i <= periodNumber) {
        if (!OBDateUtils.formatDate(date).equals(DateAcct)) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("date", OBDateUtils.formatDate(date));
            hm.put("amount", i == periodNumber ? amount.subtract(total).toString() : periodAmount.toString());
            plan.add(hm);
        }
        try {
            AcctServerData[] data = AcctServerData.periodOpen(connectionProvider, AD_Client_ID, DocumentType,
                    AD_Org_ID, OBDateUtils.formatDate(period.getEndingDate()));
            if ("".equals(data[0].period)) {
                setStatus(STATUS_PeriodClosed);
                throw new OBException("@PeriodNotAvailable@");
            }
        } catch (ServletException e) {
            log4j.warn("DocInvoice - Error checking period open.", e);
            e.printStackTrace();
        }
        if (i < periodNumber) {
            period = AccDefUtility.getNextPeriod(period);
            date = period.getEndingDate();
        }
        total = total.add(periodAmount);
        i++;
    }
    return plan;
}