001/* 
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.rendering.fm.extensions;
016
017import java.text.MessageFormat;
018import java.util.List;
019import java.util.ListResourceBundle;
020import java.util.MissingResourceException;
021import java.util.ResourceBundle;
022
023import freemarker.template.SimpleScalar;
024import freemarker.template.TemplateMethodModelEx;
025import freemarker.template.TemplateModelException;
026
027/**
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030public class MessagesMethod implements TemplateMethodModelEx {
031
032    protected static final ResourceBundle NULL_BUNDLE = new ListResourceBundle() {
033        @Override
034        protected Object[][] getContents() {
035            return new Object[0][0];
036        }
037    };
038
039    protected ResourceBundle bundle;
040
041    public MessagesMethod(ResourceBundle bundle) {
042        setBundle(bundle);
043    }
044
045    public void setBundle(ResourceBundle bundle) {
046        this.bundle = bundle;
047        if (this.bundle == null) {
048            try {
049                this.bundle = ResourceBundle.getBundle("messages");
050            } catch (MissingResourceException e) {
051                this.bundle = NULL_BUNDLE;
052            }
053        }
054    }
055
056    public ResourceBundle getBundle() {
057        return bundle;
058    }
059
060    public Object exec(List arguments) throws TemplateModelException {
061        int size = arguments.size();
062        if (size < 1) {
063            throw new TemplateModelException("Invalid number of arguments for messages(key, args ..) method");
064        }
065        String key;
066        SimpleScalar scalar = (SimpleScalar) arguments.get(0);
067        if (scalar != null) {
068            key = scalar.getAsString();
069        } else {
070            throw new TemplateModelException("the argument is not defined");
071        }
072        String value;
073        try {
074            value = bundle.getString(key);
075        } catch (MissingResourceException e) {
076            return '!' + key + '!';
077        }
078        if (size > 1) { // format the string using given args
079            String[] args = new String[size - 1];
080            for (int i = 0; i < args.length; i++) {
081                args[i] = ((SimpleScalar) arguments.get(i + 1)).getAsString();
082            }
083            value = MessageFormat.format(value, (Object[]) args);
084        }
085        return value;
086    }
087
088}