View Javadoc
1   /*
2    * CSVeed (https://github.com/42BV/CSVeed)
3    *
4    * Copyright 2013-2023 CSVeed.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * https://www.apache.org/licenses/LICENSE-2.0.txt
10   */
11  package org.csveed.row;
12  
13  import java.util.HashMap;
14  import java.util.Iterator;
15  import java.util.Locale;
16  import java.util.Map;
17  
18  import org.csveed.api.Header;
19  import org.csveed.common.Column;
20  import org.csveed.report.CsvException;
21  import org.csveed.report.GeneralError;
22  import org.csveed.report.RowReport;
23  
24  /**
25   * The Class HeaderImpl.
26   */
27  public class HeaderImpl implements Header {
28  
29      /** The header. */
30      private Line header;
31  
32      /** The index to name. */
33      private Map<Column, String> indexToName = new HashMap<>();
34  
35      /** The name to index. */
36      private Map<String, Column> nameToIndex = new HashMap<>();
37  
38      /**
39       * Instantiates a new header impl.
40       *
41       * @param row
42       *            the row
43       */
44      public HeaderImpl(Line row) {
45          this.header = row;
46          Column currentColumn = new Column();
47          for (String headerCell : header) {
48              this.indexToName.put(currentColumn, headerCell);
49              this.nameToIndex.put(headerCell.toLowerCase(Locale.getDefault()), currentColumn);
50              currentColumn = currentColumn.nextColumn();
51          }
52      }
53  
54      @Override
55      public int size() {
56          return header.size();
57      }
58  
59      @Override
60      public String getName(int columnIndex) {
61          Column column = new Column(columnIndex);
62          String name = this.indexToName.get(column);
63          if (name == null) {
64              throw new CsvException(new GeneralError("No column name found for index " + column.getColumnIndex()));
65          }
66          return name;
67      }
68  
69      @Override
70      public int getIndex(String columnName) {
71          Column column = this.nameToIndex.get(columnName.toLowerCase(Locale.getDefault()));
72          if (column == null) {
73              throw new CsvException(new GeneralError("No column index found for name " + columnName));
74          }
75          return column.getColumnIndex();
76      }
77  
78      @Override
79      public Iterator<String> iterator() {
80          return header.iterator();
81      }
82  
83      @Override
84      public RowReport reportOnEndOfLine() {
85          return header.reportOnEndOfLine();
86      }
87  
88  }