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>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>7</source>
<target>7</target>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>

View file

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

View file

@ -18,7 +18,6 @@ package com.google.zxing;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
@ -80,7 +79,7 @@ public final class StringsResourceTranslator {
" limitations under the License.\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 {
LANGUAGE_CODE_MASSAGINGS.put("zh-rCN", "zh-cn");
LANGUAGE_CODE_MASSAGINGS.put("zh-rTW", "zh-tw");
@ -130,9 +129,7 @@ public final class StringsResourceTranslator {
resultTempFile.deleteOnExit();
boolean anyChange = false;
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultTempFile), UTF8));
try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultTempFile), UTF8))) {
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.write(APACHE_2_LICENSE);
out.write("<resources>\n");
@ -161,9 +158,6 @@ public final class StringsResourceTranslator {
out.write("</resources>\n");
out.flush();
} finally {
quietClose(out);
}
if (anyChange) {
@ -216,28 +210,22 @@ public final class StringsResourceTranslator {
URLConnection connection = translateURL.openConnection();
connection.connect();
StringBuilder translateResult = new StringBuilder(200);
Reader in = null;
try {
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8));
try (Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8))) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = in.read(buffer)) > 0) {
translateResult.append(buffer, 0, charsRead);
}
} finally {
quietClose(in);
}
return translateResult;
}
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()) {
return entries;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8));
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF8))) {
String line;
while ((line = reader.readLine()) != null) {
Matcher m = ENTRY_PATTERN.matcher(line);
@ -248,18 +236,6 @@ public final class StringsResourceTranslator {
}
}
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;
int width = DEFAULT_WIDTH;
int height = DEFAULT_HEIGHT;
String contents = null;
for (String arg : args) {
if (arg.startsWith("--barcode_format")) {
barcodeFormat = BarcodeFormat.valueOf(arg.split("=")[1]);
} else if (arg.startsWith("--image_format")) {
imageFormat = arg.split("=")[1];
} else if (arg.startsWith("--output")) {
outFileString = arg.split("=")[1];
} else if (arg.startsWith("--width")) {
width = Integer.parseInt(arg.split("=")[1]);
} else if (arg.startsWith("--height")) {
height = Integer.parseInt(arg.split("=")[1]);
String[] argValue = arg.split("=");
switch (argValue[0]) {
case "--barcode_format":
barcodeFormat = BarcodeFormat.valueOf(argValue[1]);
break;
case "--image_format":
imageFormat = argValue[1];
break;
case "--output":
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)) {
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();
BitMatrix matrix = barcodeWriter.encode(contents, barcodeFormat, width, height);

View file

@ -43,7 +43,6 @@ import java.util.regex.Pattern;
*/
public final class CommandLineRunner {
private static final String POSSIBLE_FORMATS_ARG = "--possibleFormats=";
private static final Pattern COMMA = Pattern.compile(",");
private CommandLineRunner() {
@ -56,53 +55,63 @@ public final class CommandLineRunner {
}
Config config = new Config();
Queue<String> inputs = new ConcurrentLinkedQueue<>();
for (String arg : args) {
if ("--try_harder".equals(arg)) {
config.setTryHarder(true);
} else if ("--pure_barcode".equals(arg)) {
config.setPureBarcode(true);
} else if ("--products_only".equals(arg)) {
config.setProductsOnly(true);
} else if ("--dump_results".equals(arg)) {
config.setDumpResults(true);
} else if ("--dump_black_point".equals(arg)) {
config.setDumpBlackPoint(true);
} else if ("--multi".equals(arg)) {
config.setMulti(true);
} else if ("--brief".equals(arg)) {
config.setBrief(true);
} else if ("--recursive".equals(arg)) {
config.setRecursive(true);
} else if (arg.startsWith("--crop")) {
int[] crop = new int[4];
String[] tokens = COMMA.split(arg.substring(7));
for (int i = 0; i < crop.length; i++) {
crop[i] = Integer.parseInt(tokens[i]);
}
config.setCrop(crop);
} else if (arg.startsWith(POSSIBLE_FORMATS_ARG)) {
config.setPossibleFormats(COMMA.split(arg.substring(POSSIBLE_FORMATS_ARG.length())));
} else if (arg.startsWith("-")) {
System.err.println("Unknown command line option " + arg);
printUsage();
return;
String[] argValue = arg.split("=");
switch (argValue[0]) {
case "--try_harder":
config.setTryHarder(true);
break;
case "--pure_barcode":
config.setPureBarcode(true);
break;
case "--products_only":
config.setProductsOnly(true);
break;
case "--dump_results":
config.setDumpResults(true);
break;
case "--dump_black_point":
config.setDumpBlackPoint(true);
break;
case "--multi":
config.setMulti(true);
break;
case "--brief":
config.setBrief(true);
break;
case "--recursive":
config.setRecursive(true);
break;
case "--crop":
int[] crop = new int[4];
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));
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 successful = 0;
if (numThreads > 1) {
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++) {
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.
private static Map<DecodeHintType,?> buildHints(Config config) {
Collection<BarcodeFormat> possibleFormats = new ArrayList<BarcodeFormat>();
Collection<BarcodeFormat> possibleFormats = new ArrayList<>();
String[] possibleFormatsNames = config.getPossibleFormats();
if (possibleFormatsNames != null && possibleFormatsNames.length > 0) {
for (String format : possibleFormatsNames) {
@ -182,7 +191,7 @@ public final class CommandLineRunner {
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);
if (config.isTryHarder()) {
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(" --recursive: Descend into subdirectories");
System.err.println(" --crop=left,top,width,height: Only examine cropped region of input image(s)");
StringBuilder builder = new StringBuilder(
" " + POSSIBLE_FORMATS_ARG + "barcodeFormat[,barcodeFormat2...] where barcodeFormat is any of: ");
StringBuilder builder = new StringBuilder();
builder.append(" --possibleFormats=barcodeFormat[,barcodeFormat2...] where barcodeFormat is any of: ");
for (BarcodeFormat format : BarcodeFormat.values()) {
builder.append(format).append(',');
}

View file

@ -33,7 +33,6 @@ import com.google.zxing.multi.GenericMultipleBarcodeReader;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@ -52,6 +51,8 @@ import java.util.concurrent.Callable;
*/
final class DecodeWorker implements Callable<Integer> {
private static final Charset UTF8 = Charset.forName("UTF8");
private final Config config;
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 {
Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
try {
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
out.write(value);
} finally {
out.close();
}
}
private static void writeResultsToFile(Result[] results, File file) throws IOException {
String newline = System.getProperty("line.separator");
Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
try {
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
for (Result result : results) {
out.write(result.getText());
out.write(newline);
}
} finally {
out.close();
}
}
@ -225,7 +220,7 @@ final class DecodeWorker implements Callable<Integer> {
* monochrome version.
*/
private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
// TODO: Update to compare different Binarizer implementations.
String inputName = uri.getPath();
if (inputName.contains(".mono.png")) {
return;
@ -310,24 +305,12 @@ final class DecodeWorker implements Callable<Integer> {
resultName = resultName.substring(0, pos);
}
resultName += suffix;
OutputStream outStream = null;
try {
outStream = new FileOutputStream(resultName);
try (OutputStream outStream = new FileOutputStream(resultName)) {
if (!ImageIO.write(result, "png", outStream)) {
System.err.println("Could not encode an image to " + resultName);
}
} catch (FileNotFoundException ignored) {
System.err.println("Could not create " + resultName);
} catch (IOException ignored) {
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>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>7</source>
<target>7</target>
<compilerArgs>
<arg>-Xlint:all</arg>
</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 Charset UTF8 = Charset.forName("UTF-8");
// No real reason to let people upload more than a 2MB image
private static final long MAX_IMAGE_SIZE = 2000000L;
// 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;
static {
HINTS = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
HINTS = new EnumMap<>(DecodeHintType.class);
HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
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);
}
@ -113,22 +115,15 @@ public final class DecodeServlet extends HttpServlet {
diskFileItemFactory = new DiskFileItemFactory(1 << 16, repository);
diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
blockedURLSubstrings = new ArrayList<String>();
InputStream in = DecodeServlet.class.getResourceAsStream("/private/uri-block-substrings.txt");
if (in != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
try {
String line;
while ((line = reader.readLine()) != null) {
blockedURLSubstrings.add(line);
}
} finally {
reader.close();
}
} catch (IOException ioe) {
throw new ServletException(ioe);
blockedURLSubstrings = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
DecodeServlet.class.getResourceAsStream("/private/uri-block-substrings.txt"), UTF8))) {
String line;
while ((line = reader.readLine()) != null) {
blockedURLSubstrings.add(line);
}
} catch (IOException ioe) {
throw new ServletException(ioe);
}
log.info("Blocking URIs containing: " + blockedURLSubstrings);
}
@ -258,10 +253,9 @@ public final class DecodeServlet extends HttpServlet {
while ((available = is.available()) > 0) {
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
} 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.getSize() <= MAX_IMAGE_SIZE) {
log.info("Decoding uploaded file");
InputStream is = item.getInputStream();
try {
try (InputStream is = item.getInputStream()) {
processStream(is, request, response);
} finally {
is.close();
}
} else {
log.info("Too large");
@ -311,19 +302,9 @@ public final class DecodeServlet extends HttpServlet {
BufferedImage image;
try {
image = ImageIO.read(is);
} catch (IOException ioe) {
} catch (IOException | CMMException | IllegalArgumentException ioe) {
log.info(ioe.toString());
// Includes javax.imageio.IIOException
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
// Have seen these in some logs
response.sendRedirect("badimage.jspx");
return;
}
@ -348,7 +329,7 @@ public final class DecodeServlet extends HttpServlet {
Reader reader = new MultiFormatReader();
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Collection<Result> results = new ArrayList<Result>(1);
Collection<Result> results = new ArrayList<>(1);
ReaderException savedException = null;
try {
@ -417,14 +398,11 @@ public final class DecodeServlet extends HttpServlet {
if (minimalOutput) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF8");
Writer out = new OutputStreamWriter(response.getOutputStream(), Charset.forName("UTF-8"));
try {
try (Writer out = new OutputStreamWriter(response.getOutputStream(), UTF8)) {
for (Result result : results) {
out.write(result.getText());
out.write('\n');
}
} finally {
out.close();
}
} else {
request.setAttribute("results", results);