KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > krysalis > barcode > servlet > BarcodeServlet


1 /*
2  * $Id: BarcodeServlet.java,v 1.11 2003/10/29 07:50:27 jmaerki Exp $
3  * ============================================================================
4  * The Krysalis Patchy Software License, Version 1.1_01
5  * Copyright (c) 2002-2003 Nicola Ken Barozzi. All rights reserved.
6  *
7  * This Licence is compatible with the BSD licence as described and
8  * approved by http://www.opensource.org/, and is based on the
9  * Apache Software Licence Version 1.1.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  *
15  * 1. Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * 2. Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in
20  * the documentation and/or other materials provided with the
21  * distribution.
22  *
23  * 3. The end-user documentation included with the redistribution,
24  * if any, must include the following acknowledgment:
25  * "This product includes software developed for project
26  * Krysalis (http://www.krysalis.org/)."
27  * Alternately, this acknowledgment may appear in the software itself,
28  * if and wherever such third-party acknowledgments normally appear.
29  *
30  * 4. The names "Krysalis" and "Nicola Ken Barozzi" and
31  * "Krysalis Barcode" must not be used to endorse or promote products
32  * derived from this software without prior written permission. For
33  * written permission, please contact nicolaken@krysalis.org.
34  *
35  * 5. Products derived from this software may not be called "Krysalis",
36  * "Krysalis Barcode", nor may "Krysalis" appear in their name,
37  * without prior written permission of Nicola Ken Barozzi.
38  *
39  * 6. This software may contain voluntary contributions made by many
40  * individuals, who decided to donate the code to this project in
41  * respect of this licence, and was originally created by
42  * Jeremias Maerki <jeremias@maerki.org>.
43  *
44  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
45  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
46  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47  * DISCLAIMED. IN NO EVENT SHALL THE KRYSALIS PROJECT OR
48  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
50  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
51  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
52  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
53  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
54  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  * ====================================================================
57  */

58 package org.krysalis.barcode.servlet;
59
60 import java.awt.image.BufferedImage JavaDoc;
61 import java.io.ByteArrayOutputStream JavaDoc;
62 import java.io.IOException JavaDoc;
63 import javax.servlet.ServletException JavaDoc;
64 import javax.servlet.http.HttpServlet JavaDoc;
65 import javax.servlet.http.HttpServletRequest JavaDoc;
66 import javax.servlet.http.HttpServletResponse JavaDoc;
67 import javax.xml.transform.Result JavaDoc;
68 import javax.xml.transform.Source JavaDoc;
69 import javax.xml.transform.Transformer JavaDoc;
70 import javax.xml.transform.TransformerFactory JavaDoc;
71
72 import org.apache.avalon.framework.configuration.Configuration;
73 import org.apache.avalon.framework.configuration.DefaultConfiguration;
74 import org.apache.avalon.framework.logger.ConsoleLogger;
75 import org.apache.avalon.framework.logger.Logger;
76 import org.krysalis.barcode.BarcodeException;
77 import org.krysalis.barcode.BarcodeGenerator;
78 import org.krysalis.barcode.BarcodeUtil;
79 import org.krysalis.barcode.output.bitmap.BitmapCanvasProvider;
80 import org.krysalis.barcode.output.eps.EPSCanvasProvider;
81 import org.krysalis.barcode.output.svg.SVGCanvasProvider;
82 import org.krysalis.barcode.tools.MimeTypes;
83
84 /**
85  * Simple barcode servlet.
86  *
87  * @author Jeremias Maerki
88  */

89 public class BarcodeServlet extends HttpServlet JavaDoc {
90
91     /** Parameter name for the message */
92     public static final String JavaDoc BARCODE_MSG = "msg";
93     /** Parameter name for the barcode type */
94     public static final String JavaDoc BARCODE_TYPE = "type";
95     /** Parameter name for the barcode height */
96     public static final String JavaDoc BARCODE_HEIGHT = "height";
97     /** Parameter name for the module width */
98     public static final String JavaDoc BARCODE_MODULE_WIDTH = "mw";
99     /** Parameter name for the wide factor */
100     public static final String JavaDoc BARCODE_WIDE_FACTOR = "wf";
101     /** Parameter name for the quiet zone */
102     public static final String JavaDoc BARCODE_QUIET_ZONE = "qz";
103     /** Parameter name for the human-readable placement */
104     public static final String JavaDoc BARCODE_HUMAN_READABLE_POS = "hrp";
105     /** Parameter name for the output format */
106     public static final String JavaDoc BARCODE_FORMAT = "fmt";
107     /** Parameter name for the image resolution (for bitmaps) */
108     public static final String JavaDoc BARCODE_IMAGE_RESOLUTION = "res";
109     /** Parameter name for the grayscale or b/w image (for bitmaps) */
110     public static final String JavaDoc BARCODE_IMAGE_GRAYSCALE = "gray";
111
112     private Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
113
114     /**
115      * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
116      */

117     protected void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
118                 throws ServletException JavaDoc, IOException JavaDoc {
119
120         try {
121             String JavaDoc format = determineFormat(request);
122             
123             Configuration cfg = buildCfg(request);
124
125             String JavaDoc msg = request.getParameter(BARCODE_MSG);
126             if (msg == null) msg = "0123456789";
127             
128             BarcodeUtil util = BarcodeUtil.getInstance();
129             BarcodeGenerator gen = util.createBarcodeGenerator(cfg, log);
130             
131             ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc(4096);
132             try {
133                 if (format.equals(MimeTypes.MIME_SVG)) {
134                     //Create Barcode and render it to SVG
135
SVGCanvasProvider svg = new SVGCanvasProvider(false);
136                     try {
137                         gen.generateBarcode(svg, msg);
138                     } catch (Exception JavaDoc e) {
139                         throw new BarcodeException("Error while generating barcode", e);
140                     }
141                     org.w3c.dom.DocumentFragment JavaDoc frag = svg.getDOMFragment();
142                      
143                     //Serialize SVG barcode
144
TransformerFactory JavaDoc factory = TransformerFactory.newInstance();
145                     Transformer JavaDoc trans = factory.newTransformer();
146                     Source JavaDoc src = new javax.xml.transform.dom.DOMSource JavaDoc(frag);
147                     Result JavaDoc res = new javax.xml.transform.stream.StreamResult JavaDoc(bout);
148                     trans.transform(src, res);
149                 } else if (format.equals(MimeTypes.MIME_EPS)) {
150                     EPSCanvasProvider eps = new EPSCanvasProvider(bout);
151                     gen.generateBarcode(eps, msg);
152                     eps.finish();
153                 } else {
154                     String JavaDoc resText = request.getParameter(BARCODE_IMAGE_RESOLUTION);
155                     int resolution = 300; //dpi
156
if (resText != null) {
157                         resolution = Integer.parseInt(resText);
158                     }
159                     if (resolution > 2400) {
160                         throw new IllegalArgumentException JavaDoc(
161                             "Resolutions above 2400dpi are not allowed");
162                     }
163                     if (resolution < 10) {
164                         throw new IllegalArgumentException JavaDoc(
165                             "Minimum resolution must be 10dpi");
166                     }
167                     String JavaDoc gray = request.getParameter(BARCODE_IMAGE_GRAYSCALE);
168                     BitmapCanvasProvider bitmap = ("true".equalsIgnoreCase(gray)
169                         ? new BitmapCanvasProvider(
170                                 bout, format, resolution,
171                                 BufferedImage.TYPE_BYTE_GRAY, true)
172                         : new BitmapCanvasProvider(
173                                 bout, format, resolution,
174                                 BufferedImage.TYPE_BYTE_BINARY, false));
175                     gen.generateBarcode(bitmap, msg);
176                     bitmap.finish();
177                 }
178             } finally {
179                 bout.close();
180             }
181             response.setContentType(format);
182             response.setContentLength(bout.size());
183             response.getOutputStream().write(bout.toByteArray());
184             response.getOutputStream().flush();
185         } catch (Exception JavaDoc e) {
186             log.error("Error while generating barcode", e);
187             throw new ServletException JavaDoc(e);
188         } catch (Throwable JavaDoc t) {
189             log.error("Error while generating barcode", t);
190             throw new ServletException JavaDoc(t);
191         }
192     }
193     
194     /**
195      * Check the request for the desired output format.
196      * @param request the request to use
197      * @return MIME type of the desired output format.
198      */

199     protected String JavaDoc determineFormat(HttpServletRequest JavaDoc request) {
200         String JavaDoc format = request.getParameter(BARCODE_FORMAT);
201         format = MimeTypes.expandFormat(format);
202         if (format == null) format = MimeTypes.MIME_SVG;
203         return format;
204     }
205     
206     /**
207      * Build an Avalon Configuration object from the request.
208      * @param request the request to use
209      * @return the newly built COnfiguration object
210      */

211     protected Configuration buildCfg(HttpServletRequest JavaDoc request) {
212         DefaultConfiguration cfg = new DefaultConfiguration("barcode");
213         //Get type
214
String JavaDoc type = request.getParameter(BARCODE_TYPE);
215         if (type == null) type = "code128";
216         DefaultConfiguration child = new DefaultConfiguration(type);
217         cfg.addChild(child);
218         //Get additional attributes
219
DefaultConfiguration attr;
220         String JavaDoc height = request.getParameter(BARCODE_HEIGHT);
221         if (height != null) {
222             attr = new DefaultConfiguration("height");
223             attr.setValue(height);
224             child.addChild(attr);
225         }
226         String JavaDoc moduleWidth = request.getParameter(BARCODE_MODULE_WIDTH);
227         if (moduleWidth != null) {
228             attr = new DefaultConfiguration("module-width");
229             attr.setValue(moduleWidth);
230             child.addChild(attr);
231         }
232         String JavaDoc wideFactor = request.getParameter(BARCODE_WIDE_FACTOR);
233         if (wideFactor != null) {
234             attr = new DefaultConfiguration("wide-factor");
235             attr.setValue(wideFactor);
236             child.addChild(attr);
237         }
238         String JavaDoc quietZone = request.getParameter(BARCODE_QUIET_ZONE);
239         if (quietZone != null) {
240             attr = new DefaultConfiguration("quiet-zone");
241             if (quietZone.startsWith("disable")) {
242                 attr.setAttribute("enabled", "false");
243             } else {
244                 attr.setValue(quietZone);
245             }
246             child.addChild(attr);
247         }
248         String JavaDoc humanReadable = request.getParameter(BARCODE_HUMAN_READABLE_POS);
249         if (humanReadable != null) {
250             attr = new DefaultConfiguration("human-readable");
251             attr.setValue(humanReadable);
252             child.addChild(attr);
253         }
254         return cfg;
255     }
256
257 }
258
Popular Tags