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:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java

private void processDebit(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);/* ww w. j av  a  2  s  . co m*/

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

    // Set the amount
    double fromAmount = NumberUtils
            .roundToTwoPlaces(0 - mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String fromCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_FROM_CURRENCY);
    Currency fromCurrency = Currency.getInstance(fromCurrencyCode);
    format.setCurrency(fromCurrency);
    format.setMaximumFractionDigits(fromCurrency.getDefaultFractionDigits());
    holder.mAmount.setText(format.format(fromAmount));
    holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));

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

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

From source file:com.prowidesoftware.swift.utils.SwiftFormatUtils.java

/**
 * Returns the <code>Currency</code> instance for the given currency code.
 * @param code string with a currency code
 * @return a Currency initialized from the parameter code or null if parameter code is null
 * @throws IllegalArgumentException if currencyCode is not a supported ISO 4217 code.
 *//*w  w w  . j a v  a 2  s. co m*/
public static Currency getCurrency(final String code) {
    if (code != null) {
        return Currency.getInstance(code);
    } else {
        return null;
    }
}

From source file:com.premiumminds.billy.core.services.builders.impl.GenericInvoiceBuilderImpl.java

protected void validateValues() throws ValidationException {

    GenericInvoiceEntity i = this.getTypeInstance();
    i.setCurrency(Currency.getInstance("EUR")); // FIXME: Hardcoded currency.
                                                // Blocks usage of any other
                                                // currency

    MathContext mc = BillyMathContext.get();

    BigDecimal amountWithTax = BigDecimal.ZERO;
    BigDecimal taxAmount = BigDecimal.ZERO;
    BigDecimal amountWithoutTax = BigDecimal.ZERO;

    for (GenericInvoiceEntry e : this.getTypeInstance().getEntries()) {

        amountWithTax = amountWithTax.add(e.getUnitAmountWithTax().multiply(e.getQuantity(), mc), mc);
        taxAmount = taxAmount.add(e.getUnitTaxAmount().multiply(e.getQuantity(), mc), mc);
        amountWithoutTax = amountWithoutTax.add(e.getUnitAmountWithoutTax().multiply(e.getQuantity(), mc), mc);
        if (e.getCurrency() == null) {
            GenericInvoiceEntryEntity entry = (GenericInvoiceEntryEntity) e;
            entry.setCurrency(i.getCurrency());
            e = entry;//from   w  w w .  jav a 2s.com
        } else {
            Validate.isTrue(i.getCurrency().getCurrencyCode().equals(e.getCurrency().getCurrencyCode()));
        }
    }

    i.setAmountWithTax(amountWithTax);
    i.setTaxAmount(taxAmount);
    i.setAmountWithoutTax(amountWithoutTax);

    Validate.isTrue(
            i.getAmountWithTax().subtract(i.getTaxAmount(), mc).setScale(7, mc.getRoundingMode())
                    .compareTo(i.getAmountWithoutTax().setScale(7, mc.getRoundingMode())) == 0,
            "The invoice values are invalid", // TODO message
            i.getAmountWithTax(), i.getAmountWithoutTax(), i.getTaxAmount());

    Validate.isTrue(
            i.getAmountWithTax().compareTo(BigDecimal.ZERO) > 0
                    && i.getAmountWithoutTax().compareTo(BigDecimal.ZERO) >= 0
                    && i.getTaxAmount().compareTo(BigDecimal.ZERO) >= 0,
            "The invoice values are lower than zero", // TODO
            // message
            i.getAmountWithTax(), i.getAmountWithoutTax(), i.getTaxAmount());
}

From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Get the currency format from {@link SharedPreferences}.
 * //from w w  w.  j a  va 2s.  co m
 * @param context
 *            {@link Context}
 * @return currency format
 */
public static final String getCurrencyFormat(final Context context) {
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    final String pcs = p.getString(PREFS_CURRENCY_FORMAT, "");
    if (pcs.length() == 0) {
        if (defaultCurrencySymbol == null) {
            try {
                final Currency cur = Currency.getInstance(Locale.getDefault());
                defaultCurrencySymbol = cur.getSymbol();
                defaultCurrencyDigits = cur.getDefaultFractionDigits();
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "error getting currency", e);
                defaultCurrencySymbol = "$";
                defaultCurrencyDigits = 2;
            }
        }
        return "%." + defaultCurrencyDigits + "f" + getCurrencySymbol(context);
    } else {
        Log.d(TAG, "custom currency format: " + pcs);
        String c = getCurrencySymbol(context);
        Log.d(TAG, "custom currency symbol: " + c);
        if (c.equals("$")) {
            c = "\\$";
            Log.d(TAG, "custom currency symbol: " + c);
        } else if (c.equals("%")) {
            c = "%%";
            Log.d(TAG, "custom currency symbol: " + c);
        }
        final String ret = pcs.replaceAll("\\$", c).replaceAll("\u20AC", c).replaceAll("\u0440", c);
        Log.d(TAG, "custom currency format: " + ret);
        return ret;
    }
}

From source file:org.mobicents.servlet.restcomm.http.SmsMessagesEndpoint.java

private SmsMessage sms(final Sid accountSid, final String apiVersion, final String sender,
        final String recipient, final String body, final SmsMessage.Status status,
        final SmsMessage.Direction direction) {
    final SmsMessage.Builder builder = SmsMessage.builder();
    final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE);
    builder.setSid(sid);/*from  w  ww.  ja v a 2  s .co  m*/
    builder.setAccountSid(accountSid);
    builder.setSender(sender);
    builder.setRecipient(recipient);
    builder.setBody(body);
    builder.setStatus(status);
    builder.setDirection(direction);
    builder.setPrice(new BigDecimal(0.00));
    // TODO - this needs to be added as property to Configuration somehow
    builder.setPriceUnit(Currency.getInstance("USD"));
    builder.setApiVersion(apiVersion);
    String rootUri = configuration.getString("root-uri");
    rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/");
    final StringBuilder buffer = new StringBuilder();
    buffer.append(rootUri).append(apiVersion).append("/Accounts/");
    buffer.append(accountSid.toString()).append("/SMS/Messages/");
    buffer.append(sid.toString());
    final URI uri = URI.create(buffer.toString());
    builder.setUri(uri);
    return builder.build();
}

From source file:org.restcomm.connect.sms.SmsService.java

private void message(final Object message) throws IOException {
    final ActorRef self = self();
    final SipServletRequest request = (SipServletRequest) message;

    // ignore composing messages and accept content type including text only
    // https://github.com/Mobicents/RestComm/issues/494
    if (request.getContentLength() == 0 || !request.getContentType().contains("text/plain")) {
        SipServletResponse reject = request.createResponse(SipServletResponse.SC_NOT_ACCEPTABLE);
        reject.addHeader("Reason", "Content Type is not text plain");
        reject.send();/*from   w  w w  .j ava  2s.  com*/
        return;
    }

    final SipURI fromURI = (SipURI) request.getFrom().getURI();
    final String fromUser = fromURI.getUser();
    final ClientsDao clients = storage.getClientsDao();
    final Client client = clients.getClient(fromUser);
    final AccountsDao accounts = storage.getAccountsDao();
    final ApplicationsDao applications = storage.getApplicationsDao();

    // Make sure we force clients to authenticate.
    if (client != null) {
        // Make sure we force clients to authenticate.
        if (authenticateUsers // https://github.com/Mobicents/RestComm/issues/29 Allow disabling of SIP authentication
                && !CallControlHelper.checkAuthentication(request, storage)) {
            if (logger.isInfoEnabled()) {
                logger.info("Client " + client.getLogin() + " failed to authenticate");
            }
            // Since the client failed to authenticate, we will ignore the message and not process further
            return;
        }
    }
    // TODO Enforce some kind of security check for requests coming from outside SIP UAs such as ITSPs that are not
    // registered
    final String toUser = CallControlHelper.getUserSipId(request, useTo);
    // Try to see if the request is destined for an application we are hosting.
    if (redirectToHostedSmsApp(self, request, accounts, applications, toUser)) {
        // Tell the sender we received the message okay.
        if (logger.isInfoEnabled()) {
            logger.info("Message to :" + toUser + " matched to one of the hosted applications");
        }

        //this is used to send a reply back to SIP client when a Restcomm App forwards inbound sms to a Restcomm client ex. Alice
        final SipServletResponse messageAccepted = request.createResponse(SipServletResponse.SC_ACCEPTED);
        messageAccepted.send();

        monitoringService.tell(
                new TextMessage(((SipURI) request.getFrom().getURI()).getUser(),
                        ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_APP),
                self);

        return;

    }
    if (client != null) {
        // try to see if the request is destined to another registered client
        // if (client != null) { // make sure the caller is a registered client and not some external SIP agent that we
        // have little control over
        Client toClient = clients.getClient(toUser);
        if (toClient != null) { // looks like its a p2p attempt between two valid registered clients, lets redirect
            // to the b2bua
            if (B2BUAHelper.redirectToB2BUA(request, client, toClient, storage, sipFactory,
                    patchForNatB2BUASessions)) {
                // if all goes well with proxying the SIP MESSAGE on to the target client
                // then we can end further processing of this request and send response to sender
                if (logger.isInfoEnabled()) {
                    logger.info("P2P, Message from: " + client.getLogin() + " redirected to registered client: "
                            + toClient.getLogin());
                }
                monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(),
                        ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_CLIENT),
                        self);
                return;
            }
        } else {
            // Since toUser is null, try to route the message outside using the SMS Aggregator
            if (logger.isInfoEnabled()) {
                logger.info("Restcomm will route this SMS to an external aggregator: " + client.getLogin()
                        + " to: " + toUser);
            }

            final SipServletResponse trying = request.createResponse(SipServletResponse.SC_TRYING);
            trying.send();
            //TODO:do extensions check here too?
            ActorRef session = session(this.configuration);
            // Create an SMS detail record.
            final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE);
            final SmsMessage.Builder builder = SmsMessage.builder();
            builder.setSid(sid);
            builder.setAccountSid(client.getAccountSid());
            builder.setApiVersion(client.getApiVersion());
            builder.setRecipient(toUser);
            builder.setSender(client.getLogin());
            builder.setBody(new String(request.getRawContent()));
            builder.setDirection(Direction.OUTBOUND_CALL);
            builder.setStatus(Status.RECEIVED);
            builder.setPrice(new BigDecimal("0.00"));
            // TODO implement currency property to be read from Configuration
            builder.setPriceUnit(Currency.getInstance("USD"));
            final StringBuilder buffer = new StringBuilder();
            buffer.append("/").append(client.getApiVersion()).append("/Accounts/");
            buffer.append(client.getAccountSid().toString()).append("/SMS/Messages/");
            buffer.append(sid.toString());
            final URI uri = URI.create(buffer.toString());
            builder.setUri(uri);
            final SmsMessage record = builder.build();
            final SmsMessagesDao messages = storage.getSmsMessagesDao();
            messages.addSmsMessage(record);
            // Store the sms record in the sms session.
            session.tell(new SmsSessionAttribute("record", record), self());
            // Send the SMS.
            TlvSet tlvSet = new TlvSet();
            final SmsSessionRequest sms = new SmsSessionRequest(client.getLogin(), toUser,
                    new String(request.getRawContent()), request, tlvSet, null);
            monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(),
                    ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.INBOUND_TO_PROXY_OUT),
                    self);
            session.tell(sms, self());
        }
    } else {
        final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
        response.send();
        // We didn't find anyway to handle the SMS.
        String errMsg = "Restcomm cannot process this SMS because the destination number is not hosted locally. To: "
                + toUser;
        sendNotification(errMsg, 11005, "error", true);
        monitoringService.tell(new TextMessage(((SipURI) request.getFrom().getURI()).getUser(),
                ((SipURI) request.getTo().getURI()).getUser(), TextMessage.SmsState.NOT_FOUND), self);
    }
}

From source file:org.gnucash.android.ui.accounts.AddAccountFragment.java

private void saveAccount() {
    if (mAccount == null) {
        String name = getEnteredName();
        if (name == null || name.length() == 0) {
            Toast.makeText(getSherlockActivity(), R.string.toast_no_account_name_entered, Toast.LENGTH_LONG)
                    .show();/*from  w  w  w.j a  va  2  s  .co  m*/
            return;
        }
        mAccount = new Account(getEnteredName());
    } else
        mAccount.setName(getEnteredName());

    String curCode = mCurrencyCodes.get(mCurrencySpinner.getSelectedItemPosition());
    mAccount.setCurrency(Currency.getInstance(curCode));

    int selectedAccountType = mAccountTypeSpinner.getSelectedItemPosition();
    String[] accountTypeEntries = getResources().getStringArray(R.array.account_type_entries);
    mAccount.setAccountType(Account.AccountType.valueOf(accountTypeEntries[selectedAccountType]));

    if (mParentCheckBox.isChecked()) {
        long id = mParentAccountSpinner.getSelectedItemId();
        mAccount.setParentUID(mAccountsDbAdapter.getAccountUID(id));
    } else {
        mAccount.setParentUID(null);
    }

    if (mAccountsDbAdapter == null)
        mAccountsDbAdapter = new AccountsDbAdapter(getActivity());
    mAccountsDbAdapter.addAccount(mAccount);

    finishFragment();
}

From source file:org.gnucash.android.ui.chart.PieChartActivity.java

/**
 * Returns {@code PieData} instance with data entries and labels
 * @param forCurrentMonth sets data only for current month if {@code true}, otherwise for all time
 * @return {@code PieData} instance/*from   w  w  w .  j  ava  2 s .  c  o  m*/
 */
private PieData getData(boolean forCurrentMonth) {
    List<Account> accountList = mAccountsDbAdapter.getSimpleAccountList(
            AccountEntry.COLUMN_TYPE + " = ? AND " + AccountEntry.COLUMN_PLACEHOLDER + " = ?",
            new String[] { mAccountType.name(), "0" }, null);
    List<String> uidList = new ArrayList<>();
    for (Account account : accountList) {
        uidList.add(account.getUID());
    }
    double sum;
    if (forCurrentMonth) {
        long start = mChartDate.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue().toDate()
                .getTime();
        long end = mChartDate.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate()
                .getTime();
        sum = mAccountsDbAdapter.getAccountsBalance(uidList, start, end).absolute().asDouble();
    } else {
        sum = mAccountsDbAdapter.getAccountsBalance(uidList, -1, -1).absolute().asDouble();
    }

    double otherSlice = 0;
    PieDataSet dataSet = new PieDataSet(null, "");
    List<String> names = new ArrayList<>();
    List<String> skipUUID = new ArrayList<>();
    for (Account account : getCurrencyCodeToAccountMap(accountList).get(mCurrencyCode)) {
        if (mAccountsDbAdapter.getSubAccountCount(account.getUID()) > 0) {
            skipUUID.addAll(mAccountsDbAdapter.getDescendantAccountUIDs(account.getUID(), null, null));
        }
        if (!skipUUID.contains(account.getUID())) {
            double balance;
            if (forCurrentMonth) {
                long start = mChartDate.dayOfMonth().withMinimumValue().millisOfDay().withMinimumValue()
                        .toDate().getTime();
                long end = mChartDate.dayOfMonth().withMaximumValue().millisOfDay().withMaximumValue().toDate()
                        .getTime();
                balance = mAccountsDbAdapter.getAccountBalance(account.getUID(), start, end).absolute()
                        .asDouble();
            } else {
                balance = mAccountsDbAdapter.getAccountBalance(account.getUID()).absolute().asDouble();
            }

            if (balance / sum * 100 > mSlicePercentThreshold) {
                dataSet.addEntry(new Entry((float) balance, dataSet.getEntryCount()));
                if (mUseAccountColor) {
                    dataSet.getColors().set(dataSet.getColors().size() - 1,
                            (account.getColorHexCode() != null) ? Color.parseColor(account.getColorHexCode())
                                    : COLORS[(dataSet.getEntryCount() - 1) % COLORS.length]);
                }
                dataSet.addColor(COLORS[(dataSet.getEntryCount() - 1) % COLORS.length]);
                names.add(account.getName());
            } else {
                otherSlice += balance;
            }
        }
    }
    if (otherSlice > 0) {
        dataSet.addEntry(new Entry((float) otherSlice, dataSet.getEntryCount()));
        dataSet.getColors().set(dataSet.getColors().size() - 1, Color.LTGRAY);
        names.add(getResources().getString(R.string.label_other_slice));
    }

    if (dataSet.getEntryCount() == 0) {
        mChartDataPresent = false;
        dataSet.addEntry(new Entry(1, 0));
        dataSet.setColor(Color.LTGRAY);
        dataSet.setDrawValues(false);
        names.add("");
        mChart.setCenterText(getResources().getString(R.string.label_chart_no_data));
        mChart.setTouchEnabled(false);
    } else {
        mChartDataPresent = true;
        dataSet.setSliceSpace(2);
        mChart.setCenterText(String.format(TOTAL_VALUE_LABEL_PATTERN,
                getResources().getString(R.string.label_chart_total), dataSet.getYValueSum(),
                Currency.getInstance(mCurrencyCode).getSymbol(Locale.getDefault())));
        mChart.setTouchEnabled(true);
    }

    return new PieData(names, dataSet);
}

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

public void onAccountChanged(long newAccountId) {
    AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(getActivity());
    String currencyCode = accountsDbAdapter.getCurrencyCode(newAccountId);
    Currency currency = Currency.getInstance(currencyCode);
    mCurrencyTextView.setText(currency.getSymbol(Locale.getDefault()));
    accountsDbAdapter.close();//from   ww  w .  j  a v a  2 s. c  o  m
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSubscriptionController.java

@RequestMapping(value = "/utilityrates_table", method = RequestMethod.GET)
public String utilityrates_table(@RequestParam(value = "tenant", required = true) String tenantParam,
        @RequestParam(value = "serviceInstanceUuid", required = false) String serviceInstanceUuid,
        @RequestParam(value = "resourceTypeName", required = false) String resourceTypeName,
        @RequestParam(value = "contextString", required = false) String contextString,
        @RequestParam(value = "currencyCode", required = false) String currencyCode,
        @RequestParam(value = "isDialog", required = false) String isDialog,
        @RequestParam(value = "channelParam", required = false) String channelParam,
        @RequestParam(value = "revision", required = false) String timeline,
        @RequestParam(value = "revisionDate", required = false) String revisionDateString,
        @RequestParam(value = "dateFormat", required = false) String dateFormat, ModelMap map,
        HttpServletRequest request) {//from   ww w .j a  va2  s  . c o  m
    logger.debug("### utilityrates_table method starting...(GET)");
    Tenant tenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);
    Channel channel = null;
    CurrencyValue currency = null;

    if (StringUtils.isNotBlank(channelParam) && StringUtils.isNotBlank(currencyCode)) {
        channel = channelService.getChannelById(channelParam);
        currency = currencyValueService.locateBYCurrencyCode(currencyCode);
    } else {
        if (tenant == null) {
            // Public Browse Catalog Case:
            // Use the default channel
            channel = channelService.getDefaultServiceProviderChannel();
            // Use currency selected in the drop down
            currency = currencyValueService.locateBYCurrencyCode(currencyCode);
        } else {
            channel = tenant.getSourceChannel();
            currency = tenant.getCurrency();
        }
    }

    if (channel == null) {
        channel = channelService.getDefaultServiceProviderChannel();
        if (currencyCode != null && !currencyCode.equals("")) {
            currency = currencyValueService.locateBYCurrencyCode(currencyCode);
        }
    }

    if (tenant == null) {
        // Public Browse Catalog Case:
        // Put minimal fraction digits and currency formant for selected currency as UCI will not fill that in this case
        map.addAttribute(UserContextInterceptor.MIN_FRACTION_DIGITS,
                Currency.getInstance(currency.getCurrencyCode()).getDefaultFractionDigits());
        UserContextInterceptor.putCurrencyPrecisionAndFormat(map,
                config.getValue(Names.com_citrix_cpbm_portal_appearance_currency_format));
    }

    Date revisionDate = null;

    if (StringUtils.isNotBlank(dateFormat) && !dateFormat.equals("undefined")) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        try {
            revisionDate = sdf.parse(revisionDateString);
        } catch (ParseException e) {
            logger.info("Incorrect date passed in revision date : " + revisionDateString + " for date format "
                    + dateFormat + ". Skipping...");
        }
    }
    List<ServiceResourceTypeGeneratedUsage> generatedUsageListForServiceResourceType = null;

    Date startDate = channelService.getRevision(channel, timeline, revisionDate).getStartDate();

    ServiceResourceType serviceResourceType = connectorConfigurationManager
            .getServiceResourceType(serviceInstanceUuid, resourceTypeName);
    if (serviceResourceType != null) {
        generatedUsageListForServiceResourceType = serviceResourceType.getServiceResourceGenerate();
    }

    Map<Object, Object> retMap = productService.getUtilityChargesMap(channel, currency, serviceInstanceUuid,
            null, timeline, revisionDate);
    map.addAttribute("retMap", retMap);
    map.addAttribute("startDate", startDate);
    map.addAttribute("generatedUsageListForServiceResourceType", generatedUsageListForServiceResourceType);
    map.addAttribute("tenant", tenant);
    map.addAttribute("currency", currency);
    map.addAttribute("resourceTypeName", resourceTypeName);
    map.addAttribute("isDialog", isDialog);
    logger.debug("### utilityrates_table method ending...(GET)");
    return "catalog.utilityrates.table";
}