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.5 megapixels
94 private static final int MAX_PIXELS = 1 << 16;
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 response.sendRedirect("badurl.jspx");
152 imageURIString = imageURIString.trim();
154 if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
155 imageURIString = "http://" + imageURIString;
160 imageURI = new URI(imageURIString);
161 } catch (URISyntaxException urise) {
162 response.sendRedirect("badurl.jspx");
166 ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
167 HttpClient client = new DefaultHttpClient(connectionManager, params);
169 HttpUriRequest getRequest = new HttpGet(imageURI);
170 getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
174 HttpResponse getResponse;
176 getResponse = client.execute(getRequest);
177 } catch (IllegalArgumentException iae) {
178 // Thrown if hostname is bad or null
180 response.sendRedirect("badurl.jspx");
182 } catch (IOException ioe) {
183 // Encompasses lots of stuff, including
184 // java.net.SocketException, java.net.UnknownHostException,
185 // javax.net.ssl.SSLPeerUnverifiedException,
186 // org.apache.http.NoHttpResponseException,
187 // org.apache.http.client.ClientProtocolException,
189 response.sendRedirect("badurl.jspx");
193 if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
194 response.sendRedirect("badurl.jspx");
197 if (!isSizeOK(getResponse)) {
198 response.sendRedirect("badimage.jspx");
202 log.info("Decoding " + imageURI);
203 HttpEntity entity = getResponse.getEntity();
204 InputStream is = entity.getContent();
206 processStream(is, request, response);
208 entity.consumeContent();
213 connectionManager.shutdown();
219 protected void doPost(HttpServletRequest request, HttpServletResponse response)
220 throws ServletException, IOException {
222 if (!ServletFileUpload.isMultipartContent(request)) {
223 response.sendRedirect("badimage.jspx");
227 ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
228 upload.setFileSizeMax(MAX_IMAGE_SIZE);
232 for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
233 if (!item.isFormField()) {
234 if (item.getSize() <= MAX_IMAGE_SIZE) {
235 log.info("Decoding uploaded file");
236 InputStream is = item.getInputStream();
238 processStream(is, request, response);
243 response.sendRedirect("badimage.jspx");
248 } catch (FileUploadException fue) {
249 response.sendRedirect("badimage.jspx");
254 private static void processStream(InputStream is, ServletRequest request,
255 HttpServletResponse response) throws ServletException, IOException {
259 image = ImageIO.read(is);
260 } catch (IOException ioe) {
261 // Includes javax.imageio.IIOException
262 response.sendRedirect("badimage.jspx");
264 } catch (CMMException cmme) {
265 // Have seen this in logs
266 response.sendRedirect("badimage.jspx");
268 } catch (IllegalArgumentException iae) {
269 // Have seen this in logs for some JPEGs
270 response.sendRedirect("badimage.jspx");
274 image.getHeight() <= 1 || image.getWidth() >= 1 ||
275 image.getHeight() * image.getWidth() > MAX_PIXELS) {
276 response.sendRedirect("badimage.jspx");
280 Reader reader = new MultiFormatReader();
281 LuminanceSource source = new BufferedImageLuminanceSource(image);
282 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
283 Collection<Result> results = new ArrayList<Result>(1);
284 ReaderException savedException = null;
287 // Look for multiple barcodes
288 MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
289 Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
290 if (theResults != null) {
291 results.addAll(Arrays.asList(theResults));
293 } catch (ReaderException re) {
297 if (results.isEmpty()) {
299 // Look for pure barcode
300 Result theResult = reader.decode(bitmap, HINTS_PURE);
301 if (theResult != null) {
302 results.add(theResult);
304 } catch (ReaderException re) {
309 if (results.isEmpty()) {
311 // Look for normal barcode in photo
312 Result theResult = reader.decode(bitmap, HINTS);
313 if (theResult != null) {
314 results.add(theResult);
316 } catch (ReaderException re) {
321 if (results.isEmpty()) {
323 // Try again with other binarizer
324 BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
325 Result theResult = reader.decode(hybridBitmap, HINTS);
326 if (theResult != null) {
327 results.add(theResult);
329 } catch (ReaderException re) {
334 if (results.isEmpty()) {
335 handleException(savedException, response);
339 if (request.getParameter("full") == null) {
340 response.setContentType("text/plain");
341 response.setCharacterEncoding("UTF8");
342 Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
344 for (Result result : results) {
345 out.write(result.getText());
352 request.setAttribute("results", results);
353 request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
357 private static void handleException(ReaderException re, HttpServletResponse response) throws IOException {
358 if (re instanceof NotFoundException) {
359 log.info("Not found: " + re);
360 response.sendRedirect("notfound.jspx");
361 } else if (re instanceof FormatException) {
362 log.info("Format problem: " + re);
363 response.sendRedirect("format.jspx");
364 } else if (re instanceof ChecksumException) {
365 log.info("Checksum problem: " + re);
366 response.sendRedirect("format.jspx");
368 log.info("Unknown problem: " + re);
369 response.sendRedirect("notfound.jspx");
373 private static boolean isSizeOK(HttpMessage getResponse) {
374 Header lengthHeader = getResponse.getLastHeader("Content-Length");
375 if (lengthHeader != null) {
376 long length = Long.parseLong(lengthHeader.getValue());
377 if (length > MAX_IMAGE_SIZE) {
385 public void destroy() {
386 log.config("DecodeServlet shutting down...");