Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:com.salesmanager.core.util.ProductUtil.java

/**
 * Format like <blue>[if discount striked]SYMBOL BASEAMOUNT</blue> [if
 * discount <red>SYMBOL DISCOUNTAMOUNT</red>] [if discount <red>Save:
 * PERCENTAGE AMOUNT</red>] [if qty discount <red>Buy QTY save [if price qty
 * discount AMOUNT] [if percent qty discount PERCENT]</red>]
 * // w ww.ja v a  2 s .  c o m
 * @param ctx
 * @param view
 * @return
 */
public static String formatHTMLProductPriceWithAttributes(Locale locale, String currency, Product view,
        Collection attributes, boolean showDiscountDate) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }

    int decimalPlace = 2;

    String prefix = "";
    String suffix = "";

    Map currenciesmap = RefCache.getCurrenciesListWithCodes();
    Currency c = (Currency) currenciesmap.get(currency);

    // regular price
    BigDecimal bdprodprice = view.getProductPrice();

    // determine any properties prices
    BigDecimal attributesPrice = null;

    if (attributes != null) {
        Iterator i = attributes.iterator();
        while (i.hasNext()) {
            ProductAttribute attr = (ProductAttribute) i.next();
            if (!attr.isAttributeDisplayOnly() && attr.getOptionValuePrice().longValue() > 0) {
                if (attributesPrice == null) {
                    attributesPrice = new BigDecimal(0);
                }
                attributesPrice = attributesPrice.add(attr.getOptionValuePrice());
            }
        }
    }

    if (attributesPrice != null) {
        bdprodprice = bdprodprice.add(attributesPrice);// new price with
        // properties
    }

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        bddiscountprice = special.getSpecialNewProductPrice();
        if (attributesPrice != null) {
            bddiscountprice = bddiscountprice.add(attributesPrice);// new
            // price
            // with
            // properties
        }
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
    }

    // all other prices
    Set prices = view.getPrices();
    if (prices != null) {
        Iterator pit = prices.iterator();
        while (pit.hasNext()) {
            ProductPrice pprice = (ProductPrice) pit.next();
            if (pprice.isDefaultPrice()) {
                pprice.setLocale(locale);
                suffix = pprice.getPriceSuffix();
                bddiscountprice = null;
                spdate = null;
                spenddate = null;
                bdprodprice = pprice.getProductPriceAmount();
                if (attributesPrice != null) {
                    bdprodprice = bdprodprice.add(attributesPrice);// new
                    // price
                    // with
                    // properties
                }
                ProductPriceSpecial ppspecial = pprice.getSpecial();
                if (ppspecial != null) {
                    if (ppspecial.getProductPriceSpecialStartDate() != null
                            && ppspecial.getProductPriceSpecialEndDate() != null) {
                        spdate = ppspecial.getProductPriceSpecialStartDate();
                        spenddate = ppspecial.getProductPriceSpecialEndDate();
                    }
                    bddiscountprice = ppspecial.getProductPriceSpecialAmount();
                    if (bddiscountprice != null && attributesPrice != null) {
                        bddiscountprice = bddiscountprice.add(attributesPrice);// new price with
                        // properties
                    }
                }
                break;
            }
        }
    }

    double fprodprice = 0;
    ;
    if (bdprodprice != null) {
        fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // regular price String
    String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency);

    Date dt = new Date();

    // discount price String
    String discountprice = null;
    String savediscount = null;
    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

        double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

        double arith = fdiscountprice / fprodprice;
        double fsdiscount = 100 - arith * 100;

        Float percentagediscount = new Float(fsdiscount);

        savediscount = String.valueOf(percentagediscount.intValue());

    }

    StringBuffer p = new StringBuffer();
    p.append("<div class='product-price'>");
    if (discountprice == null) {
        p.append("<div class='product-price-price' style='width:50%;float:left;'>");
        p.append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</div>");
        p.append("<div class='product-line'>&nbsp;</div>");
    } else {
        p.append("<div style='width:50%;float:left;'>");
        p.append("<strike>").append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</strike>");
        p.append("</div>");
        p.append("<div style='width:50%;float:right;'>");
        p.append("<font color='red'>").append(discountprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</font>").append("<br>").append("<font color='red' style='font-size:75%;'>")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ")
                .append(savediscount)
                .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ")
                .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>");

        if (showDiscountDate && spenddate != null) {
            p.append("<br>").append(" <font style='font-size:65%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append("&nbsp;")
                    .append(DateUtil.formatDate(spenddate)).append("</font>");
        }

        p.append("</div>").toString();
    }
    p.append("</div>");
    return p.toString();

}

From source file:org.egov.ptis.domain.service.property.PropertySurveyService.java

private Double calculatetaxvariance(final String applicationType, final SurveyBean surveyBean,
        final PTGISIndex index) {
    Double taxVar;/*from  w w w . j  a  va2s.  c om*/
    BigDecimal sysTax = index.getSystemTax() == null ? surveyBean.getSystemTax()
            : new BigDecimal(index.getSystemTax());

    if (applicationType.equalsIgnoreCase(PropertyTaxConstants.APPLICATION_TYPE_ALTER_ASSESSENT)
            && sysTax.compareTo(BigDecimal.ZERO) > 0)
        taxVar = ((BigDecimal.valueOf(index.getApprovedTax()).subtract(sysTax))
                .multiply(BigDecimal.valueOf(100.0))).divide(sysTax, BigDecimal.ROUND_HALF_UP).doubleValue();
    else
        taxVar = Double.valueOf(100);
    return taxVar;
}

From source file:com.dsi.ant.antplus.pluginsampler.geocache.Dialog_GeoProgramDevice.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Program Device " + deviceData.deviceId);
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View detailsView = inflater.inflate(R.layout.dialog_geocache_programdevice, null);

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(detailsView);//from  w  w  w  . j av  a  2 s  . co  m

    // Add action buttons
    //Note we override the positive button in show() below so we can prevent it from closing
    builder.setPositiveButton("Begin Programing", null);
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Let dialog dismiss
        }
    });

    checkBox_EnableIdString = (CheckBox) detailsView.findViewById(R.id.checkBox_EnableIdentifcationString);
    checkBox_EnablePIN = (CheckBox) detailsView.findViewById(R.id.checkBox_EnablePIN);
    checkBox_EnableLatitude = (CheckBox) detailsView.findViewById(R.id.checkBox_EnableLatitude);
    checkBox_EnableLongitude = (CheckBox) detailsView.findViewById(R.id.checkBox_EnableLongitude);
    checkBox_EnableHintString = (CheckBox) detailsView.findViewById(R.id.checkBox_EnableHintString);
    checkBox_EnableLastVisit = (CheckBox) detailsView.findViewById(R.id.checkBox_EnableLastVisitInfo);

    final TextView textView_NumVisitsTitle = (TextView) detailsView
            .findViewById(R.id.textView_NumberOfVisitsTitle);
    final TextView textView_LastVisitDateTitle = (TextView) detailsView
            .findViewById(R.id.textView_LastVisitDateTitle);
    final TextView textView_LastVisitTimeTitle = (TextView) detailsView
            .findViewById(R.id.textView_LastVisitTimeTitle);

    editText_IdString = (EditText) detailsView.findViewById(R.id.editText_IdentificationString);
    editText_PIN = (EditText) detailsView.findViewById(R.id.editText_PIN);
    editText_Latitude = (EditText) detailsView.findViewById(R.id.editText_Latitude);
    editText_Longitude = (EditText) detailsView.findViewById(R.id.editText_Longitude);
    editText_HintString = (EditText) detailsView.findViewById(R.id.editText_HintString);
    editText_NumVisits = (EditText) detailsView.findViewById(R.id.editText_NumberOfVisits);
    textView_LastVisitDate = (TextView) detailsView.findViewById(R.id.textView_LastVisitDate);
    textView_LastVisitTime = (TextView) detailsView.findViewById(R.id.textView_LastVisitTime);

    radioButton_ClearExisitingData = (RadioButton) detailsView.findViewById(R.id.radioButton_ClearExistingData);

    //Hook up checkboxes to enable/disable fields
    checkBox_EnableIdString.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editText_IdString.setEnabled(isChecked);
            if (isChecked && editText_IdString.getText().length() == 0)
                editText_IdString.setText("ID STR");
        }
    });
    checkBox_EnablePIN.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editText_PIN.setEnabled(isChecked);
            if (isChecked && editText_PIN.getText().length() == 0)
                editText_PIN.setText("123456");
        }
    });
    checkBox_EnableLatitude.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editText_Latitude.setEnabled(isChecked);
            if (isChecked && editText_Latitude.getText().length() == 0)
                editText_Latitude.setText("-40.1");
        }
    });
    checkBox_EnableLongitude.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editText_Longitude.setEnabled(isChecked);
            if (isChecked && editText_Longitude.getText().length() == 0)
                editText_Longitude.setText("-20.1");
        }
    });
    checkBox_EnableHintString.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editText_HintString.setEnabled(isChecked);
            if (isChecked && editText_HintString.getText().length() == 0)
                editText_HintString.setText("Hint string.");
        }
    });
    checkBox_EnableLastVisit.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            textView_NumVisitsTitle.setEnabled(isChecked);
            textView_LastVisitDateTitle.setEnabled(isChecked);
            textView_LastVisitTimeTitle.setEnabled(isChecked);
            editText_NumVisits.setEnabled(isChecked);
            textView_LastVisitDate.setEnabled(isChecked);
            textView_LastVisitTime.setEnabled(isChecked);

            if (isChecked) {
                if (editText_NumVisits.length() == 0)
                    editText_NumVisits.setText("0");
                if (textView_LastVisitDate.length() == 0)
                    textView_LastVisitDate.setText("dd/mmm/yyyy");
                if (textView_LastVisitTime.length() == 0)
                    textView_LastVisitDate.setText("hh:mm");
            }
        }
    });

    //Set data
    editText_IdString.setText(String.valueOf(deviceData.programmableData.identificationString));
    editText_PIN.setText(String.valueOf(deviceData.programmableData.PIN));

    if (deviceData.programmableData.latitude != null)
        editText_Latitude.setText(
                String.valueOf(deviceData.programmableData.latitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    else
        editText_Latitude.setText("");

    if (deviceData.programmableData.longitude != null)
        editText_Longitude.setText(
                String.valueOf(deviceData.programmableData.longitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    else
        editText_Longitude.setText("");

    if (deviceData.programmableData.hintString != null)
        editText_HintString.setText(String.valueOf(deviceData.programmableData.hintString));
    else
        editText_HintString.setText("");

    if (deviceData.programmableData.numberOfVisits != null)
        editText_NumVisits.setText(String.valueOf(deviceData.programmableData.numberOfVisits));
    else
        editText_NumVisits.setText("");

    if (deviceData.programmableData.lastVisitTimestamp != null) {
        currentDisplayDatetime = deviceData.programmableData.lastVisitTimestamp;
        updateDateAndTime();
    } else {
        textView_LastVisitDate.setText("");
        textView_LastVisitTime.setText("");
    }

    //Hook up date and time fields to pickers
    textView_LastVisitDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (currentDisplayDatetime == null)
                currentDisplayDatetime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            DatePickerDialog d = new DatePickerDialog(getActivity(), new OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    currentDisplayDatetime.set(year, monthOfYear, dayOfMonth);
                    updateDateAndTime();
                }
            }, currentDisplayDatetime.get(Calendar.YEAR), currentDisplayDatetime.get(Calendar.MONTH),
                    currentDisplayDatetime.get(Calendar.DAY_OF_MONTH));
            d.show();
        }
    });

    textView_LastVisitTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (currentDisplayDatetime == null)
                currentDisplayDatetime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            TimePickerDialog d = new TimePickerDialog(getActivity(), new OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    currentDisplayDatetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    currentDisplayDatetime.set(Calendar.MINUTE, minute);
                    updateDateAndTime();
                }
            }, currentDisplayDatetime.get(Calendar.HOUR_OF_DAY), currentDisplayDatetime.get(Calendar.MINUTE),
                    false);
            d.show();
        }
    });

    return builder.create();
}

From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremePrestationCapital2009Test.java

private void test(int revenu, String tauxEnPourcent) {
    RecepteurMultipleImpot recepteur = recepteur("IBR", "RIBR", "CAR", "RCAR", "ADR", "COR");
    FournisseurAssiettePeriodique fournisseur = this.creerAssiettes(2009, revenu);
    producteur2009.produireImpot(situationCelibataire, fournisseur, recepteur);

    BigDecimal valeurImpot = getValeur(recepteur, "TOTAL");

    // On prend les bornes Sup et Inf
    BigDecimal borneSup = valeurImpot.add(deltaSurMontantImpotCalcule);
    BigDecimal borneInf = valeurImpot.subtract(deltaSurMontantImpotCalcule);

    BigDecimal tauxCalculeSup = borneSup.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxCalculeInf = borneInf.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxAttendu = new BigDecimal(tauxEnPourcent);

    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxSup " + tauxCalculeSup,
            0 >= tauxAttendu.compareTo(tauxCalculeSup));
    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxInf " + tauxCalculeInf,
            0 >= tauxCalculeInf.compareTo(tauxAttendu));
}

From source file:com.sfs.Formatter.java

/**
 * Round./*from   www.ja  va  2s.  c o m*/
 *
 * @param value the value
 * @param decimalPlaces the decimal places
 *
 * @return the double
 */
public static double round(final double value, final int decimalPlaces) {
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

From source file:com.konakartadmin.modules.payment.authorizenet.AdminPayment.java

/**
 * This method executes the transaction with the payment gateway. The action attribute of the
 * options object instructs the method as to what transaction should be executed. E.g. It could
 * be a payment or a payment confirmation for a transaction that has already been authorized
 * etc./*  w ww  .  j a v  a 2  s. co  m*/
 * 
 * @param options
 * @return Returns an array of NameValue objects that may contain any return information
 *         considered useful by the caller.
 * @throws Exception
 */
public NameValue[] execute(PaymentOptions options) throws Exception {
    checkRequired(options, "PaymentOptions", "options");

    // Read the configuration variables
    ConfigVariables configs = getConfigVariables();

    /*
     * Decide what to do based on the action. We could be using this class to manage
     * subscriptions
     */
    if (options.getAction() == KKConstants.ACTION_CREATE_SUBSCRIPTION) {
        return createSubscription(options);
    } else if (options.getAction() == KKConstants.ACTION_UPDATE_SUBSCRIPTION) {
        return updateSubscription(options);
    } else if (options.getAction() == KKConstants.ACTION_CANCEL_SUBSCRIPTION) {
        return cancelSubscription(options);
    } else if (options.getAction() == KKConstants.ACTION_GET_SUBSCRIPTION_STATUS) {
        return getSubscriptionStatus(options);
    }

    String errorDesc = null;
    String gatewayResult = null;
    String transactionId = null;

    AdminIpnHistory ipnHistory = new AdminIpnHistory();
    ipnHistory.setModuleCode(code);

    AdminOrder order = getAdminOrderMgr().getOrderForOrderId(options.getOrderId());
    if (order == null) {
        throw new KKAdminException("An order does not exist for id = " + options.getOrderId());
    }

    // Get the scale for currency calculations
    AdminCurrency currency = getAdminCurrMgr().getCurrency(order.getCurrencyCode());
    if (currency == null) {
        throw new KKAdminException("A currency does not exist for code = " + order.getCurrencyCode());
    }
    int scale = new Integer(currency.getDecimalPlaces()).intValue();

    List<NameValue> parmList = new ArrayList<NameValue>();

    parmList.add(new NameValue("x_delim_data", "True"));
    parmList.add(new NameValue("x_relay_response", "False"));
    parmList.add(new NameValue("x_login", configs.getAuthorizeNetLoginId()));
    parmList.add(new NameValue("x_tran_key", configs.getAuthorizeNetTxnKey()));
    parmList.add(new NameValue("x_delim_char", ","));
    parmList.add(new NameValue("x_encap_char", ""));
    parmList.add(new NameValue("x_method", "CC"));

    // AuthorizeNet requires details of the final price - inclusive of tax.
    BigDecimal total = null;
    for (int i = 0; i < order.getOrderTotals().length; i++) {
        AdminOrderTotal ot = order.getOrderTotals()[i];
        if (ot.getClassName().equals(OrderTotalMgr.ot_total)) {
            total = ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
    }

    if (total == null) {
        throw new KKAdminException("An Order Total was not found");
    }

    parmList.add(new NameValue("x_amount", total.toString()));
    parmList.add(new NameValue("x_currency_code", currency.getCode()));
    parmList.add(new NameValue("x_invoice_num", order.getId())); // TODO
    parmList.add(new NameValue("x_test_request", (configs.isTestMode() ? "TRUE" : "FALSE")));

    // Set the billing address

    // Set the billing name. If the name field consists of more than two strings, we take the
    // last one as being the surname.
    String bName = order.getBillingName();
    if (bName != null) {
        String[] names = bName.split(" ");
        int len = names.length;
        if (len >= 2) {
            StringBuffer firstName = new StringBuffer();
            for (int i = 0; i < len - 1; i++) {
                if (firstName.length() == 0) {
                    firstName.append(names[i]);
                } else {
                    firstName.append(" ");
                    firstName.append(names[i]);
                }
            }
            parmList.add(new NameValue("x_first_name", firstName.toString()));
            parmList.add(new NameValue("x_last_name", names[len - 1]));
        }
    }
    parmList.add(new NameValue("x_company", order.getBillingCompany()));
    parmList.add(new NameValue("x_city", order.getBillingCity()));
    parmList.add(new NameValue("x_state", order.getBillingState()));
    parmList.add(new NameValue("x_zip", order.getBillingPostcode()));
    parmList.add(new NameValue("x_phone", order.getCustomerTelephone()));
    parmList.add(new NameValue("x_cust_id", order.getCustomerId()));
    parmList.add(new NameValue("x_email", order.getCustomerEmail()));

    StringBuffer addrSB = new StringBuffer();
    addrSB.append(order.getBillingStreetAddress());
    if (order.getBillingSuburb() != null && order.getBillingSuburb().length() > 0) {
        addrSB.append(", ");
        addrSB.append(order.getBillingSuburb());
    }
    if (addrSB.length() > 60) {
        parmList.add(new NameValue("x_address", addrSB.substring(0, 56) + "..."));
    } else {
        parmList.add(new NameValue("x_address", addrSB.toString()));
    }

    // Country requires the two letter country code
    AdminCountry country = getAdminTaxMgr().getCountryByName(order.getBillingCountry());
    if (country != null) {
        parmList.add(new NameValue("x_country", country.getIsoCode2()));
    }

    /*
     * The following code may be customized depending on the process which could be any of the
     * following:
     */
    int mode = 1;

    if (mode == 1 && options.getCreditCard() != null) {
        /*
         * 1 . Credit card details have been passed into the method and so we use those for the
         * payment.
         */
        parmList.add(new NameValue("x_card_num", options.getCreditCard().getCcNumber()));
        parmList.add(new NameValue("x_card_code", options.getCreditCard().getCcCVV()));
        parmList.add(new NameValue("x_exp_date", options.getCreditCard().getCcExpires()));
        parmList.add(new NameValue("x_type", "AUTH_CAPTURE"));
    } else if (mode == 2) {
        /*
         * 2 . We get the Credit card details from the order since they were encrypted and saved
         * on the order.
         */
        parmList.add(new NameValue("x_card_num", order.getCcNumber()));
        parmList.add(new NameValue("x_card_code", order.getCcCVV()));
        parmList.add(new NameValue("x_exp_date", order.getCcExpires()));
        parmList.add(new NameValue("x_type", "AUTH_CAPTURE"));
    } else if (mode == 3) {
        /*
         * 3.If when the products were ordered through the store front application, an AUTH_ONLY
         * transaction was done instead of an AUTH_CAPTURE transaction and so now we need to do
         * a PRIOR_AUTH_CAPTURE transaction using the transaction id that was saved on the order
         * when the status was set.
         */
        /*
         * Get the transaction id from the status trail of the order. This bit of code will have
         * to be customized because it depends which state was used to capture the transaction
         * id and whether the transaction id is the only string in the comments field or whether
         * it has to be parsed out. The transaction id may also have been stored in an Order
         * custom field in which case it can be retrieved directly from there.
         */
        String authTransId = null;
        if (order.getStatusTrail() != null) {
            for (int i = 0; i < order.getStatusTrail().length; i++) {
                AdminOrderStatusHistory sh = order.getStatusTrail()[i];
                if (sh.getOrderStatus().equals("ENTER_THE_STATUS_WHERE_THE_AUTH_TRANS_ID_WAS SAVED")) {
                    authTransId = sh.getComments();
                }
            }
        }
        if (authTransId == null) {
            throw new KKAdminException(
                    "The authorized transaction cannot be confirmed since a transaction id cannot be found on the order");
        }

        parmList.add(new NameValue("x_type", "PRIOR_AUTH_CAPTURE"));
        parmList.add(new NameValue("x_trans_id", authTransId));
    }

    AdminPaymentDetails pDetails = new AdminPaymentDetails();
    pDetails.setParmList(parmList);
    pDetails.setRequestUrl(configs.getAuthorizeNetRequestUrl());

    // Do the post
    String gatewayResp = postData(pDetails);

    gatewayResp = URLDecoder.decode(gatewayResp, "UTF-8");
    if (log.isDebugEnabled()) {
        log.debug("Unformatted GatewayResp = \n" + gatewayResp);
    }

    // Process the parameters sent in the callback
    StringBuffer sb = new StringBuffer();
    String[] parms = gatewayResp.split(",");
    if (parms != null) {
        for (int i = 0; i < parms.length; i++) {
            String parm = parms[i];
            sb.append(getRespDesc(i + 1));
            sb.append("=");
            sb.append(parm);
            sb.append("\n");

            if (i + 1 == respTextPosition) {
                errorDesc = parm;
            } else if (i + 1 == respCodePosition) {
                gatewayResult = parm;
                ipnHistory.setGatewayResult(parm);
            } else if (i + 1 == txnIdPosition) {
                ipnHistory.setGatewayTransactionId(parm);
                transactionId = parm;
            }
        }
    }

    // Put the response in the ipnHistory record
    ipnHistory.setGatewayFullResponse(sb.toString());

    if (log.isDebugEnabled()) {
        log.debug("Formatted Authorize.net response data:");
        log.debug(sb.toString());
    }

    AdminOrderUpdate updateOrder = new AdminOrderUpdate();
    updateOrder.setUpdatedById(order.getCustomerId());

    // Determine whether the request was successful or not.
    if (gatewayResult != null && gatewayResult.equals(approved)) {
        String comment = ORDER_HISTORY_COMMENT_OK + transactionId;
        getAdminOrderMgr().updateOrder(order.getId(), com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS,
                comment, /* notifyCustomer */
                false, updateOrder);

        // Save the ipnHistory
        ipnHistory.setKonakartResultDescription(RET0_DESC);
        ipnHistory.setKonakartResultId(RET0);
        ipnHistory.setOrderId(order.getId());
        ipnHistory.setCustomerId(order.getCustomerId());
        getAdminOrderMgr().insertIpnHistory(ipnHistory);

    } else if (gatewayResult != null && (gatewayResult.equals(declined) || gatewayResult.equals(error))) {
        String comment = ORDER_HISTORY_COMMENT_KO + errorDesc;
        getAdminOrderMgr().updateOrder(order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS,
                comment, /* notifyCustomer */
                false, updateOrder);

        // Save the ipnHistory
        ipnHistory.setKonakartResultDescription(RET0_DESC);
        ipnHistory.setKonakartResultId(RET0);
        ipnHistory.setOrderId(order.getId());
        ipnHistory.setCustomerId(order.getCustomerId());
        getAdminOrderMgr().insertIpnHistory(ipnHistory);

    } else {
        /*
         * We only get to here if there was an unknown response from the gateway
         */
        String comment = RET1_DESC + gatewayResult;
        getAdminOrderMgr().updateOrder(order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS,
                comment, /* notifyCustomer */
                false, updateOrder);

        // Save the ipnHistory
        ipnHistory.setKonakartResultDescription(RET1_DESC + gatewayResult);
        ipnHistory.setKonakartResultId(RET1);
        ipnHistory.setOrderId(order.getId());
        ipnHistory.setCustomerId(order.getCustomerId());
        getAdminOrderMgr().insertIpnHistory(ipnHistory);
    }

    return new NameValue[] { new NameValue("ret", "0") };
}

From source file:com.whatlookingfor.common.utils.StringUtils.java

/**
 * ?????scale?/*w ww .j  a va  2  s.  co m*/
 * ??
 *
 * @param v1    
 * @param v2    
 * @param scale ????
 * @return ?
 */
public static double div(double v1, double v2, int scale) {
    if (scale < 0) {
        throw new IllegalArgumentException("The scale must be a positive integer or zero");
    }
    BigDecimal b1 = new BigDecimal(Double.toString(v1));
    BigDecimal b2 = new BigDecimal(Double.toString(v2));
    return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

From source file:tasly.greathealth.oms.export.financial.facades.impl.DefaulTaslyFinancialReportFacade.java

/**
 * @param taslyFinancialReportList/* w  w w  . j  a va2 s  . c o  m*/
 * @param taslyOrderDatas
 * @return
 */
private PagedResults<TaslyFinancialReport> reorganizeFreight(
        final List<TaslyFinancialReport> taslyFinancialReportList, final Page<TaslyOrderData> taslyOrderDatas) {
    // YTODO Auto-generated method stub

    if (null != taslyFinancialReportList && taslyFinancialReportList.size() > 0) {

        for (final TaslyFinancialReport taslyFinancialReport : taslyFinancialReportList) {
            double sumDouble = 0;
            final double freight = taslyFinancialReport.getFreight();

            // ??
            final Iterator<String> iter = taslyFinancialReport.getPriceMap().keySet().iterator();
            while (iter.hasNext()) {
                sumDouble += taslyFinancialReport.getPriceMap().get(iter.next());

            }

            if (sumDouble > 0) {
                // price??/*?????
                while (iter.hasNext()) {
                    final String key = iter.next();
                    final Double price = taslyFinancialReport.getPriceMap().get(key);
                    final Double sum = sumDouble(price, this.getPriceByFreight(price, sumDouble, freight), 2,
                            BigDecimal.ROUND_HALF_UP);
                    taslyFinancialReport.getPriceMap().put(key, sum);
                }
            }

            taslyFinancialReport.setTotalPrice(
                    new BigDecimal(sumDouble + freight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            countLastPrice(taslyFinancialReport, 2, BigDecimal.ROUND_HALF_UP);

        }
    }
    final PageInfo pageInfo = new PageInfo();
    pageInfo.setPageNumber(taslyOrderDatas.getNumber());
    pageInfo.setTotalPages(taslyOrderDatas.getTotalPages());
    pageInfo.setTotalResults(taslyOrderDatas.getTotalElements());

    return new PagedResults<TaslyFinancialReport>(taslyFinancialReportList, pageInfo);
}

From source file:com.servoy.extension.MarketPlaceExtensionProvider.java

private String getSizeString(int size) {
    String unit;//ww w  .j  a  v a  2  s  .c om
    double value;
    if (size > 1024 * 1024) {
        unit = " MB"; //$NON-NLS-1$
        value = ((double) size) / 1024 / 1024;
    } else {
        unit = " KB"; //$NON-NLS-1$
        value = ((double) size) / 1024;
    }

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bd.toPlainString() + unit;
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * Builds the normalized number string./*  w  w  w.  ja v  a2s .c  o  m*/
 *
 * @param nr the nr
 * @param exp10 the exp10
 * @param scale the scale
 * @param decimalChar the decimal char
 * @param unit the unit
 * @return the string
 */
public static String buildNormalizedNumberString(BigDecimal nr, int exp10, int scale, char decimalChar,
        String unit) {
    if (nr == null) {
        return "";
    }
    String str = nr.scaleByPowerOfTen(exp10).setScale(scale, BigDecimal.ROUND_HALF_UP).toPlainString()
            .replace('.', decimalChar);
    if (unit == null) {
        return str;
    }
    return str + " " + unit;
}