MonetaPluginProvider.java

package org.freshmarker.money;

import org.freshmarker.core.buildin.BuiltIn;
import org.freshmarker.core.buildin.BuiltInKey;
import org.freshmarker.core.buildin.BuiltInKeyBuilder;
import org.freshmarker.core.formatter.Formatter;
import org.freshmarker.core.model.TemplateObject;
import org.freshmarker.core.model.primitive.TemplateNumber;
import org.freshmarker.core.plugin.PluginProvider;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.spi.JDKCurrencyAdapter;

import java.util.Map;
import java.util.function.Function;

public final class MonetaPluginProvider implements PluginProvider {
    @Override
    public void registerMapper(Map<Class<?>, Function<Object, TemplateObject>> mapper) {
        mapper.put(Money.class, o -> new TemplateMoney((Money) o));
        mapper.put(JDKCurrencyAdapter.class, o -> new TemplateConcurrency((JDKCurrencyAdapter) o));
    }

    @Override
    public void registerBuildIn(Map<BuiltInKey, BuiltIn> builtIns) {
        BuiltInKeyBuilder<TemplateMoney> builder = new BuiltInKeyBuilder<>(TemplateMoney.class);
        builtIns.put(builder.of("currency"), (x, y, e) -> new TemplateConcurrency((JDKCurrencyAdapter) ((TemplateMoney) x).getValue().getCurrency()));
        builtIns.put(builder.of("amount"), (x, y, e) -> new TemplateNumber(((TemplateMoney) x).getValue().getNumberStripped()));
    }

    @Override
    public void registerFormatter(Map<Class<? extends TemplateObject>, Formatter> formatter) {
        formatter.put(TemplateMoney.class, new MonetaryFormatter());
    }
}