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 * <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 011 * <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a> 012 * 013 * 014 * $Id$ 015 */ 016 017package org.nuxeo.ecm.platform.rendering.fm.extensions; 018 019import java.text.MessageFormat; 020import java.util.List; 021import java.util.Locale; 022import java.util.MissingResourceException; 023 024import org.nuxeo.ecm.platform.rendering.fm.i18n.ResourceComposite; 025 026import freemarker.template.SimpleScalar; 027import freemarker.template.TemplateMethodModelEx; 028import freemarker.template.TemplateModelException; 029 030/** 031 * Message method that differs from the standard one as its second argument is the locale. 032 * 033 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 034 * @author <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a> 035 */ 036public class LocaleMessagesMethod implements TemplateMethodModelEx { 037 038 protected ResourceComposite bundle; 039 040 public LocaleMessagesMethod(ResourceComposite bundle) { 041 setBundle(bundle); 042 } 043 044 public void setBundle(ResourceComposite bundle) { 045 this.bundle = bundle; 046 if (this.bundle == null) { 047 this.bundle = new ResourceComposite(); 048 } 049 } 050 051 public ResourceComposite getBundle() { 052 return bundle; 053 } 054 055 public Object exec(List arguments) throws TemplateModelException { 056 int size = arguments.size(); 057 if (size < 2) { 058 throw new TemplateModelException("Invalid number of arguments for messages(key, local [, args ..]) method"); 059 } 060 String key; 061 SimpleScalar scalar = (SimpleScalar) arguments.get(0); 062 if (scalar != null) { 063 key = scalar.getAsString(); 064 } else { 065 throw new TemplateModelException("the argument is not defined"); 066 } 067 068 scalar = (SimpleScalar) arguments.get(1); 069 String locale; 070 if (scalar != null) { 071 locale = scalar.getAsString(); 072 } else { 073 throw new TemplateModelException("the argument is not defined"); 074 } 075 076 String value; 077 try { 078 value = bundle.getString(key, new Locale(locale)); 079 } catch (MissingResourceException e) { 080 return '!' + key + '!'; 081 } 082 if (size > 2) { // format the string using given args 083 String[] args = new String[size - 2]; 084 for (int i = 0; i < args.length; i++) { 085 args[i] = ((SimpleScalar) arguments.get(i + 2)).getAsString(); 086 } 087 value = MessageFormat.format(value, (Object[]) args); 088 } 089 return value; 090 } 091 092}