001    /*
002     *  Copyright 2003-2004 The Apache Software Foundation
003     *
004     *  Licensed under the Apache License, Version 2.0 (the "License");
005     *  you may not use this file except in compliance with the License.
006     *  You may obtain a copy of the License at
007     *
008     *      http://www.apache.org/licenses/LICENSE-2.0
009     *
010     *  Unless required by applicable law or agreed to in writing, software
011     *  distributed under the License is distributed on an "AS IS" BASIS,
012     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     *  See the License for the specific language governing permissions and
014     *  limitations under the License.
015     */
016    package org.apache.commons.convert1.format;
017    
018    
019    import org.apache.commons.convert1.ConversionException;
020    import org.apache.commons.convert1.Converter;
021    
022    import java.text.Format;
023    import java.text.ParseException;
024    
025    /**
026     * java.text.Format.parseObject(String); Object based converter.
027     *
028     * @author Henri Yandell
029     * @version $Id: ParseConverter.java 155441 2005-02-26 13:19:22Z dirkv $
030     * @since 0.1
031     */
032    
033    public final class ParseConverter implements Converter {
034    
035        private Format format;
036    
037        //H? Should this have a Class paramter fortype checking?
038        public ParseConverter(Format format) {
039            this.format = format;
040        }
041    
042        /**
043         * Parse the specified input String into an Object
044         *
045         * @param type Data type to which this value should be converted
046         * @param value The input value to be converted
047         *
048         * @exception ConversionException if conversion cannot be performed
049         *  successfully
050         */
051        public Object convert(Class type, Object value) {
052            if(value == null) {
053                return null; //H? ?? error?
054            }
055    
056            if(value.getClass() != String.class) {
057                throw new ConversionException("ParseConverter must parse Strings. ");
058            }
059    
060            try {
061                return this.format.parseObject(value.toString());
062            } catch(ParseException pe) {
063                throw new ConversionException("Error in parsing: "+value, pe);
064            }
065        }
066    
067    
068    }