Pre-RSS-14 changes. Necessary code changes, but not the decoder. Committing this...
[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.DecodeHintType;
22 import com.google.zxing.LuminanceSource;
23 import com.google.zxing.MultiFormatReader;
24 import com.google.zxing.Reader;
25 import com.google.zxing.ReaderException;
26 import com.google.zxing.Result;
27 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
28 import com.google.zxing.client.result.ParsedResult;
29 import com.google.zxing.client.result.ResultParser;
30 import com.google.zxing.common.GlobalHistogramBinarizer;
31 import com.google.zxing.common.HybridBinarizer;
32
33 import org.apache.commons.fileupload.FileItem;
34 import org.apache.commons.fileupload.FileUploadException;
35 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
36 import org.apache.commons.fileupload.servlet.ServletFileUpload;
37 import org.apache.commons.lang.StringEscapeUtils;
38 import org.apache.http.Header;
39 import org.apache.http.HttpMessage;
40 import org.apache.http.HttpResponse;
41 import org.apache.http.HttpVersion;
42 import org.apache.http.HttpEntity;
43 import org.apache.http.client.HttpClient;
44 import org.apache.http.client.methods.HttpGet;
45 import org.apache.http.client.methods.HttpUriRequest;
46 import org.apache.http.conn.scheme.PlainSocketFactory;
47 import org.apache.http.conn.scheme.Scheme;
48 import org.apache.http.conn.scheme.SchemeRegistry;
49 import org.apache.http.conn.ssl.SSLSocketFactory;
50 import org.apache.http.conn.ClientConnectionManager;
51 import org.apache.http.impl.client.DefaultHttpClient;
52 import org.apache.http.impl.conn.SingleClientConnManager;
53 import org.apache.http.params.BasicHttpParams;
54 import org.apache.http.params.HttpParams;
55 import org.apache.http.params.HttpProtocolParams;
56
57 import java.awt.image.BufferedImage;
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.io.OutputStreamWriter;
61 import java.io.Writer;
62 import java.net.SocketException;
63 import java.net.URI;
64 import java.net.URISyntaxException;
65 import java.net.UnknownHostException;
66 import java.util.Collection;
67 import java.util.Hashtable;
68 import java.util.List;
69 import java.util.Vector;
70 import java.util.logging.Logger;
71
72 import javax.imageio.ImageIO;
73 import javax.servlet.ServletConfig;
74 import javax.servlet.ServletException;
75 import javax.servlet.ServletRequest;
76 import javax.servlet.http.HttpServlet;
77 import javax.servlet.http.HttpServletRequest;
78 import javax.servlet.http.HttpServletResponse;
79
80 /**
81  * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will
82  * retrieve the image and decode it. It can also process image files uploaded via POST.
83  *
84  * @author Sean Owen
85  */
86 public final class DecodeServlet extends HttpServlet {
87
88   private static final long MAX_IMAGE_SIZE = 500000L;
89
90   private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
91
92   static final Hashtable<DecodeHintType, Object> HINTS;
93
94   static {
95     HINTS = new Hashtable<DecodeHintType, Object>(5);
96     HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
97     Collection<BarcodeFormat> possibleFormats = new Vector<BarcodeFormat>();
98     possibleFormats.add(BarcodeFormat.UPC_A);
99     possibleFormats.add(BarcodeFormat.UPC_E);
100     possibleFormats.add(BarcodeFormat.EAN_8);
101     possibleFormats.add(BarcodeFormat.EAN_13);
102     possibleFormats.add(BarcodeFormat.CODE_39);
103     possibleFormats.add(BarcodeFormat.CODE_128);
104     possibleFormats.add(BarcodeFormat.ITF);
105     possibleFormats.add(BarcodeFormat.RSS14);    
106     possibleFormats.add(BarcodeFormat.QR_CODE);
107     possibleFormats.add(BarcodeFormat.DATAMATRIX);
108     possibleFormats.add(BarcodeFormat.PDF417);
109     HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
110   }
111
112   private HttpParams params;
113   private SchemeRegistry registry;
114   private DiskFileItemFactory diskFileItemFactory;
115
116   @Override
117   public void init(ServletConfig servletConfig) {
118
119     Logger logger = Logger.getLogger("com.google.zxing");
120     logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
121
122     params = new BasicHttpParams();
123     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
124
125     registry = new SchemeRegistry();
126     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
127     registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
128
129     diskFileItemFactory = new DiskFileItemFactory();
130
131     log.info("DecodeServlet configured");
132   }
133
134   @Override
135   protected void doGet(HttpServletRequest request, HttpServletResponse response)
136       throws ServletException, IOException {
137     String imageURIString = request.getParameter("u");
138     if (imageURIString == null || imageURIString.length() == 0) {
139       response.sendRedirect("badurl.jspx");
140       return;
141     }
142
143     if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
144       imageURIString = "http://" + imageURIString;
145     }
146
147     URI imageURI;
148     try {
149       imageURI = new URI(imageURIString);
150     } catch (URISyntaxException urise) {
151       response.sendRedirect("badurl.jspx");
152       return;
153     }
154
155     ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
156     HttpClient client = new DefaultHttpClient(connectionManager, params);
157
158     HttpUriRequest getRequest = new HttpGet(imageURI);
159     getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
160
161     try {
162
163       HttpResponse getResponse;
164       try {
165         getResponse = client.execute(getRequest);
166       } catch (IllegalArgumentException iae) {
167         // Thrown if hostname is bad or null
168         getRequest.abort();
169         response.sendRedirect("badurl.jspx");
170         return;
171       } catch (SocketException se) {
172         // Thrown if hostname is bad or null
173         getRequest.abort();
174         response.sendRedirect("badurl.jspx");
175         return;
176       } catch (UnknownHostException uhe) {
177         getRequest.abort();
178         response.sendRedirect("badurl.jspx");
179         return;
180       }
181
182       if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
183         response.sendRedirect("badurl.jspx");
184         return;
185       }
186       if (!isSizeOK(getResponse)) {
187         response.sendRedirect("badimage.jspx");
188         return;
189       }
190
191       log.info("Decoding " + imageURI);
192       HttpEntity entity = getResponse.getEntity();
193       InputStream is = entity.getContent();
194       try {
195         processStream(is, request, response);
196       } finally {
197         entity.consumeContent();
198         is.close();
199       }
200
201     } finally {
202       connectionManager.shutdown();
203     }
204
205   }
206
207   @Override
208   protected void doPost(HttpServletRequest request, HttpServletResponse response)
209           throws ServletException, IOException {
210
211     if (!ServletFileUpload.isMultipartContent(request)) {
212       response.sendRedirect("badimage.jspx");
213       return;
214     }
215
216     ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
217     upload.setFileSizeMax(MAX_IMAGE_SIZE);
218
219     // Parse the request
220     try {
221       for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
222         if (!item.isFormField()) {
223           if (item.getSize() <= MAX_IMAGE_SIZE) {
224             log.info("Decoding uploaded file");
225             InputStream is = item.getInputStream();
226             try {
227               processStream(is, request, response);
228             } finally {
229               is.close();
230             }
231           } else {
232             response.sendRedirect("badimage.jspx");
233           }
234           break;
235         }
236       }
237     } catch (FileUploadException fue) {
238       response.sendRedirect("badimage.jspx");
239     }
240
241   }
242
243   private static void processStream(InputStream is, ServletRequest request,
244       HttpServletResponse response) throws ServletException, IOException {
245     BufferedImage image = ImageIO.read(is);
246     if (image == null) {
247       response.sendRedirect("badimage.jspx");
248       return;
249     }
250
251     Reader reader = new MultiFormatReader();
252     Result result;
253     try {
254       LuminanceSource source = new BufferedImageLuminanceSource(image);
255       BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
256       result = reader.decode(bitmap, HINTS);
257     } catch (ReaderException re) {
258       try {
259         // Try again with other binarizer
260         LuminanceSource source = new BufferedImageLuminanceSource(image);
261         BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
262         result = reader.decode(bitmap, HINTS);
263       } catch (ReaderException re2) {
264         log.info("DECODE FAILED: " + re.toString());
265         response.sendRedirect("notfound.jspx");
266         return;
267       }
268     }
269
270     if (request.getParameter("full") == null) {
271       response.setContentType("text/plain");
272       response.setCharacterEncoding("UTF8");
273       Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
274       try {
275         out.write(result.getText());
276       } finally {
277         out.close();
278       }
279     } else {
280       request.setAttribute("result", result);
281       byte[] rawBytes = result.getRawBytes();
282       if (rawBytes != null) {
283         request.setAttribute("rawBytesString", arrayToString(rawBytes));
284       } else {
285         request.setAttribute("rawBytesString", "(Not applicable)");
286       }
287       String text = result.getText();
288       if (text != null) {
289         request.setAttribute("text", StringEscapeUtils.escapeXml(text));
290       } else {
291         request.setAttribute("text", "(Not applicable)");
292       }
293       ParsedResult parsedResult = ResultParser.parseResult(result);
294       request.setAttribute("parsedResult", parsedResult);
295       String displayResult = parsedResult.getDisplayResult();
296       if (displayResult != null) {
297         request.setAttribute("displayResult", StringEscapeUtils.escapeXml(displayResult));
298       } else {
299         request.setAttribute("displayResult", "(Not applicable)");
300       }
301       request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
302     }
303   }
304
305   private static boolean isSizeOK(HttpMessage getResponse) {
306     Header lengthHeader = getResponse.getLastHeader("Content-Length");
307     if (lengthHeader != null) {
308       long length = Long.parseLong(lengthHeader.getValue());
309       if (length > MAX_IMAGE_SIZE) {
310         return false;
311       }
312     }
313     return true;
314   }
315
316   private static String arrayToString(byte[] bytes) {
317     int length = bytes.length;
318     StringBuilder result = new StringBuilder(length << 2);
319     int i = 0;
320     while (i < length) {
321       int max = Math.min(i + 8, length);
322       for (int j = i; j < max; j++) {
323         int value = bytes[j] & 0xFF;
324         result.append(Integer.toHexString(value / 16));
325         result.append(Integer.toHexString(value % 16));
326         result.append(' ');
327       }
328       result.append('\n');
329       i += 8;
330     }
331     for (int j = i - 8; j < length; j++) {
332       result.append(Integer.toHexString(bytes[j] & 0xFF));
333       result.append(' ');
334     }
335     return result.toString();
336   }
337
338   @Override
339   public void destroy() {
340     log.config("DecodeServlet shutting down...");
341   }
342
343 }