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:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that stock is updated correctly if a charge is saved multiple times in a transaction.
 *//*from   w w w .j a v a 2  s .  c  o  m*/
@Test
public void testMultipleSaveInTxn() {
    final List<FinancialAct> acts = createInvoice();
    FinancialAct item = acts.get(1);
    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity, false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(acts);
            save(acts);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    save(acts); // stock shouldn't change if resaved
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:edu.zipcloud.cloudstreetmarket.api.controllers.UsersController.java

@RequestMapping(method = POST)
@ResponseStatus(HttpStatus.CREATED)/*from   ww w . j a v a2s . c  om*/
@ApiOperation(value = "Creates a user account")
public void create(@Valid @RequestBody User user, @RequestHeader(value = "Spi", required = false) String guid,
        @RequestHeader(value = "OAuthProvider", required = false) String provider, HttpServletResponse response)
        throws IllegalAccessException {
    if (isNotBlank(guid)) {
        if (isGuidUnknownToProvider(guid, provider)
                || usersConnectionRepository.isSocialUserAlreadyRegistered(guid)) {
            throw new AccessDeniedException(guid + " @ " + provider);
        }

        user = communityService.createUserWithBalance(user, new Role[] { ROLE_BASIC, ROLE_OAUTH2 },
                BigDecimal.valueOf(20000L));

        messagingTemplate.convertAndSend(Constants.WS_TOPIC_ACTIVITY_FEED_PATH,
                new UserActivityDTO(user.getActions().iterator().next()));

        usersConnectionRepository.bindSocialUserToUser(guid, user, provider);
        communityService.signInUser(user);

        if (!SupportedCurrency.USD.equals(user.getCurrency())) {
            CurrencyExchange currencyExchange = currencyExchangeService
                    .gather("USD" + user.getCurrency().name() + "=X");
            user.setBalance(currencyExchange.getDailyLatestValue().multiply(BigDecimal.valueOf(20000L)));
        }

        communityService.save(user);
    } else {
        user = communityService.createUser(user, ROLE_BASIC);
        messagingTemplate.convertAndSend(Constants.AMQP_USER_ACTIVITY_QUEUE,
                new UserActivityDTO(user.getActions().iterator().next()));
        communityService.signInUser(user);
    }

    response.setHeader(MUST_REGISTER_HEADER, FALSE);
    response.setHeader(LOCATION_HEADER, USERS_PATH + "/" + user.getId());
}

From source file:org.parancoe.plugin.configuration.PropertyDaoTest.java

@Test
public void setRealValue() {
    Category category = categoryDao.findByName("second_category");
    String propertyName = "real_property";
    Property property = propertyDao.findByNameAndCategoryId(propertyName, category.getId());
    BigDecimal newValue = BigDecimal.valueOf(10.50);
    property.setTypedValue(newValue);//w w  w  .  j  a  va  2 s.c  om
    fixAndClearSession(property);
    property = propertyDao.findByNameAndCategoryId(propertyName, category.getId());
    assertThat(property.getValueAsReal(), equalTo(newValue));
}

From source file:com.liato.bankdroid.banking.banks.ica.ICA.java

public Urllib login() throws LoginException, BankException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_ica));
    urlopen.addHeader("Accept", "application/json;charset=UTF-8");
    urlopen.addHeader("Content-Type", "application/json;charset=UTF-8");
    urlopen.addHeader("Authorization",
            "Basic " + Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.NO_WRAP));

    try {/*from w  w w.jav  a  2s . c  om*/
        HttpResponse httpResponse = urlopen.openAsHttpResponse(API_URL + "login",
                new ArrayList<NameValuePair>(), false);
        if (httpResponse.getStatusLine().getStatusCode() == 401) {
            LoginError le = readJsonValue(httpResponse, LoginError.class);
            if (le != null && "UsernamePassword".equals(le.getMessageCode())) {
                if (!TextUtils.isEmpty(le.getMessage())) {
                    throw new LoginException(le.getMessage());
                } else {
                    throw new LoginException(context.getText(R.string.invalid_username_password).toString());
                }
            } else {
                throw new BankException(context.getText(R.string.invalid_username_password).toString());
            }
        }

        for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
            Header header = httpResponse.getFirstHeader(entry.getKey());
            if (header == null || TextUtils.isEmpty(header.getValue())) {
                throw new BankException(
                        context.getString(R.string.unable_to_find).toString() + " " + entry.getKey());
            }
            mHeaders.put(entry.getKey(), header.getValue());
        }

        urlopen.addHeader(AUTHENTICATION_TICKET_HEADER, mHeaders.get(AUTHENTICATION_TICKET_HEADER));
        httpResponse = urlopen.openAsHttpResponse(API_URL + "user/minasidor", new ArrayList<NameValuePair>(),
                false);
        Overview overview = readJsonValue(httpResponse, Overview.class);

        if (overview == null) {
            throw new BankException(context.getString(R.string.unable_to_find) + " overview.");
        }

        if (!TextUtils.isEmpty(overview.getAccountName())) {
            Account account = new Account(overview.getAccountName(),
                    BigDecimal.valueOf(overview.getAvailableAmount()), overview.getAccountNumber());
            balance = balance.add(account.getBalance());
            accounts.add(account);
            List<Transaction> transactions = new ArrayList<Transaction>();
            for (com.liato.bankdroid.banking.banks.ica.model.Transaction t : overview.getTransactions()) {
                transactions.add(new Transaction(t.getTransactionDate(), t.getDescription(),
                        BigDecimal.valueOf(t.getAmount())));
            }
            account.setTransactions(transactions);
        }
        for (com.liato.bankdroid.banking.banks.ica.model.Account a : overview.getAccounts()) {
            Account account = new Account(a.getName(), BigDecimal.valueOf(a.getAvailableAmount()),
                    a.getAccountNumber());
            balance = balance.add(account.getBalance());
            accounts.add(account);
            List<Transaction> transactions = new ArrayList<Transaction>();
            for (com.liato.bankdroid.banking.banks.ica.model.Transaction t : a.getTransactions()) {
                transactions.add(new Transaction(t.getTransactionDate(), t.getDescription(),
                        BigDecimal.valueOf(t.getAmount())));
            }
            account.setTransactions(transactions);
        }

        Account account = new Account("Erhllen bonus i r", BigDecimal.valueOf(overview.getAcquiredBonus()),
                "bonus");
        account.setType(Account.OTHER);
        accounts.add(account);
        account = new Account("rets totala inkp p ICA",
                BigDecimal.valueOf(overview.getYearlyTotalPurchased()), "totalpurchased");
        account.setType(Account.OTHER);
        accounts.add(account);

        if (accounts.isEmpty()) {
            throw new BankException(res.getText(R.string.no_accounts_found).toString());
        }

        urlopen.addHeader(LOGOUT_KEY_HEADER, mHeaders.get(LOGOUT_KEY_HEADER));
        httpResponse = urlopen.openAsHttpResponse(API_URL + "logout", new ArrayList<NameValuePair>(), false);
        httpResponse.getStatusLine();
    } catch (JsonParseException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:info.magnolia.test.mock.jcr.MockValueTest.java

@Test
public void testGetLength() throws Exception {
    assertEquals(6, new MockValue("string").getLength());
    assertEquals(5, new MockValue(Boolean.FALSE).getLength());
    assertEquals(2, new MockValue(BigDecimal.valueOf(12)).getLength());
}

From source file:alluxio.util.FormatUtils.java

/**
 * Parses a String size to Bytes./*  w  w  w  . ja  v  a 2  s  .  c o  m*/
 *
 * @param spaceSize the size of a space, e.g. 10GB, 5TB, 1024
 * @return the space size in bytes
 */
public static long parseSpaceSize(String spaceSize) {
    double alpha = 0.0001;
    String ori = spaceSize;
    String end = "";
    int index = spaceSize.length() - 1;
    while (index >= 0) {
        if (spaceSize.charAt(index) > '9' || spaceSize.charAt(index) < '0') {
            end = spaceSize.charAt(index) + end;
        } else {
            break;
        }
        index--;
    }
    spaceSize = spaceSize.substring(0, index + 1);
    double ret = Double.parseDouble(spaceSize);
    end = end.toLowerCase();
    if (end.isEmpty() || end.equals("b")) {
        return (long) (ret + alpha);
    } else if (end.equals("kb")) {
        return (long) (ret * Constants.KB + alpha);
    } else if (end.equals("mb")) {
        return (long) (ret * Constants.MB + alpha);
    } else if (end.equals("gb")) {
        return (long) (ret * Constants.GB + alpha);
    } else if (end.equals("tb")) {
        return (long) (ret * Constants.TB + alpha);
    } else if (end.equals("pb")) {
        // When parsing petabyte values, we can't multiply with doubles and longs, since that will
        // lose presicion with such high numbers. Therefore we use a BigDecimal.
        BigDecimal pBDecimal = new BigDecimal(Constants.PB);
        return pBDecimal.multiply(BigDecimal.valueOf(ret)).longValue();
    } else {
        throw new IllegalArgumentException("Fail to parse " + ori + " to bytes");
    }
}

From source file:es.upm.fiware.rss.expenditureLimit.manager.test.BalanceAccumulateManagerTest.java

/**
 * /*  w  w w .j  a  v  a  2s .  c o  m*/
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void deleteUserAccumulated() throws RSSException {
    BalanceAccumulateManagerTest.logger.debug("Into getUserAccumulated method.");
    ExpendControl control = generateExpendControl();
    balanceAccumulateManager.deleteUserAccumulated(endUserId, control);
    BalanceAccumulateManagerTest.logger.debug("Get objects after deleting.");

    AccumsExpend result = balanceAccumulateManager.getUserAccumulated(endUserId, control.getService(),
            control.getAggregator(), control.getAppProvider(), control.getCurrency(), control.getType());

    Assert.assertTrue(result.getAccums().size() > 0);
    boolean changed = false;
    for (AccumExpend accum : result.getAccums()) {
        if (accum.getType().equalsIgnoreCase(control.getType())
                && accum.getExpensedAmount().compareTo(BigDecimal.valueOf(0)) == 0) {
            changed = true;
        }
    }
    Assert.assertTrue(changed);
}

From source file:net.eusashead.hateoas.hal.response.impl.HalResponseBuilderImplTest.java

@Test
public void testDefaultConvert() throws Exception {

    // Create a test object
    Order order = new Order(1, BigDecimal.valueOf(12.32d), new Date(123456789l));

    // Create a HalGetResponseBuilder
    HalResponseBuilderImpl builder = new HalResponseBuilderImpl(representationFactory, request);

    // Create a response with a Representation
    ResponseEntity<Representation> response = builder.convert(order).etag(order.getDate())
            .lastModified(order.getDate()).expireIn(1000000).build();

    // Check the headers
    assertHeaders(response);/*www.  j  a v a2s. com*/

    // Check the body
    Assert.assertEquals("/path/to/resource", response.getBody().getLinkByRel("self").getHref());
    Assert.assertEquals("1", response.getBody().getValue("id").toString());
    Assert.assertEquals("12.32", response.getBody().getValue("total").toString());
    Assert.assertEquals(new Date(123456789l).toString(), response.getBody().getValue("date").toString());

}

From source file:churashima.action.manage.ExpensesAction.java

@Execute(validator = false)
public String search() {

    String strSerachPlace = null;
    if (StringUtils.isNotEmpty(expensesForm.searchPlace)) {
        strSerachPlace = "%" + expensesForm.searchPlace + "%";
    }/*from ww  w  .j a v a  2 s  . c o  m*/

    String strSerachName = null;
    if (StringUtils.isNotEmpty(expensesForm.searchName)) {
        strSerachName = "%" + expensesForm.searchName + "%";
    }

    Long longSubjectId = null;
    if (expensesForm.searchSubjectId != null && !"all".equals(expensesForm.searchSubjectId)) {
        longSubjectId = Long.valueOf(expensesForm.searchSubjectId);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    Date dateFrom = null;
    if (StringUtils.isNotEmpty(expensesForm.searchDayFrom)) {
        try {
            dateFrom = sdf.parse(expensesForm.searchDayFrom);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    Date dateTo = null;
    if (StringUtils.isNotEmpty(expensesForm.searchDayTo)) {
        try {
            dateTo = sdf.parse(expensesForm.searchDayTo);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    ExpensesDao expensesDao = SingletonS2Container.getComponent(ExpensesDao.class);
    List<Expenses> expensesList = expensesDao.selectForSearch(null, longSubjectId, strSerachPlace,
            strSerachName, dateFrom, dateTo, expensesForm.searchPrice, null, null);

    SubjectDao subjectDao = SingletonS2Container.getComponent(SubjectDao.class);
    expensesForm.subjectList = subjectDao.selectForSearch(null, null);

    expensesForm.expensesList = expensesList;

    // ??
    BigDecimal sumPriceTotal = BigDecimal.valueOf(0);
    for (Expenses expenses : expensesList) {
        sumPriceTotal = sumPriceTotal.add(expenses.price);
    }
    expensesForm.sumPriceTotal = sumPriceTotal;

    return "expensesList.jsp";
}

From source file:eugene.agent.noise.impl.PlaceOrderBehaviour.java

/**
 * Sends a {@link OrdType#LIMIT} order between best ask and best bid.
 *
 * @param side side of the order./*w ww .  j a v  a2s  . c  o  m*/
 */
private void limitInSpread(final Side side) {

    final Long ordQty = Double.valueOf(ordSize.sample()).longValue();

    if (!topOfBook.hasBothSides()) {
        session.send(newLimit(topOfBook.getLastPrice(side, YES), ordQty));
        return;
    }

    final BigDecimal spread = topOfBook.getSpread();
    final BigDecimal additive = BigDecimal.valueOf(inSpreadPrice.sample()).multiply(spread);
    final BigDecimal price = topOfBook.getLastPrice(Side.BUY, ReturnDefaultPrice.NO).nextPrice(additive);
    session.send(newLimit(side, price, ordQty));
}