Friday, April 10, 2015

What's new in Grails 3

A few days ago Grails 3.0 was officially released. Grails is now based on Spring Boot, the build system changed from Gant to Gradle and significant parts of the framework have been rewritten. In this post we will have a look at all the major changes introduced by Grails 3.

Updated file structure
We will start with a screenshot that shows a fresh Grails 3 project created from the Grails command line using

grails create-app hello


The first two folders (build and gradle) are related to Gradle, the new build system in Grails 3. As the name implies, build is the directory where build related files like compiled classes and assembled packages are located. The gradle directory contains the Gradle Wrapper that allows you to build the project without a local Gradle installation.

The content of the conf folder has also been changed. The default format for configuration files is now YAML. If you prefer to write your configuration in Groovy, you can still create a grails-app/conf/application.groovy configuration file manually.
Logback is now the default logging provider. The logging configuration (previously part of Config.groovy) has been moved to conf/logback.groovy.
Note that the conf folder is not a source directory anymore.

init is a new folder in Grails 3. It contains Bootstrap.groovy (same content as in previous Grails versions) and the new Application main class (we will look into this in the Spring Boot section).

The structure of the src folder has been changed to match Gradle conventions. Additional Java and Groovy files are now located in:
src/main/java
src/main/groovy
src/test/java
src/test/groovy

build.gradle and gradle.properties contain the build configuration. BuildConfig.groovy from previous Grails versions does no longer exist.

Spring 4.1 and Spring Boot
Spring Boot is the new basis for Grails. According to Graeme Rocher Grails 3 is nothing less than a ground up rewrite on top of Spring Boot.

Like Spring Boot applications Grails 3 projects come with an Application class that has a standard main() method. This means you can start a Grails 3 application simply by running the main class from your IDE.

The default Application class looks like this:
class Application extends GrailsAutoConfiguration {
  static void main(String[] args) {
    GrailsApp.run(Application)
  }
}
Note that the war file you get when packaging the application can now be executed using the java -jar command:

java -jar build/libs/myApplication-0.1.war

This runs the main method which starts the application using an embedded Tomcat server. Of course you can still deploy the war file on an application server of your choice like in previous Grails versions.

The Application class acts as Spring configuration class. So, we can use Spring's @Bean annotation to define custom beans. Methods like onStartup() or onShutdown() can be overwritten if you want to execute custom code at certain application events.
class Application extends GrailsAutoConfiguration {

  ...
 
  @Bean
  MyBean myBeanId() {
    return new MyBeanImpl();
  }
 
  @Override
  void onStartup(Map<String, Object> event) {
    super.onStartup(event)
   // custom startup code..
  }
} 

Traits
In Grails components like Controllers or Domain classes always had some magically attached functionality. For example, in Controllers you can use methods like render(), redirect() or getParams() without subclassing another class. In Grails 3 these features have been rewritten to make use of Traits introduced by Groovy 2.3.
Certain Traits are automatically attached to Controllers, Services, Tag libraries and so on to make framework methods available. For example, a Controller automatically gets the following Traits: TagLibraryInvoker, AsyncController, RestResponder, Controller.

The cool thing with Traits is that you can easily add them to your own classes.
For example: Assume you want to access the request and params objects outside a Grails Controller. All you have to do now is adding the WebAttributes trait to your class:
class MyCustomComponent implements WebAttributes {

  public MyCustomComponent() {

    // make use of WebAttributes methods like getWebRequest() or getParams()
    println "base url: " + webRequest.baseUrl
    println "params: " + params
    ...
  }
}

Interceptors
Grails 3 introduced standalone Interceptors. Interceptors can intercept incoming requests to perform common tasks (e.g. logging, authentication, etc.).

A new Interceptor can be created using create-interceptor command:

grails create-interceptor MyInterceptor

A newly created Interceptor looks like this:
class MyInterceptor {

  boolean before() { 
    // executed before a request is processed by a controller
    true 
  }

  boolean after() {
    // executed after a request is processed by a controller
    true
  }

  void afterView() { 
    // executed after the view has been rendered
  }

}

Interceptors replace Filters used by previous Grails versions. Filters still work in Grails 3 for backwards compatibility. However, they are considered deprecated now.

If you are aware of Spring web MVC, you can easily see the similarities to Springs Handler Interceptor.


Gradle
As mentioned before, Grails 3 uses Gradle instead of Gant as build system. Gradle is used for tasks like compilation, running tests and packaging the application.
When a Grails command like grails clean is executed, the job is delegated to the corresponding Gradle task (e.g. gradle clean). The Gradle-Wrapper shipped with Grails 3 is used for this.
If you want to use a local installation of Gradle you can execute the Gradle task directly with your own Gradle version. Gradle 2.2 or newer is recommended.

The following table shows Grails commands and their corresponding Gradle tasks:

Grails command      Gradle Task
cleanclean
compileclasses
packageassemble
run-apprun
test-apptest
warassemble

BuildConfig.groovy from previous Grails versions has been completely replaced by the Gradle configuration (build.gradle). Third party dependencies are now defined in build.gradle:
dependencies {
  compile 'org.grails.plugins:hibernate' 
  compile 'org.grails.plugins:cache' 
  compile 'org.hibernate:hibernate-ehcache'
  runtime 'org.grails.plugins:asset-pipeline' 
  runtime 'org.grails.plugins:scaffolding'
  ...
}
For more details, you can have a look at Dependency Management Guide in the Gradle documentation.


Profiles
Whenever you run the create-app command Grails 3 will use a Profile to create a new app.
A Profile encapsulates project structure, commands, templates and plugins. By default Grails 3 uses the web Profile, which creates an app like shown in the screenshot above.

To create a project with a different Profile, you can use the --profile parameter:

grails create-app myapp --profile=web-plugin

Grails 3 comes with three different Profiles:
  • web for standard Grails web applications
  • web-plugin for web application plugins
  • web-micro a minimal micro service application


Short summary
Grails 3 comes with major changes. The code basis changed to Spring Boot, Gant was replaced with Gradle, existing features were reimplemented using Traits and new features like Profiles and Interceptors were added.
With all those changes it can become quite challenging to upgrade an existing Grails 2.x application to Grails 3 (all Plugins need to be updated first). If you plan to Upgrade to Grails 3, you should have a look at the Grails 3 upgrade guide.

Share this post using Facebook, Twitter or Google+

Thursday, February 26, 2015

Using Java 8 Lambda expressions in Java 7 or older

I think nobody declines the usefulness of Lambda expressions, introduced by Java 8. However, many projects are stuck with Java 7 or even older versions. Upgrading can be time consuming and costly. If third party components are incompatible with Java 8 upgrading might not be possible at all.
Besides that, the whole Android platform is stuck on Java 6 and 7.

Nevertheless, there is still hope for Lambda expressions!

Retrolambda provides a backport of Lambda expressions for Java 5, 6 and 7.

From the Retrolambda documentation: 
Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime. After the transformation they are just a bunch of normal .class files, without any additional runtime dependencies.

To get Retrolambda running, you can use the Maven or Gradle plugin.

If you want to use Lambda expressions on Android, you only have to add the following lines to your gradle build files:

<project>/build.gradle:
buildscript {
  dependencies {
    classpath 'me.tatarka:gradle-retrolambda:2.4.0'    
  }
}

<project>/app/build.gradle:
apply plugin: 'com.android.application'

// Apply retro lambda plugin after the Android plugin
apply plugin: 'retrolambda' 

android {
  compileOptions {
    // change compatibility to Java 8 to get Java 8 IDE support  
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Share this post using Facebook, Twitter or Google+

Monday, February 23, 2015

Static code analysis with JArchitect

A few months ago Dane from JArchitect team was nice enough to offer me a free JArchitect 4 Pro license. Over the last days I finally managed to look into JArchitect.

JArchitect is a quite powerful static code analyser for JVM languages (besides Java it also supports Scala, Groovy and others). It is available for Windows, Linux and Mac OS X. In this post I want to show you some of JArchitect's features.


Getting started
As an example I analysed the popular Java Library JUnit using JArchitect. The Screenshots you in this post are all taken from the JUnit analysis result.

Importing JUnit into JArchitect was actually quite simple. Note that JArchitect analyses the compiled byte code, source files are not required. So I cloned the JUnit repository and called mvn compile. After that, all I had to do was adding JUnit's pom.xml to a new JArchitect project.

After pressing the Run Analysis button JArchitect summarizes common metrics on a dashboard screen:


Here we can see the lines of code, method complexity, comment rate and various other values. This summary is followed by a couple of trend charts that show how these values changed over time.


Of course you can also configure your own charts, if you want to see trends of different values. 


Looking into dependencies
Next we will look at the third party dependencies of JUnit. JArchitect provides a nice interactive graph for this.



Since JUnit only depends on the Java Runtime (rt) and Hamcrest this graph does not have much to show. I am sure you can imagine that this could be much more complex for a larger project.

Looking at JUnits package dependencies is a bit more interesting. The following Screen shows a section of JUnits package dependency graph.



I selected the junit.framework package to see how this package relates to other packages. The different colored arrows show which packages use junit.framework (green), which other packages are used by junit.framework (blue) and mutually dependent packages (red).

The dependency matrix is another way to look at project dependencies:



This matrix style view shows you exactly the dependencies between different components (packages, classes or methods). Here I selected the blue field with the number 10 (where the orange lines cross). This shows that the junit.framework package uses 10 members of the java.lang.reflect package (the dependency direction is shown by the white arrow at the selected field).

We can dig deeper, and look at this at class and method level.


So it looks like the class junit.framework.TestCase makes use of the method java.lang.Class.getName().


Tree maps
Tree map charts are another way to look into a project with JArchitect. The following chart shows the number of code lines in JUnit packages, classes and methods.



In this example chart we cannot see any overly large rectangle, which is a good sign. This probably means that complex parts are well divided into multiple classes and packages (no god object is present).

JArchitect can generate such tree maps for lines of code, cyclomatic complexity, number of variables and various other metrics.


Code queries
To extract various metrics out of a project, JArchitect uses a custom query language call Code Query Linq (CQLinq). As the name suggests this is a query language based on LINQ.



This image shows the query of JArchitect's Methods with too many parameters rule. It looks for methods with more than 8 parameters and creates a warning if one or more methods are found.

You can see (and change) all the standard queries provided by JArchitect.
Code queries are actually a very cool feature. You can easily create your own queries to extract project specific data you are interested in. 


Quick summary
JArchitect is a powerful tool for static code analysis. It can provide a lot of insight into complex code bases. Using custom code queries you are able to build your own rule sets in a very comfortable way.

In this example I used the JArchitect user interface (VisualJArchitect) for running the code analysis and viewing the results. It is also possible to integrate JArchitect directly into your build process (using a Maven plugin or command line tools). This way you are able to automatically create reports in HTML format.

Share this post using Facebook, Twitter or Google+

Friday, February 6, 2015

Creating Android Apps with Groovy 2.4

A few days ago Groovy 2.4 was released. One of the major news is that Groovy now officially supports Android application development. To see how this works I used Groovy to create a small ToDo list example application for Android. In this post I will show which steps are required to create an Android application with Groovy and how Groovy can simplify Android application development.


The following screen shows the example application written in Groovy. You can find the full source code on GitHub.



Running Groovy on Android
First we need Android Studio which already contains the latest Version of the Android SDK. Over last year the default Android environment changed from Eclipse and Ant to Android Studio (build on IntelliJ) and Gradle.
To run Groovy on Android we will need a Gradle Plugin, so make sure you are not using the old Eclipse/Ant based development tools.

We create a new Android project in Android Studio and add the following lines to our build files:

Top level build file (<project>/build.gradle):
buildscript {
  ..
  dependencies {
    ..
    classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.5'
  }
}

App build file (<project>/app/build.gradle):
apply plugin: 'com.android.application'

// apply Groovy Android plugin after the standard Android plugin
apply plugin: 'groovyx.grooid.groovy-android'

dependencies {
  ..
  compile 'org.codehaus.groovy:groovy:2.4.0:grooid'
}
Source and documentation of the Groovy Android Gradle Plugin can be found on GitHub.

This is all configuration we need, now we can move straight to Groovy code.

Please note that Groovy code files need to be placed in src/main/groovy instead of src/main/java. Adding Groovy files to src/main/java will not work!

Developing Android apps in Groovy works exactly the same way as in Java. Because of Groovy's  Java interoperability, you can use and extend Android classes like you would do in Java.

Improving the Groovy experience in Android Studio
Android Studio already contains the Groovy plugin. So, you get Groovy syntax support out of the box.

However, you might miss the option to create new Groovy classes from the context menu. Luckily this can be easily configured in Android Studio. You simply have to create a new File Template (Settings > File and code templates) and add the following template code:
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
class ${NAME} {
}

Now you can quickly create new Groovy classes using the context menu:


You might also look into this plugin which fixes the issue that you get no auto completion when overriding super class methods in Groovy. Thanks to @arasthel92 who told me about this plugin.

Running Groovy applications
Running Groovy apps is identical to running Java apps. We can simply press the run (or debug) button in Android Studio and deploy the application to a connected (or emulated) device.
The cool thing is that the Groovy debugger works out of the box. We can debug running Groovy applications from Android Studio.

The great parts
The cool thing about Groovy is that it reduces the lines of code you need to write a lot. Its dynamic nature also lets you get rid of all the type casts that are typically required when working with Android.

One example of this can be found in ToDoListActivity.onResume(). In this method the data of an Android ListAdapter is modified. With Java this would look like this:
ArrayAdapter<ToDo> adapter = (ArrayAdapter<ToDo>) getListAdapter();
ToDoApplication application = (ToDoApplication) getApplication()
adapter.clear()
adapter.addAll(application.getToDos());
adapter.notifyDataSetChanged()
With Groovy we can simply rewrite it like this:
listAdapter.clear()
listAdapter.addAll(application.toDos)
listAdapter.notifyDataSetChanged()
Groovy's closures are another feature that comes very handy when working with Android.

To add a click listener to a button you write something like this in Java
Button button = (Button) findViewById(R.id.newTodoButton);
button.setOnClickListener(new View.OnClickListener() {
  @Override
  void onClick(View v) {
    ...
  }
});
With Groovy it is just
def button = findViewById(R.id.newTodoButton)
button.onClickListener = {
  ...
}
See CreateNewTodoActivity for a complete example.

Be aware of runtime errors
Dynamic languages typically tend to increase the number of errors you find at runtime. Depending on the app you are building this can be a serious issue. Larger Apps can have a significant deployment time (the app needs to be packaged, copied via USB to the device, installed and started on the device).
Groovy's @CompileStatic annotation can be used to tackle this issue. It can be used to compile parts of your Groovy code statically to reduce runtime errors:
@CompileStatic
class ToDoListActivity extends ListActivity {
  ..
}
The downside of @CompileStatic is that you can (obviously) no longer use Groovy's dynamic features. 

Quick summary
It is very easy to get Groovy running on Android. Because of Groovy's interoperability with Java it is also very easy to mix Groovy and Java in the same application. The Groovy integration in Android Studio is actually better than I have expected (however, some manual tweaks are still required).

Share this post using Facebook, Twitter or Google+

Saturday, December 20, 2014

Looking into Java's new Money and Currency API (JSR 354)

JSR 354 defines a new Java API for working with Money and Currencies, which might be included in Java 9 (see comments). In this post we will look at the current state of the reference implementation: JavaMoney.

Like my post about the Java 8 Date/Time API this post will be mainly driven by code that shows the new API.

But before we start, I want to quote a short section from the specification that pretty much sums up the motivation for this new API:

Monetary values are a key feature of many applications, yet the JDK provides little or no support. The existing java.util.Currency class is strictly a structure used for representing current ISO 4217 currencies, but not associated values or custom currencies. The JDK also provides no support for monetary arithmetic or currency conversion, nor for a standard value type to represent a monetary amount.

If you use Maven, you can easily try the current state of the reference implementation by adding the following dependency to your project:

<dependency>
  <groupId>org.javamoney</groupId>
  <artifactId>moneta</artifactId>
  <version>0.9</version>
</dependency>

All specification classes and interfaces are located in the javax.money.* package.
We will start with the two core interfaces CurrencyUnit and MonetaryAmount. After that, we will look into exchange rates, currency conversion and formatting.


CurrencyUnit and MonetaryAmount
CurrencyUnit models a currency. CurrencyUnit is very similar to the existing java.util.Currency class, except it allows custom implementations. According to the specification it should be possible that java.util.Currency implements CurrencyUnit. CurrencyUnit instances can be obtained using the MonetaryCurrencies factory:
// getting CurrencyUnits by currency code
CurrencyUnit euro = MonetaryCurrencies.getCurrency("EUR");
CurrencyUnit usDollar = MonetaryCurrencies.getCurrency("USD");

// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);
MontetaryAmount represents a concrete numeric representation of a monetary amount. A MonetaryAmount is always bound to a CurrencyUnit. Like CurrencyUnit, MonetaryAmount is an interface that supports different implementations. CurrencyUnit and MonetaryAmount implementations must be immutable, thread safe, serializable and comparable.
// get MonetaryAmount from CurrencyUnit
CurrencyUnit euro = MonetaryCurrencies.getCurrency("EUR");
MonetaryAmount fiveEuro = Money.of(5, euro);

// get MonetaryAmount from currency code
MonetaryAmount tenUsDollar = Money.of(10, "USD");

// FastMoney is an alternative MonetaryAmount factory that focuses on performance
MonetaryAmount sevenEuro = FastMoney.of(7, euro);
Money and FastMoney are two MonetaryAmount implementations of JavaMoney. Money is the default implementation that stores number values using BigDecimal. FastMoney is an alternative implementation which stores amounts in long fields. According to the documentation  operations on FastMoney are 10-15 times faster compared to Money. However, FastMoney is limited by the size and precision of the long type.

Please note that Money and FastMoney are implementation specific classes (located in org.javamoney.moneta.* instead of javax.money.*). If you want to avoid implementation specific classes, you have to obtain a MonetaryAmountFactory to create a MonetaryAmount instance:
MonetaryAmount specAmount = MonetaryAmounts.getDefaultAmountFactory()
    .setNumber(123.45)
    .setCurrency("USD")
    .create();
Two MontetaryAmount instances are considered equal if the implementation classes, the currency units and the numeric values are equal:
MonetaryAmount oneEuro = Money.of(1, MonetaryCurrencies.getCurrency("EUR"));
boolean isEqual = oneEuro.equals(Money.of(1, "EUR")); // true
boolean isEqualFast = oneEuro.equals(FastMoney.of(1, "EUR")); // false
MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:
MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();

int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5

// NumberValue extends java.lang.Number. 
// So we assign numberValue to a variable of type Number
Number number = numberValue;

Working with MonetaryAmounts
Mathematical operations can be performed with MonetaryAmount:
MonetaryAmount twelveEuro = fiveEuro.add(sevenEuro); // "EUR 12"
MonetaryAmount twoEuro = sevenEuro.subtract(fiveEuro); // "EUR 2"
MonetaryAmount sevenPointFiveEuro = fiveEuro.multiply(1.5); // "EUR 7.5"

// MonetaryAmount can have a negative NumberValue
MonetaryAmount minusTwoEuro = fiveEuro.subtract(sevenEuro); // "EUR -2"

// some useful utility methods
boolean greaterThan = sevenEuro.isGreaterThan(fiveEuro); // true
boolean positive = sevenEuro.isPositive(); // true
boolean zero = sevenEuro.isZero(); // false

// Note that MonetaryAmounts need to have the same CurrencyUnit to do mathematical operations
// this fails with: javax.money.MonetaryException: Currency mismatch: EUR/USD
fiveEuro.add(tenUsDollar);
Rounding is another important part when working with money. MonetaryAmounts can be rounded using a rounding operator:
CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35
Here 12.3456 US Dollars are rounded with the default rounding for this currency.

When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available. These methods can be used together with the Java 8 Stream API.

Consider the following collection:
List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));
We can now filter amounts by CurrencyUnit:
CurrencyUnit yen = MonetaryCurrencies.getCurrency("JPY");
CurrencyUnit dollar = MonetaryCurrencies.getCurrency("USD");

// filter by currency, get only dollars
// result is [USD 18, USD 7, USD 42]
List<MonetaryAmount> onlyDollar = amounts.stream()
    .filter(MonetaryFunctions.isCurrency(dollar))
    .collect(Collectors.toList());

// filter by currency, get only dollars and yen
// [USD 18, USD 7, JPY 13.37, USD 42]
List<MonetaryAmount> onlyDollarAndYen = amounts.stream()
    .filter(MonetaryFunctions.isCurrency(dollar, yen))
    .collect(Collectors.toList());
We can also filter out MonetaryAmounts smaller or greater than a specific threshold:
MonetaryAmount tenDollar = Money.of(10, dollar);

// [USD 42, USD 18]
List<MonetaryAmount> greaterThanTenDollar = amounts.stream()
    .filter(MonetaryFunctions.isCurrency(dollar))
    .filter(MonetaryFunctions.isGreaterThan(tenDollar))
    .collect(Collectors.toList());
Sorting works in a similar way:
// Sorting dollar values by number value
// [USD 7, USD 18, USD 42]
List<MonetaryAmount> sortedByAmount = onlyDollar.stream()
    .sorted(MonetaryFunctions.sortNumber())
    .collect(Collectors.toList());

// Sorting by CurrencyUnit
// [EUR 2, JPY 13.37, USD 42, USD 7, USD 18]
List<MonetaryAmount> sortedByCurrencyUnit = amounts.stream()
    .sorted(MonetaryFunctions.sortCurrencyUnit())
    .collect(Collectors.toList());
Grouping functions:
// Grouping by CurrencyUnit
// {USD=[USD 42, USD 7, USD 18], EUR=[EUR 2], JPY=[JPY 13.37]}
Map<CurrencyUnit, List<MonetaryAmount>> groupedByCurrency = amounts.stream()
    .collect(MonetaryFunctions.groupByCurrencyUnit());

// Grouping by summarizing MonetaryAmounts
Map<CurrencyUnit, MonetarySummaryStatistics> summary = amounts.stream()
    .collect(MonetaryFunctions.groupBySummarizingMonetary()).get();

// get summary for CurrencyUnit USD
MonetarySummaryStatistics dollarSummary = summary.get(dollar);
MonetaryAmount average = dollarSummary.getAverage(); // "USD 22.333333333333333333.."
MonetaryAmount min = dollarSummary.getMin(); // "USD 7"
MonetaryAmount max = dollarSummary.getMax(); // "USD 42"
MonetaryAmount sum = dollarSummary.getSum(); // "USD 67"
long count = dollarSummary.getCount(); // 3
MonetaryFunctions also provides reduction function that can be used to obtain the max, min and sum of a MonetaryAmount collection:
List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(10, "EUR"));
amounts.add(Money.of(7.5, "EUR"));
amounts.add(Money.of(12, "EUR"));

Optional<MonetaryAmount> max = amounts.stream().reduce(MonetaryFunctions.max()); // "EUR 7.5"
Optional<MonetaryAmount> min = amounts.stream().reduce(MonetaryFunctions.min()); // "EUR 12"
Optional<MonetaryAmount> sum = amounts.stream().reduce(MonetaryFunctions.sum()); // "EUR 29.5"

Custom MonetaryAmount operations
MonetaryAmount provides a nice extension point called MonetaryOperator. MonetaryOperator is a functional interface that takes a MonetaryAmount as input and creates a new MonetaryAmount based on the input.
// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
  BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
  BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
  return Money.of(tenPercent, amount.getCurrency());
};

MonetaryAmount dollars = Money.of(12.34567, "USD");

// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567
Some standard API features are implemented as MonetaryOperator. For example, the rounding features we saw above are implemented as MonetaryOperator.


Exchange rates
Currency exchange rates can be obtained using an ExchangeRateProvider. JavaMoney comes with multiple different ExchangeRateProvider implementations. The two most important implementations are ECBCurrentRateProvider and IMFRateProvider.
ECBCurrentRateProvider queries the European Central Bank (ECB) data feed for getting current exchange rates while IMFRateProvider uses International Monetary Fund (IMF) conversion rates.
// get the default ExchangeRateProvider (CompoundRateProvider)
ExchangeRateProvider exchangeRateProvider = MonetaryConversions.getExchangeRateProvider();

// get the names of the default provider chain
// [IDENT, ECB, IMF, ECB-HIST]
List<String> defaultProviderChain = MonetaryConversions.getDefaultProviderChain();

// get a specific ExchangeRateProvider (here ECB)
ExchangeRateProvider ecbExchangeRateProvider = MonetaryConversions.getExchangeRateProvider("ECB");
If no specific ExchangeRateProvider is requested a CompoundRateProvider will be returned. CompoundRateProvider delegates exchange rate requests to a chain of ExchangeRateProviders and returns the result from the first provider that returns an adequate result.
// get the exchange rate from euro to us dollar
ExchangeRate rate = exchangeRateProvider.getExchangeRate("EUR", "USD");

NumberValue factor = rate.getFactor(); // 1.2537 (at time writing)
CurrencyUnit baseCurrency = rate.getBaseCurrency(); // EUR
CurrencyUnit targetCurrency = rate.getCurrency(); // USD

Currency conversion
Conversion between currencies is be done with CurrencyConversions that can be obtained from ExchangeRateProviders:
// get the CurrencyConversion from the default provider chain
CurrencyConversion dollarConversion = MonetaryConversions.getConversion("USD");

// get the CurrencyConversion from a specific provider
CurrencyConversion ecbDollarConversion = ecbExchangeRateProvider.getCurrencyConversion("USD");

MonetaryAmount tenEuro = Money.of(10, "EUR");

// convert 10 euro to us dollar 
MonetaryAmount inDollar = tenEuro.with(dollarConversion); // "USD 12.537" (at the time writing)
Note that CurrencyConversion implements MonetaryOperator. Like other operators it can be applied using MonetaryAmount.with().

Formatting and parsing
MonetaryAmounts can be parsed/formatted from/to string using a MonetaryAmountFormat:
// formatting by locale specific formats
MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMANY);
MonetaryAmountFormat usFormat = MonetaryFormats.getAmountFormat(Locale.CANADA);

MonetaryAmount amount = Money.of(12345.67, "USD");

String usFormatted = usFormat.format(amount); // "USD12,345.67"
String germanFormatted = germanFormat.format(amount); // 12.345,67 USD

// A MonetaryAmountFormat can also be used to parse MonetaryAmounts from strings
MonetaryAmount parsed = germanFormat.parse("12,4 USD");
With AmountFormatQueryBuilder custom formats can be created:
// Creating a custom MonetaryAmountFormat
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(
    AmountFormatQueryBuilder.of(Locale.US)
        .set(CurrencyStyle.NAME)
        .set("pattern", "00,00,00,00.00 ¤")
        .build());

// results in "00,01,23,45.67 US Dollar"
String formatted = customFormat.format(amount);
Note that the ¤ symbol (\u00A) is used as currency placeholder inside the pattern string.


Summary
We looked at many parts of the new Money and Currency API. The implementation already looks quite solid (but definitely needs some more documentation). I hope we will see this API included in Java 9 :-)

You can find all the examples shown here on GitHub.

Share this post using Facebook, Twitter or Google+

Tuesday, October 14, 2014

Matching Latin characters with regular expressions

Recently I needed to check user input for non Latin characters. My first impression was that this cannot be done with regular expressions. It turned out that I was completely wrong.

Standard regular expression character classes like [a-zA-Z] or \w (word character) are not suitable for matching Latin characters, they are far too restrictive. For example, these classes exclude characters like öòóô or äáàâ which are used in many western and central European languages.

Luckily Java's java.regex.Pattern supports matching Unicode characters with \p. Various arguments can be passed with curly braces to \p. To match only Latin characters \p{IsLatin} can be used:
"öôóò".matches("\\p{IsLatin}+"); // matches
"Σήμε".matches("\\p{IsLatin}+"); // greek characters do not match
\p supports a wide range of Unicode scripts. It can be used to match Greek, Cyrillic, Braille and more.
Some examples:
"Σήμε".matches("^\\p{IsGreek}+$");
"ждля".matches("^\\p{IsCyrillic}+$");
"⠇⠏⠙⠟".matches("^\\p{IsBraille}+$");
"ᚊᚎᚑᚕᚙ᚛".matches("^\\p{IsOgam}+$");
Have a look at Character.UnicodeScript for the full list of supported scripts.

Share this post using Facebook, Twitter or Google+