70a35556c28a889a6b047b42008c8ac8858f5fb5
[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 megapixels
94   private static final int MAX_PIXELS = 1 << 21;
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       log.fine("URI was empty");
149       response.sendRedirect("badurl.jspx");
150       return;
151     }
152
153     imageURIString = imageURIString.trim();
154
155     if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
156       imageURIString = "http://" + imageURIString;
157     }
158
159     URI imageURI;
160     try {
161       imageURI = new URI(imageURIString);
162     } catch (URISyntaxException urise) {
163       log.fine("URI was not valid: " + imageURIString);
164       response.sendRedirect("badurl.jspx");
165       return;
166     }
167
168     ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
169     HttpClient client = new DefaultHttpClient(connectionManager, params);
170
171     HttpUriRequest getRequest = new HttpGet(imageURI);
172     getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
173
174     try {
175
176       HttpResponse getResponse;
177       try {
178         getResponse = client.execute(getRequest);
179       } catch (IllegalArgumentException iae) {
180         // Thrown if hostname is bad or null
181         log.fine(iae.toString());
182         getRequest.abort();
183         response.sendRedirect("badurl.jspx");
184         return;
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());
192         getRequest.abort();
193         response.sendRedirect("badurl.jspx");
194         return;
195       }
196
197       if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
198         log.fine("Unsuccessful return code: " + getResponse.getStatusLine().getStatusCode());
199         response.sendRedirect("badurl.jspx");
200         return;
201       }
202       if (!isSizeOK(getResponse)) {
203         log.fine("Too large");
204         response.sendRedirect("badimage.jspx");
205         return;
206       }
207
208       log.info("Decoding " + imageURI);
209       HttpEntity entity = getResponse.getEntity();
210       InputStream is = entity.getContent();
211       try {
212         processStream(is, request, response);
213       } finally {
214         entity.consumeContent();
215         is.close();
216       }
217
218     } finally {
219       connectionManager.shutdown();
220     }
221
222   }
223
224   @Override
225   protected void doPost(HttpServletRequest request, HttpServletResponse response)
226           throws ServletException, IOException {
227
228     if (!ServletFileUpload.isMultipartContent(request)) {
229       log.fine("File upload was not multipart");
230       response.sendRedirect("badimage.jspx");
231       return;
232     }
233
234     ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
235     upload.setFileSizeMax(MAX_IMAGE_SIZE);
236
237     // Parse the request
238     try {
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();
244             try {
245               processStream(is, request, response);
246             } finally {
247               is.close();
248             }
249           } else {
250             log.fine("Too large");
251             response.sendRedirect("badimage.jspx");
252           }
253           break;
254         }
255       }
256     } catch (FileUploadException fue) {
257       log.fine(fue.toString());
258       response.sendRedirect("badimage.jspx");
259     }
260
261   }
262
263   private static void processStream(InputStream is, ServletRequest request,
264       HttpServletResponse response) throws ServletException, IOException {
265
266     BufferedImage image;
267     try {
268       image = ImageIO.read(is);
269     } catch (IOException ioe) {
270       log.fine(ioe.toString());
271       // Includes javax.imageio.IIOException
272       response.sendRedirect("badimage.jspx");
273       return;
274     } catch (CMMException cmme) {
275       log.fine(cmme.toString());
276       // Have seen this in logs
277       response.sendRedirect("badimage.jspx");
278       return;
279     } catch (IllegalArgumentException iae) {
280       log.fine(iae.toString());
281       // Have seen this in logs for some JPEGs
282       response.sendRedirect("badimage.jspx");
283       return;
284     }
285     if (image == null) {
286       response.sendRedirect("badimage.jspx");
287       return;      
288     }
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");
293       return;
294     }
295
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;
301
302     try {
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));
308       }
309     } catch (ReaderException re) {
310       savedException = re;
311     }
312
313     if (results.isEmpty()) {
314       try {
315         // Look for pure barcode
316         Result theResult = reader.decode(bitmap, HINTS_PURE);
317         if (theResult != null) {
318           results.add(theResult);
319         }
320       } catch (ReaderException re) {
321         savedException = re;
322       }
323     }
324
325     if (results.isEmpty()) {
326       try {
327         // Look for normal barcode in photo
328         Result theResult = reader.decode(bitmap, HINTS);
329         if (theResult != null) {
330           results.add(theResult);
331         }
332       } catch (ReaderException re) {
333         savedException = re;
334       }
335     }
336
337     if (results.isEmpty()) {
338       try {
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);
344         }
345       } catch (ReaderException re) {
346         savedException = re;
347       }
348     }
349
350     if (results.isEmpty()) {
351       handleException(savedException, response);
352       return;
353     }
354
355     if (request.getParameter("full") == null) {
356       response.setContentType("text/plain");
357       response.setCharacterEncoding("UTF8");
358       Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
359       try {
360         for (Result result : results) {
361           out.write(result.getText());
362           out.write('\n');
363         }
364       } finally {
365         out.close();
366       }
367     } else {
368       request.setAttribute("results", results);
369       request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
370     }
371   }
372
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");
383     } else {
384       log.info("Unknown problem: " + re);
385       response.sendRedirect("notfound.jspx");
386     }
387   }
388
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) {
394         return false;
395       }
396     }
397     return true;
398   }
399
400   @Override
401   public void destroy() {
402     log.config("DecodeServlet shutting down...");
403   }
404
405 }