Java 类java.util.Currency 实例源码

项目:wg_planer    文件:GroupSettingsActivity.java   
private ArrayList<Currency> transformLocale(Locale[] locales) {
    ArrayList<Currency> currencies = new ArrayList<>();

    for (Locale locale : locales) {
        try {
            Currency currency = Currency.getInstance(locale);

            if (!currencies.contains(currency)) {
                currencies.add(currency);
            }

        } catch (IllegalArgumentException e) {
            continue;
        }
    }

    return currencies;
}
项目:GitHub    文件:Bug_for_issue_349.java   
public void test_for_issue() throws Exception {
    Money money = new Money();
    money.currency = Currency.getInstance("CNY");
    money.amount = new BigDecimal("10.03");

    String json = JSON.toJSONString(money);

    Money moneyBack = JSON.parseObject(json, Money.class);
    Assert.assertEquals(money.currency, moneyBack.currency);
    Assert.assertEquals(money.amount, moneyBack.amount);

    JSONObject jsonObject = JSON.parseObject(json);
    Money moneyCast = JSON.toJavaObject(jsonObject, Money.class);
    Assert.assertEquals(money.currency, moneyCast.currency);
    Assert.assertEquals(money.amount, moneyCast.amount);
}
项目:GitHub    文件:CurrencyTest5.java   
public void test_0() throws Exception {
    SerializeConfig config = new SerializeConfig();
    config.put(Currency.class
            , config.createJavaBeanSerializer(Currency.class));

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("value", Currency.getInstance("CNY"));

    String text = JSON.toJSONString(jsonObject, config);
    System.out.println(text);
    String str1 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"symbol\":\"CNY\"}}";
    String str2 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"人民币\",\"symbol\":\"¥\"}}";
    String str3 = "{\"value\":{\"currencyCode\":\"CNY\",\"displayName\":\"Chinese Yuan\",\"numericCodeAsString\":\"156\",\"symbol\":\"CN¥\"}}";
    assertTrue(text.equals(str1)
            || text.equals(str2)
            || text.equals(str3));

    Currency currency = JSON.parseObject(text, VO.class).value;

    assertSame(Currency.getInstance("CNY"), currency);
}
项目:myfaces-trinidad    文件:NumberConverter.java   
private void _setCurrencyInformation(
  RequestContext context,
  DecimalFormatSymbols symbols)
{
  String currencyCode = _getCurrencyCode(context);

  // currencyCode is set we honour currency code.
  if (currencyCode != null)
  {
    symbols.setCurrency(Currency.getInstance(currencyCode));
    return;
  }

  if (getCurrencySymbol() != null)
  {
    symbols.setCurrencySymbol(getCurrencySymbol());

     // Loggin at level INFO - shows up by default - so use fine.
    _LOG.fine("Using currency symbol as currecny code evaluates to null");
  }
  // currency symbol will now default based on the locale.
}
项目:FindCurrencyExa    文件:MainFragment.java   
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    btn_find = (Button) view.findViewById(R.id.btn_find);
    et_location_name = (EditText) view.findViewById(R.id.et_location_name);
    et_country_code = (EditText) view.findViewById(R.id.et_country_code);
    et_countyISO = (EditText) view.findViewById(R.id.et_countyISO);
    et_currencyCode = (EditText) view.findViewById(R.id.et_currencyCode);
    tv_currencySymbol = (TextView) view.findViewById(R.id.tv_currencySymbol);
    tv_currencyDisplayName = (TextView) view.findViewById(R.id.tv_currencyDisplayName);
    tv_currencyCode = (TextView) view.findViewById(R.id.tv_currencyCode);
    tv_fractionDigits = (TextView) view.findViewById(R.id.tv_fractionDigits);
    tv_numericCode = (TextView) view.findViewById(R.id.tv_numericCode);
    tv_noDataFound = (TextView) view.findViewById(R.id.tv_noDataFound);
    fl_bottomContents = (FrameLayout) view.findViewById(R.id.fl_bottomContents);

    availableCurrenciesSet = Currency.getAvailableCurrencies();
    currencyList = new ArrayList<>(availableCurrenciesSet);
    btn_find.setOnClickListener(this);
}
项目:openfleet    文件:MNBExchangeService.java   
@Override
public double getExchangeRateForCurrency(Currency currency) {
    logger.trace(currency.getCurrencyCode());
    NodeList list = this.exchangeRates.getElementsByTagName("Rate");
    for(int i=0;i<list.getLength();i++)
    {
        Node n = list.item(i);
        if(n.getNodeType() == Node.ELEMENT_NODE)
        {
            Element e = (Element) n;
            logger.trace(e.getAttribute("curr") + ": " + Double.parseDouble(e.getTextContent().replace(",",".")) / Double.parseDouble(e.getAttribute("unit")));
            if(e.getAttribute("curr").equals(currency.getCurrencyCode())){
                return Double.parseDouble(e.getTextContent().replace(",",".")) / Double.parseDouble(e.getAttribute("unit"));
            }
        }
    }
    return -1.0;
}
项目:oscm    文件:BillingDataRetrievalServiceBeanCurrencyIT.java   
/**
 * Creates a subscription that is based on a price model using USD as
 * currency.
 * 
 * @param modTime
 *            The time the change to use USD should be performed at.
 * @throws Exception
 */
private void createSubUsingUSD(final long modTime) throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            SupportedCurrency sc = new SupportedCurrency();
            sc.setCurrency(Currency.getInstance("USD"));
            dm.persist(sc);

            Subscription subNew = Subscriptions.createSubscription(dm,
                    Scenario.getCustomer().getOrganizationId(),
                    Scenario.getProduct().getProductId(), "SubUSD",
                    Scenario.getSupplier());
            dm.flush();
            subNew.setHistoryModificationTime(Long.valueOf(modTime));
            PriceModel priceModel = subNew.getPriceModel();
            priceModel.setCurrency(sc);
            priceModel.setHistoryModificationTime(Long.valueOf(modTime));

            return null;
        }
    });
}
项目:openjdk-jdk10    文件:Bug8154295.java   
public static void main(String[] args) {

        String numericCode = Currency.getInstance("AFA").getNumericCodeAsString();
        if (!numericCode.equals("004")) { //should return "004" (a 3 digit string)
           throw new RuntimeException("[Expected 004, "
                + "found "+numericCode+" for AFA]");
        }

        numericCode = Currency.getInstance("AUD").getNumericCodeAsString();
        if (!numericCode.equals("036")) { //should return "036" (a 3 digit string)
            throw new RuntimeException("[Expected 036, "
                + "found "+numericCode+" for AUD]");
        }

        numericCode = Currency.getInstance("USD").getNumericCodeAsString();
        if (!numericCode.equals("840")) {// should return "840" (a 3 digit string)
            throw new RuntimeException("[Expected 840, "
                + "found "+numericCode+" for USD]");
        }

    }
项目:FuelUp    文件:CurrencyUtil.java   
public static List<Currency> getSupportedCurrencies() {
    checkPropertiesAreLoaded();

    List<Currency> currencies = new ArrayList<>();
    for (String currencyString : properties.stringPropertyNames())
        currencies.add(Currency.getInstance(currencyString));

    Collections.sort(currencies, new Comparator<Currency>() {
        @Override
        public int compare(Currency c1, Currency c2) {
            return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
        }
    });

    return currencies;
}
项目:trading4j    文件:PipetteValueCalculator.java   
private IllegalArgumentException createIlegalArgumentsException(final Currency accountCurrency,
        final ForexSymbol tradedSymbol) {
    return new IllegalArgumentException("Should calculate the value of a single pipette of the symbol \""
            + tradedSymbol + "\" in \"" + accountCurrency
            + "\" and requiering therefor the the exchange rate from \"" + tradedSymbol.getQuoteCurrency()
            + "\" to \"" + accountCurrency + "\" but that exchange rate was not available.");
}
项目:GitHub    文件:CurrencyTest3.java   
public void testJson() throws Exception {
    Money money = new Money();
    money.currency = Currency.getInstance("CNY");
    money.amount = new BigDecimal("10.03");

    String json = JSON.toJSONString(money);
    System.out.println("json = " + json);

    Money moneyBack = JSON.parseObject(json, Money.class);
    System.out.println("money = " + moneyBack);

    JSONObject jsonObject = JSON.parseObject(json);
    Money moneyCast = JSON.toJavaObject(jsonObject, Money.class);
    System.out.printf("money = " + moneyCast);
}
项目:openjdk-jdk10    文件:DecimalFormatSymbols.java   
/**
 * Reads the default serializable fields, provides default values for objects
 * in older serial versions, and initializes non-serializable fields.
 * If <code>serialVersionOnStream</code>
 * is less than 1, initializes <code>monetarySeparator</code> to be
 * the same as <code>decimalSeparator</code> and <code>exponential</code>
 * to be 'E'.
 * If <code>serialVersionOnStream</code> is less than 2,
 * initializes <code>locale</code>to the root locale, and initializes
 * If <code>serialVersionOnStream</code> is less than 3, it initializes
 * <code>exponentialSeparator</code> using <code>exponential</code>.
 * Sets <code>serialVersionOnStream</code> back to the maximum allowed value so that
 * default serialization will work properly if this object is streamed out again.
 * Initializes the currency from the intlCurrencySymbol field.
 *
 * @since  1.1.6
 */
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    if (serialVersionOnStream < 1) {
        // Didn't have monetarySeparator or exponential field;
        // use defaults.
        monetarySeparator = decimalSeparator;
        exponential       = 'E';
    }
    if (serialVersionOnStream < 2) {
        // didn't have locale; use root locale
        locale = Locale.ROOT;
    }
    if (serialVersionOnStream < 3) {
        // didn't have exponentialSeparator. Create one using exponential
        exponentialSeparator = Character.toString(exponential);
    }
    serialVersionOnStream = currentSerialVersion;

    if (intlCurrencySymbol != null) {
        try {
             currency = Currency.getInstance(intlCurrencySymbol);
        } catch (IllegalArgumentException e) {
        }
        currencyInitialized = true;
    }
}
项目:morpheus-core    文件:ArrayBuilderTests.java   
@DataProvider(name = "types")
public Object[][] types() {
    return new Object[][] {
        { Object.class },
        { Boolean.class },
        { Integer.class },
        { Long.class },
        { Double.class },
        { String.class },
        { Month.class },
        { Currency.class },
        { Date.class },
        { LocalDate.class },
        { LocalTime.class },
        { LocalDateTime.class },
        { ZonedDateTime.class }
    };
}
项目:openfleet    文件:TransferCostBuilder.java   
/**
 * Takes the parameters from the {@link org.springframework.web.context.request.WebRequest} and parses into the new {@link com.markbudai.openfleet.model.TransferCost} object by its setter methods.
 * @param request the {@link org.springframework.web.context.request.WebRequest} containing parameters for the new {@link com.markbudai.openfleet.model.TransferCost} object.
 * @return the parsed  {@link com.markbudai.openfleet.model.TransferCost} object.
 * @exception com.markbudai.openfleet.exception.EmptyParameterException if any parameter is empty.
 */
public static TransferCost buildFromWebRequest(WebRequest request){
    TransferCost t = new TransferCost();
    logger.trace("Starting builder.");
    logger.debug("start parsing data");
    if(request.getParameter("amount").isEmpty()){
        logger.debug(request.getParameter("amount"));
        throw new EmptyParameterException("amount");
    }
    logger.debug("amount");
    t.setAmount(Long.parseLong(request.getParameter("amount")));
    if(request.getParameter("costDescription").isEmpty()){
        throw new EmptyParameterException("costDescription");
    }
    logger.debug("costDescription");
    t.setCostDescription(request.getParameter("costDescription"));
    if(request.getParameter("currency").isEmpty()){
        throw new EmptyParameterException("currency");
    }
    logger.debug("currency");
    t.setCurrency(Currency.getInstance(request.getParameter("currency")));
    if(request.getParameter("date").isEmpty()){
        throw new EmptyParameterException("date");
    }
    logger.debug("date");
    t.setDate(LocalDate.parse(request.getParameter("date")));

    return t;
}
项目:trading4j    文件:PipetteValueCalculatorTest.java   
/**
 * The value of one pipette is one pipette multiplied by the account currency exchange rate when the account
 * currency is the quote currency of that account currency exchange rate symbol.
 */
@Test
public void pipetteValueIsOnePipetteMultipliedByExchangeRateOfQuoteToAccountCurrencyWhenSymbolDoesNotContainAccountCurrency() {
    when(exchangeRateStore.getExchangeRate(Currency.getInstance("AUD"), Currency.getInstance("CAD"))).thenReturn(Optional.of(new AccuratePrice(1.8)));
    assertThat(cut.calculatePipetteValue(currency("CAD"), new ForexSymbol("EURAUD"), new Price(1.2))).isEqualTo(new AccuratePrice(0.000018), ALLOWED_OFFSET);

    when(exchangeRateStore.getExchangeRate(Currency.getInstance("USD"), Currency.getInstance("CHF"))).thenReturn(Optional.of(new AccuratePrice(1.358)));
    assertThat(cut.calculatePipetteValue(currency("CHF"), new ForexSymbol("GBPUSD"), new Price(1.9))).isEqualTo(new AccuratePrice(0.00001358), ALLOWED_OFFSET);
}
项目:jdk8u-jdk    文件:DecimalFormatSymbols.java   
/**
 * Reads the default serializable fields, provides default values for objects
 * in older serial versions, and initializes non-serializable fields.
 * If <code>serialVersionOnStream</code>
 * is less than 1, initializes <code>monetarySeparator</code> to be
 * the same as <code>decimalSeparator</code> and <code>exponential</code>
 * to be 'E'.
 * If <code>serialVersionOnStream</code> is less than 2,
 * initializes <code>locale</code>to the root locale, and initializes
 * If <code>serialVersionOnStream</code> is less than 3, it initializes
 * <code>exponentialSeparator</code> using <code>exponential</code>.
 * Sets <code>serialVersionOnStream</code> back to the maximum allowed value so that
 * default serialization will work properly if this object is streamed out again.
 * Initializes the currency from the intlCurrencySymbol field.
 *
 * @since JDK 1.1.6
 */
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    if (serialVersionOnStream < 1) {
        // Didn't have monetarySeparator or exponential field;
        // use defaults.
        monetarySeparator = decimalSeparator;
        exponential       = 'E';
    }
    if (serialVersionOnStream < 2) {
        // didn't have locale; use root locale
        locale = Locale.ROOT;
    }
    if (serialVersionOnStream < 3) {
        // didn't have exponentialSeparator. Create one using exponential
        exponentialSeparator = Character.toString(exponential);
    }
    serialVersionOnStream = currentSerialVersion;

    if (intlCurrencySymbol != null) {
        try {
             currency = Currency.getInstance(intlCurrencySymbol);
        } catch (IllegalArgumentException e) {
        }
    }
}
项目:trading4j    文件:MoneyTest.java   
/**
 * Money instances can be constructed by passing the raw value.
 */
@Test
public void constructableFromRawValue() {
    assertThat(new Money(4286, EUR).asRawValue()).isEqualTo(4286);

    final Money money1 = new Money(0, USD);
    assertThat(money1.asRawValue()).isEqualTo(0);
    assertThat(money1.getCurrency()).isEqualTo(USD);

    final Money money2 = new Money(-958125, "CHF");
    assertThat(money2.asRawValue()).isEqualTo(-958125);
    assertThat(money2.getCurrency()).isEqualTo(Currency.getInstance("CHF"));
}
项目:AndroidBackendlessChat    文件:CountryPicker.java   
/**
 * Convenient function to get currency code from country code currency code
 * is in English locale
 * 
 * @param countryCode
 * @return
 */
public static Currency getCurrencyCode(String countryCode) {
    try {
        return Currency.getInstance(new Locale("en", countryCode));
    } catch (Exception e) {

    }
    return null;
}
项目:guava-mock    文件:FreshValueGenerator.java   
private Currency preJava7FreshCurrency() {
  for (Set<Locale> uselessLocales = Sets.newHashSet(); ; ) {
    Locale locale = generateLocale();
    if (uselessLocales.contains(locale)) { // exhausted all locales
      return Currency.getInstance(Locale.US);
    }
    try {
      return Currency.getInstance(locale);
    } catch (IllegalArgumentException e) {
      uselessLocales.add(locale);
    }
  }
}
项目:guava-mock    文件:FreshValueGeneratorTest.java   
@AndroidIncompatible // problem with equality of Type objects?
public void testFreshInstance() {
  assertFreshInstances(
      String.class, CharSequence.class,
      Appendable.class, StringBuffer.class, StringBuilder.class,
      Pattern.class, MatchResult.class,
      Number.class, int.class, Integer.class,
      long.class, Long.class,
      short.class, Short.class,
      byte.class, Byte.class,
      boolean.class, Boolean.class,
      char.class, Character.class,
      int[].class, Object[].class,
      UnsignedInteger.class, UnsignedLong.class,
      BigInteger.class, BigDecimal.class,
      Throwable.class, Error.class, Exception.class, RuntimeException.class,
      Charset.class, Locale.class, Currency.class,
      List.class, Map.Entry.class,
      Object.class,
      Equivalence.class, Predicate.class, Function.class,
      Comparable.class, Comparator.class, Ordering.class,
      Class.class, Type.class, TypeToken.class,
      TimeUnit.class, Ticker.class,
      Joiner.class, Splitter.class, CharMatcher.class,
      InputStream.class, ByteArrayInputStream.class,
      Reader.class, Readable.class, StringReader.class,
      OutputStream.class, ByteArrayOutputStream.class,
      Writer.class, StringWriter.class, File.class,
      Buffer.class, ByteBuffer.class, CharBuffer.class,
      ShortBuffer.class, IntBuffer.class, LongBuffer.class,
      FloatBuffer.class, DoubleBuffer.class,
      String[].class, Object[].class, int[].class);
}
项目:guava-mock    文件:FreshValueGeneratorTest.java   
public void testFreshCurrency() {
  FreshValueGenerator generator = new FreshValueGenerator();
  // repeat a few times to make sure we don't stumble upon a bad Locale
  assertNotNull(generator.generateFresh(Currency.class));
  assertNotNull(generator.generateFresh(Currency.class));
  assertNotNull(generator.generateFresh(Currency.class));
}
项目:Sega    文件:ProductAdapter.java   
public ProductAdapter(Context context, OnproductClickListener onproductClickListener) {
    this.context = context;
    this.productList = new ArrayList<>();
    this.onproductClickListener = onproductClickListener;
    formatprice = new DecimalFormat("#0,000");

    sharedPref = context.getSharedPreferences(ViMarket.TABLE_USER, Context.MODE_PRIVATE);
    imageWidth = sharedPref.getInt(ViMarket.THUMBNAIL_SIZE,
                                   0);   // Load image width for grid view
    Locale current = new Locale("vi","VN");
    Currency cur = Currency.getInstance(current);
    format = cur.getSymbol();
}
项目:oscm    文件:ServiceProvisioningServiceBean2IT.java   
@Test
public void testSetCompatibleProducts_compatibleFreeOfCharge3()
        throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            SupportedCurrency sc = new SupportedCurrency();
            sc.setCurrency(Currency.getInstance("USD"));
            mgr.persist(sc);
            return null;
        }
    });
    VOTechnicalService techProduct = createTechnicalProduct(svcProv);
    container.login(supplierUserKey, ROLE_SERVICE_MANAGER,
            ROLE_TECHNOLOGY_MANAGER);
    VOServiceDetails product1 = createProduct(techProduct, "product1",
            svcProv);
    publishToLocalMarketplaceSupplier(product1, mpSupplier);
    VOServiceDetails product2 = createProduct(techProduct, "product2",
            svcProv);
    publishToLocalMarketplaceSupplier(product2, mpSupplier);

    VOPriceModel priceModel1 = createChargeablePriceModel();
    priceModel1.setCurrencyISOCode(USD);
    priceModel1.setType(PriceModelType.FREE_OF_CHARGE);

    VOPriceModel priceModel2 = createChargeablePriceModel();
    priceModel2.setType(PriceModelType.FREE_OF_CHARGE);
    product1 = svcProv.savePriceModel(product1, priceModel1);
    product2 = svcProv.savePriceModel(product2, priceModel2);

    svcProv.setCompatibleServices(product1,
            Collections.singletonList((VOService) product2));
}
项目:oscm    文件:ServiceProvisioningServiceBean2IT.java   
@Test
public void testSet3CompatibleProducts_2compatible1FreeOfCharge()
        throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            SupportedCurrency sc = new SupportedCurrency();
            sc.setCurrency(Currency.getInstance("USD"));
            mgr.persist(sc);
            return null;
        }
    });
    VOTechnicalService techProduct = createTechnicalProduct(svcProv);
    container.login(supplierUserKey, ROLE_SERVICE_MANAGER,
            ROLE_TECHNOLOGY_MANAGER);
    VOServiceDetails product1 = createProduct(techProduct, "product1",
            svcProv);
    publishToLocalMarketplaceSupplier(product1, mpSupplier);
    VOServiceDetails product2 = createProduct(techProduct, "product2",
            svcProv);
    publishToLocalMarketplaceSupplier(product2, mpSupplier);
    VOServiceDetails product3 = createProduct(techProduct, "product3",
            svcProv);
    publishToLocalMarketplaceSupplier(product3, mpSupplier);

    VOPriceModel priceModel1 = createChargeablePriceModel();
    priceModel1.setCurrencyISOCode(USD);
    priceModel1.setType(PriceModelType.FREE_OF_CHARGE);
    VOPriceModel priceModel2 = createChargeablePriceModel();
    priceModel2.setCurrencyISOCode(USD);
    VOPriceModel priceModel3 = createChargeablePriceModel();
    product1 = svcProv.savePriceModel(product1, priceModel1);
    product2 = svcProv.savePriceModel(product2, priceModel2);
    product3 = svcProv.savePriceModel(product3, priceModel3);

    svcProv.setCompatibleServices(product1,
            Arrays.asList((VOService) product2, product3));
}
项目:oscm    文件:ServiceProvisioningServiceBean2IT.java   
@Test
public void testSet3CompatibleProducts_compatible2FreeOfCharge()
        throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            SupportedCurrency sc = new SupportedCurrency();
            sc.setCurrency(Currency.getInstance("USD"));
            mgr.persist(sc);
            return null;
        }
    });
    VOTechnicalService techProduct = createTechnicalProduct(svcProv);
    container.login(supplierUserKey, ROLE_SERVICE_MANAGER,
            ROLE_TECHNOLOGY_MANAGER);
    VOServiceDetails product1 = createProduct(techProduct, "product1",
            svcProv);
    publishToLocalMarketplaceSupplier(product1, mpSupplier);
    VOServiceDetails product2 = createProduct(techProduct, "product2",
            svcProv);
    publishToLocalMarketplaceSupplier(product2, mpSupplier);
    VOServiceDetails product3 = createProduct(techProduct, "product3",
            svcProv);
    publishToLocalMarketplaceSupplier(product3, mpSupplier);

    VOPriceModel priceModel1 = createChargeablePriceModel();
    priceModel1.setCurrencyISOCode(USD);
    VOPriceModel priceModel2 = createChargeablePriceModel();
    priceModel2.setType(PriceModelType.FREE_OF_CHARGE);
    product1 = svcProv.savePriceModel(product1, priceModel2);
    product2 = svcProv.savePriceModel(product2, priceModel1);
    product3 = svcProv.savePriceModel(product3, priceModel2);

    svcProv.setCompatibleServices(product1,
            Arrays.asList((VOService) product2, product3));
}
项目:trading4j    文件:ForexSymbolTest.java   
/**
 * A {@link ForexSymbol} can be constructed from its string representation.
 */
@Test
public void constructableForSymbolInFormOfString() {
    final ForexSymbol currency1 = new ForexSymbol("EURUSD");
    assertThat(currency1.getBaseCurrency()).isEqualTo(Currency.getInstance("EUR"));
    assertThat(currency1.getQuoteCurrency()).isEqualTo(Currency.getInstance("USD"));

    final ForexSymbol currency2 = new ForexSymbol("AUDCAD");
    assertThat(currency2.getBaseCurrency()).isEqualTo(Currency.getInstance("AUD"));
    assertThat(currency2.getQuoteCurrency()).isEqualTo(Currency.getInstance("CAD"));
}
项目:googles-monorepo-demo    文件:ArbitraryInstancesTest.java   
public void testGet_misc() {
  assertNotNull(ArbitraryInstances.get(CharMatcher.class));
  assertNotNull(ArbitraryInstances.get(Currency.class).getCurrencyCode());
  assertNotNull(ArbitraryInstances.get(Locale.class));
  assertNotNull(ArbitraryInstances.get(Joiner.class).join(ImmutableList.of("a")));
  assertNotNull(ArbitraryInstances.get(Splitter.class).split("a,b"));
  assertThat(ArbitraryInstances.get(Optional.class)).isAbsent();
  ArbitraryInstances.get(Stopwatch.class).start();
  assertNotNull(ArbitraryInstances.get(Ticker.class));
  assertFreshInstanceReturned(Random.class);
  assertEquals(ArbitraryInstances.get(Random.class).nextInt(),
      ArbitraryInstances.get(Random.class).nextInt());
}
项目:boohee_v5.6    文件:CurrencyCodec.java   
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    String text = (String) parser.parse();
    if (text == null || text.length() == 0) {
        return null;
    }
    return Currency.getInstance(text);
}
项目:openjdk-jdk10    文件:Bug4512215.java   
private static void testCountryCurrency(String country, String currencyCode,
        int digits) {
    testCurrencyDefined(currencyCode, digits);
    Currency currency = Currency.getInstance(new Locale("", country));
    if (!currency.getCurrencyCode().equals(currencyCode)) {
        throw new RuntimeException("[" + country
                + "] expected: " + currencyCode
                + "; got: " + currency.getCurrencyCode());
    }
}
项目:morpheus-core    文件:MappedArrayConstructor.java   
@Override
@SuppressWarnings("unchecked")
public <T> Array<T> apply(Class<T> type, int length, T defaultValue, String path) {
    final File file = path == null ? randomFile(true) : createDir(new File(path));
    if (type.isEnum()) {
        final IntCoding<T> enumCoding = (IntCoding<T>)IntCoding.ofEnum((Class<Enum>) type);
        return new MappedArrayWithIntCoding<>(length, defaultValue, enumCoding, file);
    } else {
        switch (ArrayType.of(type)) {
            case BOOLEAN:           return (Array<T>)new MappedArrayOfBooleans(length, (Boolean)defaultValue, file);
            case INTEGER:           return (Array<T>)new MappedArrayOfInts(length, (Integer)defaultValue, file);
            case LONG:              return (Array<T>)new MappedArrayOfLongs(length, (Long)defaultValue, file);
            case DOUBLE:            return (Array<T>)new MappedArrayOfDoubles(length, (Double)defaultValue, file);
            case CURRENCY:          return (Array<T>)new MappedArrayWithIntCoding<>(length, (Currency)defaultValue, currencyCoding, file);
            case YEAR:              return (Array<T>)new MappedArrayWithIntCoding<>(length, (Year)defaultValue, yearCoding, file);
            case ZONE_ID:           return (Array<T>)new MappedArrayWithIntCoding<>(length, (ZoneId)defaultValue, zoneIdCoding, file);
            case TIME_ZONE:         return (Array<T>)new MappedArrayWithIntCoding<>(length, (TimeZone)defaultValue, timeZoneCoding, file);
            case DATE:              return (Array<T>)new MappedArrayWithLongCoding<>(length, (Date)defaultValue, dateCoding, file);
            case INSTANT:           return (Array<T>)new MappedArrayWithLongCoding<>(length, (Instant)defaultValue, instantCoding, file);
            case LOCAL_DATE:        return (Array<T>)new MappedArrayWithLongCoding<>(length, (LocalDate)defaultValue, localDateCoding, file);
            case LOCAL_TIME:        return (Array<T>)new MappedArrayWithLongCoding<>(length, (LocalTime)defaultValue, localTimeCoding, file);
            case LOCAL_DATETIME:    return (Array<T>)new MappedArrayWithLongCoding<>(length, (LocalDateTime)defaultValue, localDateTimeCoding, file);
            case ZONED_DATETIME:    return (Array<T>)new MappedArrayOfZonedDateTimes(length, (ZonedDateTime)defaultValue, file);
            default:                throw new UnsupportedOperationException("Data type currently not supported for memory mapped arrays: " + type);
        }
    }
}
项目:lams    文件:XStream.java   
protected void setupSecurity() {
    if (securityMapper == null) {
        return;
    }

    addPermission(NullPermission.NULL);
    addPermission(PrimitiveTypePermission.PRIMITIVES);
    addPermission(ArrayTypePermission.ARRAYS);
    addPermission(InterfaceTypePermission.INTERFACES);
    allowTypeHierarchy(Calendar.class);
    allowTypeHierarchy(Collection.class);
    allowTypeHierarchy(Enum.class);
    allowTypeHierarchy(Map.class);
    allowTypeHierarchy(Map.Entry.class);
    allowTypeHierarchy(Member.class);
    allowTypeHierarchy(Number.class);
    allowTypeHierarchy(Throwable.class);
    allowTypeHierarchy(TimeZone.class);

    final Set<Class<?>> types = new HashSet<Class<?>>();
    types.addAll(Arrays.<Class<?>>asList(BitSet.class, Charset.class, Class.class, Currency.class, Date.class,
        DecimalFormatSymbols.class, File.class, Locale.class, Object.class, Pattern.class, StackTraceElement.class,
        String.class, StringBuffer.class, StringBuilder.class, URL.class, URI.class, UUID.class));
    if (JVM.isSQLAvailable()) {
        types.add(JVM.loadClassForName("java.sql.Timestamp"));
        types.add(JVM.loadClassForName("java.sql.Time"));
        types.add(JVM.loadClassForName("java.sql.Date"));
    }
    types.remove(null);
    allowTypes(types.toArray(new Class[types.size()]));
}
项目:jdk8u-jdk    文件:CurrencyTest.java   
static void testSymbol(String currencyCode, Locale locale, String expectedSymbol) {
    String symbol = Currency.getInstance(currencyCode).getSymbol(locale);
    if (!symbol.equals(expectedSymbol)) {
        throw new RuntimeException("Wrong symbol for currency " +
                currencyCode +": expected " + expectedSymbol +
                ", got " + symbol);
    }
}
项目:RandomData    文件:AmountGenerator.java   
public float next2(DataContext context) {
    Currency currency = Currency.getInstance(Locale.getDefault());
    float cents = 0;
    if (currency.getDefaultFractionDigits() == 2) {
        if (useCommon) {
            cents = common[random.nextInt(common.length)];
        } else {
            cents = (float) random.nextInt(100) / 100;
        }
    }
    return Math.min(max, random.nextInt((int) Math.floor(max + 1)) + cents);
}
项目:FuelUp    文件:AddVehicleActivity.java   
private void saveVehicle() {
    String name = txtName.getText().toString();
    String manufacturer = txtManufacturer.getText().toString();
    String actualMileage = txtActualMileage.getText().toString();
    String currency = ((Currency) spinnerCurrency.getSelectedItem()).getCurrencyCode();
    long typeId = ((VehicleType) spinnerType.getSelectedItem()).getId();

    if (name.isEmpty()) {
        Snackbar.make(findViewById(android.R.id.content), R.string.toast_emptyName, Snackbar.LENGTH_LONG).show();
        return;
    }
    if (VehicleService.isVehicleNameTaken(name, this)) {
        Snackbar.make(findViewById(android.R.id.content), R.string.toast_nameNotUnique, Snackbar.LENGTH_LONG).show();
        return;
    }

    ContentValues contentValues = new ContentValues();
    contentValues.put(VehicleEntry.COLUMN_NAME, name);
    contentValues.put(VehicleEntry.COLUMN_VEHICLE_MAKER, manufacturer);
    contentValues.put(VehicleEntry.COLUMN_CURRENCY, currency);
    contentValues.put(VehicleEntry.COLUMN_TYPE, typeId);
    contentValues.put(VehicleEntry.COLUMN_PICTURE, vehiclePicturePath);
    contentValues.put(VehicleEntry.COLUMN_VOLUME_UNIT, getVolumeUnitFromRadio().name());
    contentValues.put(VehicleEntry.COLUMN_START_MILEAGE, actualMileage.isEmpty() ? null : Long.parseLong(actualMileage));

    // TODO check name unique
    if (getContentResolver().insert(VehicleEntry.CONTENT_URI, contentValues) == null) {
        Log.e(LOG_TAG, "Cannot create vehicle " + contentValues);
        Snackbar.make(findViewById(android.R.id.content), R.string.addVehicle_fail, Snackbar.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.addVehicle_Toast_successfullyCreated, Toast.LENGTH_LONG).show();
        finish();
    }
}
项目:Unified-World-Units    文件:MoneyUnitTest.java   
@Test
public void testCurrencyEquals() {
    assertTrue(Currency.getInstance("GBP") == GBP);
}
项目:picocli    文件:CommandLineTypeConversionTest.java   
@Test
    public void testTypeConversionSucceedsForValidInput() throws Exception {
        //Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        SupportedTypes bean = CommandLine.populateCommand(new SupportedTypes(),
                "-boolean", "-Boolean", //
                "-byte", "12", "-Byte", "23", //
                "-char", "p", "-Character", "i", //
                "-short", "34", "-Short", "45", //
                "-int", "56", "-Integer", "67", //
                "-long", "78", "-Long", "89", //
                "-float", "1.23", "-Float", "2.34", //
                "-double", "3.45", "-Double", "4.56", //
                "-String", "abc", "-StringBuilder", "bcd", "-CharSequence", "xyz", //
                "-File", "abc.txt", //
                "-URL", "http://pico-cli.github.io", //
                "-URI", "http://pico-cli.github.io/index.html", //
                "-Date", "2017-01-30", //
                "-Time", "23:59:59", //
                "-BigDecimal", "12345678901234567890.123", //
                "-BigInteger", "123456789012345678901", //
                "-Charset", "UTF8", //
                "-InetAddress", InetAddress.getLocalHost().getHostName(), //
                "-Pattern", "a*b", //
                "-UUID", "c7d51423-bf9d-45dd-a30d-5b16fafe42e2", //
                "-Currency", "EUR",
                "-tz", "Japan/Tokyo",
                "-byteOrder", "LITTLE_ENDIAN",
                "-Class", "java.lang.String",
                "-NetworkInterface", "127.0.0.0",
                "-Timestamp", "2017-12-13 13:59:59.123456789"
//                ,
//                "-Connection", "jdbc:derby:testDB;create=false",
//                "-Driver", "org.apache.derby.jdbc.EmbeddedDriver"
        );
        assertEquals("boolean", true, bean.booleanField);
        assertEquals("Boolean", Boolean.TRUE, bean.aBooleanField);
        assertEquals("byte", 12, bean.byteField);
        assertEquals("Byte", Byte.valueOf((byte) 23), bean.aByteField);
        assertEquals("char", 'p', bean.charField);
        assertEquals("Character", Character.valueOf('i'), bean.aCharacterField);
        assertEquals("short", 34, bean.shortField);
        assertEquals("Short", Short.valueOf((short) 45), bean.aShortField);
        assertEquals("int", 56, bean.intField);
        assertEquals("Integer", Integer.valueOf(67), bean.anIntegerField);
        assertEquals("long", 78L, bean.longField);
        assertEquals("Long", Long.valueOf(89L), bean.aLongField);
        assertEquals("float", 1.23f, bean.floatField, Float.MIN_VALUE);
        assertEquals("Float", Float.valueOf(2.34f), bean.aFloatField);
        assertEquals("double", 3.45, bean.doubleField, Double.MIN_VALUE);
        assertEquals("Double", Double.valueOf(4.56), bean.aDoubleField);
        assertEquals("String", "abc", bean.aStringField);
        assertEquals("StringBuilder type", StringBuilder.class, bean.aStringBuilderField.getClass());
        assertEquals("StringBuilder", "bcd", bean.aStringBuilderField.toString());
        assertEquals("CharSequence", "xyz", bean.aCharSequenceField);
        assertEquals("File", new File("abc.txt"), bean.aFileField);
        assertEquals("URL", new URL("http://pico-cli.github.io"), bean.anURLField);
        assertEquals("URI", new URI("http://pico-cli.github.io/index.html"), bean.anURIField);
        assertEquals("Date", new SimpleDateFormat("yyyy-MM-dd").parse("2017-01-30"), bean.aDateField);
        assertEquals("Time", new Time(new SimpleDateFormat("HH:mm:ss").parse("23:59:59").getTime()), bean.aTimeField);
        assertEquals("BigDecimal", new BigDecimal("12345678901234567890.123"), bean.aBigDecimalField);
        assertEquals("BigInteger", new BigInteger("123456789012345678901"), bean.aBigIntegerField);
        assertEquals("Charset", Charset.forName("UTF8"), bean.aCharsetField);
        assertEquals("InetAddress", InetAddress.getByName(InetAddress.getLocalHost().getHostName()), bean.anInetAddressField);
        assertEquals("Pattern", Pattern.compile("a*b").pattern(), bean.aPatternField.pattern());
        assertEquals("UUID", UUID.fromString("c7d51423-bf9d-45dd-a30d-5b16fafe42e2"), bean.anUUIDField);
        assertEquals("Currency", Currency.getInstance("EUR"), bean.aCurrencyField);
        assertEquals("TimeZone", TimeZone.getTimeZone("Japan/Tokyo"), bean.aTimeZone);
        assertEquals("ByteOrder", ByteOrder.LITTLE_ENDIAN, bean.aByteOrder);
        assertEquals("Class", String.class, bean.aClass);
        assertEquals("NetworkInterface", NetworkInterface.getByInetAddress(InetAddress.getByName("127.0.0.0")), bean.aNetInterface);
        assertEquals("Timestamp", Timestamp.valueOf("2017-12-13 13:59:59.123456789"), bean.aTimestamp);
//        assertEquals("Connection", DriverManager.getConnection("jdbc:derby:testDB;create=false"), bean.aConnection);
//        assertEquals("Driver", DriverManager.getDriver("org.apache.derby.jdbc.EmbeddedDriver"), bean.aDriver);
    }
项目:GitHub    文件:CurrencyTest.java   
public Currency getValue() {
    return value;
}
项目:GitHub    文件:CurrencyTest.java   
public void setValue(Currency value) {
    this.value = value;
}
项目:EasyMoney-Widgets    文件:EasyMoneyEditText.java   
/**
 * Set the currency symbol for the edit text. (Default is US Dollar $).
 * @param currency the currency object of new symbol. (Defaul is Locale.US)
 */
public void setCurrency(Currency currency)
{
    setCurrency(currency.getSymbol());
}
项目:trading4j    文件:MessageBasedClientConnectionTest.java   
/**
 * The reader should be able to read {@link TradingEnvironmentInformationMessage}s correctly.
 * 
 * @throws CommunicationException
 *             Not expected to leave the test method.
 */
@Test
public void shouldReadTradingEnvironmentMessagesCorreclty() throws CommunicationException {
    when(client.tryReceiveString())
            // first read
            .thenReturn("Some Broker").thenReturn("EUR").thenReturn("EURUSD").thenReturn("EURUSD")
            // second read
            .thenReturn("Other Broker").thenReturn("GBP").thenReturn("CHFJPY").thenReturn("GBPJPY");
    when(client.tryReceiveByte()).thenReturn(MessageType.TRADING_ENVIRONMENT_INFORMATION.getMessageNumber());
    when(client.tryReceiveInteger())
            // margin than commission for first
            .thenReturn(5).thenReturn(3)
            // margin than commission for second
            .thenReturn(216).thenReturn(8);
    when(client.tryReceiveLong())
            // account number, non historic time, min-, step-, max-volume for first
            .thenReturn(42L).thenReturn(20L).thenReturn(10L).thenReturn(1000L).thenReturn(3L)
            // account number, non historic time, min-, step-, max-volume for second
            .thenReturn(80L).thenReturn(582L).thenReturn(1000L).thenReturn(2931868L).thenReturn(5L);

    final TradingEnvironmentInformationMessage message1 = cut
            .readMessage(TradingEnvironmentInformationMessage.class);
    final TradingEnvironmentInformationMessage message2 = cut
            .readMessage(TradingEnvironmentInformationMessage.class);

    assertThat(message1.getInformation().getAccountInformation().getBrokerName()).isEqualTo("Some Broker");
    assertThat(message1.getInformation().getAccountInformation().getAccountNumber()).isEqualTo(42L);
    assertThat(message1.getInformation().getAccountInformation().getAccountCurrency())
            .isEqualTo(Currency.getInstance("EUR"));
    assertThat(message1.getInformation().getTradeSymbol()).isEqualTo(new ForexSymbol("EURUSD"));
    assertThat(message1.getInformation().getAccountSymbol()).isEqualTo(new ForexSymbol("EURUSD"));
    assertThat(message1.getInformation().getSpecialFeesInformation().getMarkup()).isEqualTo(new Price(5));
    assertThat(message1.getInformation().getSpecialFeesInformation().getCommission()).isEqualTo(new Price(3));
    assertThat(message1.getInformation().getNonHistoricTime().getEpochSecond()).isEqualTo(20L);
    assertThat(message1.getInformation().getVolumeConstraints().getMinimalVolume())
            .isEqualTo(new Volume(10L, BASE));
    assertThat(message1.getInformation().getVolumeConstraints().getMaximalVolume())
            .isEqualTo(new Volume(1000L, BASE));
    assertThat(message1.getInformation().getVolumeConstraints().getAllowedStepSize())
            .isEqualTo(new Volume(3L, BASE));

    assertThat(message2.getInformation().getAccountInformation().getBrokerName()).isEqualTo("Other Broker");
    assertThat(message2.getInformation().getAccountInformation().getAccountNumber()).isEqualTo(80L);
    assertThat(message2.getInformation().getAccountInformation().getAccountCurrency())
            .isEqualTo(Currency.getInstance("GBP"));
    assertThat(message2.getInformation().getTradeSymbol()).isEqualTo(new ForexSymbol("CHFJPY"));
    assertThat(message2.getInformation().getAccountSymbol()).isEqualTo(new ForexSymbol("GBPJPY"));
    assertThat(message2.getInformation().getSpecialFeesInformation().getMarkup()).isEqualTo(new Price(216));
    assertThat(message2.getInformation().getSpecialFeesInformation().getCommission()).isEqualTo(new Price(8));
    assertThat(message2.getInformation().getNonHistoricTime().getEpochSecond()).isEqualTo(582L);
    assertThat(message2.getInformation().getVolumeConstraints().getMinimalVolume())
            .isEqualTo(new Volume(1000L, BASE));
    assertThat(message2.getInformation().getVolumeConstraints().getMaximalVolume())
            .isEqualTo(new Volume(2931868L, BASE));
    assertThat(message2.getInformation().getVolumeConstraints().getAllowedStepSize())
            .isEqualTo(new Volume(5L, BASE));
}