1 package com.opencsv.bean;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 /*
7 * Copyright 2007,2010 Kyle Miller.
8 *
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
12 *
13 * http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 */
21
22 /**
23 * Expands on {@link HeaderColumnNameMappingStrategy} by allowing the user to
24 * pass in a map of column names to bean names.
25 * This way the fields in the bean do not have to match the fields in the CSV
26 * file. This is only for when the user passes in the header names
27 * programmatically, and not for annotated beans.
28 *
29 * @param <T> Class to be mapped.
30 */
31 public class HeaderColumnNameTranslateMappingStrategy<T> extends HeaderNameBaseMappingStrategy<T> {
32 private final Map<String, String> columnMapping;
33
34 /**
35 * Default constructor. Considered stable.
36 * @see HeaderColumnNameTranslateMappingStrategyBuilder
37 */
38 public HeaderColumnNameTranslateMappingStrategy() {
39 columnMapping = new HashMap<>();
40 }
41
42 /**
43 * Constructor to allow setting options for header name mapping.
44 * Not considered stable. As new options are introduced for the mapping
45 * strategy, they will be introduced here. You are encouraged to use
46 * {@link HeaderColumnNameTranslateMappingStrategyBuilder}.
47 *
48 * @param forceCorrectRecordLength If set, every record will be shortened
49 * or lengthened to match the number of
50 * headers
51 * @see HeaderColumnNameTranslateMappingStrategyBuilder
52 */
53 public HeaderColumnNameTranslateMappingStrategy(boolean forceCorrectRecordLength) {
54 super(forceCorrectRecordLength);
55 columnMapping = new HashMap<>();
56 }
57
58 @Override
59 public String getColumnName(int col) {
60 String name = headerIndex.getByPosition(col);
61 if(name != null) {
62 name = columnMapping.get(name.toUpperCase());
63 }
64 return name;
65 }
66
67 /**
68 * Retrieves the column mappings of the strategy.
69 * @return The column mappings of the strategy.
70 */
71 public Map<String, String> getColumnMapping() {
72 return columnMapping;
73 }
74
75 /**
76 * Sets the column mapping to those passed in.
77 * @param columnMapping Source column mapping.
78 */
79 public void setColumnMapping(Map<String, String> columnMapping) {
80 this.columnMapping.clear();
81 for (Map.Entry<String, String> entry : columnMapping.entrySet()) {
82 this.columnMapping.put(entry.getKey().toUpperCase(), entry.getValue());
83 }
84 if(getType() != null) {
85 loadFieldMap();
86 }
87 }
88 }