Update non-core Java code to Java 7. Core/Android needs to stay on Java 6.

git-svn-id: https://zxing.googlecode.com/svn/trunk@2861 59b500cc-1b3d-0410-9834-0bbf25fbcc57
This commit is contained in:
srowen@gmail.com 2013-08-08 04:29:30 +00:00
parent f9b966a96e
commit 2de2f413b6
8 changed files with 123 additions and 172 deletions

View file

@ -83,8 +83,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<source>1.6</source> <source>7</source>
<target>1.6</target> <target>7</target>
<compilerArgs> <compilerArgs>
<arg>-Xlint:all</arg> <arg>-Xlint:all</arg>
</compilerArgs> </compilerArgs>

View file

@ -81,7 +81,7 @@ public final class HtmlAssetTranslator {
} }
private static Collection<String> parseLanguagesToTranslate(File assetsDir, CharSequence languageArg) { private static Collection<String> parseLanguagesToTranslate(File assetsDir, CharSequence languageArg) {
Collection<String> languages = new ArrayList<String>(); Collection<String> languages = new ArrayList<>();
if ("all".equals(languageArg)) { if ("all".equals(languageArg)) {
FileFilter fileFilter = new FileFilter() { FileFilter fileFilter = new FileFilter() {
@Override @Override
@ -99,7 +99,7 @@ public final class HtmlAssetTranslator {
} }
private static Collection<String> parseFileNamesToTranslate(File assetsDir, List<String> restOfArgs) { private static Collection<String> parseFileNamesToTranslate(File assetsDir, List<String> restOfArgs) {
Collection<String> fileNamesToTranslate = new ArrayList<String>(); Collection<String> fileNamesToTranslate = new ArrayList<>();
if ("all".equals(restOfArgs.get(0))) { if ("all".equals(restOfArgs.get(0))) {
File htmlEnAssetDir = new File(assetsDir, "html-en"); File htmlEnAssetDir = new File(assetsDir, "html-en");
FileFilter fileFilter = new FileFilter() { FileFilter fileFilter = new FileFilter() {
@ -162,7 +162,7 @@ public final class HtmlAssetTranslator {
Element rootElement = document.getDocumentElement(); Element rootElement = document.getDocumentElement();
rootElement.normalize(); rootElement.normalize();
Queue<Node> nodes = new LinkedList<Node>(); Queue<Node> nodes = new LinkedList<>();
nodes.add(rootElement); nodes.add(rootElement);
while (!nodes.isEmpty()) { while (!nodes.isEmpty()) {
@ -191,14 +191,10 @@ public final class HtmlAssetTranslator {
DOMImplementationRegistry registry; DOMImplementationRegistry registry;
try { try {
registry = DOMImplementationRegistry.newInstance(); registry = DOMImplementationRegistry.newInstance();
} catch (ClassNotFoundException cnfe) { } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(cnfe); throw new IllegalStateException(e);
} catch (InstantiationException ie) {
throw new IllegalStateException(ie);
} catch (IllegalAccessException iae) {
throw new IllegalStateException(iae);
} }
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer(); LSSerializer writer = impl.createLSSerializer();
writer.writeToURI(document, destFile.toURI().toString()); writer.writeToURI(document, destFile.toURI().toString());

View file

@ -18,7 +18,6 @@ package com.google.zxing;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -80,7 +79,7 @@ public final class StringsResourceTranslator {
" limitations under the License.\n" + " limitations under the License.\n" +
" -->\n"; " -->\n";
private static final Map<String,String> LANGUAGE_CODE_MASSAGINGS = new HashMap<String,String>(3); private static final Map<String,String> LANGUAGE_CODE_MASSAGINGS = new HashMap<>(3);
static { static {
LANGUAGE_CODE_MASSAGINGS.put("zh-rCN", "zh-cn"); LANGUAGE_CODE_MASSAGINGS.put("zh-rCN", "zh-cn");
LANGUAGE_CODE_MASSAGINGS.put("zh-rTW", "zh-tw"); LANGUAGE_CODE_MASSAGINGS.put("zh-rTW", "zh-tw");
@ -130,9 +129,7 @@ public final class StringsResourceTranslator {
resultTempFile.deleteOnExit(); resultTempFile.deleteOnExit();
boolean anyChange = false; boolean anyChange = false;
Writer out = null; try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultTempFile), UTF8))) {
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultTempFile), UTF8));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.write(APACHE_2_LICENSE); out.write(APACHE_2_LICENSE);
out.write("<resources>\n"); out.write("<resources>\n");
@ -161,9 +158,6 @@ public final class StringsResourceTranslator {
out.write("</resources>\n"); out.write("</resources>\n");
out.flush(); out.flush();
} finally {
quietClose(out);
} }
if (anyChange) { if (anyChange) {
@ -216,28 +210,22 @@ public final class StringsResourceTranslator {
URLConnection connection = translateURL.openConnection(); URLConnection connection = translateURL.openConnection();
connection.connect(); connection.connect();
StringBuilder translateResult = new StringBuilder(200); StringBuilder translateResult = new StringBuilder(200);
Reader in = null; try (Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8))) {
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8));
char[] buffer = new char[1024]; char[] buffer = new char[1024];
int charsRead; int charsRead;
while ((charsRead = in.read(buffer)) > 0) { while ((charsRead = in.read(buffer)) > 0) {
translateResult.append(buffer, 0, charsRead); translateResult.append(buffer, 0, charsRead);
} }
} finally {
quietClose(in);
} }
return translateResult; return translateResult;
} }
private static SortedMap<String,String> readLines(File file) throws IOException { private static SortedMap<String,String> readLines(File file) throws IOException {
SortedMap<String,String> entries = new TreeMap<String,String>(); SortedMap<String,String> entries = new TreeMap<>();
if (!file.exists()) { if (!file.exists()) {
return entries; return entries;
} }
BufferedReader reader = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8))) {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
Matcher m = ENTRY_PATTERN.matcher(line); Matcher m = ENTRY_PATTERN.matcher(line);
@ -248,18 +236,6 @@ public final class StringsResourceTranslator {
} }
} }
return entries; return entries;
} finally {
quietClose(reader);
}
}
private static void quietClose(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ioe) {
// continue
}
} }
} }

View file

@ -50,36 +50,45 @@ public final class CommandLineEncoder {
String outFileString = DEFAULT_OUTPUT_FILE; String outFileString = DEFAULT_OUTPUT_FILE;
int width = DEFAULT_WIDTH; int width = DEFAULT_WIDTH;
int height = DEFAULT_HEIGHT; int height = DEFAULT_HEIGHT;
String contents = null;
for (String arg : args) { for (String arg : args) {
if (arg.startsWith("--barcode_format")) { String[] argValue = arg.split("=");
barcodeFormat = BarcodeFormat.valueOf(arg.split("=")[1]); switch (argValue[0]) {
} else if (arg.startsWith("--image_format")) { case "--barcode_format":
imageFormat = arg.split("=")[1]; barcodeFormat = BarcodeFormat.valueOf(argValue[1]);
} else if (arg.startsWith("--output")) { break;
outFileString = arg.split("=")[1]; case "--image_format":
} else if (arg.startsWith("--width")) { imageFormat = argValue[1];
width = Integer.parseInt(arg.split("=")[1]); break;
} else if (arg.startsWith("--height")) { case "--output":
height = Integer.parseInt(arg.split("=")[1]); outFileString = argValue[1];
break;
case "--width":
width = Integer.parseInt(argValue[1]);
break;
case "--height":
height = Integer.parseInt(argValue[1]);
break;
default:
if (arg.startsWith("-")) {
System.err.println("Unknown command line option " + arg);
printUsage();
return;
}
contents = arg;
break;
} }
} }
if (contents == null) {
printUsage();
return;
}
if (DEFAULT_OUTPUT_FILE.equals(outFileString)) { if (DEFAULT_OUTPUT_FILE.equals(outFileString)) {
outFileString += '.' + imageFormat.toLowerCase(Locale.ENGLISH); outFileString += '.' + imageFormat.toLowerCase(Locale.ENGLISH);
} }
String contents = null;
for (String arg : args) {
if (!arg.startsWith("--")) {
contents = arg;
break;
}
}
if (contents == null) {
printUsage();
return;
}
MultiFormatWriter barcodeWriter = new MultiFormatWriter(); MultiFormatWriter barcodeWriter = new MultiFormatWriter();
BitMatrix matrix = barcodeWriter.encode(contents, barcodeFormat, width, height); BitMatrix matrix = barcodeWriter.encode(contents, barcodeFormat, width, height);

View file

@ -43,7 +43,6 @@ import java.util.regex.Pattern;
*/ */
public final class CommandLineRunner { public final class CommandLineRunner {
private static final String POSSIBLE_FORMATS_ARG = "--possibleFormats=";
private static final Pattern COMMA = Pattern.compile(","); private static final Pattern COMMA = Pattern.compile(",");
private CommandLineRunner() { private CommandLineRunner() {
@ -56,53 +55,63 @@ public final class CommandLineRunner {
} }
Config config = new Config(); Config config = new Config();
Queue<String> inputs = new ConcurrentLinkedQueue<>();
for (String arg : args) { for (String arg : args) {
if ("--try_harder".equals(arg)) { String[] argValue = arg.split("=");
config.setTryHarder(true); switch (argValue[0]) {
} else if ("--pure_barcode".equals(arg)) { case "--try_harder":
config.setPureBarcode(true); config.setTryHarder(true);
} else if ("--products_only".equals(arg)) { break;
config.setProductsOnly(true); case "--pure_barcode":
} else if ("--dump_results".equals(arg)) { config.setPureBarcode(true);
config.setDumpResults(true); break;
} else if ("--dump_black_point".equals(arg)) { case "--products_only":
config.setDumpBlackPoint(true); config.setProductsOnly(true);
} else if ("--multi".equals(arg)) { break;
config.setMulti(true); case "--dump_results":
} else if ("--brief".equals(arg)) { config.setDumpResults(true);
config.setBrief(true); break;
} else if ("--recursive".equals(arg)) { case "--dump_black_point":
config.setRecursive(true); config.setDumpBlackPoint(true);
} else if (arg.startsWith("--crop")) { break;
int[] crop = new int[4]; case "--multi":
String[] tokens = COMMA.split(arg.substring(7)); config.setMulti(true);
for (int i = 0; i < crop.length; i++) { break;
crop[i] = Integer.parseInt(tokens[i]); case "--brief":
} config.setBrief(true);
config.setCrop(crop); break;
} else if (arg.startsWith(POSSIBLE_FORMATS_ARG)) { case "--recursive":
config.setPossibleFormats(COMMA.split(arg.substring(POSSIBLE_FORMATS_ARG.length()))); config.setRecursive(true);
} else if (arg.startsWith("-")) { break;
System.err.println("Unknown command line option " + arg); case "--crop":
printUsage(); int[] crop = new int[4];
return; String[] tokens = COMMA.split(argValue[1]);
for (int i = 0; i < crop.length; i++) {
crop[i] = Integer.parseInt(tokens[i]);
}
config.setCrop(crop);
break;
case "--possibleFormats":
config.setPossibleFormats(COMMA.split(argValue[1]));
break;
default:
if (arg.startsWith("-")) {
System.err.println("Unknown command line option " + arg);
printUsage();
return;
}
addArgumentToInputs(arg, config, inputs);
break;
} }
} }
config.setHints(buildHints(config)); config.setHints(buildHints(config));
Queue<String> inputs = new ConcurrentLinkedQueue<String>();
for (String arg : args) {
if (!arg.startsWith("--")) {
addArgumentToInputs(arg, config, inputs);
}
}
int numThreads = Math.min(inputs.size(), Runtime.getRuntime().availableProcessors()); int numThreads = Math.min(inputs.size(), Runtime.getRuntime().availableProcessors());
int successful = 0; int successful = 0;
if (numThreads > 1) { if (numThreads > 1) {
ExecutorService executor = Executors.newFixedThreadPool(numThreads); ExecutorService executor = Executors.newFixedThreadPool(numThreads);
Collection<Future<Integer>> futures = new ArrayList<Future<Integer>>(numThreads); Collection<Future<Integer>> futures = new ArrayList<>(numThreads);
for (int x = 0; x < numThreads; x++) { for (int x = 0; x < numThreads; x++) {
futures.add(executor.submit(new DecodeWorker(config, inputs))); futures.add(executor.submit(new DecodeWorker(config, inputs)));
} }
@ -156,7 +165,7 @@ public final class CommandLineRunner {
// Manually turn on all formats, even those not yet considered production quality. // Manually turn on all formats, even those not yet considered production quality.
private static Map<DecodeHintType,?> buildHints(Config config) { private static Map<DecodeHintType,?> buildHints(Config config) {
Collection<BarcodeFormat> possibleFormats = new ArrayList<BarcodeFormat>(); Collection<BarcodeFormat> possibleFormats = new ArrayList<>();
String[] possibleFormatsNames = config.getPossibleFormats(); String[] possibleFormatsNames = config.getPossibleFormats();
if (possibleFormatsNames != null && possibleFormatsNames.length > 0) { if (possibleFormatsNames != null && possibleFormatsNames.length > 0) {
for (String format : possibleFormatsNames) { for (String format : possibleFormatsNames) {
@ -182,7 +191,7 @@ public final class CommandLineRunner {
possibleFormats.add(BarcodeFormat.MAXICODE); possibleFormats.add(BarcodeFormat.MAXICODE);
} }
} }
Map<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class); Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats); hints.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
if (config.isTryHarder()) { if (config.isTryHarder()) {
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
@ -206,8 +215,8 @@ public final class CommandLineRunner {
System.err.println(" --brief: Only output one line per file, omitting the contents"); System.err.println(" --brief: Only output one line per file, omitting the contents");
System.err.println(" --recursive: Descend into subdirectories"); System.err.println(" --recursive: Descend into subdirectories");
System.err.println(" --crop=left,top,width,height: Only examine cropped region of input image(s)"); System.err.println(" --crop=left,top,width,height: Only examine cropped region of input image(s)");
StringBuilder builder = new StringBuilder( StringBuilder builder = new StringBuilder();
" " + POSSIBLE_FORMATS_ARG + "barcodeFormat[,barcodeFormat2...] where barcodeFormat is any of: "); builder.append(" --possibleFormats=barcodeFormat[,barcodeFormat2...] where barcodeFormat is any of: ");
for (BarcodeFormat format : BarcodeFormat.values()) { for (BarcodeFormat format : BarcodeFormat.values()) {
builder.append(format).append(','); builder.append(format).append(',');
} }

View file

@ -33,7 +33,6 @@ import com.google.zxing.multi.GenericMultipleBarcodeReader;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@ -52,6 +51,8 @@ import java.util.concurrent.Callable;
*/ */
final class DecodeWorker implements Callable<Integer> { final class DecodeWorker implements Callable<Integer> {
private static final Charset UTF8 = Charset.forName("UTF8");
private final Config config; private final Config config;
private final Queue<String> inputs; private final Queue<String> inputs;
@ -115,24 +116,18 @@ final class DecodeWorker implements Callable<Integer> {
} }
private static void writeStringToFile(String value, File file) throws IOException { private static void writeStringToFile(String value, File file) throws IOException {
Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8")); try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
try {
out.write(value); out.write(value);
} finally {
out.close();
} }
} }
private static void writeResultsToFile(Result[] results, File file) throws IOException { private static void writeResultsToFile(Result[] results, File file) throws IOException {
String newline = System.getProperty("line.separator"); String newline = System.getProperty("line.separator");
Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8")); try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
try {
for (Result result : results) { for (Result result : results) {
out.write(result.getText()); out.write(result.getText());
out.write(newline); out.write(newline);
} }
} finally {
out.close();
} }
} }
@ -225,7 +220,7 @@ final class DecodeWorker implements Callable<Integer> {
* monochrome version. * monochrome version.
*/ */
private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) { private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
// TODO: Update to compare different Binarizer implementations.
String inputName = uri.getPath(); String inputName = uri.getPath();
if (inputName.contains(".mono.png")) { if (inputName.contains(".mono.png")) {
return; return;
@ -310,24 +305,12 @@ final class DecodeWorker implements Callable<Integer> {
resultName = resultName.substring(0, pos); resultName = resultName.substring(0, pos);
} }
resultName += suffix; resultName += suffix;
OutputStream outStream = null; try (OutputStream outStream = new FileOutputStream(resultName)) {
try {
outStream = new FileOutputStream(resultName);
if (!ImageIO.write(result, "png", outStream)) { if (!ImageIO.write(result, "png", outStream)) {
System.err.println("Could not encode an image to " + resultName); System.err.println("Could not encode an image to " + resultName);
} }
} catch (FileNotFoundException ignored) {
System.err.println("Could not create " + resultName);
} catch (IOException ignored) { } catch (IOException ignored) {
System.err.println("Could not write to " + resultName); System.err.println("Could not write to " + resultName);
} finally {
try {
if (outStream != null) {
outStream.close();
}
} catch (IOException ioe) {
// continue
}
} }
} }

View file

@ -109,8 +109,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<source>1.6</source> <source>7</source>
<target>1.6</target> <target>7</target>
<compilerArgs> <compilerArgs>
<arg>-Xlint:all</arg> <arg>-Xlint:all</arg>
</compilerArgs> </compilerArgs>

View file

@ -84,6 +84,8 @@ public final class DecodeServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(DecodeServlet.class.getName()); private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
private static final Charset UTF8 = Charset.forName("UTF-8");
// No real reason to let people upload more than a 2MB image // No real reason to let people upload more than a 2MB image
private static final long MAX_IMAGE_SIZE = 2000000L; private static final long MAX_IMAGE_SIZE = 2000000L;
// No real reason to deal with more than maybe 8.3 megapixels // No real reason to deal with more than maybe 8.3 megapixels
@ -93,10 +95,10 @@ public final class DecodeServlet extends HttpServlet {
private static final Map<DecodeHintType,Object> HINTS_PURE; private static final Map<DecodeHintType,Object> HINTS_PURE;
static { static {
HINTS = new EnumMap<DecodeHintType,Object>(DecodeHintType.class); HINTS = new EnumMap<>(DecodeHintType.class);
HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class)); HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
HINTS_PURE = new EnumMap<DecodeHintType,Object>(HINTS); HINTS_PURE = new EnumMap<>(HINTS);
HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
} }
@ -113,22 +115,15 @@ public final class DecodeServlet extends HttpServlet {
diskFileItemFactory = new DiskFileItemFactory(1 << 16, repository); diskFileItemFactory = new DiskFileItemFactory(1 << 16, repository);
diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker); diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
blockedURLSubstrings = new ArrayList<String>(); blockedURLSubstrings = new ArrayList<>();
InputStream in = DecodeServlet.class.getResourceAsStream("/private/uri-block-substrings.txt"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(
if (in != null) { DecodeServlet.class.getResourceAsStream("/private/uri-block-substrings.txt"), UTF8))) {
try { String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8"))); while ((line = reader.readLine()) != null) {
try { blockedURLSubstrings.add(line);
String line;
while ((line = reader.readLine()) != null) {
blockedURLSubstrings.add(line);
}
} finally {
reader.close();
}
} catch (IOException ioe) {
throw new ServletException(ioe);
} }
} catch (IOException ioe) {
throw new ServletException(ioe);
} }
log.info("Blocking URIs containing: " + blockedURLSubstrings); log.info("Blocking URIs containing: " + blockedURLSubstrings);
} }
@ -258,10 +253,9 @@ public final class DecodeServlet extends HttpServlet {
while ((available = is.available()) > 0) { while ((available = is.available()) > 0) {
is.read(REMAINDER_BUFFER, 0, available); // don't care about value, or collision is.read(REMAINDER_BUFFER, 0, available); // don't care about value, or collision
} }
} catch (IOException ioe) { } catch (IOException | IndexOutOfBoundsException ioe) {
// sun.net.www.http.ChunkedInputStream.read is throwing IndexOutOfBoundsException
// continue // continue
} catch (IndexOutOfBoundsException ioobe) {
// sun.net.www.http.ChunkedInputStream.read is throwing this, continue
} }
} }
@ -284,11 +278,8 @@ public final class DecodeServlet extends HttpServlet {
if (!item.isFormField()) { if (!item.isFormField()) {
if (item.getSize() <= MAX_IMAGE_SIZE) { if (item.getSize() <= MAX_IMAGE_SIZE) {
log.info("Decoding uploaded file"); log.info("Decoding uploaded file");
InputStream is = item.getInputStream(); try (InputStream is = item.getInputStream()) {
try {
processStream(is, request, response); processStream(is, request, response);
} finally {
is.close();
} }
} else { } else {
log.info("Too large"); log.info("Too large");
@ -311,19 +302,9 @@ public final class DecodeServlet extends HttpServlet {
BufferedImage image; BufferedImage image;
try { try {
image = ImageIO.read(is); image = ImageIO.read(is);
} catch (IOException ioe) { } catch (IOException | CMMException | IllegalArgumentException ioe) {
log.info(ioe.toString()); log.info(ioe.toString());
// Includes javax.imageio.IIOException // Have seen these in some logs
response.sendRedirect("badimage.jspx");
return;
} catch (CMMException cmme) {
log.info(cmme.toString());
// Have seen this in logs
response.sendRedirect("badimage.jspx");
return;
} catch (IllegalArgumentException iae) {
log.info(iae.toString());
// Have seen this in logs for some JPEGs
response.sendRedirect("badimage.jspx"); response.sendRedirect("badimage.jspx");
return; return;
} }
@ -348,7 +329,7 @@ public final class DecodeServlet extends HttpServlet {
Reader reader = new MultiFormatReader(); Reader reader = new MultiFormatReader();
LuminanceSource source = new BufferedImageLuminanceSource(image); LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Collection<Result> results = new ArrayList<Result>(1); Collection<Result> results = new ArrayList<>(1);
ReaderException savedException = null; ReaderException savedException = null;
try { try {
@ -417,14 +398,11 @@ public final class DecodeServlet extends HttpServlet {
if (minimalOutput) { if (minimalOutput) {
response.setContentType("text/plain"); response.setContentType("text/plain");
response.setCharacterEncoding("UTF8"); response.setCharacterEncoding("UTF8");
Writer out = new OutputStreamWriter(response.getOutputStream(), Charset.forName("UTF-8")); try (Writer out = new OutputStreamWriter(response.getOutputStream(), UTF8)) {
try {
for (Result result : results) { for (Result result : results) {
out.write(result.getText()); out.write(result.getText());
out.write('\n'); out.write('\n');
} }
} finally {
out.close();
} }
} else { } else {
request.setAttribute("results", results); request.setAttribute("results", results);