001    /*
002     * Apache License
003     * Version 2.0, January 2004
004     * http://www.apache.org/licenses/
005     *
006     * Copyright 2008-2010 by chenillekit.org
007     *
008     * Licensed under the Apache License, Version 2.0 (the "License");
009     * you may not use this file except in compliance with the License.
010     * You may obtain a copy of the License at
011     *
012     * http://www.apache.org/licenses/LICENSE-2.0
013     */
014    package org.chenillekit.tapestry.core.components;
015    
016    import org.apache.tapestry5.BindingConstants;
017    import org.apache.tapestry5.MarkupWriter;
018    import org.apache.tapestry5.annotations.Parameter;
019    import org.apache.tapestry5.annotations.Service;
020    import org.apache.tapestry5.ioc.annotations.Inject;
021    import org.apache.tapestry5.services.Request;
022    import org.slf4j.Logger;
023    
024    import java.text.DecimalFormat;
025    import java.text.DecimalFormatSymbols;
026    
027    /**
028     * Formats a Number object with the given <em>mask<em>.
029     *
030     * @version $Id: NumberFormat.java 645 2010-03-11 13:05:54Z homburgs $
031     */
032    public class NumberFormat
033    {
034        @Inject
035        private Logger logger;
036    
037        /**
038         * the numeric value.
039         */
040        @Parameter(required = true, defaultPrefix = BindingConstants.PROP)
041        private Number value;
042    
043        /**
044         * the format mask.
045         */
046        @Parameter(required = false, defaultPrefix = BindingConstants.LITERAL, value = "#,##0.0#;(#,##0.0#)")
047        private String mask;
048    
049        @Inject
050        @Service("Request")
051        private Request request;
052    
053        private String getFormatedValue()
054        {
055            try
056            {
057                java.text.NumberFormat numberFormat = new DecimalFormat(mask, new DecimalFormatSymbols(request.getLocale()));
058                return numberFormat.format(value);
059            }
060            catch (Exception e)
061            {
062                logger.error(e.getLocalizedMessage());
063                return value.toString();
064            }
065        }
066    
067        void beginRender(MarkupWriter writer)
068        {
069            if (value != null)
070                writer.write(getFormatedValue());
071        }
072    }