Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

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

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.yes.cart.web.service.rest.SearchController.java

private void populateSearchResults(final NavigationContext context, final SearchResultRO result,
        final ShoppingCart cart) {

    ProductSearchResultPageDTO products = productServiceFacade.getListProducts(context,
            result.getSearch().getPageNumber() * result.getSearch().getPageSize(),
            result.getSearch().getPageSize(), result.getSearch().getSortField(),
            result.getSearch().getSortDescending());

    result.setTotalResults(products.getTotalHits());

    final List<ProductSearchResultRO> ros = new ArrayList<ProductSearchResultRO>();
    if (CollectionUtils.isNotEmpty(products.getResults())) {

        final Pair<String, Boolean> symbol = currencySymbolService.getCurrencySymbol(cart.getCurrencyCode());

        for (final ProductSearchResultDTO hit : products.getResults()) {

            final ProductAvailabilityModel skuPam = productServiceFacade.getProductAvailability(hit,
                    context.getShopId());

            final ProductSearchResultRO ro = mappingMixin.map(hit, ProductSearchResultRO.class,
                    ProductSearchResultDTO.class);

            final ProductAvailabilityModelRO amRo = mappingMixin.map(skuPam, ProductAvailabilityModelRO.class,
                    ProductAvailabilityModel.class);
            ro.setProductAvailabilityModel(amRo);

            final SkuPrice price = productServiceFacade.getSkuPrice(null, skuPam.getFirstAvailableSkuCode(),
                    BigDecimal.ONE, cart.getCurrencyCode(), context.getShopId());

            final SkuPriceRO priceRo = mappingMixin.map(price, SkuPriceRO.class, SkuPrice.class);
            priceRo.setSymbol(symbol.getFirst());
            priceRo.setSymbolPosition(symbol.getSecond() != null && symbol.getSecond() ? "after" : "before");

            ro.setPrice(priceRo);//from www.  j a  v  a  2  s .  c om

            ros.add(ro);

        }
    }
    result.setProducts(ros);

}

From source file:org.apache.jackrabbit.oak.remote.http.handler.RemoteServerIT.java

@Test
public void testReadLastRevisionTreeMultiDecimalProperty() throws Exception {
    Root root = contentSession.getLatestRoot();

    Tree node = root.getTree("/").addChild("node");
    node.setProperty("jcr:primaryType", "nt:unstructured", Type.NAME);
    node.setProperty("property", asList(BigDecimal.ZERO, BigDecimal.ONE), Type.DECIMALS);

    root.commit();/*w  w w.ja  va 2s . c o  m*/

    JSONObject body = get(resource("/revisions/last/tree/node")).basicAuth("admin", "admin").asJson().getBody()
            .getObject();
    assertTrue(body.getJSONObject("children").isNull("child"));

    JSONObject property = body.getJSONObject("properties").getJSONObject("property");
    assertEquals("decimals", property.getString("type"));
    assertEquals("0", property.getJSONArray("value").getString(0));
    assertEquals("1", property.getJSONArray("value").getString(1));
}

From source file:org.kuali.rice.kew.docsearch.xml.StandardGenericXMLSearchableAttributeRangesTest.java

@Test
public void testFloatRanges() throws Exception {
    WorkflowDocument doc = setUpSearchableDoc();
    String userId = doc.getInitiatorPrincipalId();
    String docType = doc.getDocumentTypeName();

    String searchAttributeFloatKey = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_KEY;
    BigDecimal searchAttributeFloatValue = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_VALUE;

    BigDecimal floatValueToUse = null;
    // test lower bound only
    floatValueToUse = searchAttributeFloatValue; // lower bound == value
    // NOTE: original test asserted 0 results, mysql actually does match the value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            1);//from   w ww.  j  a  v  a  2s  .  c o m

    floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // lowerbound < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            1);

    floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // lowerbound > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            0);

    // test upper bound only
    floatValueToUse = searchAttributeFloatValue; // upperbound == value (does not match float)
    // NOTE: another case where original test had 0 results, but in fact we see a float match
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            1);

    floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // upperbound < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            0);

    floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // upperbound > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            1);

    // test both bounds
    // upper == lower == value
    // NOTE: original case had 0 results, now seeing 1 result
    // search generator invokes criteria which calls addNumericRangeCriteria when produces: (EXT1.VAL BETWEEN 123456.3456 AND 123456.3456)
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.toString(),
            searchAttributeFloatValue.toString(), true, 1);

    // upper and lower > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.add(new BigDecimal(4)).toString(), true, 0);

    // upper and lower < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.subtract(new BigDecimal(4)).toString(),
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, 0);

    // lower < value, upper > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(), true, 1);

    // upper < lower
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, EXPECT_EXCEPTION);
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

@Deprecated
private BigDecimal getDetails(final Long financialyearid, final Integer moduleid, final String referencenumber,
        final Integer departmentid, final Long functionid, final Integer functionaryid, final Integer schemeid,
        final Integer subschemeid, final Integer boundaryid, final List<Long> budgetheadid,
        final Integer fundid, final double amount, final boolean consumeOrRelease,
        final String appropriationnumber) {
    try {//from   w  w  w  .j av  a  2  s .co m
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber=="
                    + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid
                    + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid=="
                    + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid
                    + ",amount==" + amount);

        validateMandatoryParameters(moduleid, referencenumber);
        BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid,
                functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid);

        if (consumeOrRelease)
            amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount));
        else
            amtavailable = amtavailable.add(BigDecimal.valueOf(amount));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("budget available after consuming/releasing=" + amtavailable);

        if (amtavailable != null && amtavailable.compareTo(BigDecimal.ZERO) >= 0) {
            // need to update budget details
            final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid,
                    boundaryid, fundid);
            final Query q = persistenceService.getSession().createQuery(
                    " from BudgetDetail bd where  bd.budget.financialYear.id=:finYearId  and  bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)"
                            + query);
            if (budgetService.hasApprovedReForYear(financialyearid))
                q.setParameter("type", "RE");
            else
                q.setParameter("type", "BE");
            q.setParameter("finYearId", financialyearid);
            q.setParameterList("bgId", budgetheadid);
            final List<BudgetDetail> bdList = q.list();
            if (bdList == null || bdList.size() == 0) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!");
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group -  "
                            + budgetheadid.toString() + " Query - " + query);
                throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed");
            }
            final BudgetDetail bd = bdList.get(0);
            bd.setBudgetAvailable(amtavailable);
            update(bd);

            final BudgetUsage budgetUsage = new BudgetUsage();
            budgetUsage.setFinancialYearId(financialyearid.intValue());
            budgetUsage.setModuleId(moduleid);
            budgetUsage.setReferenceNumber(referencenumber);
            budgetUsage.setBudgetDetail(bd);
            budgetUsage.setAppropriationnumber(appropriationnumber);
            if (consumeOrRelease) {
                budgetUsage.setConsumedAmount(amount);
                budgetUsage.setReleasedAmount(0.0);
            } else {
                budgetUsage.setConsumedAmount(0.0);
                budgetUsage.setReleasedAmount(amount);
            }
            budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue());
            budgetUsageService.create(budgetUsage);
            return BigDecimal.ONE;
        } else
            return BigDecimal.ZERO;
    } catch (final ValidationException v) {
        throw v;
    } catch (final Exception e) {
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
}

From source file:org.finra.dm.service.helper.DmHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance spot price and max search
 * price is specified. The definition is not valid. The two parameters are exclusive.
 *///from   ww w . j ava 2  s  . c o  m
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterSpotPriceAndMaxSearchPriceSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances().setInstanceSpotPrice(BigDecimal.ONE);
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceMaxSearchPrice(BigDecimal.ONE);

    try {
        dmHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
        fail("expected IllegalArgumentException, but no exception was thrown");
    } catch (Exception e) {
        assertEquals("thrown exception", IllegalArgumentException.class, e.getClass());
    }
}

From source file:org.finra.herd.service.helper.HerdHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance max search price is
 * negative. The definition is not valid. All prices must be positive.
 *///from  w w w.  ja  v  a  2 s .  com
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterMaxSearchPriceNegative() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceMaxSearchPrice(BigDecimal.ONE.negate());

    try {
        herdHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
        fail("expected IllegalArgumentException, but no exception was thrown");
    } catch (Exception e) {
        assertEquals("thrown exception", IllegalArgumentException.class, e.getClass());
    }
}

From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java

/**
 * Maps a charge to a delivery item./*from  ww w.j a v a  2 s .  c om*/
 *
 * @param charge    the allowance/charge
 * @param startTime the invoice start time
 * @param invoiceId the invoice identifier
 * @param rates     the tax rates
 * @return a new delivery item
 * @throws ESCIAdapterException if the allowance/charge cannot be mapped
 */
protected FinancialAct mapCharge(UBLAllowanceCharge charge, Date startTime, String invoiceId, TaxRates rates) {
    if (!charge.isCharge()) {
        throw new ESCIAdapterException(ESCIAdapterMessages.invoiceAllowanceNotSupported(invoiceId));
    }
    BigDecimal unitPrice = charge.getAmount();
    ActBean deliveryItem = factory.createActBean(SupplierArchetypes.DELIVERY_ITEM);
    BigDecimal tax = charge.getTaxAmount();
    BigDecimal rate = checkTaxCategory(charge.getTaxCategory(), rates);
    BigDecimal divisor = BigDecimal.valueOf(100);
    if (tax.compareTo(BigDecimal.ZERO) != 0) {
        BigDecimal expectedTax = MathRules.divide(unitPrice.multiply(rate), divisor, 2);
        if (expectedTax.compareTo(tax) != 0) {
            ErrorContext context = new ErrorContext(charge, "TaxTotal/TaxAmount");
            throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(),
                    context.getType(), context.getID(), expectedTax.toString(), tax.toString()));
        }
    }
    deliveryItem.setValue("startTime", startTime);
    deliveryItem.setValue("quantity", BigDecimal.ONE);
    deliveryItem.setValue("packageUnits", null); // override default
    deliveryItem.setValue("unitPrice", unitPrice);
    deliveryItem.setValue("tax", tax);
    deliveryItem.setValue("reorderDescription", charge.getAllowanceChargeReason()); // TODO - not ideal

    getArchetypeService().deriveValues(deliveryItem.getObject());
    return (FinancialAct) deliveryItem.getAct();
}

From source file:org.finra.dm.service.helper.DmHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance max search price is
 * negative. The definition is not valid. All prices must be positive.
 *///www .j  av  a2 s .  c o  m
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterMaxSearchPriceNegative() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceMaxSearchPrice(BigDecimal.ONE.negate());

    try {
        dmHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
        fail("expected IllegalArgumentException, but no exception was thrown");
    } catch (Exception e) {
        assertEquals("thrown exception", IllegalArgumentException.class, e.getClass());
    }
}

From source file:org.finra.herd.service.helper.HerdHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance on-demand threshold is
 * specified. The definition is not valid. On-demand threshold is only allowed when max search price is specified.
 *///w  w  w . ja v a2  s.co m
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterOnDemandThresholdSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceOnDemandThreshold(BigDecimal.ONE);

    try {
        herdHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
        fail("expected IllegalArgumentException, but no exception was thrown");
    } catch (Exception e) {
        assertEquals("thrown exception", IllegalArgumentException.class, e.getClass());
    }
}

From source file:org.finra.dm.service.helper.DmHelperTest.java

/**
 * Tests case where validation is run against the definition generated by createValidEmrClusterDefinition() The master instance on-demand threshold is
 * specified. The definition is not valid. On-demand threshold is only allowed when max search price is specified.
 *//*from  w  w w .ja v a2  s.  co  m*/
@Test
public void testValidateEmrClusterDefinitionConfigurationMasterOnDemandThresholdSpecified() {
    EmrClusterDefinition emrClusterDefinition = createValidEmrClusterDefinition();
    emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
            .setInstanceOnDemandThreshold(BigDecimal.ONE);

    try {
        dmHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition);
        fail("expected IllegalArgumentException, but no exception was thrown");
    } catch (Exception e) {
        assertEquals("thrown exception", IllegalArgumentException.class, e.getClass());
    }
}