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.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;
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;
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;
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;
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;
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.
86 public final class DecodeServlet extends HttpServlet {
88 private static final long MAX_IMAGE_SIZE = 500000L;
90 private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
92 static final Hashtable<DecodeHintType, Object> HINTS;
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.QR_CODE);
106 possibleFormats.add(BarcodeFormat.DATAMATRIX);
107 possibleFormats.add(BarcodeFormat.PDF417);
108 HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
111 private HttpParams params;
112 private SchemeRegistry registry;
113 private DiskFileItemFactory diskFileItemFactory;
116 public void init(ServletConfig servletConfig) {
118 Logger logger = Logger.getLogger("com.google.zxing");
119 logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
121 params = new BasicHttpParams();
122 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
124 registry = new SchemeRegistry();
125 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
126 registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
128 diskFileItemFactory = new DiskFileItemFactory();
130 log.info("DecodeServlet configured");
134 protected void doGet(HttpServletRequest request, HttpServletResponse response)
135 throws ServletException, IOException {
136 String imageURIString = request.getParameter("u");
137 if (imageURIString == null || imageURIString.length() == 0) {
138 response.sendRedirect("badurl.jspx");
142 if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
143 imageURIString = "http://" + imageURIString;
148 imageURI = new URI(imageURIString);
149 } catch (URISyntaxException urise) {
150 response.sendRedirect("badurl.jspx");
154 ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry);
155 HttpClient client = new DefaultHttpClient(connectionManager, params);
157 HttpUriRequest getRequest = new HttpGet(imageURI);
158 getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
162 HttpResponse getResponse;
164 getResponse = client.execute(getRequest);
165 } catch (IllegalArgumentException iae) {
166 // Thrown if hostname is bad or null
168 response.sendRedirect("badurl.jspx");
170 } catch (SocketException se) {
171 // Thrown if hostname is bad or null
173 response.sendRedirect("badurl.jspx");
175 } catch (UnknownHostException uhe) {
177 response.sendRedirect("badurl.jspx");
181 if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
182 response.sendRedirect("badurl.jspx");
185 if (!isSizeOK(getResponse)) {
186 response.sendRedirect("badimage.jspx");
190 log.info("Decoding " + imageURI);
191 HttpEntity entity = getResponse.getEntity();
192 InputStream is = entity.getContent();
194 processStream(is, request, response);
196 entity.consumeContent();
201 connectionManager.shutdown();
207 protected void doPost(HttpServletRequest request, HttpServletResponse response)
208 throws ServletException, IOException {
210 if (!ServletFileUpload.isMultipartContent(request)) {
211 response.sendRedirect("badimage.jspx");
215 ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
216 upload.setFileSizeMax(MAX_IMAGE_SIZE);
220 for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
221 if (!item.isFormField()) {
222 if (item.getSize() <= MAX_IMAGE_SIZE) {
223 log.info("Decoding uploaded file");
224 InputStream is = item.getInputStream();
226 processStream(is, request, response);
231 response.sendRedirect("badimage.jspx");
236 } catch (FileUploadException fue) {
237 response.sendRedirect("badimage.jspx");
242 private static void processStream(InputStream is, ServletRequest request,
243 HttpServletResponse response) throws ServletException, IOException {
244 BufferedImage image = ImageIO.read(is);
246 response.sendRedirect("badimage.jspx");
250 Reader reader = new MultiFormatReader();
253 LuminanceSource source = new BufferedImageLuminanceSource(image);
254 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
255 result = reader.decode(bitmap, HINTS);
256 } catch (ReaderException re) {
258 // Try again with other binarizer
259 LuminanceSource source = new BufferedImageLuminanceSource(image);
260 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
261 result = reader.decode(bitmap, HINTS);
262 } catch (ReaderException re2) {
263 log.info("DECODE FAILED: " + re.toString());
264 response.sendRedirect("notfound.jspx");
269 if (request.getParameter("full") == null) {
270 response.setContentType("text/plain");
271 response.setCharacterEncoding("UTF8");
272 Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
274 out.write(result.getText());
279 request.setAttribute("result", result);
280 byte[] rawBytes = result.getRawBytes();
281 if (rawBytes != null) {
282 request.setAttribute("rawBytesString", arrayToString(rawBytes));
284 request.setAttribute("rawBytesString", "(Not applicable)");
286 String text = result.getText();
288 request.setAttribute("text", StringEscapeUtils.escapeXml(text));
290 request.setAttribute("text", "(Not applicable)");
292 ParsedResult parsedResult = ResultParser.parseResult(result);
293 request.setAttribute("parsedResult", parsedResult);
294 String displayResult = parsedResult.getDisplayResult();
295 if (displayResult != null) {
296 request.setAttribute("displayResult", StringEscapeUtils.escapeXml(displayResult));
298 request.setAttribute("displayResult", "(Not applicable)");
300 request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
304 private static boolean isSizeOK(HttpMessage getResponse) {
305 Header lengthHeader = getResponse.getLastHeader("Content-Length");
306 if (lengthHeader != null) {
307 long length = Long.parseLong(lengthHeader.getValue());
308 if (length > MAX_IMAGE_SIZE) {
315 private static String arrayToString(byte[] bytes) {
316 int length = bytes.length;
317 StringBuilder result = new StringBuilder(length << 2);
320 int max = Math.min(i + 8, length);
321 for (int j = i; j < max; j++) {
322 int value = bytes[j] & 0xFF;
323 result.append(Integer.toHexString(value / 16));
324 result.append(Integer.toHexString(value % 16));
330 for (int j = i - 8; j < length; j++) {
331 result.append(Integer.toHexString(bytes[j] & 0xFF));
334 return result.toString();
338 public void destroy() {
339 log.config("DecodeServlet shutting down...");