KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > anupam > csv > CSVParserFactory


1 /*
2  * CSVParserFactory.java
3  *
4  * Copyright (C) 2005 Anupam Sengupta (anupamsg@users.sourceforge.net)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Version: $Revision: 1.3 $
21  */

22 package net.sf.anupam.csv;
23
24 import net.sf.anupam.csv.formatters.CSVFieldFormatter;
25 import net.sf.anupam.csv.formatters.CSVFormatterFactory;
26 import net.sf.anupam.csv.mapping.CSVBeanMapping;
27 import net.sf.anupam.csv.mapping.CSVFieldMapping;
28 import net.sf.anupam.csv.mapping.CSVMappingParser;
29 import net.sf.anupam.csv.exceptions.CSVOException;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33
34 import java.io.FileNotFoundException JavaDoc;
35 import java.io.FileReader JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.InputStreamReader JavaDoc;
38 import java.io.Reader JavaDoc;
39 import java.util.HashMap JavaDoc;
40 import java.util.Map JavaDoc;
41
42 /**
43  * Singleton factory for creating the {@link CSVParser CSVParser} parser objects
44  * for clients' of the framework. This factory uses the
45  * <code>csv-mapping.xml</code> mapping configuration to create CSV parsers
46  * customized for the POJO bean to parse. This is the first interface for
47  * clients of the framework.
48  *
49  * @author Anupam Sengupta
50  * @version $Revision: 1.3 $
51  * @see CSVParser
52  * @since 1.5
53  */

54 public final class CSVParserFactory {
55
56     /**
57      * The Mapping file name.
58      */

59     private static final String JavaDoc MAPPING_FILE_NAME = "csv-mapping.xml";
60
61     /**
62      * The logger to use.
63      */

64     private static final Log LOG = LogFactory.getLog(CSVParserFactory.class);
65
66     /**
67      * The singleton factory instance.
68      */

69     private static CSVParserFactory singleton;
70
71     private static final CSVFormatterFactory FORMATTER_FACTORY = CSVFormatterFactory
72             .getSingleton();
73
74     /**
75      * The CSV to POJO mapping repository.
76      */

77     private Map JavaDoc<String JavaDoc, CSVBeanMapping> beanMappings;
78
79     static {
80
81     }
82
83     /**
84      * Constructor for CSVParserFactory. Private as this is a singleton.
85      */

86     private CSVParserFactory() {
87         super();
88         beanMappings = new HashMap JavaDoc<String JavaDoc, CSVBeanMapping>();
89     }
90
91     /**
92      * Returns the singleton instance of this factory.
93      *
94      * @return the singleton parser factory
95      * @throws CSVOException thrown if the singleton cannot be created
96      */

97     public synchronized static CSVParserFactory getSingleton()
98             throws CSVOException {
99         if (singleton == null) {
100             // Create the singleton at startup.
101
singleton = new CSVParserFactory();
102             singleton.loadMappings();
103             LOG.info("Created the Singleton for: " + CSVParserFactory.class);
104         }
105         return singleton;
106     }
107
108     /**
109      * Loads the bean mapping configuration from the XML mapping file.
110      *
111      * @throws CSVOException thrown if the mapping cannot be loaded
112      */

113     private void loadMappings()
114             throws CSVOException {
115         final CSVMappingParser parser = new CSVMappingParser();
116         beanMappings.putAll(parser.getMappings(MAPPING_FILE_NAME, true));
117
118         for (String JavaDoc beanNames : beanMappings.keySet()) {
119             final CSVBeanMapping currentBeanMapping = beanMappings
120                     .get(beanNames);
121             for (CSVFieldMapping currentFieldMapping : currentBeanMapping) {
122                 createFormattersFor(currentFieldMapping);
123                 resolveBeanReferencesFor(currentFieldMapping);
124             }
125         }
126         LOG.debug("Loaded the CSV Mapping configuration from "
127                 + MAPPING_FILE_NAME);
128     }
129
130     /**
131      * Creates any necessary field formatters for the specified field mapping.
132      *
133      * @param fieldMapping the field for which formatters should be created
134      * @throws net.sf.anupam.csv.exceptions.CSVOException
135      * thrown if the specified formatters cannot be created
136      */

137     private void createFormattersFor(final CSVFieldMapping fieldMapping)
138             throws CSVOException {
139
140         final CSVFieldFormatter formatter = FORMATTER_FACTORY
141                 .createFormatterFor(fieldMapping.getReformatterName());
142         fieldMapping.setFormatter(formatter);
143
144     }
145
146     /**
147      * Resolves bean references for the specified field, and sets the bean
148      * mapping hierarchy accordingly.
149      *
150      * @param fieldMapping the field for which references need to be resolved
151      */

152     private void resolveBeanReferencesFor(final CSVFieldMapping fieldMapping) {
153
154         final String JavaDoc beanRefName = fieldMapping.getBeanReferenceName();
155         if (!beanRefName.equalsIgnoreCase("none")) {
156             final CSVBeanMapping referencedBean = getBeanMapping(beanRefName);
157
158             if (referencedBean != null) {
159                 fieldMapping.setBeanReference(referencedBean);
160             } else {
161                 LOG.warn("For field " + fieldMapping
162                         + " the referenced bean does not exist");
163                 fieldMapping.setBeanReferenceName("none");
164             }
165         }
166
167     }
168
169     /**
170      * Returns the requested bean mapping configuration.
171      *
172      * @param beanName the POJO bean for which the mapping is to be returned
173      * @return the CSV bean mapping, or <code>null</code> if not found
174      */

175     public CSVBeanMapping getBeanMapping(final String JavaDoc beanName) {
176         return beanMappings.get(beanName);
177     }
178
179     /**
180      * Returns a new CSV file parser for the specified mapping, and the
181      * specified CSV file.
182      *
183      * @param mappingName the CSV mapping to for which the parser should be created
184      * @param csvFileName the CSV file to be parsed
185      * @param inClassPath indicates whether the CSV file is in the classpath
186      * @return the CSV Parser, or <code>null</code> if not found
187      * @throws FileNotFoundException thrown if the specified CSV file cannot be found
188      * @see #getCSVParser(String,java.io.Reader)
189      */

190     public CSVParser getCSVParser(final String JavaDoc mappingName,
191                                   final String JavaDoc csvFileName, final boolean inClassPath
192     ) throws FileNotFoundException JavaDoc {
193
194         if (StringUtils.isEmpty(csvFileName)) {
195             LOG.warn("The specified CSV Filename is empty");
196             throw new IllegalArgumentException JavaDoc("File Name is empty");
197         }
198
199         final Reader JavaDoc reader;
200
201         try {
202             if (inClassPath) {
203                 final InputStream JavaDoc is = ClassLoader
204                         .getSystemResourceAsStream(csvFileName);
205                 if (is == null) {
206                     throw new FileNotFoundException JavaDoc("The CSV File: "
207                             + csvFileName + " was not found in the classpath");
208                 }
209                 reader = new InputStreamReader JavaDoc(is);
210             } else {
211                 reader = new FileReader JavaDoc(csvFileName);
212
213             }
214             LOG.debug("Successfully read the CSV file");
215         } catch (final FileNotFoundException JavaDoc e) {
216             LOG.warn("The specified CSV File: " + csvFileName
217                     + " was not found", e);
218             throw e;
219         }
220
221         return getCSVParser(mappingName, reader);
222     }
223
224     /**
225      * Returns a new CSV file parser for the specified mapping and the specified
226      * CSV reader stream.
227      *
228      * @param mappingName the CSV mapping for which the parser should be returned
229      * @param csvReader the CSV stream to parse
230      * @return the CSV Parser, or <code>null</code> if not found
231      * @see #getCSVParser(String,String,boolean)
232      */

233     public CSVParser getCSVParser(final String JavaDoc mappingName,
234                                   final Reader JavaDoc csvReader) {
235
236         final CSVBeanMapping beanMapping = getBeanMapping(mappingName);
237
238         if (beanMapping == null) {
239             LOG.warn("Specified bean mapping was not found");
240             throw new IllegalArgumentException JavaDoc(
241                     "Specified bean mapping was not found");
242         }
243
244         if (csvReader == null) {
245             LOG.warn("Specified CSV IO Reader was null");
246             throw new IllegalArgumentException JavaDoc(
247                     "Specified CSV IO Reader was null");
248         }
249
250         final CSVReader reader = new CSVReader(csvReader, beanMapping
251                 .isCsvHeaderPresent());
252
253         return new CSVParser(beanMapping, reader);
254     }
255 }
256
Popular Tags