001// Copyright 2009 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
015package org.apache.tapestry5.internal.translator;
016
017import org.apache.tapestry5.Field;
018import org.apache.tapestry5.MarkupWriter;
019import org.apache.tapestry5.ValidationException;
020import org.apache.tapestry5.services.FormSupport;
021
022import java.text.ParseException;
023
024/**
025 * Uses a {@link org.apache.tapestry5.internal.translator.NumericTranslatorSupport} to provide proper locale-aware
026 * support for all the built-in numeric types.
027 *
028 * @since 5.1.0.1
029 */
030public class NumericTranslator<T extends Number> extends AbstractTranslator<T>
031{
032    private final NumericTranslatorSupport support;
033
034    public NumericTranslator(String name, Class<T> type, NumericTranslatorSupport support)
035    {
036        super(name, type, support.getMessageKey(type));
037
038        this.support = support;
039    }
040
041    public void render(Field field, String message, MarkupWriter writer, FormSupport formSupport)
042    {
043        if (formSupport.isClientValidationEnabled())
044            support.addValidation(getType(), field, message);
045    }
046
047    public T parseClient(Field field, String clientValue, String message) throws ValidationException
048    {
049        try
050        {
051            return support.parseClient(getType(), clientValue);
052        }
053        catch (ParseException ex)
054        {
055            throw new ValidationException(message);
056        }
057    }
058
059    public String toClient(T value)
060    {
061        return support.toClient(getType(), value);
062    }
063}