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:de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderTest.java

/**
 * This is test for issue #34:/*from ww  w . j  av  a  2s  .c  om*/
 * msm-javolution-serializer: java.util.Currency gets deserialized with ReflectionFormat
 *
 * See http://code.google.com/p/memcached-session-manager/issues/detail?id=34
 *
 * @throws Exception
 */
@Test(enabled = true)
public void testCurrency() throws Exception {
    final MemcachedBackupSession session = _manager.createEmptySession();
    session.setValid(true);

    final Currency orig = Currency.getInstance("EUR");
    session.setAttribute("currency1", orig);
    session.setAttribute("currency2", orig);

    final Map<String, Object> deserialized = _transcoder
            .deserializeAttributes(_transcoder.serializeAttributes(session, session.getAttributesInternal()));

    assertDeepEquals(deserialized, session.getAttributesInternal());

    // Check that the transient field defaultFractionDigits is initialized correctly (that was the bug)
    final Currency currency1 = (Currency) deserialized.get("currency1");
    Assert.assertEquals(currency1.getCurrencyCode(), orig.getCurrencyCode());
    Assert.assertEquals(currency1.getDefaultFractionDigits(), orig.getDefaultFractionDigits());

}

From source file:net.sourceforge.eclipsetrader.core.ui.dialogs.ExchangeRateDialog.java

protected Control createDialogArea(Composite parent) {
    Composite content = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout(6, false);
    gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
    gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
    gridLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
    gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
    content.setLayout(gridLayout);//from w ww. j a v  a 2  s . c  o  m
    content.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));

    Label label = new Label(content, SWT.NONE);
    label.setText(Messages.ExchangeRateDialog_Date);
    label.setLayoutData(new GridData(60, SWT.DEFAULT));

    text = new Text(content, SWT.BORDER);
    text.setSize(80, SWT.DEFAULT);
    GridData gridData = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 5, 1);
    gridData.widthHint = 80;
    text.setLayoutData(gridData);
    text.addFocusListener(new FocusAdapter() {
        public void focusLost(FocusEvent e) {
            try {
                Date date = dateParse.parse(text.getText());
                text.setText(dateFormat.format(date));
            } catch (Exception e1) {
                text.setText(dateFormat.format(Calendar.getInstance().getTime()));
            }
            update();
        }
    });
    text.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.keyCode == SWT.ARROW_UP) {
                try {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(dateParse.parse(text.getText()));
                    calendar.add(Calendar.DATE, 1);
                    text.setText(dateFormat.format(calendar.getTime()));
                } catch (Exception e1) {
                    text.setText(dateFormat.format(Calendar.getInstance().getTime()));
                }
                update();
            } else if (e.keyCode == SWT.ARROW_DOWN) {
                try {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(dateParse.parse(text.getText()));
                    calendar.add(Calendar.DATE, -1);
                    text.setText(dateFormat.format(calendar.getTime()));
                } catch (Exception e1) {
                    text.setText(dateFormat.format(Calendar.getInstance().getTime()));
                }
                update();
            }
        }
    });

    label = new Label(content, SWT.NONE);

    from = new Combo(content, SWT.READ_ONLY);
    from.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
    from.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            update();
        }
    });

    label = new Label(content, SWT.NONE);
    label.setText(Messages.ExchangeRateDialog_To);

    to = new Combo(content, SWT.READ_ONLY);
    to.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
    to.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            update();
        }
    });

    label = new Label(content, SWT.NONE);
    label.setText(Messages.ExchangeRateDialog_Equals);

    ratio = new Spinner(content, SWT.BORDER);
    ratio.setMinimum(1);
    ratio.setMaximum(999999999);
    ratio.setDigits(4);
    ratio.setIncrement(100);

    List list = CurrencyConverter.getInstance().getCurrencies();
    Collections.sort(list, new Comparator() {
        public int compare(Object arg0, Object arg1) {
            return ((String) arg0).compareTo((String) arg1);
        }
    });
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        String symbol = (String) iter.next();
        from.add(symbol);
        to.add(symbol);
    }

    text.setText(dateFormat.format(Calendar.getInstance().getTime()));
    String locale = Currency.getInstance(Locale.getDefault()).getCurrencyCode();
    from.setText(locale.equals(Messages.ExchangeRateDialog_DefaultTo) ? Messages.ExchangeRateDialog_DefaultFrom
            : Messages.ExchangeRateDialog_DefaultTo);
    to.setText(locale.equals(Messages.ExchangeRateDialog_DefaultTo) ? Messages.ExchangeRateDialog_DefaultTo
            : Messages.ExchangeRateDialog_DefaultFrom);
    update();

    return content;
}

From source file:no.abmu.lise.domain.HsqlMemHibernate3VanillaTest.java

public void testInvoiceToCustomerByAddingToProductCustomerRelation() throws Exception {

    Consortium consortium = new Consortium();
    OrganisationUnit customer = new OrganisationUnit();
    Product product = new Product();

    VanillaTester.populateAndPersistObject(session, customer);
    VanillaTester.populateObject(consortium);
    VanillaTester.populateObject(product);
    consortium.addProduct(product);/*from   w  ww. j  a v  a 2 s . com*/
    VanillaTester.persistObject(session, consortium);

    InvoiceToCustomer invoiceToCustomer = new InvoiceToCustomer();
    invoiceToCustomer.setCustomerInvoiceType(CustomerInvoiceType.SPECIAL_INVOICE);
    invoiceToCustomer.setCurrency(Currency.getInstance("NOK"));
    VanillaTester.populateObject(invoiceToCustomer);

    ProductCustomerRelation productCustomerRelation = new ProductCustomerRelation(product, customer);
    productCustomerRelation.addInvoicesToCustomer(invoiceToCustomer);

    VanillaTester.populatePersistLoadAndTesObject(session, productCustomerRelation);
}

From source file:org.yawlfoundation.yawl.util.StringUtil.java

/**
 * Utility routine which takes a decimal value as a string (e.g. 0.25 equating to 25p) and returns the
 * value in UI currency format (e.g. 0.25).
 *
 * @return A formatted currency//from  w w  w .  ja  v a2  s .c  o m
 */
public static String formatDecimalCost(BigDecimal value) {
    Currency currency = Currency.getInstance(Locale.getDefault());
    NumberFormat fmt = DecimalFormat.getInstance();
    fmt.setMinimumFractionDigits(2);
    fmt.setMaximumFractionDigits(2);
    return currency.getSymbol() + fmt.format(value);
}

From source file:org.gnucash.android.ui.report.PieChartFragment.java

/**
 * Returns {@code PieData} instance with data entries, colors and labels
 * @return {@code PieData} instance//w w w.  j  a va  2s  .  c  o m
 */
private PieData getData() {
    PieDataSet dataSet = new PieDataSet(null, "");
    List<String> labels = new ArrayList<>();
    List<Integer> colors = new ArrayList<>();
    for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
        if (account.getAccountType() == mAccountType && !account.isPlaceholderAccount()
                && account.getCurrency() == Currency.getInstance(mCurrencyCode)) {

            double balance = mAccountsDbAdapter.getAccountsBalance(Collections.singletonList(account.getUID()),
                    mReportStartTime, mReportEndTime).absolute().asDouble();
            if (balance != 0) {
                dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount()));
                colors.add(mUseAccountColor && account.getColorHexCode() != null
                        ? Color.parseColor(account.getColorHexCode())
                        : ReportsActivity.COLORS[(dataSet.getEntryCount() - 1)
                                % ReportsActivity.COLORS.length]);
                labels.add(account.getName());
            }
        }
    }
    dataSet.setColors(colors);
    dataSet.setSliceSpace(SPACE_BETWEEN_SLICES);
    return new PieData(labels, dataSet);
}

From source file:org.gnucash.android.ui.report.ReportSummaryFragment.java

/**
 * Returns {@code PieData} instance with data entries, colors and labels
 * @return {@code PieData} instance//from w  ww  .j  ava 2s. c  o m
 */
private PieData getData() {
    String mCurrencyCode = GnuCashApplication.getDefaultCurrencyCode();
    PieDataSet dataSet = new PieDataSet(null, "");
    List<String> labels = new ArrayList<>();
    List<Integer> colors = new ArrayList<>();
    for (Account account : mAccountsDbAdapter.getSimpleAccountList()) {
        if (account.getAccountType() == AccountType.EXPENSE && !account.isPlaceholderAccount()
                && account.getCurrency() == Currency.getInstance(mCurrencyCode)) {

            long start = new LocalDate().minusMonths(2).dayOfMonth().withMinimumValue().toDate().getTime();
            long end = new LocalDate().plusDays(1).toDate().getTime();
            double balance = mAccountsDbAdapter
                    .getAccountsBalance(Collections.singletonList(account.getUID()), start, end).absolute()
                    .asDouble();
            if (balance != 0) {
                dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount()));
                colors.add(account.getColorHexCode() != null ? Color.parseColor(account.getColorHexCode())
                        : ReportsActivity.COLORS[(dataSet.getEntryCount() - 1)
                                % ReportsActivity.COLORS.length]);
                labels.add(account.getName());
            }
        }
    }
    dataSet.setColors(colors);
    dataSet.setSliceSpace(PieChartFragment.SPACE_BETWEEN_SLICES);
    return new PieData(labels, dataSet);
}

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

private void processTransfer(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);/*www.  j a  v a 2s.co  m*/

    // Set the account
    String fromAccount = mCursor.getString(TransactionsFragment.COLUMN_FROM_ACCOUNT_TITLE);
    String toAccount = mCursor.getString(TransactionsFragment.COLUMN_TO_ACCOUNT_TITLE);
    holder.mAccount.setText(mContext.getResources().getString(R.string.breadcrumbs, fromAccount, toAccount));

    // Set the amount
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String fromCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_FROM_CURRENCY);
    String toCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_TO_CURRENCY);
    if (fromCurrencyCode.equals(toCurrencyCode)) {
        double amount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
        Currency currency = Currency.getInstance(fromCurrencyCode);
        format.setCurrency(currency);
        format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
        holder.mAmount.setText(format.format(amount));

        double fromBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_BALANCE) / 100.0);
        String fromBalanceFormatted = format.format(fromBalance);
        double toBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);
        holder.mRunningBalance.setText(mContext.getResources().getString(R.string.breadcrumbs,
                fromBalanceFormatted, format.format(toBalance)));
    } else {
        Currency fromCurrency = Currency.getInstance(fromCurrencyCode);
        format.setCurrency(fromCurrency);
        format.setMaximumFractionDigits(fromCurrency.getDefaultFractionDigits());
        double fromAmount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
        String fromAmountFormatted = format.format(fromAmount);
        double fromBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_BALANCE) / 100.0);
        String fromBalanceFormatted = format.format(fromBalance);

        Currency toCurrency = Currency.getInstance(toCurrencyCode);
        format.setCurrency(toCurrency);
        format.setMaximumFractionDigits(toCurrency.getDefaultFractionDigits());
        double toAmount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_AMOUNT) / 100.0);
        double toBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);

        holder.mAmount.setText(mContext.getResources().getString(R.string.breadcrumbs, fromAmountFormatted,
                format.format(toAmount)));
        holder.mRunningBalance.setText(mContext.getResources().getString(R.string.breadcrumbs,
                fromBalanceFormatted, format.format(toBalance)));
    }

    // Set the color for the amount and the transaction type icon
    if (mSelectedAccountId == 0) {
        holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorOrange700));
        holder.mTypeIcon.setImageDrawable(
                DrawableHelper.tint(mContext, R.drawable.ic_swap_horiz_black_24dp, R.color.colorOrange700));
    } else {
        long fromAccountId = mCursor.getLong(TransactionsFragment.COLUMN_FROM_ACCOUNT_ID);
        long toAccountId = mCursor.getLong(TransactionsFragment.COLUMN_TO_ACCOUNT_ID);
        if (mSelectedAccountId == fromAccountId) {
            holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));
            holder.mTypeIcon.setImageDrawable(
                    DrawableHelper.tint(mContext, R.drawable.ic_call_made_black_24dp, R.color.colorRed700));
        } else if (mSelectedAccountId == toAccountId) {
            holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));
            holder.mTypeIcon.setImageDrawable(DrawableHelper.tint(mContext,
                    R.drawable.ic_call_received_black_24dp, R.color.colorGreen700));
        }
    }
}

From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java

private String defaultCurrencyCode() {
    try {//from   w w w  .  j  av a 2  s  .c o  m
        return Currency.getInstance(Locale.getDefault()).getCurrencyCode();
    } catch (final IllegalArgumentException x) {
        return null;
    }
}

From source file:net.rrm.ehour.ui.manage.assignment.AssignmentListPanel.java

private ListView<ProjectAssignment> getProjectAssignmentLists(
        final List<ProjectAssignment> projectAssignments) {
    assignmentListView = new ListView<ProjectAssignment>("assignments", projectAssignments) {
        @Override/*from  w w w. j a v a2s .  com*/
        protected void populateItem(ListItem<ProjectAssignment> item) {
            final ProjectAssignment assignment = item.getModelObject();

            AjaxLink<Void> link = new AjaxLink<Void>("itemLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    EventPublisher.publishAjaxEvent(AssignmentListPanel.this,
                            new PayloadAjaxEvent<>(AssignmentAjaxEventType.ASSIGNMENT_EDIT, assignment));
                }
            };

            AjaxLink<Void> imgLink = new AjaxLink<Void>("imgLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    EventPublisher.publishAjaxEvent(AssignmentListPanel.this,
                            new PayloadAjaxEvent<>(AssignmentAjaxEventType.ASSIGNMENT_EDIT, assignment));
                }
            };

            item.add(imgLink);
            item.add(link);
            link.add(new Label("project", assignment.getProject().getFullName()));
            item.add(new Label("customer", assignment.getProject().getCustomer().getFullName()));

            Label dateStart = new Label("dateStart",
                    new DateModel(assignment.getDateStart(), config, DateModel.DATESTYLE_FULL_SHORT));
            dateStart.setEscapeModelStrings(false);
            item.add(dateStart);

            Label dateEnd = new Label("dateEnd",
                    new DateModel(assignment.getDateEnd(), config, DateModel.DATESTYLE_FULL_SHORT));
            dateEnd.setEscapeModelStrings(false);
            item.add(dateEnd);

            item.add(new Label("assignmentType", new ResourceModel(
                    WebUtils.getResourceKeyForProjectAssignmentType(assignment.getAssignmentType()))));

            item.add(new Label("role",
                    (StringUtils.isBlank(assignment.getRole())) ? "--" : assignment.getRole()));

            item.add(new Label("currency",
                    Currency.getInstance(config.getCurrency()).getSymbol(config.getCurrency())));
            item.add(new Label("rate", new Model<>(assignment.getHourlyRate())));

        }
    };

    return assignmentListView;
}

From source file:com.einzig.ipst2.billing.SkusActivity.java

private void sendFabricPurchase(String sku) {
    try {/* ww  w . j a v  a  2 s .c o  m*/
        double price = 0;
        String itemName = "";
        switch (sku) {
        case "000001":
            itemName = "Small Donation";
            price = 0.99;
            break;
        case "000003":
            itemName = "Medium Donation";
            price = 4.99;
            break;
        case "000005":
            itemName = "Large Donation";
            price = 9.99;
            break;
        case "000007":
            itemName = "Huge Donation";
            price = 19.99;
            break;
        }
        if (price != 0) {
            Answers.getInstance()
                    .logPurchase(new PurchaseEvent().putItemPrice(BigDecimal.valueOf(price))
                            .putCurrency(Currency.getInstance("USD")).putItemName(itemName)
                            .putItemType("Single Donate").putItemId(sku).putSuccess(true));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}