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