001/* 002 * (C) Copyright 2010-2013 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Olivier Grisel 018 */ 019package org.nuxeo.ecm.platform.suggestbox.service.suggesters; 020 021import java.util.Map; 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025/** 026 * Simple interpolation for i18n messages with parameters independently of the UI layer. Only support parameter 027 * replacement with the "{0}", "{1}"... syntax. 028 * 029 * @author ogrisel 030 */ 031public class I18nHelper { 032 033 public static final Pattern PLACEHOLDER = Pattern.compile("\\{(\\d+)\\}"); 034 035 protected Map<String, String> messages; 036 037 public I18nHelper(Map<String, String> messages) { 038 this.messages = messages; 039 } 040 041 public static I18nHelper instanceFor(Map<String, String> messages) { 042 return new I18nHelper(messages); 043 } 044 045 public static String interpolate(String message, Object... params) { 046 Matcher matcher = PLACEHOLDER.matcher(message); 047 StringBuffer sb = new StringBuffer(); 048 while (matcher.find()) { 049 int paramId = Integer.valueOf(matcher.group(1)); 050 if (paramId >= 0 && paramId < params.length) { 051 String replacement = params[paramId].toString(); 052 matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); 053 } else { 054 throw new IllegalArgumentException(String.format("Invalid placeholder %d in message '%s': %d " 055 + "parameters provided", paramId, message, params.length)); 056 } 057 } 058 matcher.appendTail(sb); 059 return sb.toString(); 060 } 061 062 public String translate(String label, Object... params) { 063 String message = messages.get(label); 064 if (message == null) { 065 message = label; 066 } 067 return interpolate(message, params); 068 } 069 070}