SlideShare a Scribd company logo
JSR 354: Money and Currency API
Rajmahendra Hegde
JUGChennai Lead
Tweets: @rajonjava
JavaOne India 2013 Hyderabad 8th & 9th M
Bio
Rajmahendra Hegde
 Founder and Leader of JUGChennai
 Working for CGI as Project Lead/Architect
 Individual JCP Member
 Committer: Visage, ScalaFX,
 Interest: JEE, Glassfish, Groovy, Scala, JavaFX, Visage, ScalaFX, Gradle,
Netbeans
Agenda
> History and Motivation
> Overview
> Currencies and Amounts
> Precision and Rounding
> Formatting and Parsing
> Currency Conversion
> Currency Services and Extensions
> Extras
> Adopt – A – JSR
> TrakStok
> Demo
Platform (SE) Scope1
Standalone Scope
1 See http://mreinhold.org/blog/secure-the-train
this may no longer be part of Money API 1.0
History and Motivation
Gold coin of Muhammad bin Sam showing the Goddess Lakshmi
Minted in Delhi, AD 1192 - 1206
This gold coin features a stylized image of the Hindu goddess Lakshmi. It
is an image which was prevalent on coins throughout the Indian sub-
continent for over a millennium, so much so that it was even used by
Muslim rulers.
Source: http://www.britishmuseum.org/explore/highlights/highlight_objects/cm/g/gold_coin_of_muhammad_ibn_sam.aspx
Earlier Approaches
Martin Fowler:
A large proportion of the computers in this
world manipulate money, so it’s always
puzzled me that money isn’t actually a first
class data type in any mainstream
programming language. The lack of a type
causes problems, the most obvious
surrounding currencies…
see
http://martinfowler.com/eaaCatalog/money.html
Eric Evans – Time and Money:
On project after project, software developers have
to reinvent the wheel, creating objects for simple
recurring concepts such as “money” and
“currency”. Although most languages have a
“date” or “time” object, these are rudimentary, and
do not cover many needs, such as recurring
sequences of time, durations of time, or intervals
of time. …
To be quite frank, their code isn’t more than an
academic POC, factories called dollars() or
euros() are useless in real globally deployed
frameworks, but he made a good point.
Motivation
> Monetary values are a key feature to many applications and it’s a very important
scope of any general purpose language
> Existing java.util.Currency class is strictly a structure used for representing
ISO-4217 standard currencies.
> No standard value type to represent a monetary amount
> No support for currency arithmetic or conversion
> JDK Formatting features lack flexibility
Schedule
> Standalone JSR
 EDR: April 2013 - Just started
> Java ME/Embedded 8 oder 9
 Following the EC Merge and Standard/Embedded harmonization, no JSR should be SE/EE or
ME only. Money is so important, and has almost no legacy in the JDK except
java.util.Currency, that it should be supported by all possible platforms, except maybe
JavaCard for now.
> Minimum Java Version: 7 (given, 8 won’t be here till 2014)
with reasonable support of previous Java versions
still relevant (e.g. Java 6)
 Java SE 9: Early 2016
 Either a Maintenance Release or new version of this JSR shall be integrated
with
OpenJDK 9.
JSR Renewal Ballot - 2013-02-04
Overview
Overview of JSR 354
> Core API: javax.money
 CurrencyUnit, MonetaryAmount and exceptions
> Conversion API: javax.money.conversion
 ExchangeRate, CurrencyConverter
> Formatting: javax.money.format
 LocalizationStyle, ItemFormatter, ItemParser
> Extensions: javax.money.ext
 Region support, compound values
 MonetaryCurrencies,…
> Reference Implementation: net.java.javamoney.ri
> TCK: net.java.javamoney.tck
Currencies and Amounts
javax.money
Currencies
ISO 4217
Special Codes
Ambiguities
Unmodeled Aspects
Minor units
• Precious Metals (XAU, XAG)
• Testing (XTS)
• No Currency (XXX)
• Supranational currencies, e.g. East Caribbean dollar, the CFP
franc, the CFA franc.
• CFA franc: West African CFA franc und Central African CFA
franc = denotes 2 effectively interchangeable (!).
• Switzerland: CHF, CHE (WIR-EURO), CHW (WIR)
• USA: USD, USN (next day), USS (same day)
Legal acceptance, e.g. Indian Rupees are legally accepted in
Bhutan/Nepal, but not vice versa!
Typically 1/100, rarely 1/1000, but also 1/5
(Mauritania, Madagascar), 0.00000001 (Bitcoin)
Virtual Currencies
> Video Game Currencies (Gold, Gil, Rupees, Credits, Gold Rings, Hearts, Zenny,
Potch, Munny, Nuyen…)
> Facebook Credits are a virtual currency you can use to buy
virtual goods in any games or apps of the Facebook
platform that accept payments. You can purchase
Facebook Credits directly from within an app using your
credit card, PayPal, mobile phone and many other local
payment methods.
> Bitcoin (sign: BTC) is a decentralized digital currency
based on an open-source, peer-to-peer internet protocol.
It was introduced by a pseudonymous developer named
Satoshi Nakamoto in 2009.
Improve java.util.Currency
Current Limitations
> No support for historical Currencies
> No support for non standard Currencies
(e.g. cows or camels)
> No support for virtual
Currencies (Lindon Dollars Brixton Pound,
Bitcoin, Social Currencies)
> No support for custom
schemes (e.g. legacy codes)
> Only access by currency
code, or Locale
> No support for special use
cases/extensions
Implementation:
MoneyCurrency
public interface CurrencyUnit{
public String getCurrencyCode();
public int getNumericCode();
public int getDefaultFractionDigits();
// new methods
public String getNamespace();
public boolean isLegalTender();
public boolean isVirtual();
public Long getValidFrom();
public Long getValidUntil();
}
public interface Localizable{
public String getDisplayName(Locale locale);
}
Access/Create Currencies
Usage
/**
* Shows simple creation of a CurrencyUnit for ISO, backed by JDK
* Currency implementation.
*/
public void forISOCurrencies() {
CurrencyUnit currency = MoneyCurrency.of("USD"); // backed up util.Currency!
currency = MoneyCurrency.of("myNamespace", "myCode"); // may be null!
}
Access/Create Currencies
Usage (continued)
public void buildACurrencyUnit() {
MoneyCurrency.Builder builder = new MoneyCurrency.Builder();
builder.setNamespace("myNamespace");
builder.setCurrencyCode("myCode");
builder.setDefaultFractionDigits(4);
builder.setLegalTender(false);
builder.setValidFrom(System.currentTimeMillis());
builder.setVirtual(true);
CurrencyUnit unit = builder.build();
// nevertheless MoneyCurrency.of("myNamespace", "myCode"); still returns
// null, since the instance created is not added to the cache for reuse!
unit = builder.build(true);
// now it is added to the cache, so the unit == unit2
CurrencyUnit unit2 = MoneyCurrency.of("myNamespace", "myCode"); }
Monetary Amount
Amount = Number + Currency + Operations
How to represent the numeric amount? Contradictory requirements:
 Performance (e.g. for trading)
 Precision and Scale (e.g. for calculations)
 Must model small numbers (e.g. web shop)
 Must support large Numbers (e.g. risk calculations, statistics)
 Rounding
 Financial Operations and Functions, function chaining
Solution:
• support several numeric representations!
• MonetaryFunction similar to java.function.Function
• MonetaryOperator similar to java.function.UnaryOperator
Monetary Amount (continued)
public 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 substract(…);
public MonetaryAmount divide(…);
public MonetaryAmount[] divideAndRemainder(…);
public MonetaryAmount divideToIntegralValue(…);
public MonetaryAmount remainder(…);
public MonetaryAmount multiply(…);
public MonetaryAmount withAmount(Number amount);
[…]
public int getScale(); public int getPrecision();
[…]
public boolean isPositive(); public boolean isPositiveOrZero();
public boolean isNegative(); public boolean isNegativeOrZero();
public boolean isLessThan(…);
public boolean isLessThanOrEqualTo(…);
[…]
public MonetaryAmount with(MonetaryOperator op);
}
Algorithmic Operations…
Data Representation and
Comparison.
Data Access.
Implementation:
Money
Monetary Function, Monetary Operator
//@FunctionalInterface for Java 9
public interface MonetaryFunction<T, R> {
public R apply(T value);
}
Implementations:
MinorPart
MajorPart
Reciprocal
MonetaryRounding
CurrencyConversion
//@FunctionalInterface for Java 9
public interface MonetaryOperator
extends
MonetaryFunction<MonetaryAmount,MonetaryAmount> {
}
Implementations:
Minimum
Maximum
Average
SeparateAmount
SeparateCurrencies
Total
Creating Amounts
Usage
/**
* Simplest case create an amount with an ISO currency.
*/
public void forISOCurrencies() {
Money amount = Money.of("USD", 1234566.15); // using ISO namespace by default
}
/**
* Create an amount using a custom currency.
*/
public void forCustomCurrencies() {
CurrencyUnit currency = MoneyCurrency.of(
"myNamespace", "myCode");
Money amount = Money.of(currency, 1234566.15);
}
Precision and Rounding
javax.money
Numeric Precision
> Internal Precision (implied by internal number type)
> External Precision (Rounding applied, when the numeric part is accessed/passed
outside)
> Formatting Precision (Rounding for display and output)
> Interoperability
– Different precision/scale
– Distinct numeric representations
– Serialization
By default
• only internal rounding is applied automatically.
• The precision/scale capabilities of an MonetaryAmount are inherited to
its operational results
Mixing Numeric Representations
• Mechanism applies similarly for operation chaining
Money amt1 = Money.of(“CHF”, 10.23d);
IntegralMoney amt2 = IntegralMoney.of(“CHF”, 123456789);
MonetaryAmount result = amt1.add(amt2);
// returns Money instance, since its the class on which
// add() was called.
Money amt1 = …;
IntegralMoney amt2 = …;
CurrencyConversion conversion = …;
MonetaryAmount result = amt1
.add(amt2)
.multiply(2)
.with(conversion)
.round(MoneyRounding.of());
Rounding
> External Rounding and Formatting Rounding can be implemented in many ways,
depending on the use cases
> Rounding is modeled as a MonetaryOperator
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 it to 0.
Original Rounded Remark
123.452 123.45 3. digit <3 -> round down
123.456 123.455 3<= 3. digit <=7 -> change to 5
123.459 123.46 3. digit >=8 -> round up
Implementation:
MoneyRounding
Rounding
Usage
/**
* Round amount based on its currency (defaultFractionUnits).
*/
public MonetaryAmount roundDefault(MonetaryAmount amount){
Rounding rounding = MoneyRounding.of();
return rounding.round(amount);
}
public MonetaryAmount halfConvertAndRound(MonetaryAmount amount,
CurrencyConversion conversion){
return amount.divide(2).with(conversion).with(MoneyRounding.of());
}
Formatting and Parsing
javax.money.format
Formatting and Parsing
Challenges
> Multiple Locale instances for Translation, Dates, Time, Numbers, Currencies
> Additional parameters, e.g. Currency Placement, Rounding, Lenient Fractions, Min,
Max etc.
> Natural language support for non-decimal valuations for example
– Lakhs, Crores (1 Lakh = 100,000,
1 Crore = 100 Lakh)
– INR 12,34,56,000.21 is written 12 Crore, 34 Lakh,
56 Thousand Rupees and 21 Paise
> How handle different formatting styles?
 LocalizationStyle
 ItemFormat
 ItemFormatBuilder
 MonetaryFormats singleton
public class LocalizationStyle
implements 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 boolean isDefaultStyle() ;
[…]
public static LocalizationStyle of(
Locale locale);
}
public interface ItemFormat<T> {
public Class<T> getTargetClass();
public LocalizationStyle getStyle();
public String format(T item);
public void print(Appendable appendable,
T item)
throws IOException;
public T parse(CharSequence input)
throws ParseException;
}
public class ItemFormatBuilder<T> {
private List<FormatToken<T>> tokens = new ArrayList<FormatToken<T>>();
[…]
public ItemFormatBuilder(){…}
public ItemFormatBuilder(Class<T> targetType){…}
public ItemFormatBuilder<T> addToken(FormatToken<T> token) {…}
public ItemFormatBuilder<T> addLiteral(String token) {…}
public boolean isBuildable() {…}
public ItemFormat<T> build() {…}
[…] }
public interface FormatToken<T> {
public void print(Appendable appendable,
T item, LocalizationStyle s)
throws IOException;
public void parse(ParseContext<T> context,
LocalizationStyle style)
throws ItemParseException;
}
Implementations:
LiteralToken
NumberToken
CurrencyToken
AmountToken
…
Formatting and Parsing
ItemFormat, FormatToken and ItemFormatBuilder
Currency Conversion
javax.money.conversion
Currency Conversion
> ExchangeRateType
> ExchangeRate:
– ExchangeRateType
– Base, Term currency
– Conversion factor
– Validity (from/until)
– Provider (optional)
– Direct/Derived Rates
> ConversionProvider/CurrencyConverter
> MonetaryConversions accessor singleton
public interface ExchangeRate {
public ExchangeRateType getExchangeRateType();
public CurrencyUnit getBase();
public CurrencyUnit getTerm();
public BigDecimal getFactor();
public Long getValidFrom();
public Long getValidUntil();
public boolean isValid();
public String getProvider();
public List<ExchangeRate> getExchangeRateChain();
public boolean isDerived();
}
Currency Conversion
Usage
/**
* Shows simple conversion of an amount.
*/
public Money convertAmountToCHF(Money amount){
ConversionProvider provider = MonetaryConversion
.getConversionProvider(ExchangeRateType.of("EZB"));
CurrencyConversion chfConversion = provider.getConverter()
.getCurrencyConversion(MoneyCurrency.of("CHF"));
return amount.with(chfConversion);
}
Currency Services & Extensions
javax.money.ext
> javax.money.MonetaryCurrencies singleton provides
 access to registered namespaces
 access to contained currencies within a namespace
 access to historic currencies
 Mapping of currencies between (or within) namespaces
public final class MonetaryCurrencies{
[…]
public static boolean isNamespaceAvailable(String namespace){…}
public static Collection<String> getNamespaces(){…}
public static boolean isAvailable(String namespace, String code, Long timestamp
public static CurrencyUnit get(String namespace, String code, Long timestamp)
public static Collection<CurrencyUnit> getAll(String namespace)
public static Collection<CurrencyUnit> getAll(String namespace, Long timestamp)
[…]
public static CurrencyUnit map(String targetNamespace, Long timestamp,
CurrencyUnit currencyUnit)
public static List<CurrencyUnit> mapAll(String targetNamespace, Long timestamp, CurrencyUnit... units)
}
Currency Services & Extensions
MonetaryCurrencies Singleton
Extensions
Some Functionalities that may or may not be included with the JSR:
 Calculation Utilities
 Regions/Regional Providers,
e.g. for mapping accepting
currencies, legal tenders etc.
 …
Recent direction:
 If and what extensions are useful
 Some could be factored out into Extras (see next slide)
Extras
Additional Functionalities, not part of the
actual JSR
 Multi-Currency
 Compound Values
 Statistical Modules
 Financial Modules
 CDI Extensions (e.g. via Apache DeltaSpike)
 JavaFX Bindings and Components
 …
Extras are provided:
 as separate javamoney-extras GitHub repository
 What’s in for you, e.g. like javamoney-examples, no full JCP
Membership is required to contribute there, contribute if you want/can…
Adopt – A - JSR
> JUG’s initiative to encourage there members to
contribute to JSRs
> Open for all the Java User Groups
> MainSite: http://adoptajsr.java.net/
> For JSR-354
 London Java Community
 JUGChennai
> Started by JUGChennai
> Currently 5 members on-board
> Built using: current version of JSR-354, Glassfish,
PrimeFaces
> Current Status: Integrating basic design with the JSR,
Integrating EmpireAvenue using Agorava
> Future plan:JavaFX, Mobile (Android & Blackberry),
Identity API (Proposed), Virtual Currency (Proposed)
> GitHub: https://github.com/jugchennaiadoptjava/TrakStok
TrakStok - POC project using JSR-354
Stay Tuned!
• JSR 354: http://jcp.org
• Java.net Project: http://java.net/projects/javamoney
• GitHub Project: https://github.com/JavaMoney/javamoney
• Twitter: @jsr354
Rajmahendra Hegde
rajmahendra@gmail.com
tweet: @rajonjava
Java User Group Chennai
http://jugchennai.in
Twitter: jug_chennai
GoogleGroup: jugchennai
FacebookGroup: chennai.jug
GitHub Org: jugchennai

More Related Content

Viewers also liked

About JUGChennai 2011
About JUGChennai 2011About JUGChennai 2011
About JUGChennai 2011
Rajmahendra Hegde
 
JUGChennai UserGroup BestPractices
JUGChennai UserGroup BestPracticesJUGChennai UserGroup BestPractices
JUGChennai UserGroup BestPractices
Rajmahendra Hegde
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Rajmahendra Hegde
 
mobile phone based patient care
mobile phone based patient caremobile phone based patient care
mobile phone based patient care
imran2
 
Monetize your idea! By Orkun Saitoglu
Monetize your idea! By Orkun SaitogluMonetize your idea! By Orkun Saitoglu
Monetize your idea! By Orkun Saitoglu
Codemotion
 
Hyderabad Scala Community first meetup
Hyderabad Scala Community first meetupHyderabad Scala Community first meetup
Hyderabad Scala Community first meetup
Rajmahendra Hegde
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
RichardWarburton
 
JavaFX JumpStart @JavaOne 2016
JavaFX JumpStart @JavaOne 2016JavaFX JumpStart @JavaOne 2016
JavaFX JumpStart @JavaOne 2016
Hendrik Ebbers
 

Viewers also liked (9)

About JUGChennai 2011
About JUGChennai 2011About JUGChennai 2011
About JUGChennai 2011
 
JUGChennai UserGroup BestPractices
JUGChennai UserGroup BestPracticesJUGChennai UserGroup BestPractices
JUGChennai UserGroup BestPractices
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
mobile phone based patient care
mobile phone based patient caremobile phone based patient care
mobile phone based patient care
 
Monetize your idea! By Orkun Saitoglu
Monetize your idea! By Orkun SaitogluMonetize your idea! By Orkun Saitoglu
Monetize your idea! By Orkun Saitoglu
 
Javafx
JavafxJavafx
Javafx
 
Hyderabad Scala Community first meetup
Hyderabad Scala Community first meetupHyderabad Scala Community first meetup
Hyderabad Scala Community first meetup
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 
JavaFX JumpStart @JavaOne 2016
JavaFX JumpStart @JavaOne 2016JavaFX JumpStart @JavaOne 2016
JavaFX JumpStart @JavaOne 2016
 

Similar to JSR 354 - Money and Currency API

Go for the Money - JSR 354
Go for the Money - JSR 354Go for the Money - JSR 354
Go for the Money - JSR 354
Anatole Tresch
 
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !jazoon13
 
Adopt JSR 354
Adopt JSR 354Adopt JSR 354
Adopt JSR 354
Anatole Tresch
 
JSR 354 LJC-Hackday
JSR 354 LJC-HackdayJSR 354 LJC-Hackday
JSR 354 LJC-Hackday
Anatole Tresch
 
JSR 354 Hackday - What you can do...
JSR 354 Hackday - What you can do...JSR 354 Hackday - What you can do...
JSR 354 Hackday - What you can do...
Anatole Tresch
 
JSR 354: Money and Currency API - Short Overview
JSR 354: Money and Currency API - Short OverviewJSR 354: Money and Currency API - Short Overview
JSR 354: Money and Currency API - Short Overview
Werner Keil
 
JUGChennai and Adopt-a-JSR program
JUGChennai and Adopt-a-JSR programJUGChennai and Adopt-a-JSR program
JUGChennai and Adopt-a-JSR program
Rajmahendra Hegde
 
Skye Wallet Pitch Deck
Skye Wallet Pitch DeckSkye Wallet Pitch Deck
Skye Wallet Pitch Deck
OlawaleOAjayi
 
Smartphone Behavior On A Featurephone Budget
Smartphone Behavior On A Featurephone BudgetSmartphone Behavior On A Featurephone Budget
Smartphone Behavior On A Featurephone Budget
Gail Frederick
 
AMAN .PPT.pptx
AMAN .PPT.pptxAMAN .PPT.pptx
AMAN .PPT.pptx
AmandeepWebthinknext
 
JSR354 Utrecht JUG 20171027
JSR354 Utrecht JUG 20171027JSR354 Utrecht JUG 20171027
JSR354 Utrecht JUG 20171027
Wim van Haaren
 
Refactor Large apps with Backbone
Refactor Large apps with BackboneRefactor Large apps with Backbone
Refactor Large apps with Backbone
devObjective
 
Refactor Large applications with Backbone
Refactor Large applications with BackboneRefactor Large applications with Backbone
Refactor Large applications with Backbone
ColdFusionConference
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.js
Stacy London
 
How to Get Rich with Cryptocurrency
How to Get Rich with CryptocurrencyHow to Get Rich with Cryptocurrency
How to Get Rich with Cryptocurrency
RuviSamarasekera
 
Technical Team Leader- Paula Mansour
Technical Team Leader- Paula MansourTechnical Team Leader- Paula Mansour
Technical Team Leader- Paula MansourPaula Mansour
 
Curriculum_Vitae
Curriculum_VitaeCurriculum_Vitae
Curriculum_VitaeAjay Sharma
 
Refactor to Reactive With Spring 5 and Project Reactor
Refactor to Reactive With Spring 5 and Project ReactorRefactor to Reactive With Spring 5 and Project Reactor
Refactor to Reactive With Spring 5 and Project Reactor
EatDog
 

Similar to JSR 354 - Money and Currency API (20)

Go for the Money - JSR 354
Go for the Money - JSR 354Go for the Money - JSR 354
Go for the Money - JSR 354
 
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !
JAZOON'13 - Anatole Tresch - Go for the money (JSR 354) !
 
Adopt JSR 354
Adopt JSR 354Adopt JSR 354
Adopt JSR 354
 
JSR 354 LJC-Hackday
JSR 354 LJC-HackdayJSR 354 LJC-Hackday
JSR 354 LJC-Hackday
 
JSR 354 Hackday - What you can do...
JSR 354 Hackday - What you can do...JSR 354 Hackday - What you can do...
JSR 354 Hackday - What you can do...
 
JSR 354: Money and Currency API - Short Overview
JSR 354: Money and Currency API - Short OverviewJSR 354: Money and Currency API - Short Overview
JSR 354: Money and Currency API - Short Overview
 
JUGChennai and Adopt-a-JSR program
JUGChennai and Adopt-a-JSR programJUGChennai and Adopt-a-JSR program
JUGChennai and Adopt-a-JSR program
 
Skye Wallet Pitch Deck
Skye Wallet Pitch DeckSkye Wallet Pitch Deck
Skye Wallet Pitch Deck
 
Resume & CV
Resume & CVResume & CV
Resume & CV
 
Smartphone Behavior On A Featurephone Budget
Smartphone Behavior On A Featurephone BudgetSmartphone Behavior On A Featurephone Budget
Smartphone Behavior On A Featurephone Budget
 
AMAN .PPT.pptx
AMAN .PPT.pptxAMAN .PPT.pptx
AMAN .PPT.pptx
 
Travel India
Travel IndiaTravel India
Travel India
 
JSR354 Utrecht JUG 20171027
JSR354 Utrecht JUG 20171027JSR354 Utrecht JUG 20171027
JSR354 Utrecht JUG 20171027
 
Refactor Large apps with Backbone
Refactor Large apps with BackboneRefactor Large apps with Backbone
Refactor Large apps with Backbone
 
Refactor Large applications with Backbone
Refactor Large applications with BackboneRefactor Large applications with Backbone
Refactor Large applications with Backbone
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.js
 
How to Get Rich with Cryptocurrency
How to Get Rich with CryptocurrencyHow to Get Rich with Cryptocurrency
How to Get Rich with Cryptocurrency
 
Technical Team Leader- Paula Mansour
Technical Team Leader- Paula MansourTechnical Team Leader- Paula Mansour
Technical Team Leader- Paula Mansour
 
Curriculum_Vitae
Curriculum_VitaeCurriculum_Vitae
Curriculum_Vitae
 
Refactor to Reactive With Spring 5 and Project Reactor
Refactor to Reactive With Spring 5 and Project ReactorRefactor to Reactive With Spring 5 and Project Reactor
Refactor to Reactive With Spring 5 and Project Reactor
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 

JSR 354 - Money and Currency API

  • 1. JSR 354: Money and Currency API Rajmahendra Hegde JUGChennai Lead Tweets: @rajonjava JavaOne India 2013 Hyderabad 8th & 9th M
  • 2. Bio Rajmahendra Hegde  Founder and Leader of JUGChennai  Working for CGI as Project Lead/Architect  Individual JCP Member  Committer: Visage, ScalaFX,  Interest: JEE, Glassfish, Groovy, Scala, JavaFX, Visage, ScalaFX, Gradle, Netbeans
  • 3. Agenda > History and Motivation > Overview > Currencies and Amounts > Precision and Rounding > Formatting and Parsing > Currency Conversion > Currency Services and Extensions > Extras > Adopt – A – JSR > TrakStok > Demo Platform (SE) Scope1 Standalone Scope 1 See http://mreinhold.org/blog/secure-the-train this may no longer be part of Money API 1.0
  • 4. History and Motivation Gold coin of Muhammad bin Sam showing the Goddess Lakshmi Minted in Delhi, AD 1192 - 1206 This gold coin features a stylized image of the Hindu goddess Lakshmi. It is an image which was prevalent on coins throughout the Indian sub- continent for over a millennium, so much so that it was even used by Muslim rulers. Source: http://www.britishmuseum.org/explore/highlights/highlight_objects/cm/g/gold_coin_of_muhammad_ibn_sam.aspx
  • 5. Earlier Approaches Martin Fowler: A large proportion of the computers in this world manipulate money, so it’s always puzzled me that money isn’t actually a first class data type in any mainstream programming language. The lack of a type causes problems, the most obvious surrounding currencies… see http://martinfowler.com/eaaCatalog/money.html Eric Evans – Time and Money: On project after project, software developers have to reinvent the wheel, creating objects for simple recurring concepts such as “money” and “currency”. Although most languages have a “date” or “time” object, these are rudimentary, and do not cover many needs, such as recurring sequences of time, durations of time, or intervals of time. … To be quite frank, their code isn’t more than an academic POC, factories called dollars() or euros() are useless in real globally deployed frameworks, but he made a good point.
  • 6. Motivation > Monetary values are a key feature to many applications and it’s a very important scope of any general purpose language > Existing java.util.Currency class is strictly a structure used for representing ISO-4217 standard currencies. > No standard value type to represent a monetary amount > No support for currency arithmetic or conversion > JDK Formatting features lack flexibility
  • 7. Schedule > Standalone JSR  EDR: April 2013 - Just started > Java ME/Embedded 8 oder 9  Following the EC Merge and Standard/Embedded harmonization, no JSR should be SE/EE or ME only. Money is so important, and has almost no legacy in the JDK except java.util.Currency, that it should be supported by all possible platforms, except maybe JavaCard for now. > Minimum Java Version: 7 (given, 8 won’t be here till 2014) with reasonable support of previous Java versions still relevant (e.g. Java 6)  Java SE 9: Early 2016  Either a Maintenance Release or new version of this JSR shall be integrated with OpenJDK 9. JSR Renewal Ballot - 2013-02-04
  • 9. Overview of JSR 354 > Core API: javax.money  CurrencyUnit, MonetaryAmount and exceptions > Conversion API: javax.money.conversion  ExchangeRate, CurrencyConverter > Formatting: javax.money.format  LocalizationStyle, ItemFormatter, ItemParser > Extensions: javax.money.ext  Region support, compound values  MonetaryCurrencies,… > Reference Implementation: net.java.javamoney.ri > TCK: net.java.javamoney.tck
  • 11. Currencies ISO 4217 Special Codes Ambiguities Unmodeled Aspects Minor units • Precious Metals (XAU, XAG) • Testing (XTS) • No Currency (XXX) • Supranational currencies, e.g. East Caribbean dollar, the CFP franc, the CFA franc. • CFA franc: West African CFA franc und Central African CFA franc = denotes 2 effectively interchangeable (!). • Switzerland: CHF, CHE (WIR-EURO), CHW (WIR) • USA: USD, USN (next day), USS (same day) Legal acceptance, e.g. Indian Rupees are legally accepted in Bhutan/Nepal, but not vice versa! Typically 1/100, rarely 1/1000, but also 1/5 (Mauritania, Madagascar), 0.00000001 (Bitcoin)
  • 12. Virtual Currencies > Video Game Currencies (Gold, Gil, Rupees, Credits, Gold Rings, Hearts, Zenny, Potch, Munny, Nuyen…) > Facebook Credits are a virtual currency you can use to buy virtual goods in any games or apps of the Facebook platform that accept payments. You can purchase Facebook Credits directly from within an app using your credit card, PayPal, mobile phone and many other local payment methods. > Bitcoin (sign: BTC) is a decentralized digital currency based on an open-source, peer-to-peer internet protocol. It was introduced by a pseudonymous developer named Satoshi Nakamoto in 2009.
  • 13. Improve java.util.Currency Current Limitations > No support for historical Currencies > No support for non standard Currencies (e.g. cows or camels) > No support for virtual Currencies (Lindon Dollars Brixton Pound, Bitcoin, Social Currencies) > No support for custom schemes (e.g. legacy codes) > Only access by currency code, or Locale > No support for special use cases/extensions Implementation: MoneyCurrency public interface CurrencyUnit{ public String getCurrencyCode(); public int getNumericCode(); public int getDefaultFractionDigits(); // new methods public String getNamespace(); public boolean isLegalTender(); public boolean isVirtual(); public Long getValidFrom(); public Long getValidUntil(); } public interface Localizable{ public String getDisplayName(Locale locale); }
  • 14. Access/Create Currencies Usage /** * Shows simple creation of a CurrencyUnit for ISO, backed by JDK * Currency implementation. */ public void forISOCurrencies() { CurrencyUnit currency = MoneyCurrency.of("USD"); // backed up util.Currency! currency = MoneyCurrency.of("myNamespace", "myCode"); // may be null! }
  • 15. Access/Create Currencies Usage (continued) public void buildACurrencyUnit() { MoneyCurrency.Builder builder = new MoneyCurrency.Builder(); builder.setNamespace("myNamespace"); builder.setCurrencyCode("myCode"); builder.setDefaultFractionDigits(4); builder.setLegalTender(false); builder.setValidFrom(System.currentTimeMillis()); builder.setVirtual(true); CurrencyUnit unit = builder.build(); // nevertheless MoneyCurrency.of("myNamespace", "myCode"); still returns // null, since the instance created is not added to the cache for reuse! unit = builder.build(true); // now it is added to the cache, so the unit == unit2 CurrencyUnit unit2 = MoneyCurrency.of("myNamespace", "myCode"); }
  • 16. Monetary Amount Amount = Number + Currency + Operations How to represent the numeric amount? Contradictory requirements:  Performance (e.g. for trading)  Precision and Scale (e.g. for calculations)  Must model small numbers (e.g. web shop)  Must support large Numbers (e.g. risk calculations, statistics)  Rounding  Financial Operations and Functions, function chaining Solution: • support several numeric representations! • MonetaryFunction similar to java.function.Function • MonetaryOperator similar to java.function.UnaryOperator
  • 17. Monetary Amount (continued) public 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 substract(…); public MonetaryAmount divide(…); public MonetaryAmount[] divideAndRemainder(…); public MonetaryAmount divideToIntegralValue(…); public MonetaryAmount remainder(…); public MonetaryAmount multiply(…); public MonetaryAmount withAmount(Number amount); […] public int getScale(); public int getPrecision(); […] public boolean isPositive(); public boolean isPositiveOrZero(); public boolean isNegative(); public boolean isNegativeOrZero(); public boolean isLessThan(…); public boolean isLessThanOrEqualTo(…); […] public MonetaryAmount with(MonetaryOperator op); } Algorithmic Operations… Data Representation and Comparison. Data Access. Implementation: Money
  • 18. Monetary Function, Monetary Operator //@FunctionalInterface for Java 9 public interface MonetaryFunction<T, R> { public R apply(T value); } Implementations: MinorPart MajorPart Reciprocal MonetaryRounding CurrencyConversion //@FunctionalInterface for Java 9 public interface MonetaryOperator extends MonetaryFunction<MonetaryAmount,MonetaryAmount> { } Implementations: Minimum Maximum Average SeparateAmount SeparateCurrencies Total
  • 19. Creating Amounts Usage /** * Simplest case create an amount with an ISO currency. */ public void forISOCurrencies() { Money amount = Money.of("USD", 1234566.15); // using ISO namespace by default } /** * Create an amount using a custom currency. */ public void forCustomCurrencies() { CurrencyUnit currency = MoneyCurrency.of( "myNamespace", "myCode"); Money amount = Money.of(currency, 1234566.15); }
  • 21. Numeric Precision > Internal Precision (implied by internal number type) > External Precision (Rounding applied, when the numeric part is accessed/passed outside) > Formatting Precision (Rounding for display and output) > Interoperability – Different precision/scale – Distinct numeric representations – Serialization By default • only internal rounding is applied automatically. • The precision/scale capabilities of an MonetaryAmount are inherited to its operational results
  • 22. Mixing Numeric Representations • Mechanism applies similarly for operation chaining Money amt1 = Money.of(“CHF”, 10.23d); IntegralMoney amt2 = IntegralMoney.of(“CHF”, 123456789); MonetaryAmount result = amt1.add(amt2); // returns Money instance, since its the class on which // add() was called. Money amt1 = …; IntegralMoney amt2 = …; CurrencyConversion conversion = …; MonetaryAmount result = amt1 .add(amt2) .multiply(2) .with(conversion) .round(MoneyRounding.of());
  • 23. Rounding > External Rounding and Formatting Rounding can be implemented in many ways, depending on the use cases > Rounding is modeled as a MonetaryOperator 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 it to 0. Original Rounded Remark 123.452 123.45 3. digit <3 -> round down 123.456 123.455 3<= 3. digit <=7 -> change to 5 123.459 123.46 3. digit >=8 -> round up Implementation: MoneyRounding
  • 24. Rounding Usage /** * Round amount based on its currency (defaultFractionUnits). */ public MonetaryAmount roundDefault(MonetaryAmount amount){ Rounding rounding = MoneyRounding.of(); return rounding.round(amount); } public MonetaryAmount halfConvertAndRound(MonetaryAmount amount, CurrencyConversion conversion){ return amount.divide(2).with(conversion).with(MoneyRounding.of()); }
  • 26. Formatting and Parsing Challenges > Multiple Locale instances for Translation, Dates, Time, Numbers, Currencies > Additional parameters, e.g. Currency Placement, Rounding, Lenient Fractions, Min, Max etc. > Natural language support for non-decimal valuations for example – Lakhs, Crores (1 Lakh = 100,000, 1 Crore = 100 Lakh) – INR 12,34,56,000.21 is written 12 Crore, 34 Lakh, 56 Thousand Rupees and 21 Paise > How handle different formatting styles?  LocalizationStyle  ItemFormat  ItemFormatBuilder  MonetaryFormats singleton public class LocalizationStyle implements 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 boolean isDefaultStyle() ; […] public static LocalizationStyle of( Locale locale); }
  • 27. public interface ItemFormat<T> { public Class<T> getTargetClass(); public LocalizationStyle getStyle(); public String format(T item); public void print(Appendable appendable, T item) throws IOException; public T parse(CharSequence input) throws ParseException; } public class ItemFormatBuilder<T> { private List<FormatToken<T>> tokens = new ArrayList<FormatToken<T>>(); […] public ItemFormatBuilder(){…} public ItemFormatBuilder(Class<T> targetType){…} public ItemFormatBuilder<T> addToken(FormatToken<T> token) {…} public ItemFormatBuilder<T> addLiteral(String token) {…} public boolean isBuildable() {…} public ItemFormat<T> build() {…} […] } public interface FormatToken<T> { public void print(Appendable appendable, T item, LocalizationStyle s) throws IOException; public void parse(ParseContext<T> context, LocalizationStyle style) throws ItemParseException; } Implementations: LiteralToken NumberToken CurrencyToken AmountToken … Formatting and Parsing ItemFormat, FormatToken and ItemFormatBuilder
  • 29. Currency Conversion > ExchangeRateType > ExchangeRate: – ExchangeRateType – Base, Term currency – Conversion factor – Validity (from/until) – Provider (optional) – Direct/Derived Rates > ConversionProvider/CurrencyConverter > MonetaryConversions accessor singleton public interface ExchangeRate { public ExchangeRateType getExchangeRateType(); public CurrencyUnit getBase(); public CurrencyUnit getTerm(); public BigDecimal getFactor(); public Long getValidFrom(); public Long getValidUntil(); public boolean isValid(); public String getProvider(); public List<ExchangeRate> getExchangeRateChain(); public boolean isDerived(); }
  • 30. Currency Conversion Usage /** * Shows simple conversion of an amount. */ public Money convertAmountToCHF(Money amount){ ConversionProvider provider = MonetaryConversion .getConversionProvider(ExchangeRateType.of("EZB")); CurrencyConversion chfConversion = provider.getConverter() .getCurrencyConversion(MoneyCurrency.of("CHF")); return amount.with(chfConversion); }
  • 31. Currency Services & Extensions javax.money.ext
  • 32. > javax.money.MonetaryCurrencies singleton provides  access to registered namespaces  access to contained currencies within a namespace  access to historic currencies  Mapping of currencies between (or within) namespaces public final class MonetaryCurrencies{ […] public static boolean isNamespaceAvailable(String namespace){…} public static Collection<String> getNamespaces(){…} public static boolean isAvailable(String namespace, String code, Long timestamp public static CurrencyUnit get(String namespace, String code, Long timestamp) public static Collection<CurrencyUnit> getAll(String namespace) public static Collection<CurrencyUnit> getAll(String namespace, Long timestamp) […] public static CurrencyUnit map(String targetNamespace, Long timestamp, CurrencyUnit currencyUnit) public static List<CurrencyUnit> mapAll(String targetNamespace, Long timestamp, CurrencyUnit... units) } Currency Services & Extensions MonetaryCurrencies Singleton
  • 33. Extensions Some Functionalities that may or may not be included with the JSR:  Calculation Utilities  Regions/Regional Providers, e.g. for mapping accepting currencies, legal tenders etc.  … Recent direction:  If and what extensions are useful  Some could be factored out into Extras (see next slide)
  • 34. Extras Additional Functionalities, not part of the actual JSR  Multi-Currency  Compound Values  Statistical Modules  Financial Modules  CDI Extensions (e.g. via Apache DeltaSpike)  JavaFX Bindings and Components  … Extras are provided:  as separate javamoney-extras GitHub repository  What’s in for you, e.g. like javamoney-examples, no full JCP Membership is required to contribute there, contribute if you want/can…
  • 35. Adopt – A - JSR > JUG’s initiative to encourage there members to contribute to JSRs > Open for all the Java User Groups > MainSite: http://adoptajsr.java.net/ > For JSR-354  London Java Community  JUGChennai
  • 36. > Started by JUGChennai > Currently 5 members on-board > Built using: current version of JSR-354, Glassfish, PrimeFaces > Current Status: Integrating basic design with the JSR, Integrating EmpireAvenue using Agorava > Future plan:JavaFX, Mobile (Android & Blackberry), Identity API (Proposed), Virtual Currency (Proposed) > GitHub: https://github.com/jugchennaiadoptjava/TrakStok TrakStok - POC project using JSR-354
  • 37. Stay Tuned! • JSR 354: http://jcp.org • Java.net Project: http://java.net/projects/javamoney • GitHub Project: https://github.com/JavaMoney/javamoney • Twitter: @jsr354
  • 38.
  • 39. Rajmahendra Hegde rajmahendra@gmail.com tweet: @rajonjava Java User Group Chennai http://jugchennai.in Twitter: jug_chennai GoogleGroup: jugchennai FacebookGroup: chennai.jug GitHub Org: jugchennai