View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
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.argeo.util;
17  
18  import java.util.HashMap;
19  import java.util.List;
20  import java.util.Map;
21  
22  /**
23   * CSV parser allowing to process lines as maps whose keys are the header
24   * fields.
25   */
26  public abstract class CsvParserWithLinesAsMap extends CsvParser {
27  
28  	/**
29  	 * Actually processes a line.
30  	 * 
31  	 * @param lineNumber
32  	 *            the current line number, starts at 1 (the header, if header
33  	 *            processing is enabled, the first lien otherwise)
34  	 * @param line
35  	 *            the parsed tokens as a map whose keys are the header fields
36  	 */
37  	protected abstract void processLine(Integer lineNumber,
38  			Map<String, String> line);
39  
40  	protected final void processLine(Integer lineNumber, List<String> header,
41  			List<String> tokens) {
42  		if (header == null)
43  			throw new UtilsException("Only CSV with header is supported");
44  		Map<String, String> line = new HashMap<String, String>();
45  		for (int i = 0; i < header.size(); i++) {
46  			String key = header.get(i);
47  			String value = null;
48  			if (i < tokens.size())
49  				value = tokens.get(i);
50  			line.put(key, value);
51  		}
52  		processLine(lineNumber, line);
53  	}
54  
55  }