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