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 a Long.
25   * 
26   * @author Kasper B. Graversen
27   */
28  public class ParseLong extends CellProcessorAdaptor implements StringCellProcessor {
29  	
30  	/**
31  	 * Constructs a new <tt>ParseLong</tt> processor, which converts a String to a Long.
32  	 */
33  	public ParseLong() {
34  		super();
35  	}
36  	
37  	/**
38  	 * Constructs a new <tt>ParseLong</tt> processor, which converts a String to a Long, then calls the next processor
39  	 * 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 ParseLong(final LongCellProcessor next) {
47  		super(next);
48  	}
49  	
50  	/**
51  	 * {@inheritDoc}
52  	 * 
53  	 * @throws SuperCsvCellProcessorException
54  	 *             if value is null, isn't a Long or String, or can't be parsed as a Long
55  	 */
56  	public Object execute(final Object value, final CsvContext context) {
57  		validateInputNotNull(value, context);
58  		
59  		final Long result;
60  		if( value instanceof Long ) {
61  			result = (Long) value;
62  		} else if( value instanceof String ) {
63  			try {
64  				result = Long.parseLong((String) value);
65  			}
66  			catch(final NumberFormatException e) {
67  				throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as an Long", value),
68  					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 Long or String but is of type %s", actualClassName), context, this);
74  		}
75  		
76  		return next.execute(result, context);
77  	}
78  }