1 58 package org.krysalis.barcode; 59 60 import org.apache.avalon.framework.activity.Initializable; 61 import org.apache.avalon.framework.configuration.Configurable; 62 import org.apache.avalon.framework.configuration.Configuration; 63 import org.apache.avalon.framework.logger.LogEnabled; 64 import org.apache.avalon.framework.logger.Logger; 65 import org.krysalis.barcode.output.svg.SVGCanvasProvider; 66 import org.w3c.dom.DocumentFragment ; 67 68 76 public class BarcodeUtil { 77 78 private static BarcodeUtil instance = null; 79 80 private BarcodeClassResolver classResolver = new DefaultBarcodeClassResolver(); 81 82 83 87 protected BarcodeUtil() { 88 } 90 91 95 public static BarcodeUtil getInstance() { 96 if (instance == null) { 97 instance = new BarcodeUtil(); 98 } 99 return instance; 100 } 101 102 111 public static BarcodeGenerator createBarcodeGenerator(Configuration cfg, 112 Logger logger, 113 BarcodeClassResolver classResolver) 114 throws BarcodeException { 115 try { 116 Class cl = null; 117 118 String type = cfg.getName(); 120 try { 121 cl = classResolver.resolve(type); 122 } catch (ClassNotFoundException cnfe) { 123 cl = null; 124 } 125 Configuration child = null; 126 if (cl == null) { 127 Configuration[] children = cfg.getChildren(); 129 if (children.length == 0) { 130 throw new BarcodeException("Barcode configuration element expected"); 131 } 132 133 for (int i = 0; i < children.length; i++) { 135 child = children[i]; 136 type = child.getName(); 137 try { 138 cl = classResolver.resolve(type); 139 break; 140 } catch (ClassNotFoundException cnfe) { 141 cl = null; 142 } 143 } 144 } 145 146 if (cl == null) { 147 throw new BarcodeException( 148 "No barcode configuration element not found"); 149 } 150 151 BarcodeGenerator gen = (BarcodeGenerator)cl.newInstance(); 153 if (gen instanceof LogEnabled) { 154 ((LogEnabled)gen).enableLogging(logger); 155 } 156 if (gen instanceof Configurable) { 157 ((Configurable)gen).configure((child != null ? child : cfg)); 158 } 159 if (gen instanceof Initializable) { 160 ((Initializable)gen).initialize(); 161 } 162 return gen; 163 } catch (Exception e) { 164 throw new BarcodeException("Error instantiating a barcode generator", e); 165 } 166 } 167 168 175 public BarcodeGenerator createBarcodeGenerator(Configuration cfg, 176 Logger logger) 177 throws BarcodeException { 178 return createBarcodeGenerator(cfg, logger, this.classResolver); 179 } 180 181 189 public DocumentFragment generateBarcode(Configuration cfg, 190 Logger logger, 191 String msg) 192 throws BarcodeException { 193 BarcodeGenerator gen = createBarcodeGenerator(cfg, logger); 194 try { 195 SVGCanvasProvider svg = new SVGCanvasProvider(false); 196 197 gen.generateBarcode(svg, msg); 199 200 return svg.getDOMFragment(); 201 } catch (Exception e) { 202 throw new BarcodeException("Error while generating barcode", e); 203 } 204 } 205 206 } 207 | Popular Tags |