936155d773f83edd247eb5fe4fc82a6215036282
[zxing.git] / zxingorg / src / com / google / zxing / web / DecodeServlet.java
1 /*
2  * Copyright 2008 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.web;
18
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;
33
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;
58
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;
65 import java.net.URI;
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;
74
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;
82
83 /**
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.
86  *
87  * @author Sean Owen
88  */
89 public final class DecodeServlet extends HttpServlet {
90
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;
95
96   private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
97
98   static final Hashtable<DecodeHintType, Object> HINTS;
99   static final Hashtable<DecodeHintType, Object> HINTS_PURE;
100
101   static {
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);
119   }
120
121   private HttpParams params;
122   private SchemeRegistry registry;
123   private DiskFileItemFactory diskFileItemFactory;
124
125   @Override
126   public void init(ServletConfig servletConfig) {
127
128     Logger logger = Logger.getLogger("com.google.zxing");
129     logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
130
131     params = new BasicHttpParams();
132     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
133
134     registry = new SchemeRegistry();
135     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
136     registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
137
138     diskFileItemFactory = new DiskFileItemFactory();
139
140     log.info("DecodeServlet configured");
141   }
142
143   @Override
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");
149       return;
150     }
151
152     imageURIString = imageURIString.trim();
153
154     if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
155       imageURIString = "http://" + imageURIString;
156     }
157
158     URI imageURI;
159     try {
160       imageURI = new URI(imageURIString);
161     } catch (URISyntaxException urise) {
162       response.sendRedirect("badurl.jspx");
163       return;
164     }
165
166     ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
167     HttpClient client = new DefaultHttpClient(connectionManager, params);
168
169     HttpUriRequest getRequest = new HttpGet(imageURI);
170     getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
171
172     try {
173
174       HttpResponse getResponse;
175       try {
176         getResponse = client.execute(getRequest);
177       } catch (IllegalArgumentException iae) {
178         // Thrown if hostname is bad or null
179         getRequest.abort();
180         response.sendRedirect("badurl.jspx");
181         return;
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,
188         getRequest.abort();
189         response.sendRedirect("badurl.jspx");
190         return;
191       }
192
193       if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
194         response.sendRedirect("badurl.jspx");
195         return;
196       }
197       if (!isSizeOK(getResponse)) {
198         response.sendRedirect("badimage.jspx");
199         return;
200       }
201
202       log.info("Decoding " + imageURI);
203       HttpEntity entity = getResponse.getEntity();
204       InputStream is = entity.getContent();
205       try {
206         processStream(is, request, response);
207       } finally {
208         entity.consumeContent();
209         is.close();
210       }
211
212     } finally {
213       connectionManager.shutdown();
214     }
215
216   }
217
218   @Override
219   protected void doPost(HttpServletRequest request, HttpServletResponse response)
220           throws ServletException, IOException {
221
222     if (!ServletFileUpload.isMultipartContent(request)) {
223       response.sendRedirect("badimage.jspx");
224       return;
225     }
226
227     ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
228     upload.setFileSizeMax(MAX_IMAGE_SIZE);
229
230     // Parse the request
231     try {
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();
237             try {
238               processStream(is, request, response);
239             } finally {
240               is.close();
241             }
242           } else {
243             response.sendRedirect("badimage.jspx");
244           }
245           break;
246         }
247       }
248     } catch (FileUploadException fue) {
249       response.sendRedirect("badimage.jspx");
250     }
251
252   }
253
254   private static void processStream(InputStream is, ServletRequest request,
255       HttpServletResponse response) throws ServletException, IOException {
256
257     BufferedImage image;
258     try {
259       image = ImageIO.read(is);
260     } catch (IOException ioe) {
261       // Includes javax.imageio.IIOException
262       response.sendRedirect("badimage.jspx");
263       return;
264     } catch (CMMException cmme) {
265       // Have seen this in logs
266       response.sendRedirect("badimage.jspx");
267       return;
268     } catch (IllegalArgumentException iae) {
269       // Have seen this in logs for some JPEGs
270       response.sendRedirect("badimage.jspx");
271       return;
272     }
273     if (image == null ||
274         image.getHeight() <= 1 || image.getWidth() >= 1 ||
275         image.getHeight() * image.getWidth() > MAX_PIXELS) {
276       response.sendRedirect("badimage.jspx");
277       return;
278     }
279
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;
285
286     try {
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));
292       }
293     } catch (ReaderException re) {
294       savedException = re;
295     }
296
297     if (results.isEmpty()) {
298       try {
299         // Look for pure barcode
300         Result theResult = reader.decode(bitmap, HINTS_PURE);
301         if (theResult != null) {
302           results.add(theResult);
303         }
304       } catch (ReaderException re) {
305         savedException = re;
306       }
307     }
308
309     if (results.isEmpty()) {
310       try {
311         // Look for normal barcode in photo
312         Result theResult = reader.decode(bitmap, HINTS);
313         if (theResult != null) {
314           results.add(theResult);
315         }
316       } catch (ReaderException re) {
317         savedException = re;
318       }
319     }
320
321     if (results.isEmpty()) {
322       try {
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);
328         }
329       } catch (ReaderException re) {
330         savedException = re;
331       }
332     }
333
334     if (results.isEmpty()) {
335       handleException(savedException, response);
336       return;
337     }
338
339     if (request.getParameter("full") == null) {
340       response.setContentType("text/plain");
341       response.setCharacterEncoding("UTF8");
342       Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
343       try {
344         for (Result result : results) {
345           out.write(result.getText());
346           out.write('\n');
347         }
348       } finally {
349         out.close();
350       }
351     } else {
352       request.setAttribute("results", results);
353       request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
354     }
355   }
356
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");
367     } else {
368       log.info("Unknown problem: " + re);
369       response.sendRedirect("notfound.jspx");
370     }
371   }
372
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) {
378         return false;
379       }
380     }
381     return true;
382   }
383
384   @Override
385   public void destroy() {
386     log.config("DecodeServlet shutting down...");
387   }
388
389 }