Introduction to JSR 354 – Java Money & CurrencyAnatole Tresch, Werner Keilatsticks@java.net @atsticks keilw@java.net @wern...
BiosAnatole Tresch• Consultant - Coach• Software and FrameworkArchitect• Open Source Addicted• Credit Suisse• Specificatio...
Agenda• History and Motivation• Overview• Amounts, Currencies• Numeric precision, Rounding• Formatting & Parsing• Currency...
History and Motivation
Earlier ApproachesAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneyEric Evans – Time a...
MotivationAnatole Tresch, Werner Keil Monetary values are a key feature to manyapplications The existing java.util.Curre...
ScheduleAnatole Tresch, Werner Keil• Targeting Java 9• Aiming at Java ME/Embedded 8 or 9– Following the EC Merge and Stand...
Overview
Overview on JSR 354Anatole Tresch, Werner Keil• Core API: javax.money• CurrencyUnit, MonetaryAmount and exceptions• Conver...
Amounts & Currenciesjavax.money
Currencies: What’s all in ISO 4217Anatole Tresch, Werner Keil• Special Codes• For precious metals (XAU, XAG)• for testing ...
Virtual CurrenciesAnatole Tresch, Werner Keil• Video Game Currencies (Gold,Gil, Rupees, Credits, Gold Rings,Hearts, Zenny,...
Limitations of java.util.CurrencyAnatole Tresch, Werner Keil• No support for historical Currencies• No support for non sta...
Monetary AmountAnatole Tresch, Werner Keil• Amount = Number + Currency + Operations• How to represent the numeric amount?•...
Monetary Amount (Continued)Anatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneypublic int...
Precision & Roundingjavax.money
Types of Numeric PrecisionAnatole Tresch, Werner Keil• Internal Precision (implied by number representation and arithmetic...
Rounding rounding =Monetary.getRoundingProvider().getRounding(“Argentina”);MontaryAmount myAmount = …;MonetaryAmount round...
Formatting & Parsingjavax.money.format
Formatting & Parsing ChallengesAnatole Tresch, Werner Keil• Different Locale for Translation, Dates, Time, Numbers,Currenc...
Currency Conversionjavax.money.conversion
Currency ConversionAnatole Tresch, Werner Keil• ExchangeRateType• ExchangeRate:• ExchangeRateType• Source, target currency...
Provider & Extensionsjavax.money, javax.money.ext
Provider: Monetary SingletonAnatole Tresch, Werner Keil• javax.money.Monetary provides access to allcomponents• Loading me...
ExtensionsAnatole Tresch, Werner Keil• Idea: allow registration of additional functionalities into Monetary:• Compound Val...
DemoAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoney
Q & AAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoney
Stay TunedAnatole Tresch, Werner Keil• JSR 354: http://jcp.org• Java.net Project: http://java.net/projects/javamoney• GitH...
Upcoming SlideShare
Loading in …5
×

Introduction to JSR 354 (Currency and Money) by Anatole Tresch, Werner Keil

1,442 views

Published on

The presentation introduces JSR 354 (Java Currency and Money). It is shown how the JSR allows to flexible represent and manipulate monetary
amounts in different currencies (including virtual ones). The presentation will discuss some considerations done according to numeric precision.
Finally the presentation will also discuss more advanced usage scenarios such as currency exchange, complex rounding and formatting parsing.
Also included is a running demo that uses the specification in a EE context and also illustrates some of the SPIs defined.

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

Introduction to JSR 354 (Currency and Money) by Anatole Tresch, Werner Keil

  1. 1. Introduction to JSR 354 – Java Money & CurrencyAnatole Tresch, Werner Keilatsticks@java.net @atsticks keilw@java.net @wernerkeilhttp://java.net/projects/javamoney
  2. 2. BiosAnatole Tresch• Consultant - Coach• Software and FrameworkArchitect• Open Source Addicted• Credit Suisse• Specification LeadJSR 354Anatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneyWerner Keil• Consultant – Coach• Creative Cosmopolitan• Open Source Evangelist• Software Architect• Java Godfather• JCP Executive CommitteeMember• Eclipse UOMo Project Lead• DevOps Guy• Expert Group JSR 354
  3. 3. Agenda• History and Motivation• Overview• Amounts, Currencies• Numeric precision, Rounding• Formatting & Parsing• Currency Conversion• Provider & Extensions• DemoAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneyScope: Platform (SE)Scope: Standalone
  4. 4. History and Motivation
  5. 5. Earlier ApproachesAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneyEric Evans – Time and Money:On project after project, softwaredevelopers have to reinvent the wheel,creating objects for simple recurringconcepts such as "money" and "currency".Although most languages have a "date" or"time" object, these are rudimentary, anddo not cover many needs, such as recurringsequences of time, durations of time, orintervals of time. …To be quite frank, their code isn‘t more thanan academic POC, factories called dollars()or euros() are useless in real globallydeployed frameworks, but he made a goodpoint.Martin Fowler:A large proportion of thecomputers in this worldmanipulate money, so itsalways puzzled me that moneyisnt actually a first class datatype in any mainstreamprogramming language. Thelack of a type causes problems,the most obvious surroundingcurrencies…seehttp://martinfowler.com/eaaCatalog/money.html
  6. 6. MotivationAnatole Tresch, Werner Keil Monetary values are a key feature to manyapplications The existing java.util.Currency class isstrictly a structure used for representing ISO-4217standard currencies. No standard value type to represent a monetaryamount. No support for currency arithmetic or conversion. JDK Formatting features lack of flexibility.Introduction to JSR 354http://java.net/projects/javamoney
  7. 7. ScheduleAnatole Tresch, Werner Keil• Targeting Java 9• Aiming at Java ME/Embedded 8 or 9– Following the EC Merge and Standard/Embeddedharmonization, no JSR should be SE/EE or ME only, with veryfew, specialized exceptions. Money is so important, and hasalmost no legacy in the JDK except java.util.Currency, that itshould be supported by ALL POSSIBLE platforms, exceptmaybe JavaCard for now.• With back-port to previous versions still supported andin relevant use• EDR: Beginning of April 2013Introduction to JSR 354http://java.net/projects/javamoney
  8. 8. Overview
  9. 9. Overview on JSR 354Anatole Tresch, Werner Keil• Core API: javax.money• CurrencyUnit, MonetaryAmount and exceptions• Conversion API: javax.money.conversion• ExchangeRate, CurrencyConverter• Formatting: javax.money.format• LocalizationStyle, ItemFormatter, ItemParser• Provider singleton: javax.money .Monetary• Extensions: javax.money.ext• Region support, Calculations• Reference Implementation: net.java.javamoney.ri• TCKIntroduction to JSR 354http://java.net/projects/javamoney
  10. 10. Amounts & Currenciesjavax.money
  11. 11. Currencies: What’s all in ISO 4217Anatole Tresch, Werner Keil• Special Codes• For precious metals (XAU, XAG)• for testing (XTS)• no currency (XXX)• Supranational currencies, e.g. East Caribbean dollar, the CFP franc, the CFA franc.• «Ambiguities»:• CFA franc: West African CFA franc and the Central African CFA franc.Although theoretically separate, the two CFA franc currencies are effectivelyinterchangeable.• Switzerland: CHF, CHE (WIR-EURO), CHW (WIR)• USA: USD, USN (next day), USS (same day)• Unmodeled Aspects:• Different legal acceptance, e.g. Indian Rupees are accepted in Buthan/Nepal,but not vice versa• Minor units 1/100, 1/1000, but also 1/5 (Mauritania,Madagaskar), 0.00000001 (BitCoin)Introduction to JSR 354http://java.net/projects/javamoney
  12. 12. Virtual CurrenciesAnatole Tresch, Werner Keil• Video Game Currencies (Gold,Gil, Rupees, Credits, Gold Rings,Hearts, Zenny, Potch, Munny, Nuyen…)• Facebook Credits are a virtual currency you can use to buyvirtual goods in any games or apps of the Facebookplatform that accept payments. You can purchaseFacebook Credits directly from within an app using yourcredit card, PayPal, mobile phone and many other localpayment methods.• Bitcoin (sign: BTC) is a decentralized digital currencybased on an open-source, peer-to-peer internet protocol.It was introduced by a pseudonymous developer namedSatoshi Nakamoto in 2009.Introduction to JSR 354http://java.net/projects/javamoney
  13. 13. Limitations of java.util.CurrencyAnatole Tresch, Werner Keil• No support for historical Currencies• No support for non standard Currencies (e.g. cows orcamels)• No support for virtualCurrencies (Lindon Dollars,BitCoin, Social Currencies)• No support for customschemes (e.g. legacy codes)• Only access by currencycode, or Locale• No support for special usecases/extensionsIntroduction to JSR 354http://java.net/projects/javamoneypublic interface CurrencyUnit{public String getCurrencyCode();public int getNumericCode();public intgetDefaultFractionDigits();// new methodspublic String getNamespace();public boolean isLegalTender();public boolean isVirtual();public Long getValidFrom();public Long getValidUntil();public <T> T getAttribute(String key, Class<T> type);public Enumeration<String>getAttributeKeys();public Class<?> getAttributeType(String key);}
  14. 14. Monetary AmountAnatole Tresch, Werner Keil• Amount = Number + Currency + Operations• How to represent the numeric amount?• Performant (e.g. for trading)• Precise (e.g. for calculations)• For small numbers (e.g. webshop)• For huge Numbers (e.g. risk calulations, statistics)• Rounding, Precision, ScaleIntroduction to JSR 354http://java.net/projects/javamoneySolution: allow different number representations!
  15. 15. Monetary Amount (Continued)Anatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoneypublic interface MonetaryAmount{public CurrencyUnit getCurrency();public Class<?> getNumberType();public <T> T asType(Class<T>);public int intValue(); public int intValueExact();public long longValue(); public long longValueExact();[…]public MonetaryAmount abs();public MonetaryAmount min(…);public MonetaryAmount max(…);public MonetaryAmount add(…);public MonetaryAmount subtract(…);public MonetaryAmount divide(…);public MonetaryAmount[] divideAndRemainder(…);public MonetaryAmount divideToIntegralValue(…);public MonetaryAmount remainder(…);public MonetaryAmount multiply(…);public MonetaryAmount with(Number amount);[…]public int getScale(); public int getPrecision();[…]public boolean isPositive(); public boolean isPositiveOrZero();public boolean isNegative(); public boolean isNegativeOrZero();public boolean lessThan(…);public boolean lessThanOrEqualTo(…);[…]}Access Currency andNumber part.AlgorithmicOperations…Data Representationand Comparison .
  16. 16. Precision & Roundingjavax.money
  17. 17. Types of Numeric PrecisionAnatole Tresch, Werner Keil• Internal Precision (implied by number representation and arithmetic)• External Precision (rounding applied when a numeric value of anamount is accessed)• Formatting Precision (rounding applied for display and output)• Interoperability Challenges• Different precision/scale• Different numeric representations• SerializationBy default only internal rounding is applied automatically.Introduction to JSR 354http://java.net/projects/javamoney
  18. 18. Rounding rounding =Monetary.getRoundingProvider().getRounding(“Argentina”);MontaryAmount myAmount = …;MonetaryAmount rounded =rounding.round(myAmount);Rounding APIAnatole Tresch, Werner Keil• External Rounding and Formatting Rounding can be implemented in many ways,depending on the use cases:• Example for non standard-rounding: Argentina:• If the third digit is 2 or less, change it to 0 or drop it.• If the third digit is between 3 and 7, change it to 5.• If the third digit is 8 or more, add one to the second digit and drop the third digit or change itto 0.Introduction to JSR 354http://java.net/projects/javamoneypublic interface Rounding{public MonetaryAmount round(MonetaryAmount );}OriginalNumberRounded Notes123.452 123.45 Third digit<3 round down123.456 123.455 3<=third digit<=7 change to 5123.459 123.46 Third digit>=8 round up
  19. 19. Formatting & Parsingjavax.money.format
  20. 20. Formatting & Parsing ChallengesAnatole Tresch, Werner Keil• Different Locale for Translation, Dates, Time, Numbers,Currencies• Additional configuration• Currency Placement, Rounding, Lenient Fractions, Min, Max,legal units, customer group etc.• Natural language supportfor non-decimal valuations,eg.– Lakhs, Crores (1 Lakh =100,000, 1 Crore = 100 Lakh)– INR 12,34,56,000.21 is written12 Crore, 34 Lakh, 56 ThousandRupees and 21 Paise• Different styles.Introduction to JSR 354http://java.net/projects/javamoneyDefine LocalizationStyle andaccording ItemFormatter/-Parserpublic class LocalizationStyleimplements Serializable {[…]public String getId();public Locale getTranslationLocale();public Locale getNumberLocale();public Locale getDateLocale();public Locale getTimeLocale();public Map<String, Object> getAttributes() ;public <T> T getAttribute(String key, Class<T> type);public static LocalizationStyle of(Locale locale);public boolean isDefaultStyle() ;[…]}
  21. 21. Currency Conversionjavax.money.conversion
  22. 22. Currency ConversionAnatole Tresch, Werner Keil• ExchangeRateType• ExchangeRate:• ExchangeRateType• Source, target currency• Conversion Factor• Validity Range (from/until)• Provider (optional)• Direct/Derived Rate• Attributes• ExchangeRateProvider• CurrencyConverterIntroduction to JSR 354http://java.net/projects/javamoneypublic interface ExchangeRate {public ExchangeRateType getExchangeRateType();public CurrencyUnit getSource();public CurrencyUnit getTarget();public Number getFactor();public Long getValidFrom();public Long getValidUntil();public boolean isValid();public String getProvider();public ExchangeRate[] getExchangeRateChain();public boolean isDerived();public boolean isIdentity();public <T> T getAttribute(String key,Class<T> type);public Enumeration<String> getAttributeKeys();public Class<?> getAttributeType(String key);}ExchangeRateType rateType = …;CurrencyConverter conv =Monetary.getCurrencyConverter(rateType);
  23. 23. Provider & Extensionsjavax.money, javax.money.ext
  24. 24. Provider: Monetary SingletonAnatole Tresch, Werner Keil• javax.money.Monetary provides access to allcomponents• Loading mechanism is configurable, e.g.• ServiceLoader (default)• CDI• Spring• …Introduction to JSR 354http://java.net/projects/javamoneypublic final class Monetary{public static MonetaryAmountProvider getMonetaryAmountProvider(Class<?> numberClass);public static MonetaryAmountProvider getMonetaryAmountProvider()public static CurrencyUnitProvider getCurrencyUnitProvider();public static ConversionProvider getConversionProvider();public static ItemFormatterFactory getItemFormatterFactory();public static ItemParserFactory getItemParserFactory();public static RoundingProvider getRoundingProvider();public static <T> T getExtension(Class<T> extensionType);public static boolean isExtensionAvailable(Class<?> type);public static Enumeration<Class<?>> getLoadedExtensions();}+Extensions
  25. 25. ExtensionsAnatole Tresch, Werner Keil• Idea: allow registration of additional functionalities into Monetary:• Compound Values• Utilities and Calculation Modules• Regions/Regional Providers• To be discussed:• what extensions should be part of the JSR?• Should extensions by part of this JSR at all?Introduction to JSR 354http://java.net/projects/javamoneyCalculationUtils utils =Monetary.getExtension(CalculationUtils.class);utils.total(…);
  26. 26. DemoAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoney
  27. 27. Q & AAnatole Tresch, Werner Keil Introduction to JSR 354http://java.net/projects/javamoney
  28. 28. Stay TunedAnatole Tresch, Werner Keil• JSR 354: http://jcp.org• Java.net Project: http://java.net/projects/javamoney• GitHub Project: https://github.com/JavaMoney/javamoney• Eclipse UOMo: http://www.eclipse.org/uomo• Twitter: @jsr354Introduction to JSR 354http://java.net/projects/javamoney

×