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.example.dozer;
17  
18  import java.io.FileReader;
19  
20  import org.supercsv.cellprocessor.CellProcessorAdaptor;
21  import org.supercsv.cellprocessor.Optional;
22  import org.supercsv.cellprocessor.ParseBool;
23  import org.supercsv.cellprocessor.ParseInt;
24  import org.supercsv.cellprocessor.ift.CellProcessor;
25  import org.supercsv.io.dozer.CsvDozerBeanReader;
26  import org.supercsv.io.dozer.ICsvDozerBeanReader;
27  import org.supercsv.mock.dozer.Answer;
28  import org.supercsv.mock.dozer.SurveyResponse;
29  import org.supercsv.prefs.CsvPreference;
30  import org.supercsv.util.CsvContext;
31  
32  /**
33   * Dozer reading examples.
34   */
35  public class Reading {
36  	
37  	private static final String CSV_FILENAME = "src/test/resources/surveyresponses.csv";
38  	
39  	private static final String[] FIELD_MAPPING = new String[] { 
40  		"age",                   // simple field mapping (like CsvBeanReader)
41  		"consentGiven",          // as above
42  		"answers[0].questionNo", // indexed (first element) + deep mapping
43  		"answers[0].answer", 
44  		"answers[1].questionNo", // indexed (second element) + deep mapping
45  		"answers[1].answer", 
46  		"answers[2].questionNo", 
47  		"answers[2].answer" };
48  	
49  	public static void main(String[] args) throws Exception {
50  		readWithCsvDozerBeanReader();
51  		partialReadWithCsvDozerBeanReader();
52  		readWithCsvDozerBeanReaderUsingIndexMappingAndHints();
53  	}
54  	
55  	/**
56  	 * An example of reading using CsvDozerBeanReader.
57  	 */
58  	private static void readWithCsvDozerBeanReader() throws Exception {
59  		
60  		final CellProcessor[] processors = new CellProcessor[] { 
61  			new Optional(new ParseInt()), // age
62  			new ParseBool(),              // consent
63  			new ParseInt(),               // questionNo 1
64  			new Optional(),               // answer 1
65  			new ParseInt(),               // questionNo 2
66  			new Optional(),               // answer 2
67  			new ParseInt(),               // questionNo 3
68  			new Optional()                // answer 3
69  		};
70  		
71  		ICsvDozerBeanReader beanReader = null;
72  		try {
73  			beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
74  			
75  			beanReader.getHeader(true); // ignore the header
76  			beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING);
77  			
78  			SurveyResponse surveyResponse;
79  			while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) {
80  				System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(),
81  					beanReader.getRowNumber(), surveyResponse));
82  			}
83  			
84  		}
85  		finally {
86  			if( beanReader != null ) {
87  				beanReader.close();
88  			}
89  		}
90  	}
91  	
92  	/**
93  	 * An example of partial reading using CsvDozerBeanReader.
94  	 */
95  	private static void partialReadWithCsvDozerBeanReader() throws Exception {
96  		
97  		// ignore age, and question/answer 3
98  		final String[] partialFieldMapping = new String[] { null, "consentGiven", "answers[0].questionNo",
99  			"answers[0].answer", "answers[1].questionNo", "answers[1].answer", null, null };
100 		
101 		// set processors for ignored columns to null for efficiency (could have used full array if we wanted them to execute anyway)
102 		final CellProcessor[] processors = new CellProcessor[] { null, new ParseBool(), new ParseInt(), new Optional(),
103 			new ParseInt(), new Optional(), null, null };
104 		
105 		ICsvDozerBeanReader beanReader = null;
106 		try {
107 			beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
108 			
109 			beanReader.getHeader(true); // ignore the header
110 			beanReader.configureBeanMapping(SurveyResponse.class, partialFieldMapping);
111 			
112 			SurveyResponse surveyResponse;
113 			while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) {
114 				System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(),
115 					beanReader.getRowNumber(), surveyResponse));
116 			}
117 			
118 		}
119 		finally {
120 			if( beanReader != null ) {
121 				beanReader.close();
122 			}
123 		}
124 	}
125 	
126 	/**
127 	 * An example of reading using CsvDozerBeanReader that uses indexed mapping and a cell processor
128 	 * to read into a List of Answer beans (this requires a hint).
129 	 */
130 	private static void readWithCsvDozerBeanReaderUsingIndexMappingAndHints() throws Exception {
131 		
132 		// simple cell processor that creates an Answer with a value
133 		final CellProcessor parseAnswer = new CellProcessorAdaptor() {
134 			public Object execute(Object value, CsvContext context) {
135 				return new Answer(null, (String) value);
136 			}
137 		};
138 		
139 		final CellProcessor[] processors = new CellProcessor[] { 
140 			new Optional(new ParseInt()), // age
141 			null,                         // consent
142 			null,                         // questionNo 1
143 			new Optional(parseAnswer),    // answer 1
144 			null,                         // questionNo 2
145 			new Optional(parseAnswer),    // answer 2
146 			null,                         // questionNo 3
147 			new Optional(parseAnswer)     // answer 3
148 		};
149 		
150 		// no deep mapping (answers[0].answer) required as we're using a cell processor to create the bean
151 		final String[] fieldMapping = {"age", null, null, "answers[0]", null, "answers[1]", null, "answers[2]"};
152 		
153 		// the indexed mappings need a hint for Dozer to work
154 		final Class<?>[] hintTypes = {null, null, null, Answer.class, null, Answer.class, null, Answer.class};
155 		
156 		ICsvDozerBeanReader beanReader = null;
157 		try {
158 			beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
159 			
160 			beanReader.getHeader(true); // ignore the header
161 			beanReader.configureBeanMapping(SurveyResponse.class, fieldMapping, hintTypes);
162 			
163 			SurveyResponse surveyResponse;
164 			while( (surveyResponse = beanReader.read(SurveyResponse.class, processors)) != null ) {
165 				System.out.println(String.format("lineNo=%s, rowNo=%s, surveyResponse=%s", beanReader.getLineNumber(),
166 					beanReader.getRowNumber(), surveyResponse));
167 			}
168 			
169 		}
170 		finally {
171 			if( beanReader != null ) {
172 				beanReader.close();
173 			}
174 		}
175 	}
176 	
177 }