001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.dataformat.bindy.format;
018    
019    import java.text.DecimalFormat;
020    import java.text.NumberFormat;
021    import java.util.Locale;
022    
023    import org.apache.camel.dataformat.bindy.PatternFormat;
024    import org.apache.camel.util.ObjectHelper;
025    
026    public abstract class NumberPatternFormat<T> implements PatternFormat<T> {
027    
028        private String pattern;
029        private Locale locale = Locale.getDefault();
030    
031        public NumberPatternFormat() {
032        }
033    
034        public NumberPatternFormat(String pattern, Locale locale) {
035            this.pattern = pattern;
036            this.locale = locale != null ? locale : Locale.getDefault();
037        }
038    
039        public String format(T object) throws Exception {
040            ObjectHelper.notNull(this.pattern, "pattern");
041            return this.getNumberFormat().format(object);
042        }
043    
044        @SuppressWarnings("unchecked")
045        public T parse(String string) throws Exception {
046            ObjectHelper.notNull(this.pattern, "pattern");
047            return (T)this.getNumberFormat().parse(string);
048        }
049    
050        protected NumberFormat getNumberFormat() {
051            NumberFormat format = NumberFormat.getNumberInstance(locale);
052            if (format instanceof DecimalFormat) {
053                ((DecimalFormat)format).applyLocalizedPattern(pattern);
054            }
055            return format;
056        }
057    
058        public String getPattern() {
059            return pattern;
060        }
061    
062        public void setPattern(String pattern) {
063            this.pattern = pattern;
064        }
065    }