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:com.prowidesoftware.swift.model.field.Field11A.java

public List<Currency> currencies() {
    final List<String> l = currencyStrings();
    if (l.isEmpty()) {
        return java.util.Collections.emptyList();
    }//from  ww  w  .  ja  v a2s .  com
    final ArrayList<Currency> result = new ArrayList<Currency>();
    for (String s : l) {
        result.add(Currency.getInstance(s));
    }
    return result;
}

From source file:org.openestate.io.examples.Is24CsvWritingExample.java

/**
 * Init common values of an {@link Is24CsvRecord}.
 *
 * @param obj/* ww w  . ja va 2  s . co m*/
 * record to init
 */
protected static void init(Is24CsvRecord obj) {
    obj.setAdressdruck(RandomUtils.nextInt(0, 2) == 1);
    obj.setAktiv(RandomUtils.nextInt(0, 2) == 1);
    obj.setAnbieterObjektId(RandomStringUtils.randomAlphanumeric(5));
    obj.setBeschreibungAusstattung("description about features");
    obj.setBeschreibungLage("description about location");
    obj.setBeschreibungObjekt("description about object");
    obj.setBeschreibungSonstiges("further descriptions");
    obj.setGruppierungId(RandomUtils.nextInt(0, 1000));
    obj.setImportmodus(Importmodus.IMPORTIEREN);
    obj.setInternationaleRegion("name of international region");
    obj.setKontaktAnrede("Mr");
    obj.setKontaktEmail("tester@test.org");
    obj.setKontaktHausNr("123");
    obj.setKontaktLand("DEU");
    obj.setKontaktMobiltelefon("030/123456");
    obj.setKontaktNachname("Mustermann");
    obj.setKontaktOrt("Berlin");
    obj.setKontaktPlz("12345");
    obj.setKontaktStrasse("example street");
    obj.setKontaktTelefax("030/123457");
    obj.setKontaktTelefon("030/123458");
    obj.setKontaktVorname("Max");
    obj.setKontaktWebseite("http://www.test.org/");
    obj.setObjektHausNr("124");
    obj.setObjektLand("DEU");
    obj.setObjektOrt("Berlin");
    obj.setObjektPlz("12345");
    obj.setObjektStrasse("example street");
    obj.setProvision("commission");
    obj.setProvisionpflichtig(RandomUtils.nextInt(0, 2) == 1);
    obj.setProvisionshinweis("notes about commission");
    obj.setScoutKundenId(RandomStringUtils.randomAlphanumeric(5));
    obj.setScoutObjektId(RandomStringUtils.randomAlphanumeric(5));
    obj.setUeberschrift("a nice title for the object");
    obj.setWaehrung(Currency.getInstance("EUR"));

    obj.setDatei1(new Datei("test1.jpg", DateiTyp.BILD, DateiSuffix.JPG, "a nice image"));
    obj.setDatei2(new Datei("test2.png", DateiTyp.BILD, DateiSuffix.PNG, "another nice image"));
    obj.setDatei3(
            new Datei("test3.pdf", DateiTyp.GRUNDRISS_PDF, DateiSuffix.PDF, "a document with groundplan"));
    obj.setDatei4(new Datei("http://www.test.org/", DateiTyp.LINK, null, "agency website"));
}

From source file:org.openestate.io.immobiliare_it.ImmobiliareItUtils.java

public static Currency parseCurrency(String value) {
    value = StringUtils.trimToNull(value);
    if (value == null)
        return null;
    try {/*w  ww.jav a2 s.  c  o  m*/
        if (value.trim().length() != 3)
            throw new Exception("Currency code must contain of 3 characters.");

        return Currency.getInstance(value.trim().toUpperCase());
    } catch (Exception ex) {
        throw new IllegalArgumentException("Can't parse currency value '" + value + "'!", ex);
    }
}

From source file:org.gnucash.android.ui.account.AccountsActivity.java

/**
 * Loads default setting for currency and performs app first-run initialization
 *//*w ww  .ja v a 2  s.  co m*/
private void init() {
    PreferenceManager.setDefaultValues(this, R.xml.fragment_transaction_preferences, false);

    Locale locale = Locale.getDefault();
    //sometimes the locale en_UK is returned which causes a crash with Currency
    if (locale.getCountry().equals("UK")) {
        locale = new Locale(locale.getLanguage(), "GB");
    }

    String currencyCode;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    try { //there are some strange locales out there
        currencyCode = prefs.getString(getString(R.string.key_default_currency),
                Currency.getInstance(locale).getCurrencyCode());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        currencyCode = "USD";
    }

    Money.DEFAULT_CURRENCY_CODE = currencyCode;

    boolean firstRun = prefs.getBoolean(getString(R.string.key_first_run), true);
    if (firstRun) {
        createDefaultAccounts();
        //default to using double entry and save the preference explicitly
        prefs.edit().putBoolean(getString(R.string.key_use_double_entry), true).commit();
    }

    if (hasNewFeatures()) {
        showWhatsNewDialog(this);
    }

}

From source file:org.broadleafcommerce.common.web.BroadleafRequestContext.java

/**
 * Returns the java.util.Currency constructed from the org.broadleafcommerce.common.currency.domain.BroadleafCurrency.
 * If there is no BroadleafCurrency specified this will return the currency based on the JVM locale
 * /*from w w w  .  j  a  v  a  2s  .c  o m*/
 * @return
 */
public Currency getJavaCurrency() {
    if (javaCurrency == null) {
        try {
            if (getBroadleafCurrency() != null && getBroadleafCurrency().getCurrencyCode() != null) {
                javaCurrency = Currency.getInstance(getBroadleafCurrency().getCurrencyCode());
            } else {
                javaCurrency = Currency.getInstance(getJavaLocale());
            }
        } catch (IllegalArgumentException e) {
            LOG.warn(
                    "There was an error processing the configured locale into the java currency. This is likely because the default"
                            + " locale is set to something like 'en' (which is NOT apart of ISO 3166 and does not have a currency"
                            + " associated with it) instead of 'en_US' (which IS apart of ISO 3166 and has a currency associated"
                            + " with it). Because of this, the currency is now set to the default locale of the JVM");
            LOG.warn(
                    "To fully resolve this, update the default entry in the BLC_LOCALE table to take into account the"
                            + " country code as well as the language. Alternatively, you could also update the BLC_CURRENCY table"
                            + " to contain a default currency.");
            javaCurrency = Currency.getInstance(java.util.Locale.getDefault());
        }
    }
    return javaCurrency;
}

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

/**
 * Get the currency symbol from {@link SharedPreferences}.
 * /*ww  w  . j a va  2  s.  com*/
 * @param context
 *            {@link Context}
 * @return currency symbol
 */
public static final String getCurrencySymbol(final Context context) {
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    final String pcs = p.getString(PREFS_CURRENCY_SYMBOL, "");
    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 defaultCurrencySymbol;
    } else {
        return pcs;
    }
}

From source file:org.gnucash.android.test.ui.TransactionsActivityTest.java

public void testToggleTransactionType() {
    mSolo.waitForText(DUMMY_ACCOUNT_NAME);

    validateTransactionListDisplayed();/*  w w  w . ja v  a2s  .c  o m*/
    mSolo.clickOnText(TRANSACTION_NAME);
    mSolo.waitForText("Note");

    validateEditTransactionFields(mTransaction);

    mSolo.clickOnButton(getActivity().getString(R.string.label_credit));
    String amountString = mSolo.getEditText(1).getText().toString();
    NumberFormat formatter = NumberFormat.getInstance();
    try {
        amountString = formatter.parse(amountString).toString();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Money amount = new Money(amountString, Currency.getInstance(Locale.getDefault()).getCurrencyCode());
    assertEquals("-9.99", amount.toPlainString());

    clickSherlockActionBarItem(R.id.menu_save);
    mSolo.waitForText(DUMMY_ACCOUNT_NAME);

    TransactionsDbAdapter adapter = new TransactionsDbAdapter(getActivity());
    List<Transaction> transactions = adapter.getAllTransactionsForAccount(DUMMY_ACCOUNT_UID);

    assertEquals(1, transactions.size());
    Transaction trx = transactions.get(0);
    assertTrue(trx.getAmount().isNegative());

    mSolo.goBack();
}

From source file:org.mobicents.servlet.restcomm.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  a  v  a2s.c  om*/
        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();

            ActorRef session = session();
            // 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.
            final SmsSessionRequest sms = new SmsSessionRequest(client.getLogin(), toUser,
                    new String(request.getRawContent()), request, 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.totschnig.myexpenses.activity.AccountEdit.java

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    setDirty(true);//from w w  w.  j  ava 2s  .c om
    switch (parent.getId()) {
    case R.id.Color:
        if (mColors.get(position) != 0)
            mAccount.color = mColors.get(position);
        break;
    case R.id.Currency:
        try {
            mAmountText.setFractionDigits(
                    Money.getFractionDigits(Currency.getInstance(CurrencyEnum.values()[position].name())));
        } catch (IllegalArgumentException e) {
            //will be reported to user when he tries so safe
        }
        break;
    }
}