@Override public CurrencyUnit fromNonNullValue(Integer i) { return CurrencyUnit.ofNumericCode(i); }
@Override public CurrencyUnit fromNonNullString(String s) { try { return CurrencyUnit.ofNumericCode(s); } catch (IllegalCurrencyException e) { return CurrencyUnit.of(s); } }
/** * Obtains an instance of {@code CurrencyUnit} for the specified ISO-4217 numeric currency code. * <p> * The numeric code is an alternative to the three letter code. * This method is lenient and does not require the string to be left padded with zeroes. * * @param numericCurrencyCode the currency code, not null * @return the singleton instance, never null * @throws IllegalCurrencyException if the currency is unknown */ public static CurrencyUnit ofNumericCode(String numericCurrencyCode) { MoneyUtils.checkNotNull(numericCurrencyCode, "Currency code must not be null"); switch (numericCurrencyCode.length()) { case 1: return ofNumericCode(numericCurrencyCode.charAt(0) - '0'); case 2: return ofNumericCode((numericCurrencyCode.charAt(0) - '0') * 10 + numericCurrencyCode.charAt(1) - '0'); case 3: return ofNumericCode((numericCurrencyCode.charAt(0) - '0') * 100 + (numericCurrencyCode.charAt(1) - '0') * 10 + numericCurrencyCode.charAt(2) - '0'); default: throw new IllegalCurrencyException("Unknown currency '" + numericCurrencyCode + '\''); } }
@Override public void parse(MoneyParseContext context) { int count = 0; for ( ; count < 3 && context.getIndex() + count < context.getTextLength(); count++) { char ch = context.getText().charAt(context.getIndex() + count); if (ch < '0' || ch > '9') { break; } } int endPos = context.getIndex() + count; String code = context.getTextSubstring(context.getIndex(), endPos); try { context.setCurrency(CurrencyUnit.ofNumericCode(code)); context.setIndex(endPos); } catch (IllegalCurrencyException ex) { context.setError(); } } };
@Override public void parse(MoneyParseContext context) { int endPos = context.getIndex() + 3; if (endPos > context.getTextLength()) { context.setError(); } else { String code = context.getTextSubstring(context.getIndex(), endPos); try { context.setCurrency(CurrencyUnit.ofNumericCode(code)); context.setIndex(endPos); } catch (IllegalCurrencyException ex) { context.setError(); } } } },