Example usage for java.util Currency getInstance

List of usage examples for java.util Currency getInstance

Introduction

In this page you can find the example usage for java.util Currency getInstance.

Prototype

public static Currency getInstance(Locale locale) 

Source Link

Document

Returns the Currency instance for the country of the given locale.

Usage

From source file:ch.silviowangler.dox.DocumentServiceIntegrationTest.java

@Test
public void importCurrencyAmount()
        throws DocumentClassNotFoundException, DocumentDuplicationException, ValidationException, IOException {

    File singlePagePdf = loadFile("document-1p.pdf");

    Map<TranslatableKey, DescriptiveIndex> indexes = newHashMapWithExpectedSize(1);
    indexes.put(COMPANY, new DescriptiveIndex("Sunrise"));
    indexes.put(MONEY, new DescriptiveIndex(new Money(Currency.getInstance("CHF"), new BigDecimal("1235.50"))));
    indexes.put(INVOICE_AMOUNT, new DescriptiveIndex(12350L));
    indexes.put(INVOICE_DATE, new DescriptiveIndex(new Date()));

    PhysicalDocument doc = new PhysicalDocument(documentClass, readFileToByteArray(singlePagePdf), indexes,
            singlePagePdf.getName());/*from w  w w  . j  a  v a2s. c o m*/
    doc.setClient(CLIENT_WANGLER);
    final DocumentReference documentReference = documentService.importDocument(doc);

    final Money money = (Money) documentReference.getIndices().get(MONEY).getValue();
    assertThat(money, is(not(nullValue())));
    assertThat(money.getCurrency().getCurrencyCode(), is("CHF"));
    assertThat(money.getAmount().toPlainString(), is("1235.50"));
}

From source file:org.apache.empire.struts2.jsp.controls.TextInputControl.java

private String getUnitString(ValueInfo vi) {
    // Is unit supplied as a format option
    String format = getFormatOption(vi, FORMAT_UNIT);
    if (format != null)
        return format;
    // Is it a currency column
    Column column = vi.getColumn();/*  www . jav  a 2  s  . co m*/
    if (column != null && column.getDataType() == DataType.DECIMAL) {
        String numberType = StringUtils.toString(column.getAttribute(InputControl.NUMBER_FORMAT_ATTRIBUTE));
        if (numberType != null) {
            if (numberType.equalsIgnoreCase("Currency")) {
                String currencyCode = StringUtils
                        .toString(column.getAttribute(InputControl.CURRENCY_CODE_ATTRIBUTE));
                if (currencyCode != null) { // nf = NumberFormat.getCurrencyInstance(locale);
                    Currency currency = Currency.getInstance(currencyCode);
                    return (currency != null) ? currency.getSymbol() : null;
                }
            } else if (numberType.equalsIgnoreCase("Percent")) {
                return "%";
            }
        }
    }
    // No Unit supplied
    return null;
}

From source file:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java

private void processCredit(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);/*from   w w  w. j a  v a  2  s.  c o m*/

    // Set the account
    String toAccount = mCursor.getString(TransactionsFragment.COLUMN_TO_ACCOUNT_TITLE);
    holder.mAccount.setText(toAccount);

    // Set the amount
    double toAmount = NumberUtils
            .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_AMOUNT) / 100.0);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String toCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_TO_CURRENCY);
    Currency toCurrency = Currency.getInstance(toCurrencyCode);
    format.setCurrency(toCurrency);
    format.setMaximumFractionDigits(toCurrency.getDefaultFractionDigits());
    holder.mAmount.setText(format.format(toAmount));
    holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));

    double toBalance = NumberUtils
            .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);
    holder.mRunningBalance.setText(format.format(toBalance));

    // Set the transaction type icon
    holder.mTypeIcon.setImageDrawable(
            DrawableHelper.tint(mContext, R.drawable.ic_call_received_black_24dp, R.color.colorGreen700));
}

From source file:org.cocos2dx.plugin.UserFacebook.java

public void logPurchase(JSONObject info) {
    int length = info.length();
    if (3 == length) {
        try {/*from  w  w w  .  j a va  2s . c  om*/
            Double purchaseNum = info.getDouble("Param1");
            String currency = info.getString("Param2");

            JSONObject params = info.getJSONObject("Param3");
            Iterator<?> keys = params.keys();
            Bundle bundle = new Bundle();
            while (keys.hasNext()) {
                String key = keys.next().toString();
                bundle.putString(key, params.getString(key));
            }
            Currency currencyStr = null;
            try {
                currencyStr = Currency.getInstance(currency);
            } catch (IllegalArgumentException e) {
                currencyStr = Currency.getInstance(Locale.getDefault());
                e.printStackTrace();
            }

            FacebookWrapper.getAppEventsLogger().logPurchase(new BigDecimal(purchaseNum), currencyStr, bundle);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (2 == length) {
        try {
            Double purchaseNum = info.getDouble("Param1");
            String currency = info.getString("Param2");
            FacebookWrapper.getAppEventsLogger().logPurchase(new BigDecimal(purchaseNum),
                    Currency.getInstance(currency));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.gnucash.android.ui.transaction.dialog.SplitEditorDialogFragment.java

/**
 * Extracts the input from the views and builds {@link org.gnucash.android.model.Split}s to correspond to the input.
 * @return List of {@link org.gnucash.android.model.Split}s represented in the view
 */// w w  w .  java  2s.  c o m
private List<Split> extractSplitsFromView() {
    List<Split> splitList = new ArrayList<Split>();
    for (View splitView : mSplitItemViewList) {
        EditText splitMemoEditText = (EditText) splitView.findViewById(R.id.input_split_memo);
        EditText splitAmountEditText = (EditText) splitView.findViewById(R.id.input_split_amount);
        Spinner accountsSpinner = (Spinner) splitView.findViewById(R.id.input_accounts_spinner);
        TextView splitUidTextView = (TextView) splitView.findViewById(R.id.split_uid);
        TransactionTypeToggleButton splitTypeButton = (TransactionTypeToggleButton) splitView
                .findViewById(R.id.btn_split_type);

        BigDecimal amountBigDecimal = TransactionFormFragment
                .parseInputToDecimal(splitAmountEditText.getText().toString());
        String currencyCode = mAccountsDbAdapter.getCurrencyCode(accountsSpinner.getSelectedItemId());
        String accountUID = mAccountsDbAdapter.getAccountUID(accountsSpinner.getSelectedItemId());
        Money amount = new Money(amountBigDecimal, Currency.getInstance(currencyCode));
        Split split = new Split(amount, accountUID);
        split.setMemo(splitMemoEditText.getText().toString());
        split.setType(splitTypeButton.getTransactionType());
        split.setUID(splitUidTextView.getText().toString().trim());
        splitList.add(split);
    }
    return splitList;
}

From source file:org.gnucash.android.ui.transactions.NewTransactionFragment.java

/**
 * Collects information from the fragment views and uses it to create 
 * and save a transaction/*  w w  w.j av  a2  s .co  m*/
 */
private void saveNewTransaction() {
    Calendar cal = new GregorianCalendar(mDate.get(Calendar.YEAR), mDate.get(Calendar.MONTH),
            mDate.get(Calendar.DAY_OF_MONTH), mTime.get(Calendar.HOUR_OF_DAY), mTime.get(Calendar.MINUTE),
            mTime.get(Calendar.SECOND));
    String name = mNameEditText.getText().toString();
    String description = mDescriptionEditText.getText().toString();
    BigDecimal amountBigd = parseInputToDecimal(mAmountEditText.getText().toString());

    long accountID = ((TransactionsActivity) getSherlockActivity()).getCurrentAccountID(); //mAccountsSpinner.getSelectedItemId();
    Currency currency = Currency.getInstance(mTransactionsDbAdapter.getCurrencyCode(accountID));
    Money amount = new Money(amountBigd, currency);
    TransactionType type = mTransactionTypeButton.isChecked() ? TransactionType.DEBIT : TransactionType.CREDIT;
    if (mTransaction != null) {
        mTransaction.setAmount(amount);
        mTransaction.setName(name);
        mTransaction.setTransactionType(type);
    } else {
        mTransaction = new Transaction(amount, name, type);
    }
    mTransaction.setAccountUID(mTransactionsDbAdapter.getAccountUID(accountID));
    mTransaction.setTime(cal.getTimeInMillis());
    mTransaction.setDescription(description);

    mTransactionsDbAdapter.addTransaction(mTransaction);
    mTransactionsDbAdapter.close();

    //update widgets, if any
    WidgetConfigurationActivity.updateAllWidgets(getActivity().getApplicationContext());

    finish();
}

From source file:com.acc.fulfilmentprocess.test.PaymentIntegrationTest.java

protected OrderModel placeTestOrder(final boolean valid) throws InvalidCartException, CalculationException {
    final CartModel cart = cartService.getSessionCart();
    final UserModel user = userService.getCurrentUser();
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct1"), 1, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct2"), 2, null);
    cartService.addNewEntry(cart, productService.getProductForCode("testProduct3"), 3, null);

    final AddressModel deliveryAddress = new AddressModel();
    deliveryAddress.setOwner(user);/*ww  w  .  j a va  2 s . co  m*/
    deliveryAddress.setFirstname("Der");
    deliveryAddress.setLastname("Buck");
    deliveryAddress.setTown("Muenchen");
    deliveryAddress.setCountry(commonI18NService.getCountry("DE"));
    modelService.save(deliveryAddress);

    final DebitPaymentInfoModel paymentInfo = new DebitPaymentInfoModel();
    paymentInfo.setOwner(cart);
    paymentInfo.setBank("MeineBank");
    paymentInfo.setUser(user);
    paymentInfo.setAccountNumber("34434");
    paymentInfo.setBankIDNumber("1111112");
    paymentInfo.setBaOwner("Ich");
    paymentInfo.setCode("testPaymentInfo1");
    modelService.save(paymentInfo);

    cart.setDeliveryMode(deliveryService.getDeliveryModeForCode("free"));
    cart.setDeliveryAddress(deliveryAddress);
    cart.setPaymentInfo(paymentInfo);

    final CardInfo card = new CardInfo();
    card.setCardType(CreditCardType.VISA);
    card.setCardNumber("4111111111111111");
    card.setExpirationMonth(Integer.valueOf(12));
    if (valid) {
        card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 2));
    } else {
        card.setExpirationYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 2));
    }

    final PaymentTransactionModel paymentTransaction = paymentService.authorize("code4" + codeNo++,
            BigDecimal.ONE, Currency.getInstance("EUR"), deliveryAddress, deliveryAddress, card)
            .getPaymentTransaction();

    cart.setPaymentTransactions(Collections.singletonList(paymentTransaction));
    modelService.save(cart);
    calculationService.calculate(cart);

    return commerceCheckoutService.placeOrder(cart);
}

From source file:org.gnucash.android.ui.transaction.TransactionFormFragment.java

/**
* Initialize views in the fragment with information from a transaction.
* This method is called if the fragment is used for editing a transaction
*///from   www  .j a va 2 s  .  com
private void initializeViewsWithTransaction() {
    mNameEditText.setText(mTransaction.getName());

    //FIXME: You need to revisit me when splits are introduced
    //checking the type button means the amount will be shown as negative (in red) to user

    mTransactionTypeButton.setChecked(mTransaction.getAmount().isNegative());

    if (!mAmountManuallyEdited) {
        //when autocompleting, only change the amount if the user has not manually changed it already
        mAmountEditText.setText(mTransaction.getAmount().toPlainString());
    }
    mCurrencyTextView.setText(mTransaction.getAmount().getCurrency().getSymbol(Locale.getDefault()));
    mDescriptionEditText.setText(mTransaction.getDescription());
    mDateTextView.setText(DATE_FORMATTER.format(mTransaction.getTimeMillis()));
    mTimeTextView.setText(TIME_FORMATTER.format(mTransaction.getTimeMillis()));
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTimeInMillis(mTransaction.getTimeMillis());
    mDate = mTime = cal;

    if (mUseDoubleEntry) {
        if (isInDoubleAccount()) {
            long accountId = mTransactionsDbAdapter.getAccountID(mTransaction.getAccountUID());
            setSelectedTransferAccount(accountId);
        } else {
            long doubleAccountId = mTransactionsDbAdapter.getAccountID(mTransaction.getDoubleEntryAccountUID());
            setSelectedTransferAccount(doubleAccountId);
        }
    }

    final long accountId = mTransactionsDbAdapter.getAccountID(mTransaction.getAccountUID());
    String code = mTransactionsDbAdapter.getCurrencyCode(accountId);
    Currency accountCurrency = Currency.getInstance(code);
    mCurrencyTextView.setText(accountCurrency.getSymbol());

    setSelectedRecurrenceOption();
}

From source file:com.prowidesoftware.swift.model.field.Field.java

/**
 * Get the given component as the given object type.
 * If the class is not recognized, it returns null, as well as if conversion fails.
 * @param component one-based index of the component to retrieve
 * @see #getComponent(int)/*from  w  ww.  jav  a  2 s. c  o m*/
 * @throws IllegalArgumentException if c is not any of: String, BIC, Currency, Number, BigDecimal Character or Integer
 */
public Object getComponentAs(final int component, @SuppressWarnings("rawtypes") final Class c) {
    try {
        final String s = getComponent(component);
        log.finest("converting string value: " + s);

        if (c.equals(String.class)) {
            return s;

        } else if (c.equals(Number.class) || c.equals(BigDecimal.class)) {
            return SwiftFormatUtils.getNumber(s);

        } else if (c.equals(BIC.class)) {
            return new BIC(s);

        } else if (c.equals(Currency.class)) {
            return Currency.getInstance(s);

        } else if (c.equals(Character.class)) {
            return SwiftFormatUtils.getSign(s);

        } else if (c.equals(Integer.class)) {
            return Integer.valueOf(s);

        } else {
            throw new IllegalArgumentException("Can't handle " + c.getName());
        }
    } catch (final Exception e) {
        log.severe("Error converting component content: " + e);
    }
    return null;
}