| 1 22 package net.sf.anupam.csv.mapping; 23 24 import org.apache.commons.digester.Digester; 25 import org.apache.commons.digester.xmlrules.FromXmlRuleSet; 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 import org.xml.sax.InputSource ; 29 import org.xml.sax.SAXException ; 30 31 import java.io.BufferedInputStream ; 32 import java.io.FileInputStream ; 33 import java.io.FileNotFoundException ; 34 import java.io.IOException ; 35 import java.io.InputStream ; 36 import java.util.ArrayList ; 37 import java.util.List ; 38 import java.util.Map ; 39 import java.util.WeakHashMap ; 40 41 50 public class CSVMappingParser { 51 52 55 private static final Log LOG = LogFactory 56 .getLog(CSVMappingParser.class); 57 58 61 private static FromXmlRuleSet ruleSet; 62 63 66 private Digester digester = new Digester(); 67 68 static { 69 70 final InputStream is = ClassLoader 71 .getSystemResourceAsStream("net/sf/anupam/csv/mapping/csv-mapping-digester-rules.xml"); 72 if (is != null) { 73 final InputSource isrc = new InputSource (is); 74 ruleSet = new FromXmlRuleSet(isrc); 75 LOG.info("Loaded Digester Rules for " 76 + CSVMappingParser.class); 77 } else { 78 LOG.error("The CSV Mapping Digester Rules XML was not found"); 79 } 80 81 } 82 83 86 public CSVMappingParser() { 87 super(); 88 digester.clear(); 89 90 CSVMappingParser.ruleSet.addRuleInstances(digester); 91 digester.push(new ArrayList <CSVBeanMapping>()); 92 93 } 94 95 101 @Override  102 protected void finalize() throws Throwable { 103 super.finalize(); 104 if (digester != null) { 105 digester.clear(); 106 digester = null; 107 } 108 } 109 110 118 public Map <String , CSVBeanMapping> getMappings(final String xmlFileName, 119 final boolean inClassPath) { 120 121 final Map <String , CSVBeanMapping> beanMap = new WeakHashMap <String , CSVBeanMapping>(); 122 123 try { 124 final InputStream xmlStream = (inClassPath) 125 ? ClassLoader.getSystemResourceAsStream(xmlFileName) 126 : new BufferedInputStream (new FileInputStream (xmlFileName)); 127 128 final InputSource inputSrc = new InputSource (xmlStream); 129 130 final List <CSVBeanMapping> mappingList = (List <CSVBeanMapping>) digester 131 .parse(inputSrc); 132 133 for (CSVBeanMapping mappedBean : mappingList) { 134 beanMap.put(mappedBean.getBeanName(), mappedBean); 135 } 136 } catch (final FileNotFoundException e) { 137 LOG.warn("The XML File: " 138 + xmlFileName + " was not found", e); 139 } catch (final IOException e) { 140 LOG.warn("The XML File: " 141 + xmlFileName + " could not be read", e); 142 } catch (final SAXException e) { 143 LOG.warn("The XML File: " 144 + xmlFileName + " could not be parsed", e); 145 } 146 return beanMap; 147 } 148 149 } 150 | Popular Tags |