diff --git a/README.md b/README.md index 395d9977..2b352e76 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The current project structure is as follows: - [Simple Console Examples](console/javamoney-console-simple) - [Java 8 Console Examples](console/javamoney-console-java8) - [Java Functional Examples](console/functional-example): examples using Java 8 with streams, lambda and money-api + - [Money Machine](console/moneymachine): Adopt JSR API Testing project for getting feedback on the API - [JavaFX examples](javafx) - [JavaFX Demo application](javafx/money-fxdemo) - [JavaFX binding examples](javafx/money-javafx-binding) diff --git a/console/moneymachine/.gitignore b/console/moneymachine/.gitignore new file mode 100644 index 00000000..2a704d59 --- /dev/null +++ b/console/moneymachine/.gitignore @@ -0,0 +1,4 @@ +target/ +*.iml +.idea/ +.resourceCache diff --git a/console/moneymachine/LICENSE b/console/moneymachine/LICENSE new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/console/moneymachine/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/console/moneymachine/README.md b/console/moneymachine/README.md new file mode 100644 index 00000000..1d4da258 --- /dev/null +++ b/console/moneymachine/README.md @@ -0,0 +1,4 @@ +moneymachine +============ + +Adopt JSR API Testing project for getting feedback on the API, similar to what has been done for JSR 310. diff --git a/console/moneymachine/pom.xml b/console/moneymachine/pom.xml new file mode 100644 index 00000000..1330daea --- /dev/null +++ b/console/moneymachine/pom.xml @@ -0,0 +1,136 @@ + + + + 4.0.0 + + + javamoney-examples-console + org.javamoney.examples.console + 1.0.1-SNAPSHOT + + + moneymachine + + Money Machine (API Test suite) + http://java.net/projects/javamoney + 2014 + JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with + Money and Currency. + This module is an API test suite to guide a workshop to gain feedback on the API. + + + + JavaMoney + http://javamoney.org + + + + Apache 2 License + Spec + LICENSE.html + repo + + + + + . + . + + jcp_spec + src/license + + + + + atsticks + Anatole Tresch + Credit Suisse + + Specification Lead + + + + + + 3.0.4 + + + + scm:git:https://github.com/atsticks/javamachine.git + master + scm:git:https://github.com/atsticks/javamaschine.git + https://github.com/atsticks/javamaschine + + + + + junit + junit + ${junit.version} + test + + + javax.money + money-api + ${api.version} + + + org.javamoney + moneta + ${impl.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jul-to-slf4j + ${slf4j.version} + + + + + + install + + + + org.apache.maven.wagon + wagon-ssh + 2.4 + + + org.apache.maven.wagon + wagon-webdav-jackrabbit + 2.2 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + true + true + true + ${maven.compile.sourceLevel} + ${maven.compile.targetLevel} + -g + ${project.build.sourceEncoding} + + + + + + diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/Basics.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Basics.java new file mode 100644 index 00000000..139831d2 --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Basics.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.*; +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Collection; +import java.util.Locale; + +/** + * This class has to be implemented and helps us giving feedback on the JSR 354's API. This part of the + * project deals with basic aspects such as getting currencies and creating amounts of different types and with + * different + * capabilities. + *

+ * Created by Anatole on 07.03.14. + */ +public class Basics{ + + /** + * Get a {@link javax.money.CurrencyUnit} using a currency code. + * + * @param currencyCode the currency code + * @return the corresponding CurrencyUnit instance. + * @see javax.money.Monetary + */ + public CurrencyUnit getProvidedCurrency(String currencyCode){ + // throw new UnsupportedOperationException(); + return Monetary.getCurrency(currencyCode); + } + + /** + * Get a {@link javax.money.CurrencyUnit} using a Locale, modeling a country. + * + * @param locale The country locale. + * @return the corresponding CurrencyUnit instance. + * @see javax.money.Monetary + * @see java.util.Locale + */ + public CurrencyUnit getProvidedCurrency(Locale locale){ + throw new UnsupportedOperationException(); + } + + /** + * Create a custom {@link javax.money.CurrencyUnit}. + * + * @param currencyCode the currency code + * @param numericCode the numeric code. + * @param defaultFractionUnits the default fraction units. + * @return the new currency unit instance created. + * @see org.javamoney.moneta.BuildableCurrencyUnit + */ + public CurrencyUnit buildCustomCurrency(String currencyCode, int numericCode, int defaultFractionUnits){ + throw new UnsupportedOperationException(); + } + + /** + * Build and register a {@link javax.money.CurrencyUnit}. + * + * @param currencyCode the currency code (non null). + * @param numericCode the numeric code. + * @param defaultFractionUnits the default fraction units. + * @return the CurrencyUnit. Additionally the unit should be registered, + * so it accessible from {@link }MonetaryCurrencies}. + * @see org.javamoney.moneta.BuildableCurrencyUnit + * @see javax.money.Monetary + */ + public CurrencyUnit buildAndRegisterCustomCurrency(String currencyCode, int numericCode, int defaultFractionUnits){ + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the current registered implementation {@link javax.money.MonetaryAmount} types for amounts. + * + * @return the current amount types. + * @see javax.money.Monetary + */ + public Collection> getMonetaryAmountTypes(){ + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the current registered default implementation {@link javax.money.MonetaryAmount} type for amounts. + * + * @return the current default amount type. + * @see javax.money.Monetary + */ + public Class getDefaultMonetaryAmountType(){ + throw new UnsupportedOperationException(); + } + + /** + * Lookup the a corresponding factory for creating {@link javax.money.MonetaryAmount} instances of a certain type. + * + * @param moneyType the monetary amount's implementation class. + * @return the corresponding factory, not null. + * @see javax.money.Monetary + */ + public MonetaryAmountFactory getMoneyFactory(Class moneyType){ + throw new UnsupportedOperationException(); + } + + /** + * Get an amount with the given amount and currency. THe advanced might try to of an amount that has a + * {@link javax.money.CurrencyUnit}, which is not registered in {@link javax.money.Monetary}. + * + * @param number the amount + * @param currencyCode the currency code + * @return a corresponding amount instance. + * @see javax.money.Monetary + * @see javax.money.MonetaryAmountFactory + */ + public MonetaryAmount getMoney(Number number, String currencyCode){ + throw new UnsupportedOperationException(); + } + + /** + * Converts the given amount to a new amount with the given BigDecimal value and currencyCode. + * + * @param amount the amount + * @param bd the BD number + * @param currencyCode the currency code + * @return a corresponding amount instance. + * @see javax.money.Monetary + * @see javax.money.MonetaryAmountFactory + */ + public MonetaryAmount convertAmount(MonetaryAmount amount, BigDecimal bd, String currencyCode){ + throw new UnsupportedOperationException(); + } + + /** + * Change the numeric capabilities of the given amount to a new capabilities given. + * + * @param amount the amount + * @param scale the maximal scale + * @param precision the target precision + * @param context the MathContext + * @return a corresponding amount instance. + * @see javax.money.Monetary + * @see javax.money.MonetaryAmountFactory + * @see javax.money.MonetaryContext + */ + public MonetaryAmount convertAmount(MonetaryAmount amount, int scale, int precision, MathContext context){ + throw new UnsupportedOperationException(); + } + + /** + * Create a {@link javax.money.MonetaryAmount} that covers the capabilities as defined in the {@link javax.money + * .MonetaryContext}. + * + * @param number the amount + * @param currencyCode the currency code + * @param context the Monetary context + * @return an according money instance + * @see javax.money.Monetary + * @see javax.money.MonetaryAmountFactory + * @see javax.money.MonetaryContext + */ + public MonetaryAmount getMoneyWithContext(Number number, String currencyCode, MonetaryContext context){ + throw new UnsupportedOperationException(); + } + + /** + * Create a {@link javax.money.MonetaryAmount} that covers the following capabilities: + *

+ * Within this test you should query a corresponding implementation type and then of the corresponding amount. + * + * @param number the amount + * @param currencyCode the currency code + * @return an according money instance + * @see javax.money.MonetaryAmounts + * @see javax.money.MonetaryAmountFactory + * @see javax.money.MonetaryContext + */ + public MonetaryAmount getMoneyWithSpecificCapabilities(Number number, String currencyCode){ + throw new UnsupportedOperationException(); + } +} diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/Conversions.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Conversions.java new file mode 100644 index 00000000..861f7f84 --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Conversions.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.CurrencyUnit; +import javax.money.MonetaryAmount; +import javax.money.convert.ConversionContext; +import javax.money.convert.ExchangeRate; +import javax.money.convert.ProviderContext; +import java.time.LocalDate; +import java.util.List; + +/** + * API test class that allows to test out the API for currency conversion. Hint the available providers can be + * evaluated by calling {@link javax.money.convert.MonetaryConversions#getProviderNames()}, by default the moneta + * reference implementation comes with the following providers: + * + * Created by Anatole on 21.03.14. + * + * @see javax.money.convert.MonetaryConversions + */ +public class Conversions { + + /** + * Get the corresponding exchange rate provided by the International Monetary Fonds (IMF). + * + * @param src the source/base {@link javax.money.CurrencyUnit}, not null + * @param tgt the target {@link javax.money.CurrencyUnit}, not null + * @return the rate found. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public ExchangeRate getExchangeRateFromIMF(CurrencyUnit src, CurrencyUnit tgt) { + throw new UnsupportedOperationException(); + } + + /** + * Get the an exchange rate provided by the International Monetary Fonds (IMF) for a given UTC timestamp. + * + * @param src the source/base {@link javax.money.CurrencyUnit}, not null + * @param tgt the target {@link javax.money.CurrencyUnit}, not null + * @param timestamp The target UTC timestamp + * @return the rate found. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public ExchangeRate getExchangeRateWithTime(CurrencyUnit src, CurrencyUnit tgt, LocalDate timestamp) { + throw new UnsupportedOperationException(); + } + + /** + * Converts an amount to the given target currency, using the current default conversion. + * + * @param tgt The target currency + * @param amount the amount to be converted + * @return the converted amount, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.CurrencyConversion + * @see javax.money.MonetaryOperator + */ + public MonetaryAmount convertAmountDefault(CurrencyUnit tgt, MonetaryAmount amount) { + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the current default Conversion Context. + * + * @param src the source/base {@link javax.money.CurrencyUnit}, not null + * @param tgt the target {@link javax.money.CurrencyUnit}, not null + * @return the converted amount, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.CurrencyConversion + * @see javax.money.MonetaryOperator + */ + public ConversionContext getDefaultConversionContext(CurrencyUnit src, CurrencyUnit tgt) { + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the Provider Context of the IMF provider. Optionally print the details to the console. + * + * @return the ConversionContext, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public ProviderContext getIMFProviderContext() { + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the Provider Context of the ECB provider. Optionally print the details to the console. + * + * @return the ConversionContext, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public ProviderContext getECBProviderContext() { + throw new UnsupportedOperationException(); + } + + /** + * Evaluate the Provider Context of the ECB provider. Optionally print the details to the console. + * + * @return the ConversionContext, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public ProviderContext getDefaultProviderContext() { + throw new UnsupportedOperationException(); + } + + /** + * Converts an amount to the given target currency, based on the given timestamp. + * + * @param tgt The target currency + * @param amount the amount to be converted + * @param timestamp the target timestamp + * @return the converted amount, not null. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.CurrencyConversion + * @see javax.money.MonetaryOperator + */ + public MonetaryAmount convertAmount(CurrencyUnit tgt, MonetaryAmount amount, LocalDate timestamp) { + throw new UnsupportedOperationException(); + } + + + /** + * Get the default provider chain.

+ * Hint: This is not an API specific target. It is based on the current RI. Nevertheless we might + * discuss, if standardizing this mechanism would make sense. Or if we even would add an additional method + * on {@link javax.money.convert.ExchangeRateProvider} for evaluating this. + * + * @return the provider ID, the test will check, if the provider is correctly registered. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public List getDefaultProviderChain() { + throw new UnsupportedOperationException(); + } + + /** + * Register your own custom {@link }ExchangeRateProvider} implementation and return the according provider ID. + * The test will check, if the provider is visible and print out the according {@link javax.money.convert + * .ProviderContext}. + * + * @return the provider ID, the test will check, if the provider is correctly registered. + * @see javax.money.convert.MonetaryConversions + * @see javax.money.convert.ExchangeRateProvider + */ + public String getNewProviderName() { + throw new UnsupportedOperationException(); + } +} diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/Formatting.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Formatting.java new file mode 100644 index 00000000..8d6a80f3 --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Formatting.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2012, 2013, Werner Keil, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.format.AmountFormatContext; + +import org.javamoney.moneta.format.CurrencyStyle; +import javax.money.format.MonetaryAmountFormat; +import javax.money.format.MonetaryFormats; +import java.util.Collection; +import java.util.Locale; + +/** + * Implement formatting. + * Created by Anatole on 08.03.14. + */ +public class Formatting{ + + /** + * Access a predefined MonetaryFormat using the given style. + * + * @param locale the target locale + * @return the format instance + * @see javax.money.format.MonetaryFormats + */ + public MonetaryAmountFormat getAmountFormat(Locale locale){ + throw new UnsupportedOperationException(); + } + + /** + * Access a predefined MonetaryFormat using the given style. + * + * @param style + * @return the amount format instance + * @see javax.money.format.MonetaryFormats + */ + public MonetaryAmountFormat getAmountFormat(AmountFormatContext style){ + throw new UnsupportedOperationException(); + } + + /** + * Access the locales, for which formatters are available. + * + * @return the locales available. + * @see javax.money.format.MonetaryFormats + */ + public Collection getAvailableLocales(){ + throw new UnsupportedOperationException(); + } + + /** + * Create a customized MonetaryAmountFormat, with: + *

+ * + * @return + */ + public MonetaryAmountFormat createCustomFormat(){ + throw new UnsupportedOperationException(); + } + + + /** + * Get the formatter ID of the registered custom {@link javax.money.format.MonetaryAmountFormat}. + * @return the formatter ID + */ + public String getRegisteredCustomFormat(){ + throw new UnsupportedOperationException(); + } +} diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/MoneyAlgorithmics.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/MoneyAlgorithmics.java new file mode 100644 index 00000000..ee81dc4e --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/MoneyAlgorithmics.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2012, 2013, Werner Keil, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.CurrencyUnit; +import javax.money.MonetaryAmount; +import javax.money.MonetaryOperator; +import javax.money.MonetaryQuery; +import java.math.BigDecimal; +import java.util.List; + +/** + * Class to perform algorithmic calculations and some of the provided external functions on amounts. + * Created by Anatole on 07.03.14. + */ +public class MoneyAlgorithmics { + + /** + * Add up all {@link MonetaryAmount} instances. + * + * @param amounts the amounts (only in one single currency). + * @return the sum of all amounts + */ + public MonetaryAmount addAll(MonetaryAmount... amounts) { + throw new UnsupportedOperationException(); + } + + /** + * Multiply the {@link MonetaryAmount} with the given factor. + * + * @param amount the amount + * @param factor the the factor + * @return the multiplied amount + */ + public MonetaryAmount multiply(MonetaryAmount amount, Number factor) { + throw new UnsupportedOperationException(); + } + + /** + * subtract two {@link MonetaryAmount}s. + * + * @param amount the amount + * @param amt2 the amoun to be + * @return + */ + public MonetaryAmount subtract(MonetaryAmount amount, MonetaryAmount amt2) { + throw new UnsupportedOperationException(); + } + + /** + * Divide an {@link MonetaryAmount}. + * + * @param amount the amount + * @param factor the factor + * @return + */ + public MonetaryAmount divide(MonetaryAmount amount, BigDecimal factor) { + throw new UnsupportedOperationException(); + } + + /** + * Scale an {@link MonetaryAmount}. + * + * @param amount the amount + * @param scale the scale factor + * @return + */ + public MonetaryAmount scaleByTen(MonetaryAmount amount, int scale) { + throw new UnsupportedOperationException(); + } + + /** + * Sort the given {@link MonetaryAmount}s, by currency and number. + * + * @param amounts the amounts + * @return + */ + public List sortAmounts(MonetaryAmount... amounts) { + throw new UnsupportedOperationException(); + } + + /** + * Calculate the sum of only the given amounts, that are of the given currency. + * + * @param targetCurrency the target currency + * @param amounts the amounts to filter and add + * @return the amount's total, in the given target currency. + */ + public MonetaryAmount querySumOf(CurrencyUnit targetCurrency, MonetaryAmount... amounts) { + throw new UnsupportedOperationException(); + } + + /** + * Calculate the reciprocal of the given {@link MonetaryAmount} (1/amount). + * + * @param amount the amount, with the same currency. + * @return the amount's reciprocal value. + */ + public MonetaryAmount calculateReciprocal(MonetaryAmount amount) { + throw new UnsupportedOperationException(); + } + + /** + * Calulculate the given percentage of an {@link MonetaryAmount}. + * + * @param amt the amount + * @param percent the percentage, with the same currency. + * @return the amount's percentage value. + * @see org.javamoney.moneta.function.MonetaryFunctions + */ + public MonetaryAmount calculatePercent(MonetaryAmount amt, double percent) { + throw new UnsupportedOperationException(); + } + + /** + * Calulculate the given permil of an {@link MonetaryAmount}. + * + * @param amt the amount + * @param permil the percentage, with the same currency. + * @return the amount's permil value. + * @see org.javamoney.moneta.function.MonetaryFunctions + */ + public MonetaryAmount calculatePermil(MonetaryAmount amt, double permil) { + throw new UnsupportedOperationException(); + } + + /** + * Get the major part only of the given {@link MonetaryAmount}. + * + * @param amt the amount + * @return the major part of it, with the same currency. + * @see org.javamoney.moneta.function.MonetaryFunctions + * @see org.javamoney.moneta.function.MonetaryUtil + */ + public MonetaryAmount getMajorPart(MonetaryAmount amt) { + throw new UnsupportedOperationException(); + } + + /** + * Calculate a compound interest, defined as {@code }base * (1+interest)^n} + * + * @param base the base amount + * @param rate the interest rate + * @param n the periods + * @return the compound interest. + */ + public MonetaryAmount getCompoundInterest(MonetaryAmount base, double rate, int n) { + throw new UnsupportedOperationException(); + } + + + /** + * Multiply amount with the given factor (advanced).

+ * Hint: The factor may exceed the numeric capabilities of the + * amount implementation given! + * + * @param amount the amount + * @param factor the factor + * @return the correct result + * @see javax.money.MonetaryAmount#getContext() + * @see javax.money.MonetaryContext + * @see javax.money.MonetaryAmounts#getAmountFactory(Class) (javax.money.AmountFactoryQuery) + */ + public MonetaryAmount multiplyAdvanced(MonetaryAmount amount, BigDecimal factor) { + throw new UnsupportedOperationException(); + } + + /** + * Subtract two amounts.

+ * Hint: The valuation may exceed the numeric capabilities of the + * amount implementation given! You should handle this situation, e.g. by using a more appropriate amount + * implementation. + * + * @param amount the base amount + * @param amt2 the amount to be subtracted + * @return the subtraction result + * @see javax.money.MonetaryAmount#getContext() + * @see javax.money.MonetaryContext + * @see javax.money.MonetaryAmounts#getAmountFactory(Class) (javax.money.AmountFactoryQuery) + */ + public MonetaryAmount subtractAdvanced(MonetaryAmount amount, MonetaryAmount amt2) { + throw new UnsupportedOperationException(); + } + + /** + * Divide an amount.

+ * Hint: The valuation may exceed the numeric capabilities of the + * amount implementation given! You should handle this situation, e.g. by using a more appropriate amount + * implementation. + * + * @param amount the amount + * @param factor the factor (divisor) + * @return the division result + * @see javax.money.MonetaryAmount#getContext() + * @see javax.money.MonetaryContext + * @see javax.money.MonetaryAmounts#getAmountFactory(Class) (javax.money.AmountFactoryQuery) + */ + public MonetaryAmount divideAdvanced(MonetaryAmount amount, BigDecimal factor) { + throw new UnsupportedOperationException(); + } + + + /** + * Implement a {@link javax.money.MonetaryOperator} that simply duplicates the amount given. + * + * @return the duplicating operator. + */ + public MonetaryOperator getDuplicateOperator() { + throw new UnsupportedOperationException(); + } + + /** + * Implement a {@link javax.money.MonetaryOperator} that calculates the total of all amounts operated on. + */ + public MonetaryOperator getTotalOperator() { + throw new UnsupportedOperationException(); + } + + /** + * Implement a {@link javax.money.MonetaryQuery} that return {@code true} for each amount, that has an ISO + * currency (as available on {@link java.util.Currency}. + */ + public MonetaryQuery getCountingQuery() { + throw new UnsupportedOperationException(); + } + +} diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/NumericRepresentation.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/NumericRepresentation.java new file mode 100644 index 00000000..f92d0aea --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/NumericRepresentation.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.*; +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Locale; + +/** + * This class has to be implemented and helps us giving feedback on the JSR 354's API. This part of the + * project deals with extraction and modelling of the numeric part of a value. + * + * Created by Anatole on 07.03.14. + */ +public class NumericRepresentation{ + + /** + * Get a {@link java.math.BigDecimal} from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding BigDecimal value + * @see javax.money.MonetaryCurrencies + */ + public BigDecimal getBigDecimal(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get a long (truncated) from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding BigDecimal value + * @see javax.money.MonetaryCurrencies + */ + public long getLongTruncated(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current precision from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding precision value + */ + public int getPrecision(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current scale from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding scale value + */ + public int getScale(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current fraction denominator from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding fraction denominator value + */ + public long getFractionDenominator(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current fraction denominator from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding fraction denominator value + */ + public long getFractionNumerator(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current number representation type from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding number representation type + */ + public Class getNumberType(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Get the current number from the given amount. + * + * @param amount the {@link javax.money.MonetaryAmount} + * @return the corresponding (JDK) number value + */ + public Number getNumber(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + +} diff --git a/console/moneymachine/src/main/java/org/javamoney/adopjsr/Rounding.java b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Rounding.java new file mode 100644 index 00000000..643eb092 --- /dev/null +++ b/console/moneymachine/src/main/java/org/javamoney/adopjsr/Rounding.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012, 2013, Werner Keil, Credit Suisse (Anatole Tresch). Licensed under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. Contributors: Anatole Tresch - initial version. + */ +package org.javamoney.adopjsr; + +import javax.money.MonetaryAmount; +import javax.money.Monetary; +import java.util.Collection; + +/** + * Access roundings based on currency, as well as using customized rounding. + * + * @see javax.money.Monetary + * Created by Anatole on 08.03.14. + */ +public class Rounding{ + + /** + * Round Amounts with the default rounding. + * + * @return the rounded amount + * @see javax.money.Monetary + */ + public MonetaryAmount roundWithDefaultRounding(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + + /** + * Round Amounts with a cash rounding.

+ * Hint: Set the 'cashRounding' property to {@code true}, + * when accessing the rounding. + * + * @return the rounded amount + * @see javax.money.Monetary + * @see javax.money.RoundingContext + */ + public MonetaryAmount roundForCash(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Round Amounts with a mathematical rounding: + *

+ * Hint: Pass the according MathContext as a parameter. + * + * @return the rounded amount + * @see javax.money.MonetaryContext + */ + public MonetaryAmount roundMathematical(MonetaryAmount amount){ + throw new UnsupportedOperationException(); + } + + /** + * Evaluate which roundings are currently available in the system. + * @return the array of rounding ids currently known. + */ + public Collection getKnownRoundings(){ + throw new UnsupportedOperationException(); + } + + /** + * Register your own custom rounding. The test will check, if your rounding is available and perform a test + * rounding. + * + * @return the rounding name of your custom rounding. + */ + public String getCustomRoundingName(){ + throw new UnsupportedOperationException(); + } +} diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/BasicsTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/BasicsTest.java new file mode 100644 index 00000000..6f0c8fb3 --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/BasicsTest.java @@ -0,0 +1,174 @@ +/* + * CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE + * CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. + * PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY + * DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE + * AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" + * BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency + * API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights + * reserved. + */ + +package org.javamoney.adopjsr; + +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.javamoney.moneta.RoundedMoney; +import org.junit.Test; + +import javax.money.*; +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.Collection; +import java.util.Currency; +import java.util.Locale; + +import static org.junit.Assert.*; + +/** + * Test class to ensure the basic core API is well understood. + * Created by Anatole on 07.03.14. + */ +public class BasicsTest { + + private Basics basics = new Basics(); + + @Test + public void testGetProvidedCurrency() throws Exception { + for (Currency cur : Currency.getAvailableCurrencies()) { + assertNotNull(basics.getProvidedCurrency(cur.getCurrencyCode())); + } + } + + @Test + public void testGetProvidedCurrency1() throws Exception { + for (String country : Locale.getISOCountries()) { + Locale locale = new Locale("", country); + try { + Currency.getInstance(locale); + } catch (Exception e) { + continue; + } + assertNotNull(basics.getProvidedCurrency(locale)); + } + } + + @Test + public void testBuildCustomCurrency() throws Exception { + CurrencyUnit cur = basics.buildCustomCurrency("BTC", -1, 10); + assertEquals("BTC", cur.getCurrencyCode()); + assertEquals(-1, cur.getNumericCode()); + assertEquals(10, cur.getDefaultFractionDigits()); + cur = basics.buildCustomCurrency("BarFoo15-t3", 1234, 3); + assertEquals("BarFoo15-t3", cur.getCurrencyCode()); + assertEquals(1234, cur.getNumericCode()); + assertEquals(3, cur.getDefaultFractionDigits()); + } + + @Test + public void testBuildAndRegisterCustomCurrency() throws Exception { + CurrencyUnit cur = basics.buildAndRegisterCustomCurrency("GeeCOIN", 2014, 0); + assertEquals("GeeCOIN", cur.getCurrencyCode()); + assertEquals(2014, cur.getNumericCode()); + assertEquals(0, cur.getDefaultFractionDigits()); + CurrencyUnit unit = Monetary.getCurrency("GeeCOIN"); + assertNotNull("Currency not registered.", unit); + assertEquals("GeeCOIN", unit.getCurrencyCode()); + assertEquals(2014, unit.getNumericCode()); + assertEquals(0, unit.getDefaultFractionDigits()); + } + + @Test + public void testGetMonetaryAmountTypes() throws Exception { + Collection> types = basics.getMonetaryAmountTypes(); + assertNotNull(types); + assertTrue(types.contains(Money.class)); + assertTrue(types.contains(FastMoney.class)); + assertTrue(types.contains(RoundedMoney.class)); + } + + @Test + public void testGetDefaultMonetaryAmountType() throws Exception { + Class type = basics.getDefaultMonetaryAmountType(); + assertNotNull(type); + assertEquals(type, Money.class); + } + + @Test + public void testGetMoneyFactory() throws Exception { + assertNotNull(basics.getMoneyFactory(Money.class)); + assertNotNull(basics.getMoneyFactory(FastMoney.class)); + } + + @Test + public void testGetMoney() throws Exception { + MonetaryAmount amt = basics.getMoney(10.50d, "CHF"); + assertNotNull(amt); + assertEquals("CHF", amt.getCurrency().getCurrencyCode()); + assertEquals(10.50d, amt.getNumber().doubleValue(), 0.0d); + amt = basics.getMoney(Long.MAX_VALUE, "USD"); + assertNotNull(amt); + assertEquals("USD", amt.getCurrency().getCurrencyCode()); + assertEquals(Long.MAX_VALUE, amt.getNumber().longValue()); + } + + @Test + public void testGetMoneyWithContext() throws Exception { + MonetaryContext preciseCtx = MonetaryContextBuilder.of().set("AmountFlavor", "PRECISION").build(); + MonetaryContext fastCtx = MonetaryContextBuilder.of().set("AmountFlavor", "PERFORMANCE").build(); + MonetaryAmount amt = + basics.getMoneyWithContext(new BigDecimal("10.50792323200000000000236823"), "CHF", preciseCtx); + assertNotNull(amt); + assertEquals("CHF", amt.getCurrency().getCurrencyCode()); + assertEquals(new BigDecimal("10.50792323200000000000236823"), amt.getNumber().numberValue(BigDecimal.class)); + amt = basics.getMoneyWithContext(6546546464L, "USD", fastCtx); + assertNotNull(amt); + assertEquals("USD", amt.getCurrency().getCurrencyCode()); + assertEquals(6546546464L, amt.getNumber().longValueExact()); + } + + @Test + public void testGetMoneyWithSpecification() throws Exception { + MonetaryAmount amt = + basics.getMoneyWithSpecificCapabilities(new BigDecimal("10.50792323200000000000236823"), "CHF"); + assertNotNull(amt); + assertEquals("CHF", amt.getCurrency().getCurrencyCode()); + assertEquals(new BigDecimal("10.50792323200000000000236823"), amt.getNumber().numberValue(BigDecimal.class)); + MonetaryContext ctx = amt.getContext(); + assertTrue(ctx.getMaxScale() >= 128); + assertTrue(ctx.getPrecision() >= 256 || ctx.getPrecision() == 0); + assertEquals(ctx.get(RoundingMode.class), RoundingMode.FLOOR); + amt = basics.getMoneyWithSpecificCapabilities(6546546464L, "USD"); + assertNotNull(amt); + assertEquals("USD", amt.getCurrency().getCurrencyCode()); + assertEquals(6546546464L, amt.getNumber().longValueExact()); + assertTrue(ctx.getMaxScale() >= 128); + assertTrue(ctx.getPrecision() >= 256 || ctx.getPrecision() == 0); + assertEquals(ctx.get(RoundingMode.class), RoundingMode.FLOOR); + } + + @Test + public void testConvertAmount() { + MonetaryAmount converted = + basics.convertAmount(Money.of(200, "USD"), new BigDecimal("23628732374387462.87638476"), "GBP"); + assertNotNull(converted); + assertEquals(new BigDecimal("23628732374387462.87638476"), + converted.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()); + assertEquals("GBP", converted.getCurrency().getCurrencyCode()); + } + + @Test + public void testConvertAmountAdvanced() { + MonetaryAmount converted = basics.convertAmount(Money.of(200.234, "USD"), 100, 200, MathContext.UNLIMITED); + assertNotNull(converted); + assertEquals(new BigDecimal("200.234"), + converted.getNumber().numberValue(BigDecimal.class).stripTrailingZeros()); + assertEquals("USD", converted.getCurrency().getCurrencyCode()); + assertEquals(200, converted.getNumber().getPrecision()); + assertEquals(200, converted.getContext().getPrecision()); + assertEquals(100, converted.getContext().getMaxScale()); + assertEquals(MathContext.UNLIMITED, converted.getContext().get(MathContext.class)); + } + +} diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/ConversionsTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/ConversionsTest.java new file mode 100644 index 00000000..1a92ad9f --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/ConversionsTest.java @@ -0,0 +1,208 @@ +/* + * CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE + * CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. + * PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY + * DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE + * AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" + * BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency + * API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights + * reserved. + */ +package org.javamoney.adopjsr; + +import org.javamoney.moneta.Money; +import org.junit.Test; + +import javax.money.CurrencyUnit; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.money.convert.*; + +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Created by Anatole on 21.03.14. + */ +public class ConversionsTest { + + private Conversions conv = new Conversions(); + private static final long ONEYEAR = 3600000L * 24 * 365; + + @Test + public void testGetExchangeRateFromIMF() throws Exception { + CurrencyUnit[] units = + new CurrencyUnit[]{Monetary.getCurrency("CHF"), Monetary.getCurrency("EUR"), + Monetary.getCurrency("USD")}; + for (CurrencyUnit u1 : units) { + for (CurrencyUnit u2 : units) { + if (u1.equals(u2)) { + continue; + } + boolean exception = false; + ExchangeRate expected = null; + try { + expected = MonetaryConversions.getExchangeRateProvider("IMF").getExchangeRate(u1, u2); + } catch (Exception e) { + exception = true; + } + ExchangeRate r = conv.getExchangeRateFromIMF(u1, u2); + try { + assertEquals(expected, r); + } catch (Exception e) { + if (!exception) { + throw e; + } + } + } + } + } + + @Test + public void testGetExchangeRatewithTime() throws Exception { + long now = System.currentTimeMillis(); + LocalDate[] times = new LocalDate[]{LocalDate.now(), LocalDate.now().minus(1, ChronoUnit.YEARS), + LocalDate.now().minus(2, ChronoUnit.YEARS), LocalDate.now().minus(3, ChronoUnit.YEARS)}; + CurrencyUnit[] units = + new CurrencyUnit[]{Monetary.getCurrency("CHF"), Monetary.getCurrency("EUR"), + Monetary.getCurrency("USD")}; + for (CurrencyUnit u1 : units) { + for (CurrencyUnit u2 : units) { + if (u1.equals(u2)) { + continue; + } + for (LocalDate time : times) { + boolean exception = false; + ExchangeRate expected = null; + try { + expected = MonetaryConversions.getExchangeRateProvider("IMF").getExchangeRate( + ConversionQueryBuilder.of().set(time).setBaseCurrency(u1) + .setTermCurrency(u2).build()); + } catch (Exception e) { + exception = true; + } + ExchangeRate r = conv.getExchangeRateWithTime(u1, u2, time); + try { + assertEquals(expected, r); + } catch (Exception e) { + if (!exception) { + throw e; + } + } + } + } + } + } + + @Test + public void testConvertAmount() throws Exception { + CurrencyUnit[] units = + new CurrencyUnit[]{Monetary.getCurrency("CHF"), Monetary.getCurrency("EUR"), + Monetary.getCurrency("USD"), Monetary.getCurrency("JPY"), + Monetary.getCurrency("INR"),}; + Money[] moneys = new Money[]{Money.of(10, "CHF"), Money.of(123.34, "USD"), Money.of(2300.30, "INR")}; + long now = System.currentTimeMillis(); + LocalDate[] times = new LocalDate[]{LocalDate.now(), LocalDate.now().minus(1, ChronoUnit.YEARS), + LocalDate.now().minus(2, ChronoUnit.YEARS), LocalDate.now().minus(3, ChronoUnit.YEARS)}; + for (CurrencyUnit u1 : units) { + for (Money m : moneys) { + for (LocalDate time : times) { + boolean exception = false; + MonetaryAmount expected = null; + try { + expected = m.with(MonetaryConversions.getConversion( + ConversionQueryBuilder.of().set(time).setTermCurrency(u1).build())); + } catch (Exception e) { + exception = true; + } + MonetaryAmount res = conv.convertAmount(u1, m, time); + try { + assertEquals(expected, res); + } catch (Exception e) { + if (!exception) { + throw e; + } + } + } + } + } + } + + @Test + public void testConvertAmountDefault() throws Exception { + CurrencyUnit[] units = + new CurrencyUnit[]{Monetary.getCurrency("CHF"), Monetary.getCurrency("EUR"), + Monetary.getCurrency("USD"), Monetary.getCurrency("JPY"), + Monetary.getCurrency("INR"),}; + Money[] moneys = new Money[]{Money.of(10, "CHF"), Money.of(123.34, "USD"), Money.of(2300.30, "INR")}; + for (CurrencyUnit u1 : units) { + for (Money m : moneys) { + boolean exception = false; + MonetaryAmount expected = null; + try { + expected = m.with(MonetaryConversions + .getConversion(ConversionQueryBuilder.of().setTermCurrency(u1).build())); + } catch (Exception e) { + exception = true; + } + MonetaryAmount res = conv.convertAmountDefault(u1, m); + try { + assertEquals(expected, res); + } catch (Exception e) { + if (!exception) { + throw e; + } + } + } + } + } + + @Test + public void testGetDefaultConversionContext() { + ConversionContext ctx = conv.getDefaultConversionContext(Monetary.getCurrency("CHF"), + Monetary.getCurrency("EUR")); + assertNotNull(ctx); + assertEquals("ECB", ctx.getProviderName()); + ctx = conv.getDefaultConversionContext(Monetary.getCurrency("CHF"), + Monetary.getCurrency("INR")); + assertNotNull(ctx); + assertEquals("IMF", ctx.getProviderName()); + } + + @Test + public void testGetIMFProviderContext() { + ProviderContext ctx = conv.getIMFProviderContext(); + assertNotNull(ctx); + assertEquals("IMF", ctx.getProviderName()); + } + + @Test + public void testGetECBProviderContext() { + ProviderContext ctx = conv.getECBProviderContext(); + assertNotNull(ctx); + assertEquals("ECB", ctx.getProviderName()); + } + + @Test + public void testGetDefaultProviderContext() { + ProviderContext ctx = conv.getDefaultProviderContext(); + assertNotNull(ctx); + assertEquals(MonetaryConversions.getExchangeRateProvider().getContext().getProviderName(), + ctx.getProviderName()); + } + + @Test + public void testGetDefaultProviderChain() { + assertEquals(MonetaryConversions.getDefaultConversionProviderChain(), conv.getDefaultProviderChain()); + } + + @Test + public void testCustomProvider() { + String provName = conv.getNewProviderName(); + ExchangeRateProvider prov = MonetaryConversions.getExchangeRateProvider(provName); + assertNotNull(prov); + } +} diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/FormattingTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/FormattingTest.java new file mode 100644 index 00000000..68eefb52 --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/FormattingTest.java @@ -0,0 +1,88 @@ +/* + * CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE + * CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. + * PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY + * DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE + * AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" + * BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency + * API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights + * reserved. + */ +package org.javamoney.adopjsr; + +import org.javamoney.moneta.Money; +import org.junit.Test; + +import javax.money.MonetaryAmount; +import javax.money.MonetaryOperator; +import javax.money.format.*; + +import org.javamoney.moneta.format.CurrencyStyle; + +import java.text.DecimalFormat; +import java.util.Collection; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Test cases for the formatting API. + * Created by Anatole on 21.03.14. + */ +public class FormattingTest { + + private Formatting formatting = new Formatting(); + + @Test + public void testGetAmountFormat() throws Exception { + for (Locale loc : DecimalFormat.getAvailableLocales()) { + MonetaryAmountFormat fmt = formatting.getAmountFormat(loc); + assertEquals(fmt.getContext().getLocale(), loc); + } + } + + @Test + public void testGetAmountFormat1() throws Exception { + for (Locale loc : DecimalFormat.getAvailableLocales()) { + MonetaryAmountFormat fmt = formatting.getAmountFormat(loc); + assertEquals(fmt, MonetaryFormats.getAmountFormat(loc)); + } + } + + @Test + public void testCreateCustomFormat() throws Exception { + MonetaryOperator outOp = (value) -> value.divide(1000000); + MonetaryOperator inOp = new MonetaryOperator() { + @Override + public MonetaryAmount apply(MonetaryAmount value) { + return value.multiply(1000000); + } + }; + MonetaryAmountFormat fmt = MonetaryFormats.getAmountFormat( + AmountFormatQueryBuilder.of(Locale.ENGLISH).set(CurrencyStyle.SYMBOL) + .set("groupingSizes", new int[]{3, 2}).set("pattern", " ##0.00 ¤ Mio;[##0.00] ¤ Mio") + .set("displayConversion", outOp).set("parseConversion", inOp).build()); + Money m = Money.of(2323233223232424.23, "CHF"); + MonetaryAmountFormat toTest = formatting.createCustomFormat(); + assertEquals(fmt.format(m), toTest.format(m)); + m = Money.of(-2323233223232424.23, "CHF"); + assertEquals(fmt.format(m), toTest.format(m)); + } + + @Test + public void testRegisterCustomFormat() { + String formatId = formatting.getRegisteredCustomFormat(); + assertNotNull(formatId); + AmountFormatQuery ctx = AmountFormatQueryBuilder.of(formatId).build(); + MonetaryAmountFormat f = MonetaryFormats.getAmountFormat(ctx); + assertNotNull(f); + } + + @Test + public void testAvailableLocales() { + Collection locales = formatting.getAvailableLocales(); + assertEquals(MonetaryFormats.getAvailableLocales(), locales); + } + +} diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/MoneyAlgorithmicsTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/MoneyAlgorithmicsTest.java new file mode 100644 index 00000000..5bb55c1f --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/MoneyAlgorithmicsTest.java @@ -0,0 +1,192 @@ +/* + * CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE + * CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. + * PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY + * DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE + * AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" + * BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency + * API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights + * reserved. + */ + +package org.javamoney.adopjsr; + +import org.javamoney.moneta.CurrencyUnitBuilder; +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.javamoney.moneta.function.MonetaryUtil; +import org.junit.Test; + +import javax.money.*; +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.*; + +/** + * Created by Anatole on 08.03.14. + */ +public class MoneyAlgorithmicsTest{ + + private MoneyAlgorithmics alg = new MoneyAlgorithmics(); + private static final CurrencyContext CURENCY_CONTEXT = CurrencyContextBuilder.of("MoneyAlgorithmicsTest").build(); + + @Test + public void testAddAll() throws Exception{ + assertEquals(Money.of(20, "CHF"), alg.addAll(Money.of(10, "CHF"), Money.of(10, "CHF"))); + assertEquals(Money.of(20.8, "CHF"), alg.addAll(Money.of(10.5, "CHF"), Money.of(10.3, "CHF"))); + assertEquals(Money.of(-90, "CHF"), alg.addAll(Money.of(-100.3, "CHF"), Money.of(10.3, "CHF"))); + assertEquals(Money.of(0, "CHF"), alg.addAll(Money.of(0, "CHF"), Money.of(0, "CHF"))); + assertEquals(Money.of(283976.34, "CHF"), alg.addAll(Money.of(283976.34, "CHF"), Money.of(0, "CHF"))); + } + + @Test + public void testMultiply() throws Exception{ + assertEquals(Money.of(100, "CHF"), alg.multiply(Money.of(10, "CHF"), 10)); + assertEquals(Money.of(101, "CHF"), alg.multiply(Money.of(10.1, "CHF"), 10)); + assertEquals(Money.of(21323120, "CHF"), alg.multiply(Money.of(2132312, "CHF"), 10)); + assertEquals(Money.of(100, "CHF"), alg.multiply(Money.of(-100, "CHF"), -1)); + } + + @Test + public void testSubtract() throws Exception{ + assertEquals(Money.of(0, "CHF"), alg.subtract(Money.of(10, "CHF"), Money.of(10, "CHF"))); + assertEquals(Money.of(-110, "CHF"), alg.subtract(Money.of(10, "CHF"), Money.of(120, "CHF"))); + assertEquals(Money.of(-2.5, "CHF"), alg.subtract(Money.of(10, "CHF"), Money.of(12.5, "CHF"))); + assertEquals(Money.of(0.06, "CHF"), alg.subtract(Money.of(10.56, "CHF"), Money.of(10.5, "CHF"))); + } + + @Test + public void testDivide() throws Exception{ + assertEquals(Money.of(1, "CHF"), alg.divide(Money.of(10, "CHF"), new BigDecimal(10))); + assertEquals(Money.of(1, "CHF"), alg.divide(Money.of(10.345, "CHF"), new BigDecimal("10.345"))); + assertEquals(Money.of(10.345, "CHF"), alg.divide(Money.of(10.345, "CHF"), BigDecimal.ONE)); + assertEquals(Money.of(0.0837991089509923, "CHF"), + alg.divide(Money.of(10.345, "CHF"), new BigDecimal("123.45"))); + } + + @Test + public void testScaleByTen() throws Exception{ + assertEquals(Money.of(100, "CHF"), alg.scaleByTen(Money.of(10, "CHF"), 1)); + assertEquals(Money.of(123234405.6, "CHF"), alg.scaleByTen(Money.of(123234.4056, "CHF"), 3)); + } + + @Test + public void testSortAmounts() throws Exception{ + List amounts = + alg.sortAmounts(Money.of(0, "CHF"), FastMoney.of(1, "CHF"), Money.of(-200, "CHF"), + FastMoney.of(210, "USD")); + List sortedAmounts = new ArrayList<>(); + sortedAmounts.addAll(amounts); + Collections.sort(sortedAmounts); + } + + @Test + public void testQuerySumOf() throws Exception{ + MonetaryAmount amt = + alg.querySumOf(Monetary.getCurrency("CHF"), FastMoney.of(10, "CHF"), Money.of(0, "CHF"), + FastMoney.of(1, "USD"), Money.of(200.45, "CHF"), FastMoney.of(210, "USD")); + assertTrue(Money.of(210.45, "CHF").isEqualTo(amt)); + } + + @Test + public void testCalculateReciprocal() throws Exception{ + MonetaryAmount amt = alg.calculateReciprocal(Money.of(10, "CHF")); + assertTrue(Money.of(0.1, "CHF").isEqualTo(amt)); + } + + @Test + public void testCalculatePercent() throws Exception{ + MonetaryAmount amt = alg.calculatePercent(FastMoney.of(100, "EUR"), 20.5); + assertTrue(Money.of(20.5, "EUR").isEqualTo(amt)); + amt = alg.calculatePercent(Money.of(10.45, "EUR"), 1.345); + assertTrue(Money.of(0.1405525, "EUR").isEqualTo(amt)); + } + + @Test + public void testCalculatePermil() throws Exception{ + MonetaryAmount amt = alg.calculatePermil(FastMoney.of(100, "EUR"), 20.5); + assertTrue(Money.of(2.05, "EUR").isEqualTo(amt)); + amt = alg.calculatePermil(Money.of(10.45, "EUR"), 1.345); + assertTrue(Money.of(0.01405525, "EUR").isEqualTo(amt)); + } + + @Test + public void testGetMajorPart() throws Exception{ + MonetaryAmount amt1 = alg.getMajorPart(FastMoney.of(100.1223, "EUR")); + assertEquals(amt1, FastMoney.of(100.1223, "EUR").with(MonetaryUtil.majorPart())); + } + + @Test + public void testGetCompoundInterest() throws Exception{ + MonetaryAmount amt1 = alg.getCompoundInterest(FastMoney.of(100, "EUR"), 10.5, 1); + assertTrue(Money.of(110.5, "EUR").isEqualTo(amt1)); + MonetaryAmount amt2 = alg.getCompoundInterest(FastMoney.of(100, "EUR"), 10.5, 2); + assertTrue(amt1.multiply(1.105).isEqualTo(amt2)); + } + + @Test + public void testMultiplyAdvanced() throws Exception{ + MonetaryAmount amt1 = alg.multiplyAdvanced(FastMoney.of(100, "EUR"), BigDecimal.valueOf(Long.MAX_VALUE)); + assertTrue(Monetary.getDefaultAmountFactory().setNumber(100).setCurrency("EUR") + .setContext(MonetaryContextBuilder.of().set(MathContext.UNLIMITED).build()).create() + .multiply(BigDecimal.valueOf(Long.MAX_VALUE)).isEqualTo(amt1)); + } + + @Test + public void testSubtractAdvanced() throws Exception{ + MonetaryAmount amt1 = alg.subtractAdvanced(FastMoney.of(100, "EUR"), + Money.of(new BigDecimal("0.0000000000000000000001"), "EUR")); + assertTrue(Money.of(100, "EUR", MonetaryContextBuilder.of().set(MathContext.UNLIMITED).build()) + .subtract(Money.of(new BigDecimal("0.0000000000000000000001"), "EUR")).isEqualTo(amt1)); + } + + @Test + public void testDivideAdvanced() throws Exception{ + MonetaryAmount amt1 = alg.divideAdvanced(FastMoney.of(100, "EUR"), new BigDecimal("0.0000000000000000000001")); + assertTrue(Money.of(100, "EUR", MonetaryContextBuilder.of().set(MathContext.UNLIMITED).build()) + .divide(new BigDecimal("0.0000000000000000000001")).isEqualTo(amt1)); + } + + + /** + * Implement a {@link javax.money.MonetaryOperator} that simply duplicates the amount given. + */ + @Test + public void testDuplicateOperator(){ + MonetaryOperator op = alg.getDuplicateOperator(); + assertEquals(Money.of(20, "CHF"), Money.of(10, "CHF").with(op)); + assertEquals(Money.of(20.86, "CHF"), Money.of(10.43, "CHF").with(op)); + assertEquals(Money.of(-4, "CHF"), Money.of(-2, "CHF").with(op)); + assertEquals(Money.of(0, "CHF"), Money.of(0, "CHF").with(op)); + } + + /** + * Implement a {@link javax.money.MonetaryOperator} that calculates the total of all amounts operated on. + */ + @Test + public void testTotalOperator(){ + MonetaryOperator op = alg.getTotalOperator(); + op.apply(Money.of(2, "CHF")); + op.apply(FastMoney.of(4.5, "CHF")); + op.apply(Money.of(10, "CHF")); + op.apply(FastMoney.of(-1.5, "CHF")); + assertEquals(Money.of(35.1234, "CHF"), op.apply(Money.of(20.1234, "CHF"))); + } + + /** + * Implement a {@link javax.money.MonetaryQuery} that return {@code true} for each amount, that has an ISO + * currency (as available on {@link java.util.Currency}. + */ + @Test + public void testCountingQuery(){ + MonetaryQuery query = alg.getCountingQuery(); + assertTrue(Money.of(2, "CHF").query(query)); + assertFalse(FastMoney.of(4.5, CurrencyUnitBuilder.of("GEEC", CURENCY_CONTEXT).build()).query(query)); + assertTrue(Money.of(10, "INR").query(query)); + assertFalse(FastMoney.of(-1.5, CurrencyUnitBuilder.of("2xx2", CURENCY_CONTEXT).build()).query(query)); + } +} diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/NumericRepresentationTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/NumericRepresentationTest.java new file mode 100644 index 00000000..6c6ecd25 --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/NumericRepresentationTest.java @@ -0,0 +1,98 @@ +package org.javamoney.adopjsr; + + +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.junit.Test; + +import javax.money.MonetaryAmount; +import javax.money.NumberValue; +import java.math.BigDecimal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class NumericRepresentationTest{ + + NumericRepresentation np = new NumericRepresentation(); + + @Test + public void testGetBigDecimal() throws Exception{ + BigDecimal bd = new BigDecimal("123435443565465409683468327434324.3748634"); + MonetaryAmount amount = Money.of(bd, "INR"); + BigDecimal bd2 = np.getBigDecimal(amount); + assertEquals("Invalid BigDecimal value", bd.stripTrailingZeros(), bd2.stripTrailingZeros()); + } + + @Test + public void testGetLongTruncated() throws Exception{ + BigDecimal bd = new BigDecimal( + "1234354435654654092372883687236483274632894623894693284632864832648329462836473276352763527615382176521785321876352178654327684532765218745823745327865327654723684683468327434324.3748634"); + MonetaryAmount amount = Money.of(bd, "CHF"); + assertEquals("Invalid truncated long", amount.getNumber().longValue(), np.getLongTruncated(amount)); + } + + @Test + public void testGetPrecision() throws Exception{ + BigDecimal bd = new BigDecimal( + "1234354435654654092372883687236483274632894623894693284632864832648329462836473276352763527615382176521785321876352178654327684532765218745823745327865327654723684683468327434324.3748634"); + MonetaryAmount amount = Money.of(bd, "CHF"); + assertEquals("Invalid precision for " + bd, amount.getNumber().getPrecision(), np.getPrecision(amount)); + } + + @Test + public void testGetScale() throws Exception{ + BigDecimal bd = new BigDecimal( + "1234354435654654092372883687236483274632894623894693284632" + + ".8648326483294628364732763527635276153821765217853218763521786543276845327652187458237453278653276547236846834683274343243748634"); + MonetaryAmount amount = Money.of(bd, "CHF"); + assertEquals("Invalid scale for " + bd, amount.getNumber().getScale(), np.getScale(amount)); + } + + @Test + public void testGetFractionDenominator() throws Exception{ + BigDecimal bd = new BigDecimal("0.1234523"); + MonetaryAmount amount = Money.of(bd, "USD"); + assertEquals("Invalid fraction denominator for " + bd, amount.getNumber().getAmountFractionDenominator(), + np.getFractionDenominator(amount)); + } + + @Test + public void testGetFractionNumerator() throws Exception{ + BigDecimal bd = new BigDecimal("0.1234553"); + MonetaryAmount amount = Money.of(bd, "USD"); + assertEquals("Invalid fraction numerator for " + bd, amount.getNumber().getAmountFractionDenominator(), + np.getFractionNumerator(amount)); + } + + @Test + public void testGetNumberType() throws Exception{ + BigDecimal bd = new BigDecimal("0.1234523"); + MonetaryAmount[] amounts = new MonetaryAmount[]{Money.of(bd, "USD"), FastMoney.of(2334434354L, "CHF")}; + for(MonetaryAmount amount : amounts){ + assertEquals("Invalid number type for " + amount, amount.getNumber().getNumberType(), + np.getNumberType(amount)); + } + } + + @Test + public void testGetNumber() throws Exception{ + BigDecimal bd = new BigDecimal("0.1234523"); + MonetaryAmount[] amounts = new MonetaryAmount[]{Money.of(bd, "USD"), FastMoney.of(2334434354L, "CHF")}; + for(MonetaryAmount amount : amounts){ + assertEquals("Invalid number type for " + amount, amount.getNumber().getNumberType(), + np.getNumberType(amount)); + } + } + + @Test + public void testGetJDKNumber() throws Exception{ + BigDecimal bd = new BigDecimal("0.1234523"); + MonetaryAmount[] amounts = new MonetaryAmount[]{Money.of(bd, "USD"), FastMoney.of(2334434354L, "CHF")}; + for(MonetaryAmount amount : amounts){ + assertTrue("JDK Number can be more easily extracted for " + amount, + np.getNumber(amount) instanceof NumberValue); + assertEquals("Invalid JDK Number for " + amount, amount.getNumber(), np.getNumber(amount)); + } + } +} \ No newline at end of file diff --git a/console/moneymachine/src/test/java/org/javamoney/adopjsr/RoundingTest.java b/console/moneymachine/src/test/java/org/javamoney/adopjsr/RoundingTest.java new file mode 100644 index 00000000..d5a493e4 --- /dev/null +++ b/console/moneymachine/src/test/java/org/javamoney/adopjsr/RoundingTest.java @@ -0,0 +1,92 @@ +/* + * CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE + * CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT. + * PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY + * DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE + * AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE" + * BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency + * API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights + * reserved. + */ + +package org.javamoney.adopjsr; + +import org.javamoney.moneta.CurrencyUnitBuilder; +import org.javamoney.moneta.Money; +import org.junit.Test; + +import javax.money.*; +import java.math.RoundingMode; +import java.util.Collection; +import java.util.Set; + +import static org.junit.Assert.*; + +/** + * Created by Anatole on 21.03.14. + */ +public class RoundingTest{ + + private static final CurrencyContext CURRENCY_CONTEXT = CurrencyContextBuilder.of("RoundingTest").build(); + + private Rounding rnd = new Rounding(); + private Money[] moneys = + new Money[]{org.javamoney.moneta.Money.of(200.12345678, "CHF"), Money.of(100.1234567, "JPY"), + Money.of(100.1234567, CurrencyUnitBuilder.of("API-TEST", CURRENCY_CONTEXT).setNumericCode(1234) + .setDefaultFractionDigits(5).build() + )}; + + @Test + public void testRoundWithDefaultRounding() throws Exception{ + for(Money m : moneys){ + assertEquals(m.with(Monetary.getDefaultRounding()), rnd.roundWithDefaultRounding(m)); + } + } + + + @Test + public void testRoundForCash() throws Exception{ + for(Money m : moneys){ + assertEquals(m.with(Monetary.getRounding( + RoundingQueryBuilder.of().setCurrency(m.getCurrency()).set("cashRounding", true) + .build())), + rnd.roundForCash(m)); + } + } + + @Test + public void testRoundMathematical() throws Exception{ + RoundingQuery ctx = RoundingQueryBuilder.of().set(RoundingMode.HALF_UP).set("maxScale", 3).build(); + for(Money m : moneys){ + assertEquals(rnd.roundMathematical(m), m.with(Monetary.getRounding(ctx))); + } + } + + @Test + public void testKnownRoundings() throws Exception{ + Collection roundings = rnd.getKnownRoundings(); + assertNotNull(roundings); + Set curSet = Monetary.getRoundingNames(); + for(String roundingId : curSet){ + assertTrue(roundings.contains(roundingId)); + } + for(String roundingId : roundings){ + assertTrue(curSet.contains(roundingId)); + } + } + + /** + * Test your own custom rounding. The test will check, if your rounding is available and perform a test + * rounding. + */ + @Test + public void testCustomRoundingName(){ + String rndId = rnd.getCustomRoundingName(); + MonetaryOperator rounding = Monetary.getRounding(rndId); + assertNotNull(rounding); + for(Money m : moneys){ + assertNotNull(m.with(rounding)); + assertEquals(m.getClass().getName(), m.with(rounding).getClass().getName()); + } + } +} diff --git a/console/pom.xml b/console/pom.xml index 9b6c4499..46d0f0c5 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -14,6 +14,7 @@ javamoney-console-simple javamoney-console-java8 functional-example + moneymachine