001/* 002 * (C) Copyright 2010-2013 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Olivier Grisel 016 */ 017package org.nuxeo.ecm.platform.suggestbox.service.suggesters; 018 019import java.util.Map; 020import java.util.regex.Matcher; 021import java.util.regex.Pattern; 022 023/** 024 * Simple interpolation for i18n messages with parameters independently of the UI layer. Only support parameter 025 * replacement with the "{0}", "{1}"... syntax. 026 * 027 * @author ogrisel 028 */ 029public class I18nHelper { 030 031 public static final Pattern PLACEHOLDER = Pattern.compile("\\{(\\d+)\\}"); 032 033 protected Map<String, String> messages; 034 035 public I18nHelper(Map<String, String> messages) { 036 this.messages = messages; 037 } 038 039 public static I18nHelper instanceFor(Map<String, String> messages) { 040 return new I18nHelper(messages); 041 } 042 043 public static String interpolate(String message, Object... params) { 044 Matcher matcher = PLACEHOLDER.matcher(message); 045 StringBuffer sb = new StringBuffer(); 046 while (matcher.find()) { 047 int paramId = Integer.valueOf(matcher.group(1)); 048 if (paramId >= 0 && paramId < params.length) { 049 String replacement = params[paramId].toString(); 050 matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); 051 } else { 052 throw new IllegalArgumentException(String.format("Invalid placeholder %d in message '%s': %d " 053 + "parameters provided", paramId, message, params.length)); 054 } 055 } 056 matcher.appendTail(sb); 057 return sb.toString(); 058 } 059 060 public String translate(String label, Object... params) { 061 String message = messages.get(label); 062 if (message == null) { 063 message = label; 064 } 065 return interpolate(message, params); 066 } 067 068}