Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.FrequencyFirstConsecutiveValueThresholdConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    FrequencyValueThresholdConverter converter = new FrequencyValueThresholdConverter();
    converter.setConverterVisitor(converterVisitor);
    SystemProposition primParam = new SystemProposition();
    primParam.setId(1L);/* w ww  .j  a v a2  s .  c om*/
    primParam.setKey("test-primparam1");
    primParam.setInSystem(true);
    primParam.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    ValueThresholdGroupEntity thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(2L);
    thresholdGroup.setKey("test-valuethreshold");
    thresholdGroupKey = thresholdGroup.getKey();

    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    ValueThresholdEntity threshold = new ValueThresholdEntity();
    threshold.setAbstractedFrom(primParam);
    threshold.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold.setMinValueComp(gt);
    threshold.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold.setMaxValueComp(lt);
    threshold.setId(Long.valueOf(1));

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold);
    thresholdGroup.setValueThresholds(thresholds);

    TimeUnit dayUnit = new TimeUnit();
    dayUnit.setName("day");

    FrequencyType ft = new FrequencyType();
    ft.setName("first");

    frequency = new FrequencyEntity();
    frequency.setId(3L);
    frequency.setKey("test-freqhla-key");
    frequency.setCount(2);
    frequency.setWithinAtLeast(1);
    frequency.setWithinAtLeastUnits(dayUnit);
    frequency.setWithinAtMost(90);
    frequency.setWithinAtMostUnits(dayUnit);
    frequency.setFrequencyType(ft);
    frequency.setConsecutive(true);

    ExtendedPhenotype af = new ExtendedPhenotype();
    af.setPhenotypeEntity(thresholdGroup);
    frequency.setExtendedProposition(af);

    propDefs = converter.convert(frequency);

    llas = new ArrayList<>();
    for (PropositionDefinition propDef : propDefs) {
        if (propDef instanceof LowLevelAbstractionDefinition) {
            llas.add((LowLevelAbstractionDefinition) propDef);
        }
    }
    llaDef = llas.get(0);
    hlad = converter.getPrimaryPropositionDefinition();

    userConstraintName = asValueString(thresholdGroupKey);
    compConstraintName = asValueCompString(thresholdGroupKey);

    tepd = (TemporalExtendedPropositionDefinition) hlad.getExtendedPropositionDefinitions().iterator().next();

    gf = (SimpleGapFunction) hlad.getGapFunction();
}

From source file:info.magnolia.ui.vaadin.integration.jcr.DefaultPropertyUtil.java

/**
 * Create a custom Field Object based on the Type and defaultValue.
 * If the fieldType is null, the defaultValue will be returned as String or null.
 * If the defaultValue is null, null will be returned.
 *
 * @throws NumberFormatException In case of the default value could not be parsed to the desired class.
 *///from w  ww  .j  ava2  s  . c o  m
public static Object createTypedValue(Class<?> type, String defaultValue) throws NumberFormatException {
    if (StringUtils.isBlank(defaultValue)) {
        return defaultValue;
    } else if (defaultValue != null) {
        if (type.getName().equals(String.class.getName())) {
            return defaultValue;
        } else if (type.getName().equals(Long.class.getName())) {
            return Long.decode(defaultValue);
        } else if (type.isAssignableFrom(Binary.class)) {
            return null;
        } else if (type.getName().equals(Double.class.getName())) {
            return Double.valueOf(defaultValue);
        } else if (type.getName().equals(Date.class.getName())) {
            try {
                return new SimpleDateFormat(DateUtil.YYYY_MM_DD).parse(defaultValue);
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        } else if (type.getName().equals(Boolean.class.getName())) {
            return BooleanUtils.toBoolean(defaultValue);
        } else if (type.getName().equals(BigDecimal.class.getName())) {
            return BigDecimal.valueOf(Long.decode(defaultValue));
        } else if (type.isAssignableFrom(List.class)) {
            return Arrays.asList(defaultValue.split(","));
        } else {
            throw new IllegalArgumentException("Unsupported property type " + type.getName());
        }
    }
    return null;
}

From source file:com.gst.portfolio.tax.serialization.TaxValidator.java

public void validateForTaxComponentCreate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from   w  ww . ja  v a  2 s.  c o  m

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
            this.supportedTaxComponentCreateParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("tax.component");

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final String name = this.fromApiJsonHelper.extractStringNamed(TaxApiConstants.nameParamName, element);
    baseDataValidator.reset().parameter(TaxApiConstants.nameParamName).value(name).notBlank();

    final BigDecimal percentage = this.fromApiJsonHelper
            .extractBigDecimalWithLocaleNamed(TaxApiConstants.percentageParamName, element);
    baseDataValidator.reset().parameter(TaxApiConstants.percentageParamName).value(percentage).notBlank()
            .positiveAmount().notGreaterThanMax(BigDecimal.valueOf(100));

    final Integer debitAccountType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(TaxApiConstants.debitAccountTypeParamName, element);
    baseDataValidator.reset().parameter(TaxApiConstants.debitAccountTypeParamName).value(debitAccountType)
            .ignoreIfNull().isOneOfTheseValues(GLAccountType.ASSET.getValue(),
                    GLAccountType.LIABILITY.getValue(), GLAccountType.EQUITY.getValue(),
                    GLAccountType.INCOME.getValue(), GLAccountType.EXPENSE.getValue());

    final Long debitAccountId = this.fromApiJsonHelper.extractLongNamed(TaxApiConstants.debitAcountIdParamName,
            element);
    baseDataValidator.reset().parameter(TaxApiConstants.debitAcountIdParamName).value(debitAccountId)
            .longGreaterThanZero();
    if (debitAccountType != null || debitAccountId != null) {
        baseDataValidator.reset().parameter(TaxApiConstants.debitAccountTypeParamName).value(debitAccountType)
                .notBlank();
        baseDataValidator.reset().parameter(TaxApiConstants.debitAcountIdParamName).value(debitAccountId)
                .notBlank();
    }

    final Integer creditAccountType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(TaxApiConstants.creditAccountTypeParamName, element);
    baseDataValidator.reset().parameter(TaxApiConstants.creditAccountTypeParamName).value(creditAccountType)
            .ignoreIfNull().isOneOfTheseValues(GLAccountType.ASSET.getValue(),
                    GLAccountType.LIABILITY.getValue(), GLAccountType.EQUITY.getValue(),
                    GLAccountType.INCOME.getValue(), GLAccountType.EXPENSE.getValue());

    final Long creditAccountId = this.fromApiJsonHelper
            .extractLongNamed(TaxApiConstants.creditAcountIdParamName, element);
    baseDataValidator.reset().parameter(TaxApiConstants.creditAcountIdParamName).value(creditAccountId)
            .longGreaterThanZero();
    if (creditAccountType != null || creditAccountId != null) {
        baseDataValidator.reset().parameter(TaxApiConstants.creditAcountIdParamName).value(creditAccountId)
                .notBlank();
        baseDataValidator.reset().parameter(TaxApiConstants.creditAccountTypeParamName).value(creditAccountType)
                .notBlank();
    }
    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:com.chiralbehaviors.seurat.service.DemoScenarioTest.java

private void loadState(Model model) throws InstantiationException {
    Customer cafleurBon = model.wrap(Customer.class, testScenario.getCafleurBon());
    Customer gu = model.wrap(Customer.class, testScenario.getGeorgetownUniversity());
    gu.setCustomerName("George Washington University");
    Customer orgA = model.wrap(Customer.class, testScenario.getOrgA());
    orgA.setCustomerName("Der Org A");

    PricedProduct computer = model.wrap(PricedProduct.class, testScenario.getAbc486());
    computer.setUnitPrice(BigDecimal.valueOf(1250.10));
    PricedProduct chemB = model.wrap(PricedProduct.class, testScenario.getChemB());
    chemB.setUnitPrice(BigDecimal.valueOf(10.25));

    Order order = model.construct(Order.class, "Cafluer Bon Order", "emergency order");
    order.setOrderDate(new Timestamp(System.currentTimeMillis()));
    addItem(computer, order, 2, 0, 0.07, model);
    addItem(chemB, order, 50, 0, 0.05, model);
    cafleurBon.addOrder(order);/*from   ww  w . j a  v a 2 s .c  o m*/
    cafleurBon.setCustomerName("Cafleur Bon");

    order = model.construct(Order.class, "GU Order", "monthly ship");
    order.setOrderDate(new Timestamp(System.currentTimeMillis()));
    addItem(computer, order, 20, 0.05, 0, model);
    addItem(chemB, order, 050, 0.05, 0, model);
    gu.addOrder(order);

    order = model.construct(Order.class, "Org A", "computer!  STAT!");
    order.setOrderDate(new Timestamp(System.currentTimeMillis()));
    addItem(computer, order, 500, 0.10, 0, model);
    orgA.addOrder(order);
}

From source file:data.services.CarService.java

public List<Car> getCarsWithBrandsLesserPrice(List<Mark> mlist, BigDecimal price) {
    if (mlist.isEmpty()) {
        return carDao.getCarLesserPrice(price);
    } else {//ww  w.  j ava 2s  .c o m
        List<Car> clist = new ArrayList();
        for (Mark m : mlist) {
            for (Model mod : m.getModels()) {
                for (Car c : mod.getCars()) {
                    if (BigDecimal.valueOf(c.getCmPrice()).compareTo(price) <= 0
                            && BigDecimal.valueOf(c.getCmPrice()).compareTo(BigDecimal.valueOf(0)) > 0) {
                        clist.add(c);
                    }
                }
            }
        }
        return clist;
    }
}

From source file:org.stockwatcher.data.cassandra.DailySummaryGenerator.java

private List<ResultSetFuture> processTradesForSymbol(List<ResultSetFuture> selectFutures) {
    List<ResultSetFuture> insertFutures = new ArrayList<ResultSetFuture>();
    for (ResultSetFuture future : selectFutures) {
        String symbol = null;// w w  w. ja v a 2  s. c om
        Date tradeDate = null;
        BigDecimal open = BigDecimal.ZERO;
        BigDecimal high = BigDecimal.ZERO;
        BigDecimal low = BigDecimal.valueOf(Long.MAX_VALUE);
        BigDecimal close = BigDecimal.ZERO;
        BigDecimal sharePrice = null;
        int volume = 0;
        for (Row row : future.getUninterruptibly()) {
            if (symbol == null) {
                symbol = row.getString("stock_symbol");
                tradeDate = row.getDate("trade_date");
                open = row.getDecimal("share_price");
                LOGGER.debug("Processing trades for symbol {} on {}", symbol, tradeDate);
            }
            sharePrice = row.getDecimal("share_price");
            if (sharePrice.compareTo(high) > 0) {
                high = sharePrice;
            }
            if (sharePrice.compareTo(low) < 0) {
                low = sharePrice;
            }
            close = sharePrice;
            volume += row.getInt("share_quantity");
        }
        if (volume > 0) {
            insertFutures.add(insert(symbol, tradeDate, open, high, low, close, volume));
        }
    }
    selectFutures.clear();
    return insertFutures;
}

From source file:com.music.web.CartController.java

@RequestMapping("/bitcoinCheckout")
@ResponseBody//from   ww w.ja  va2s  .  c  o m
public String bitcoinCheckout(@RequestParam(required = false) String email) {
    Long userId = null;
    if (userContext.getUser() != null) {
        userId = userContext.getUser().getId();
    } else {
        if (!emailValidator.isValid(email, null)) {
            throw new IllegalArgumentException("Invalid email");
        }
    }
    long purchaseId = purchaseService.bitcoinCheckout(new ArrayList<>(cart.getPieceIds()), userId, email);

    long amount = cart.getPieceIds().size();
    Map<String, BigDecimal> rates = purchaseService.getConversionRates();
    String code = purchaseService.getButtonCode(
            rates.get("usd_to_btc").multiply(BigDecimal.valueOf(0.50d)).multiply(BigDecimal.valueOf(amount)),
            purchaseId);

    return code;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.ValueThresholdsCompoundLowLevelAbstractionConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    ValueThresholdsCompoundLowLevelAbstractionConverter converter = new ValueThresholdsCompoundLowLevelAbstractionConverter();
    converter.setConverterVisitor(converterVisitor);

    ThresholdsOperator op = new ThresholdsOperator();
    op.setName("all");

    ValueComparator eq = new ValueComparator();
    eq.setName("=");
    ValueComparator ne = new ValueComparator();
    ne.setName("not=");
    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    eq.setComplement(ne);//from   www. ja  v  a 2s.c om
    ne.setComplement(eq);
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    SystemProposition primParam1 = new SystemProposition();
    primParam1.setId(1L);
    primParam1.setKey("test-primparam1");
    primParam1.setInSystem(true);
    primParam1.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    SystemProposition primParam2 = new SystemProposition();
    primParam2.setId(2L);
    primParam2.setKey("test-primparam2");
    primParam2.setInSystem(true);
    primParam2.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(3L);
    thresholdGroup.setKey("test-valuethreshold");

    ValueThresholdEntity threshold1 = new ValueThresholdEntity();
    threshold1.setAbstractedFrom(primParam1);
    threshold1.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold1.setMinValueComp(gt);
    threshold1.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold1.setMaxValueComp(lt);
    threshold1.setId(1L);

    ValueThresholdEntity threshold2 = new ValueThresholdEntity();
    threshold2.setAbstractedFrom(primParam2);
    threshold2.setMinValueThreshold(BigDecimal.valueOf(5));
    threshold2.setMinValueComp(eq);
    threshold2.setId(2L);

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold1);
    thresholds.add(threshold2);
    thresholdGroup.setValueThresholds(thresholds);
    thresholdGroup.setThresholdsOperator(op);

    propDefs = converter.convert(thresholdGroup);
    llaDefs = new ArrayList<>();
    for (PropositionDefinition pd : propDefs) {
        if (pd instanceof LowLevelAbstractionDefinition) {
            llaDefs.add((LowLevelAbstractionDefinition) pd);
        }
    }
    firstLlaDef = llaDefs.get(0);
    secondLlaDef = llaDefs.get(1);
    for (PropositionDefinition ld : propDefs) {
        if (ld.getId().equals("test-valuethreshold_PRIMARY")) {
            cllaDef = (CompoundLowLevelAbstractionDefinition) ld;
            break;
        }
    }
    userConstraintName = asValueString(thresholdGroup);
    compConstraintName = asValueCompString(thresholdGroup);
    secondUserConstraintName = asValueString(thresholdGroup);
    secondCompConstraintName = asValueCompString(thresholdGroup);
}

From source file:fixio.fixprotocol.fields.FieldFactoryTest.java

@Test
public void testValueOfPrice() throws Exception {
    BigDecimal value = BigDecimal.valueOf(new Random().nextInt()).movePointLeft(5);

    FloatField field = FieldFactory.valueOf(FieldType.MktBidPx.tag(), value.toPlainString().getBytes(US_ASCII));

    assertEquals("tagnum", FieldType.MktBidPx.tag(), field.getTagNum());
    assertEquals("value", value.doubleValue(), field.getValue().doubleValue(), 0.0);
    assertEquals("value", value.floatValue(), field.floatValue(), 0.0);
}

From source file:de.hybris.platform.integration.cis.payment.commands.DefaultCisSubscriptionAuthorizationCommandTest.java

@Test
public void shouldAuthorizeAndGetRejected() throws Exception {
    final RestResponse hpfUrl = this.paymentClient.pspUrl("http://test.cybersouce.com");
    final String testClientRef = "JUNIT-TEST-CLIENT";

    //here we create a profile through Cybersource SOP, this profile will be used for the test authorizations
    final List<BasicNameValuePair> validFormData = CisPaymentIntegrationTestHelper.getValidFormDataMap();
    final Map<String, String> profileCreationResponse = CisPaymentIntegrationTestHelper
            .createNewProfile(hpfUrl.getLocation().toASCIIString(), validFormData);
    final CreateSubscriptionResult subscriptionResult = getCreateSubscriptionResult(testClientRef,
            profileCreationResponse);/*from w ww. ja v a  2  s .  c  o  m*/

    final BillingInfo billingInfo = createBillingInfo();
    final SubscriptionAuthorizationRequest request = new SubscriptionAuthorizationRequest(
            String.valueOf(System.currentTimeMillis()),
            subscriptionResult.getSubscriptionInfoData().getSubscriptionID(), Currency.getInstance("USD"),
            BigDecimal.valueOf(1500D), billingInfo, "cisCybersource");

    final CommandFactory commandFactory = commandFactoryRegistry.getFactory("cisCybersource");
    final SubscriptionAuthorizationCommand command = commandFactory
            .createCommand(SubscriptionAuthorizationCommand.class);

    final AuthorizationResult authResult;
    try {
        TestUtils.disableFileAnalyzer(
                "expected exception com.hybris.cis.api.exception.ServiceRequestException: 4015");
        authResult = command.perform(request);
    } finally {
        TestUtils.enableFileAnalyzer();
    }
    Assert.assertEquals(TransactionStatus.REJECTED, authResult.getTransactionStatus());
}