2 * Copyright 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.web;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.BinaryBitmap;
21 import com.google.zxing.ChecksumException;
22 import com.google.zxing.DecodeHintType;
23 import com.google.zxing.FormatException;
24 import com.google.zxing.LuminanceSource;
25 import com.google.zxing.MultiFormatReader;
26 import com.google.zxing.NotFoundException;
27 import com.google.zxing.Reader;
28 import com.google.zxing.ReaderException;
29 import com.google.zxing.Result;
30 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
31 import com.google.zxing.common.GlobalHistogramBinarizer;
32 import com.google.zxing.common.HybridBinarizer;
34 import com.google.zxing.multi.GenericMultipleBarcodeReader;
35 import com.google.zxing.multi.MultipleBarcodeReader;
36 import org.apache.commons.fileupload.FileItem;
37 import org.apache.commons.fileupload.FileUploadException;
38 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
39 import org.apache.commons.fileupload.servlet.ServletFileUpload;
40 import org.apache.http.Header;
41 import org.apache.http.HttpMessage;
42 import org.apache.http.HttpResponse;
43 import org.apache.http.HttpVersion;
44 import org.apache.http.HttpEntity;
45 import org.apache.http.client.HttpClient;
46 import org.apache.http.client.methods.HttpGet;
47 import org.apache.http.client.methods.HttpUriRequest;
48 import org.apache.http.conn.scheme.PlainSocketFactory;
49 import org.apache.http.conn.scheme.Scheme;
50 import org.apache.http.conn.scheme.SchemeRegistry;
51 import org.apache.http.conn.ssl.SSLSocketFactory;
52 import org.apache.http.conn.ClientConnectionManager;
53 import org.apache.http.impl.client.DefaultHttpClient;
54 import org.apache.http.impl.conn.SingleClientConnManager;
55 import org.apache.http.params.BasicHttpParams;
56 import org.apache.http.params.HttpParams;
57 import org.apache.http.params.HttpProtocolParams;
59 import java.awt.color.CMMException;
60 import java.awt.image.BufferedImage;
61 import java.io.IOException;
62 import java.io.InputStream;
63 import java.io.OutputStreamWriter;
64 import java.io.Writer;
66 import java.net.URISyntaxException;
67 import java.util.ArrayList;
68 import java.util.Arrays;
69 import java.util.Collection;
70 import java.util.Hashtable;
71 import java.util.List;
72 import java.util.Vector;
73 import java.util.logging.Logger;
75 import javax.imageio.ImageIO;
76 import javax.servlet.ServletConfig;
77 import javax.servlet.ServletException;
78 import javax.servlet.ServletRequest;
79 import javax.servlet.http.HttpServlet;
80 import javax.servlet.http.HttpServletRequest;
81 import javax.servlet.http.HttpServletResponse;
84 * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will
85 * retrieve the image and decode it. It can also process image files uploaded via POST.
89 public final class DecodeServlet extends HttpServlet {
91 // No real reason to let people upload more than a 2MB image
92 private static final long MAX_IMAGE_SIZE = 2000000L;
93 // No real reason to deal with more than maybe 2 megapixels
94 private static final int MAX_PIXELS = 1 << 21;
96 private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
98 static final Hashtable<DecodeHintType, Object> HINTS;
99 static final Hashtable<DecodeHintType, Object> HINTS_PURE;
102 HINTS = new Hashtable<DecodeHintType, Object>(5);
103 HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
104 Collection<BarcodeFormat> possibleFormats = new Vector<BarcodeFormat>();
105 possibleFormats.add(BarcodeFormat.UPC_A);
106 possibleFormats.add(BarcodeFormat.UPC_E);
107 possibleFormats.add(BarcodeFormat.EAN_8);
108 possibleFormats.add(BarcodeFormat.EAN_13);
109 possibleFormats.add(BarcodeFormat.CODE_39);
110 possibleFormats.add(BarcodeFormat.CODE_128);
111 possibleFormats.add(BarcodeFormat.ITF);
112 possibleFormats.add(BarcodeFormat.RSS14);
113 possibleFormats.add(BarcodeFormat.QR_CODE);
114 possibleFormats.add(BarcodeFormat.DATAMATRIX);
115 possibleFormats.add(BarcodeFormat.PDF417);
116 HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
117 HINTS_PURE = new Hashtable<DecodeHintType, Object>(HINTS);
118 HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
121 private HttpParams params;
122 private SchemeRegistry registry;
123 private DiskFileItemFactory diskFileItemFactory;
126 public void init(ServletConfig servletConfig) {
128 Logger logger = Logger.getLogger("com.google.zxing");
129 logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
131 params = new BasicHttpParams();
132 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
134 registry = new SchemeRegistry();
135 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
136 registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
138 diskFileItemFactory = new DiskFileItemFactory();
140 log.info("DecodeServlet configured");
144 protected void doGet(HttpServletRequest request, HttpServletResponse response)
145 throws ServletException, IOException {
146 String imageURIString = request.getParameter("u");
147 if (imageURIString == null || imageURIString.length() == 0) {
148 log.fine("URI was empty");
149 response.sendRedirect("badurl.jspx");
153 imageURIString = imageURIString.trim();
155 if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
156 imageURIString = "http://" + imageURIString;
161 imageURI = new URI(imageURIString);
162 } catch (URISyntaxException urise) {
163 log.fine("URI was not valid: " + imageURIString);
164 response.sendRedirect("badurl.jspx");
168 ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
169 HttpClient client = new DefaultHttpClient(connectionManager, params);
171 HttpUriRequest getRequest = new HttpGet(imageURI);
172 getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
176 HttpResponse getResponse;
178 getResponse = client.execute(getRequest);
179 } catch (IllegalArgumentException iae) {
180 // Thrown if hostname is bad or null
181 log.fine(iae.toString());
183 response.sendRedirect("badurl.jspx");
185 } catch (IOException ioe) {
186 // Encompasses lots of stuff, including
187 // java.net.SocketException, java.net.UnknownHostException,
188 // javax.net.ssl.SSLPeerUnverifiedException,
189 // org.apache.http.NoHttpResponseException,
190 // org.apache.http.client.ClientProtocolException,
191 log.fine(ioe.toString());
193 response.sendRedirect("badurl.jspx");
197 if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
198 log.fine("Unsuccessful return code: " + getResponse.getStatusLine().getStatusCode());
199 response.sendRedirect("badurl.jspx");
202 if (!isSizeOK(getResponse)) {
203 log.fine("Too large");
204 response.sendRedirect("badimage.jspx");
208 log.info("Decoding " + imageURI);
209 HttpEntity entity = getResponse.getEntity();
210 InputStream is = entity.getContent();
212 processStream(is, request, response);
214 entity.consumeContent();
219 connectionManager.shutdown();
225 protected void doPost(HttpServletRequest request, HttpServletResponse response)
226 throws ServletException, IOException {
228 if (!ServletFileUpload.isMultipartContent(request)) {
229 log.fine("File upload was not multipart");
230 response.sendRedirect("badimage.jspx");
234 ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
235 upload.setFileSizeMax(MAX_IMAGE_SIZE);
239 for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
240 if (!item.isFormField()) {
241 if (item.getSize() <= MAX_IMAGE_SIZE) {
242 log.info("Decoding uploaded file");
243 InputStream is = item.getInputStream();
245 processStream(is, request, response);
250 log.fine("Too large");
251 response.sendRedirect("badimage.jspx");
256 } catch (FileUploadException fue) {
257 log.fine(fue.toString());
258 response.sendRedirect("badimage.jspx");
263 private static void processStream(InputStream is, ServletRequest request,
264 HttpServletResponse response) throws ServletException, IOException {
268 image = ImageIO.read(is);
269 } catch (IOException ioe) {
270 log.fine(ioe.toString());
271 // Includes javax.imageio.IIOException
272 response.sendRedirect("badimage.jspx");
274 } catch (CMMException cmme) {
275 log.fine(cmme.toString());
276 // Have seen this in logs
277 response.sendRedirect("badimage.jspx");
279 } catch (IllegalArgumentException iae) {
280 log.fine(iae.toString());
281 // Have seen this in logs for some JPEGs
282 response.sendRedirect("badimage.jspx");
286 response.sendRedirect("badimage.jspx");
289 if (image.getHeight() <= 1 || image.getWidth() <= 1 ||
290 image.getHeight() * image.getWidth() > MAX_PIXELS) {
291 log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight());
292 response.sendRedirect("badimage.jspx");
296 Reader reader = new MultiFormatReader();
297 LuminanceSource source = new BufferedImageLuminanceSource(image);
298 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
299 Collection<Result> results = new ArrayList<Result>(1);
300 ReaderException savedException = null;
303 // Look for multiple barcodes
304 MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
305 Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
306 if (theResults != null) {
307 results.addAll(Arrays.asList(theResults));
309 } catch (ReaderException re) {
313 if (results.isEmpty()) {
315 // Look for pure barcode
316 Result theResult = reader.decode(bitmap, HINTS_PURE);
317 if (theResult != null) {
318 results.add(theResult);
320 } catch (ReaderException re) {
325 if (results.isEmpty()) {
327 // Look for normal barcode in photo
328 Result theResult = reader.decode(bitmap, HINTS);
329 if (theResult != null) {
330 results.add(theResult);
332 } catch (ReaderException re) {
337 if (results.isEmpty()) {
339 // Try again with other binarizer
340 BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
341 Result theResult = reader.decode(hybridBitmap, HINTS);
342 if (theResult != null) {
343 results.add(theResult);
345 } catch (ReaderException re) {
350 if (results.isEmpty()) {
351 handleException(savedException, response);
355 if (request.getParameter("full") == null) {
356 response.setContentType("text/plain");
357 response.setCharacterEncoding("UTF8");
358 Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
360 for (Result result : results) {
361 out.write(result.getText());
368 request.setAttribute("results", results);
369 request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
373 private static void handleException(ReaderException re, HttpServletResponse response) throws IOException {
374 if (re instanceof NotFoundException) {
375 log.info("Not found: " + re);
376 response.sendRedirect("notfound.jspx");
377 } else if (re instanceof FormatException) {
378 log.info("Format problem: " + re);
379 response.sendRedirect("format.jspx");
380 } else if (re instanceof ChecksumException) {
381 log.info("Checksum problem: " + re);
382 response.sendRedirect("format.jspx");
384 log.info("Unknown problem: " + re);
385 response.sendRedirect("notfound.jspx");
389 private static boolean isSizeOK(HttpMessage getResponse) {
390 Header lengthHeader = getResponse.getLastHeader("Content-Length");
391 if (lengthHeader != null) {
392 long length = Long.parseLong(lengthHeader.getValue());
393 if (length > MAX_IMAGE_SIZE) {
401 public void destroy() {
402 log.config("DecodeServlet shutting down...");