View Javadoc
1   /*
2    * Copyright 2007 Kasper B. Graversen
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.supercsv.cellprocessor;
17  
18  import org.supercsv.cellprocessor.ift.LongCellProcessor;
19  import org.supercsv.cellprocessor.ift.StringCellProcessor;
20  import org.supercsv.exception.SuperCsvCellProcessorException;
21  import org.supercsv.util.CsvContext;
22  
23  /**
24   * Converts a String to an Integer.
25   * 
26   * @author Kasper B. Graversen
27   */
28  public class ParseInt extends CellProcessorAdaptor implements StringCellProcessor {
29  	
30  	/**
31  	 * Constructs a new <tt>ParseInt</tt> processor, which converts a String to an Integer.
32  	 */
33  	public ParseInt() {
34  		super();
35  	}
36  	
37  	/**
38  	 * Constructs a new <tt>ParseInt</tt> processor, which converts a String to an Integer, then calls the next
39  	 * processor in the chain.
40  	 * 
41  	 * @param next
42  	 *            the next processor in the chain
43  	 * @throws NullPointerException
44  	 *             if next is null
45  	 */
46  	public ParseInt(final LongCellProcessor next) {
47  		super(next);
48  	}
49  	
50  	/**
51  	 * {@inheritDoc}
52  	 * 
53  	 * @throws SuperCsvCellProcessorException
54  	 *             if value is null, isn't an Integer or String, or can't be parsed as an Integer
55  	 */
56  	public Object execute(final Object value, final CsvContext context) {
57  		validateInputNotNull(value, context);
58  		
59  		final Integer result;
60  		if( value instanceof Integer ) {
61  			result = (Integer) value;
62  		} else if( value instanceof String ) {
63  			try {
64  				result = Integer.valueOf((String) value);
65  			}
66  			catch(final NumberFormatException e) {
67  				throw new SuperCsvCellProcessorException(
68  					String.format("'%s' could not be parsed as an Integer", value), context, this, e);
69  			}
70  		} else {
71  			final String actualClassName = value.getClass().getName();
72  			throw new SuperCsvCellProcessorException(String.format(
73  				"the input value should be of type Integer or String but is of type %s", actualClassName), context,
74  				this);
75  		}
76  		
77  		return next.execute(result, context);
78  	}
79  }