From ecff2b8654d7d349ef00aa7c4a604cb215dd3794 Mon Sep 17 00:00:00 2001 From: srowen Date: Mon, 5 May 2008 17:39:33 +0000 Subject: [PATCH] Reformatted code, updated to new Analytics tags, fixed a problem with EmailAuthenticator git-svn-id: http://zxing.googlecode.com/svn/trunk@386 59b500cc-1b3d-0410-9834-0bbf25fbcc57 --- .../com/google/zxing/web/DecodeEmailTask.java | 15 +- .../com/google/zxing/web/DecodeServlet.java | 217 +++++++++--------- .../src/com/google/zxing/web/DoSFilter.java | 144 ++++++------ .../google/zxing/web/EmailAuthenticator.java | 6 + zxingorg/src/com/google/zxing/web/IPTrie.java | 83 +++---- zxingorg/web/badimage.jspx | 50 ++-- zxingorg/web/badurl.jspx | 50 ++-- zxingorg/web/decode.jspx | 90 +++++--- zxingorg/web/index.jspx | 69 ++++-- zxingorg/web/notfound.jspx | 51 ++-- 10 files changed, 430 insertions(+), 345 deletions(-) diff --git a/zxingorg/src/com/google/zxing/web/DecodeEmailTask.java b/zxingorg/src/com/google/zxing/web/DecodeEmailTask.java index 347c3a11..a1e5c25e 100644 --- a/zxingorg/src/com/google/zxing/web/DecodeEmailTask.java +++ b/zxingorg/src/com/google/zxing/web/DecodeEmailTask.java @@ -55,14 +55,8 @@ final class DecodeEmailTask extends TimerTask { private static final String SMTP_PORT = "465"; private static final String POP_PORT = "995"; private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; - private static final Address fromAddress; private static final Properties sessionProperties = new Properties(); static { - try { - fromAddress = new InternetAddress("w@zxing.org", "ZXing By Email"); - } catch (UnsupportedEncodingException uee) { - throw new RuntimeException(uee); - } sessionProperties.setProperty("mail.transport.protocol", "smtp"); sessionProperties.setProperty("mail.smtp.host", SMTP_HOST); sessionProperties.setProperty("mail.smtp.auth", "true"); @@ -80,9 +74,16 @@ final class DecodeEmailTask extends TimerTask { } private final Authenticator emailAuthenticator; + private final Address fromAddress; - DecodeEmailTask(Authenticator emailAuthenticator) { + DecodeEmailTask(String emailAddress, Authenticator emailAuthenticator) { this.emailAuthenticator = emailAuthenticator; + try { + fromAddress = new InternetAddress(emailAddress, "ZXing By Email"); + } catch (UnsupportedEncodingException uee) { + // Can't happen? + throw new RuntimeException(uee); + } } @Override diff --git a/zxingorg/src/com/google/zxing/web/DecodeServlet.java b/zxingorg/src/com/google/zxing/web/DecodeServlet.java index 33ecb0fb..7c69cc51 100644 --- a/zxingorg/src/com/google/zxing/web/DecodeServlet.java +++ b/zxingorg/src/com/google/zxing/web/DecodeServlet.java @@ -67,23 +67,24 @@ import java.util.logging.Logger; */ public final class DecodeServlet extends HttpServlet { - private static final long MAX_IMAGE_SIZE = 500000L; + private static final long MAX_IMAGE_SIZE = 500000L; private static final long EMAIL_CHECK_INTERVAL = 60000L; private static final Logger log = Logger.getLogger(DecodeServlet.class.getName()); static final Hashtable HINTS; + static { HINTS = new Hashtable(3); HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); } private HttpClient client; - private DiskFileItemFactory diskFileItemFactory; + private DiskFileItemFactory diskFileItemFactory; private Timer emailTimer; @Override - public void init(ServletConfig servletConfig) throws ServletException { + public void init(ServletConfig servletConfig) throws ServletException { Logger logger = Logger.getLogger("com.google.zxing"); logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext())); @@ -107,138 +108,138 @@ public final class DecodeServlet extends HttpServlet { Authenticator emailAuthenticator = new EmailAuthenticator(emailAddress, emailPassword); emailTimer = new Timer("Email decoder timer", true); - emailTimer.schedule(new DecodeEmailTask(emailAuthenticator), 0L, EMAIL_CHECK_INTERVAL); + emailTimer.schedule(new DecodeEmailTask(emailAddress, emailAuthenticator), 0L, EMAIL_CHECK_INTERVAL); log.info("DecodeServlet configured"); } - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { - String imageURIString = request.getParameter("u"); - if (imageURIString == null || imageURIString.length() == 0) { - response.sendRedirect("badurl.jspx"); - return; - } + String imageURIString = request.getParameter("u"); + if (imageURIString == null || imageURIString.length() == 0) { + response.sendRedirect("badurl.jspx"); + return; + } - if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) { - imageURIString = "http://" + imageURIString; - } + if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) { + imageURIString = "http://" + imageURIString; + } - URI imageURI; - try { - imageURI = new URI(imageURIString); - } catch (URISyntaxException urise) { - response.sendRedirect("badurl.jspx"); - return; - } + URI imageURI; + try { + imageURI = new URI(imageURIString); + } catch (URISyntaxException urise) { + response.sendRedirect("badurl.jspx"); + return; + } HttpGet getRequest = new HttpGet(imageURI); - try { + try { HttpResponse getResponse = client.execute(getRequest); if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { - response.sendRedirect("badurl.jspx"); - return; - } - if (!isSizeOK(getResponse)) { - response.sendRedirect("badimage.jspx"); - return; - } + response.sendRedirect("badurl.jspx"); + return; + } + if (!isSizeOK(getResponse)) { + response.sendRedirect("badimage.jspx"); + return; + } log.info("Decoding " + imageURI); InputStream is = getResponse.getEntity().getContent(); - try { - processStream(is, response); - } finally { - is.close(); - } + try { + processStream(is, response); + } finally { + is.close(); + } } catch (InterruptedException ie) { getRequest.abort(); response.sendRedirect("badurl.jspx"); } catch (HttpException he) { getRequest.abort(); response.sendRedirect("badurl.jspx"); - } + } - } + } - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { - if (!ServletFileUpload.isMultipartContent(request)) { - response.sendRedirect("badimage.jspx"); - return; - } + if (!ServletFileUpload.isMultipartContent(request)) { + response.sendRedirect("badimage.jspx"); + return; + } - ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); - upload.setFileSizeMax(MAX_IMAGE_SIZE); + ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); + upload.setFileSizeMax(MAX_IMAGE_SIZE); - // Parse the request - try { - for (FileItem item : (List) upload.parseRequest(request)) { - if (!item.isFormField()) { - if (item.getSize() <= MAX_IMAGE_SIZE) { + // Parse the request + try { + for (FileItem item : (List) upload.parseRequest(request)) { + if (!item.isFormField()) { + if (item.getSize() <= MAX_IMAGE_SIZE) { log.info("Decoding uploaded file"); - InputStream is = item.getInputStream(); - try { - processStream(is, response); - } finally { - is.close(); - } - } else { - throw new ServletException("File is too large: " + item.getSize()); - } - break; - } - } - } catch (FileUploadException fue) { - response.sendRedirect("badimage.jspx"); - } - - } - - private static void processStream(InputStream is, HttpServletResponse response) throws IOException { - BufferedImage image = ImageIO.read(is); - if (image == null) { - response.sendRedirect("badimage.jspx"); - return; - } - - Reader reader = new MultiFormatReader(); - Result result; - try { - result = reader.decode(new BufferedImageMonochromeBitmapSource(image), HINTS); - } catch (ReaderException re) { - log.info("DECODE FAILED: " + re.toString()); - response.sendRedirect("notfound.jspx"); - return; - } - - response.setContentType("text/plain"); - response.setCharacterEncoding("UTF-8"); - Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); - try { - out.write(result.getText()); - } finally { - out.close(); - } - } - - private static boolean isSizeOK(HttpMessage getResponse) { + InputStream is = item.getInputStream(); + try { + processStream(is, response); + } finally { + is.close(); + } + } else { + throw new ServletException("File is too large: " + item.getSize()); + } + break; + } + } + } catch (FileUploadException fue) { + response.sendRedirect("badimage.jspx"); + } + + } + + private static void processStream(InputStream is, HttpServletResponse response) throws IOException { + BufferedImage image = ImageIO.read(is); + if (image == null) { + response.sendRedirect("badimage.jspx"); + return; + } + + Reader reader = new MultiFormatReader(); + Result result; + try { + result = reader.decode(new BufferedImageMonochromeBitmapSource(image), HINTS); + } catch (ReaderException re) { + log.info("DECODE FAILED: " + re.toString()); + response.sendRedirect("notfound.jspx"); + return; + } + + response.setContentType("text/plain"); + response.setCharacterEncoding("UTF-8"); + Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + try { + out.write(result.getText()); + } finally { + out.close(); + } + } + + private static boolean isSizeOK(HttpMessage getResponse) { Header lengthHeader = getResponse.getLastHeader("Content-Length"); - if (lengthHeader != null) { - long length = Long.parseLong(lengthHeader.getValue()); - if (length > MAX_IMAGE_SIZE) { - return false; - } - } - return true; - } - - @Override - public void destroy() { - log.config("DecodeServlet shutting down..."); + if (lengthHeader != null) { + long length = Long.parseLong(lengthHeader.getValue()); + if (length > MAX_IMAGE_SIZE) { + return false; + } + } + return true; + } + + @Override + public void destroy() { + log.config("DecodeServlet shutting down..."); emailTimer.cancel(); } diff --git a/zxingorg/src/com/google/zxing/web/DoSFilter.java b/zxingorg/src/com/google/zxing/web/DoSFilter.java index 8c6f3880..bb94cea3 100755 --- a/zxingorg/src/com/google/zxing/web/DoSFilter.java +++ b/zxingorg/src/com/google/zxing/web/DoSFilter.java @@ -19,105 +19,105 @@ package com.google.zxing.web; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Timer; import java.util.TimerTask; -import java.util.Collection; /** * @author Sean Owen */ public final class DoSFilter implements Filter { - private static final int MAX_ACCESSES_PER_IP_PER_TIME = 10; - private static final long MAX_ACCESS_INTERVAL_MSEC = 10L * 1000L; - private static final long UNBAN_INTERVAL_MSEC = 60L * 60L * 1000L; + private static final int MAX_ACCESSES_PER_IP_PER_TIME = 10; + private static final long MAX_ACCESS_INTERVAL_MSEC = 10L * 1000L; + private static final long UNBAN_INTERVAL_MSEC = 60L * 60L * 1000L; - private final IPTrie numRecentAccesses; - private final Timer timer; - private final Set bannedIPAddresses; - private final Collection manuallyBannedIPAddresses; - private ServletContext context; + private final IPTrie numRecentAccesses; + private final Timer timer; + private final Set bannedIPAddresses; + private final Collection manuallyBannedIPAddresses; + private ServletContext context; - public DoSFilter() { - numRecentAccesses = new IPTrie(); - timer = new Timer("DosFilter reset timer"); - bannedIPAddresses = Collections.synchronizedSet(new HashSet()); - manuallyBannedIPAddresses = new HashSet(); - } + public DoSFilter() { + numRecentAccesses = new IPTrie(); + timer = new Timer("DosFilter reset timer"); + bannedIPAddresses = Collections.synchronizedSet(new HashSet()); + manuallyBannedIPAddresses = new HashSet(); + } - public void init(FilterConfig filterConfig) { - context = filterConfig.getServletContext(); - String bannedIPs = filterConfig.getInitParameter("bannedIPs"); - if (bannedIPs != null) { - for (String ip : bannedIPs.split(",")) { - manuallyBannedIPAddresses.add(ip.trim()); - } - } - timer.scheduleAtFixedRate(new ResetTask(), 0L, MAX_ACCESS_INTERVAL_MSEC); - timer.scheduleAtFixedRate(new UnbanTask(), 0L, UNBAN_INTERVAL_MSEC); + public void init(FilterConfig filterConfig) { + context = filterConfig.getServletContext(); + String bannedIPs = filterConfig.getInitParameter("bannedIPs"); + if (bannedIPs != null) { + for (String ip : bannedIPs.split(",")) { + manuallyBannedIPAddresses.add(ip.trim()); + } } + timer.scheduleAtFixedRate(new ResetTask(), 0L, MAX_ACCESS_INTERVAL_MSEC); + timer.scheduleAtFixedRate(new UnbanTask(), 0L, UNBAN_INTERVAL_MSEC); + } - public void doFilter(ServletRequest request, - ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (isBanned(request)) { - HttpServletResponse servletResponse = (HttpServletResponse) response; - servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); - } else { - chain.doFilter(request, response); - } + public void doFilter(ServletRequest request, + ServletResponse response, + FilterChain chain) throws IOException, ServletException { + if (isBanned(request)) { + HttpServletResponse servletResponse = (HttpServletResponse) response; + servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); + } else { + chain.doFilter(request, response); } + } - private boolean isBanned(ServletRequest request) { - String remoteIPAddressString = request.getRemoteAddr(); - if (bannedIPAddresses.contains(remoteIPAddressString) || - manuallyBannedIPAddresses.contains(remoteIPAddressString)) { - return true; - } - InetAddress remoteIPAddress; - try { - remoteIPAddress = InetAddress.getByName(remoteIPAddressString); - } catch (UnknownHostException uhe) { - context.log("Can't determine host from: " + remoteIPAddressString + "; assuming banned"); - return true; - } - if (numRecentAccesses.incrementAndGet(remoteIPAddress) > MAX_ACCESSES_PER_IP_PER_TIME) { - context.log("Possible DoS attack from " + remoteIPAddressString); - bannedIPAddresses.add(remoteIPAddressString); - return true; - } - return false; - } - - public void destroy() { - timer.cancel(); - numRecentAccesses.clear(); - bannedIPAddresses.clear(); + private boolean isBanned(ServletRequest request) { + String remoteIPAddressString = request.getRemoteAddr(); + if (bannedIPAddresses.contains(remoteIPAddressString) || + manuallyBannedIPAddresses.contains(remoteIPAddressString)) { + return true; } + InetAddress remoteIPAddress; + try { + remoteIPAddress = InetAddress.getByName(remoteIPAddressString); + } catch (UnknownHostException uhe) { + context.log("Can't determine host from: " + remoteIPAddressString + "; assuming banned"); + return true; + } + if (numRecentAccesses.incrementAndGet(remoteIPAddress) > MAX_ACCESSES_PER_IP_PER_TIME) { + context.log("Possible DoS attack from " + remoteIPAddressString); + bannedIPAddresses.add(remoteIPAddressString); + return true; + } + return false; + } - private final class ResetTask extends TimerTask { - @Override - public void run() { - numRecentAccesses.clear(); - } - } + public void destroy() { + timer.cancel(); + numRecentAccesses.clear(); + bannedIPAddresses.clear(); + } - private final class UnbanTask extends TimerTask { - @Override - public void run() { - bannedIPAddresses.clear(); - } - } + private final class ResetTask extends TimerTask { + @Override + public void run() { + numRecentAccesses.clear(); + } + } + + private final class UnbanTask extends TimerTask { + @Override + public void run() { + bannedIPAddresses.clear(); + } + } } \ No newline at end of file diff --git a/zxingorg/src/com/google/zxing/web/EmailAuthenticator.java b/zxingorg/src/com/google/zxing/web/EmailAuthenticator.java index 546cc55a..7fd79c6a 100644 --- a/zxingorg/src/com/google/zxing/web/EmailAuthenticator.java +++ b/zxingorg/src/com/google/zxing/web/EmailAuthenticator.java @@ -17,6 +17,7 @@ package com.google.zxing.web; import javax.mail.Authenticator; +import javax.mail.PasswordAuthentication; final class EmailAuthenticator extends Authenticator { @@ -28,4 +29,9 @@ final class EmailAuthenticator extends Authenticator { this.emailPassword = emailPassword; } + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(emailUsername, emailPassword); + } + } diff --git a/zxingorg/src/com/google/zxing/web/IPTrie.java b/zxingorg/src/com/google/zxing/web/IPTrie.java index bd4edc5a..e9ebc63c 100755 --- a/zxingorg/src/com/google/zxing/web/IPTrie.java +++ b/zxingorg/src/com/google/zxing/web/IPTrie.java @@ -24,50 +24,51 @@ import java.util.Arrays; */ final class IPTrie { - private final IPTrieNode root; + private final IPTrieNode root; - IPTrie() { - root = new IPTrieNode(false); - } + IPTrie() { + root = new IPTrieNode(false); + } - int incrementAndGet(InetAddress ipAddress) { - byte[] octets = ipAddress.getAddress(); - synchronized (root) { - IPTrieNode current = root; - int max = octets.length - 1; - for (int offset = 0; offset < max; offset++) { - int index = 0xFF & octets[offset]; - IPTrieNode child = current.children[index]; - if (child == null) { - child = new IPTrieNode(offset == max - 1); - current.children[index] = child; - } - current = child; - } - int index = 0xFF & octets[max]; - current.values[index]++; - return current.values[index]; - } - } + int incrementAndGet(InetAddress ipAddress) { + byte[] octets = ipAddress.getAddress(); + synchronized (root) { + IPTrieNode current = root; + int max = octets.length - 1; + for (int offset = 0; offset < max; offset++) { + int index = 0xFF & octets[offset]; + IPTrieNode child = current.children[index]; + if (child == null) { + child = new IPTrieNode(offset == max - 1); + current.children[index] = child; + } + current = child; + } + int index = 0xFF & octets[max]; + current.values[index]++; + return current.values[index]; + } + } - void clear() { - synchronized (root) { - Arrays.fill(root.children, null); - } - } + void clear() { + synchronized (root) { + Arrays.fill(root.children, null); + } + } - private static final class IPTrieNode { - final IPTrieNode[] children; - final int[] values; - private IPTrieNode(boolean terminal) { - if (terminal) { - children = null; - values = new int[256]; - } else { - children = new IPTrieNode[256]; - values = null; - } - } - } + private static final class IPTrieNode { + final IPTrieNode[] children; + final int[] values; + + private IPTrieNode(boolean terminal) { + if (terminal) { + children = null; + values = new int[256]; + } else { + children = new IPTrieNode[256]; + values = null; + } + } + } } \ No newline at end of file diff --git a/zxingorg/web/badimage.jspx b/zxingorg/web/badimage.jspx index a22368ec..0fed7b1b 100644 --- a/zxingorg/web/badimage.jspx +++ b/zxingorg/web/badimage.jspx @@ -15,23 +15,35 @@ limitations under the License. --> - - -response.setHeader("Cache-Control", "public"); - -No Barcode Found - -

Bad URL

-

The image you uploaded could not be decoded, or was too large. Go "Back" in your browser and try another image.

- - - - + + + response.setHeader("Cache-Control", "public"); + + + No Barcode Found + + +

+ Bad URL +

+

The image you uploaded could not be decoded, or was too large. Go "Back" in your browser and try another + image. +

+ + + +
diff --git a/zxingorg/web/badurl.jspx b/zxingorg/web/badurl.jspx index c9459b23..10e8b5cc 100644 --- a/zxingorg/web/badurl.jspx +++ b/zxingorg/web/badurl.jspx @@ -15,23 +15,35 @@ limitations under the License. --> - - -response.setHeader("Cache-Control", "public"); - -No Barcode Found - -

Bad URL

-

You didn't specify a URL, or the URL was not valid, or did not return an image. Go "Back" in your browser and try again.

- - - - + + + response.setHeader("Cache-Control", "public"); + + + No Barcode Found + + +

+ Bad URL +

+

You didn't specify a URL, or the URL was not valid, or did not return an image. Go "Back" in your browser and + try again. +

+ + + +
diff --git a/zxingorg/web/decode.jspx b/zxingorg/web/decode.jspx index 7ac2ff8a..4a4d4dff 100644 --- a/zxingorg/web/decode.jspx +++ b/zxingorg/web/decode.jspx @@ -15,40 +15,58 @@ limitations under the License. --> - - -response.setHeader("Cache-Control", "public"); - -ZXing Decoder Online - - -

ZXing Decoder Online

- -

Under Construction: This is a simple page that will let you decode a 1D or 2D barcode found -in an image online. Enter a URL below.

- -
-

-
- -

Or try uploading a file:

- -
-

-
- -

See the project page for details.

- - - - - - + + + response.setHeader("Cache-Control", "public"); + + + ZXing Decoder Online + + + +

ZXing Decoder Online

+ +

Under Construction: This is a simple page that will let you decode a 1D or 2D barcode found + in an image online. Enter a URL below. +

+ +
+

+ + +

+
+ +

Or try uploading a file:

+ +
+

+ + +

+
+ +

See the + project page + for details. +

+ + + + + +
diff --git a/zxingorg/web/index.jspx b/zxingorg/web/index.jspx index c258094c..9d670fd2 100644 --- a/zxingorg/web/index.jspx +++ b/zxingorg/web/index.jspx @@ -15,27 +15,50 @@ limitations under the License. --> - - -response.setHeader("Cache-Control", "public"); - -Download ZXing Reader - -

Welcome to zxing!

-

Download the ZXing Barcode Reader.

-

Having problems with the regular version?

-

Download the ZXing Barcode Reader Basic version.

-

An Android client is available for the curious:

-

Download the Android client.

- - - - + + + response.setHeader("Cache-Control", "public"); + + + Download ZXing Reader + + +

+ Welcome to zxing! +

+

+ Download + the ZXing Barcode Reader. +

+

+ Having problems with the regular version? +

+

+ Download + the ZXing Barcode Reader Basic version. +

+

+ An Android client is available for the curious: +

+

+ Download + the Android client. +

+ + + +
diff --git a/zxingorg/web/notfound.jspx b/zxingorg/web/notfound.jspx index fdd4dd4b..cdec2079 100644 --- a/zxingorg/web/notfound.jspx +++ b/zxingorg/web/notfound.jspx @@ -15,24 +15,35 @@ limitations under the License. --> - - -response.setHeader("Cache-Control", "public"); - -No Barcode Found - -

No Barcode Found

-

No barcode was found in this image. Either it did not contain a barcode, or did not contain one in a -supported format, or the software was simply unable to find it. Go "Back" in your browser and try another image.

- - - - + + + response.setHeader("Cache-Control", "public"); + + + No Barcode Found + + +

+ No Barcode Found +

+

No barcode was found in this image. Either it did not contain a barcode, or did not contain one in a + supported format, or the software was simply unable to find it. Go "Back" in your browser and try another image. +

+ + + +
-- 2.20.1