001 // Copyright 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry.form;
016
017 import java.text.MessageFormat;
018 import java.util.Locale;
019
020 import org.apache.hivemind.util.Defense;
021 import org.apache.tapestry.valid.ValidationStrings;
022
023 /**
024 * Wrapper around
025 * {@link org.apache.tapestry.valid.ValidationStrings#getMessagePattern(String, Locale)} and
026 * {@link java.text.MessageFormat#format(java.lang.String, java.lang.Object[])}.
027 *
028 * @author Howard Lewis Ship
029 * @since 4.0
030 */
031 public class ValidationMessagesImpl implements ValidationMessages
032 {
033 private final IFormComponent _field;
034
035 private final Locale _locale;
036
037 public ValidationMessagesImpl(IFormComponent field, Locale locale)
038 {
039 Defense.notNull(field, "field");
040 Defense.notNull(locale, "locale");
041
042 _field = field;
043 _locale = locale;
044 }
045
046 public String formatValidationMessage(String messageOverride, String messageKey,
047 Object[] arguments)
048 {
049 String message = extractLocalizedMessage(messageOverride, messageKey);
050
051 return MessageFormat.format(message, arguments);
052 }
053
054 private String extractLocalizedMessage(String messageOverride, String messageKey)
055 {
056 if (messageOverride == null)
057 return ValidationStrings.getMessagePattern(messageKey, _locale);
058
059 if (messageOverride.startsWith("%"))
060 {
061 String key = messageOverride.substring(1);
062
063 return _field.getContainer().getMessages().getMessage(key);
064 }
065
066 // Otherwise, a literal string
067
068 return messageOverride;
069 }
070
071 public Locale getLocale()
072 {
073 return _locale;
074 }
075
076 }