Move to use of Java 7 NIO2 APIs

This commit is contained in:
Sean Owen 2014-01-31 13:01:18 +00:00
parent 024a353939
commit dddc1c4e19
21 changed files with 408 additions and 618 deletions

View file

@ -27,7 +27,7 @@ import com.google.zxing.common.DecoderResult;
import org.junit.Assert;
import org.junit.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -42,8 +42,6 @@ import java.util.TreeSet;
*/
public final class DetectorTest extends Assert {
private static final Charset LATIN_1 = Charset.forName("ISO-8859-1");
@Test
public void testErrorInParameterLocatorZeroZero() throws Exception {
// Layers=1, CodeWords=1. So the parameter info and its Reed-Solomon info
@ -64,7 +62,7 @@ public final class DetectorTest extends Assert {
// Test that we can tolerate errors in the parameter locator bits
private static void testErrorInParameterLocator(String data) throws Exception {
AztecCode aztec = Encoder.encode(data.getBytes(LATIN_1), 25, Encoder.DEFAULT_AZTEC_LAYERS);
AztecCode aztec = Encoder.encode(data.getBytes(StandardCharsets.ISO_8859_1), 25, Encoder.DEFAULT_AZTEC_LAYERS);
Random random = new Random(aztec.getMatrix().hashCode()); // pseudo-random, but deterministic
int layers = aztec.getLayers();
boolean compact = aztec.isCompact();

View file

@ -30,6 +30,7 @@ import org.junit.Assert;
import org.junit.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.EnumMap;
import java.util.Map;
@ -44,7 +45,6 @@ import java.util.regex.Pattern;
*/
public final class EncoderTest extends Assert {
private static final Charset LATIN_1 = Charset.forName("ISO-8859-1");
private static final Pattern DOTX = Pattern.compile("[^.X]");
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
@ -138,7 +138,7 @@ public final class EncoderTest extends Assert {
String data = "In ut magna vel mauris malesuada";
AztecWriter writer = new AztecWriter();
BitMatrix matrix = writer.encode(data, BarcodeFormat.AZTEC, 0, 0);
AztecCode aztec = Encoder.encode(data.getBytes(LATIN_1),
AztecCode aztec = Encoder.encode(data.getBytes(StandardCharsets.ISO_8859_1),
Encoder.DEFAULT_EC_PERCENT, Encoder.DEFAULT_AZTEC_LAYERS);
BitMatrix expectedMatrix = aztec.getMatrix();
assertEquals(matrix, expectedMatrix);
@ -386,7 +386,7 @@ public final class EncoderTest extends Assert {
@Test
public void testUserSpecifiedLayers() throws Exception {
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(LATIN_1);
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.ISO_8859_1);
AztecCode aztec = Encoder.encode(alphabet, 25, -2);
assertEquals(2, aztec.getLayers());
assertTrue(aztec.isCompact());
@ -413,7 +413,7 @@ public final class EncoderTest extends Assert {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// encodes as 26 * 5 * 4 = 520 bits of data
String alphabet4 = alphabet + alphabet + alphabet + alphabet;
byte[] data = alphabet4.getBytes(LATIN_1);
byte[] data = alphabet4.getBytes(StandardCharsets.ISO_8859_1);
try {
Encoder.encode(data, 0, -4);
fail("Encode should have failed. Text can't fit in 1-layer compact");
@ -426,7 +426,7 @@ public final class EncoderTest extends Assert {
// But shortening the string to 100 bytes (500 bits of data), compact works fine, even if we
// include more error checking.
aztecCode = Encoder.encode(alphabet4.substring(0, 100).getBytes(LATIN_1), 10, Encoder.DEFAULT_AZTEC_LAYERS);
aztecCode = Encoder.encode(alphabet4.substring(0, 100).getBytes(StandardCharsets.ISO_8859_1), 10, Encoder.DEFAULT_AZTEC_LAYERS);
assertTrue(aztecCode.isCompact());
assertEquals(4, aztecCode.getLayers());
}
@ -434,7 +434,7 @@ public final class EncoderTest extends Assert {
// Helper routines
private static void testEncode(String data, boolean compact, int layers, String expected) throws Exception {
AztecCode aztec = Encoder.encode(data.getBytes(LATIN_1), 33, Encoder.DEFAULT_AZTEC_LAYERS);
AztecCode aztec = Encoder.encode(data.getBytes(StandardCharsets.ISO_8859_1), 33, Encoder.DEFAULT_AZTEC_LAYERS);
assertEquals("Unexpected symbol format (compact)", compact, aztec.isCompact());
assertEquals("Unexpected nr. of layers", layers, aztec.getLayers());
BitMatrix matrix = aztec.getMatrix();
@ -442,7 +442,7 @@ public final class EncoderTest extends Assert {
}
private static void testEncodeDecode(String data, boolean compact, int layers) throws Exception {
AztecCode aztec = Encoder.encode(data.getBytes(LATIN_1), 25, Encoder.DEFAULT_AZTEC_LAYERS);
AztecCode aztec = Encoder.encode(data.getBytes(StandardCharsets.ISO_8859_1), 25, Encoder.DEFAULT_AZTEC_LAYERS);
assertEquals("Unexpected symbol format (compact)", compact, aztec.isCompact());
assertEquals("Unexpected nr. of layers", layers, aztec.getLayers());
BitMatrix matrix = aztec.getMatrix();
@ -468,7 +468,7 @@ public final class EncoderTest extends Assert {
int layers) throws FormatException {
// 1. Perform an encode-decode round-trip because it can be lossy.
// 2. Aztec Decoder currently always decodes the data with a LATIN-1 charset:
String expectedData = new String(data.getBytes(Charset.forName(charset)), LATIN_1);
String expectedData = new String(data.getBytes(Charset.forName(charset)), StandardCharsets.ISO_8859_1);
Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, charset);
hints.put(EncodeHintType.ERROR_CORRECTION, eccPercent);
@ -537,14 +537,14 @@ public final class EncoderTest extends Assert {
}
private static void testHighLevelEncodeString(String s, String expectedBits) {
BitArray bits = new HighLevelEncoder(s.getBytes(LATIN_1)).encode();
BitArray bits = new HighLevelEncoder(s.getBytes(StandardCharsets.ISO_8859_1)).encode();
String receivedBits = bits.toString().replace(" ", "");
assertEquals("highLevelEncode() failed for input string: " + s, expectedBits.replace(" ", ""), receivedBits);
assertEquals(s, Decoder.highLevelDecode(toBooleanArray(bits)));
}
private static void testHighLevelEncodeString(String s, int expectedReceivedBits) {
BitArray bits = new HighLevelEncoder(s.getBytes(LATIN_1)).encode();
BitArray bits = new HighLevelEncoder(s.getBytes(StandardCharsets.ISO_8859_1)).encode();
int receivedBitCount = bits.toString().replace(" ", "").length();
assertEquals("highLevelEncode() failed for input string: " + s,
expectedReceivedBits, receivedBitCount);

View file

@ -35,17 +35,17 @@ import java.awt.geom.RectangularShape;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
@ -58,18 +58,7 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
private static final Logger log = Logger.getLogger(AbstractBlackBoxTestCase.class.getSimpleName());
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Charset ISO88591 = Charset.forName("ISO-8859-1");
private static final FilenameFilter IMAGE_NAME_FILTER = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String lowerCase = name.toLowerCase(Locale.ENGLISH);
return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
lowerCase.endsWith(".gif") || lowerCase.endsWith(".png");
}
};
private final File testBase;
private final Path testBase;
private final Reader barcodeReader;
private final BarcodeFormat expectedFormat;
private final List<TestResult> testResults;
@ -78,10 +67,10 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
Reader barcodeReader,
BarcodeFormat expectedFormat) {
// A little workaround to prevent aggravation in my IDE
File testBase = new File(testBasePathSuffix);
if (!testBase.exists()) {
Path testBase = Paths.get(testBasePathSuffix);
if (!Files.exists(testBase)) {
// try starting with 'core' since the test base is often given as the project root
testBase = new File("core/" + testBasePathSuffix);
testBase = Paths.get("core").resolve(testBasePathSuffix);
}
this.testBase = testBase;
this.barcodeReader = barcodeReader;
@ -91,6 +80,10 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%6$s%n");
}
protected final Path getTestBase() {
return testBase;
}
protected final void addTest(int mustPassCount, int tryHarderCount, float rotation) {
addTest(mustPassCount, tryHarderCount, 0, 0, rotation);
}
@ -113,12 +106,18 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
testResults.add(new TestResult(mustPassCount, tryHarderCount, maxMisreads, maxTryHarderMisreads, rotation));
}
protected final File[] getImageFiles() {
assertTrue("Please download and install test images, and run from the 'core' directory", testBase.exists());
return testBase.listFiles(IMAGE_NAME_FILTER);
protected final List<Path> getImageFiles() throws IOException {
assertTrue("Please download and install test images, and run from the 'core' directory", Files.exists(testBase));
List<Path> paths = new ArrayList<>();
try (DirectoryStream<Path> pathIt = Files.newDirectoryStream(testBase, "*.{jpg,jpeg,gif,png,JPG,JPEG,GIF,PNG}")) {
for (Path path : pathIt) {
paths.add(path);
}
}
return paths;
}
protected final Reader getReader() {
final Reader getReader() {
return barcodeReader;
}
@ -132,7 +131,7 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
public final SummaryResults testBlackBoxCountingResults(boolean assertOnFailure) throws IOException {
assertFalse(testResults.isEmpty());
File[] imageFiles = getImageFiles();
List<Path> imageFiles = getImageFiles();
int testCount = testResults.size();
int[] passedCounts = new int[testCount];
@ -140,31 +139,28 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
int[] tryHarderCounts = new int[testCount];
int[] tryHaderMisreadCounts = new int[testCount];
for (File testImage : imageFiles) {
log.info(String.format("Starting %s", testImage.getAbsolutePath()));
for (Path testImage : imageFiles) {
log.info(String.format("Starting %s", testImage));
BufferedImage image = ImageIO.read(testImage);
BufferedImage image = ImageIO.read(testImage.toFile());
String testImageFileName = testImage.getName();
String testImageFileName = testImage.getFileName().toString();
String fileBaseName = testImageFileName.substring(0, testImageFileName.indexOf('.'));
File expectedTextFile = new File(testBase, fileBaseName + ".txt");
Path expectedTextFile = testBase.resolve(fileBaseName + ".txt");
String expectedText;
if (expectedTextFile.exists()) {
expectedText = readFileAsString(expectedTextFile, UTF8);
if (Files.exists(expectedTextFile)) {
expectedText = readFileAsString(expectedTextFile, StandardCharsets.UTF_8);
} else {
expectedTextFile = new File(testBase, fileBaseName + ".bin");
assertTrue(expectedTextFile.exists());
expectedText = readFileAsString(expectedTextFile, ISO88591);
expectedTextFile = testBase.resolve(fileBaseName + ".bin");
assertTrue(Files.exists(expectedTextFile));
expectedText = readFileAsString(expectedTextFile, StandardCharsets.ISO_8859_1);
}
File expectedMetadataFile = new File(testBase, fileBaseName + ".metadata.txt");
Path expectedMetadataFile = testBase.resolve(fileBaseName + ".metadata.txt");
Properties expectedMetadata = new Properties();
if (expectedMetadataFile.exists()) {
InputStream expectedStream = new FileInputStream(expectedMetadataFile);
try {
expectedMetadata.load(expectedStream);
} finally {
expectedStream.close();
if (Files.exists(expectedMetadataFile)) {
try (BufferedReader reader = Files.newBufferedReader(expectedMetadataFile, StandardCharsets.UTF_8)) {
expectedMetadata.load(reader);
}
}
@ -204,13 +200,13 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
TestResult testResult = testResults.get(x);
log.info(String.format("Rotation %d degrees:", (int) testResult.getRotation()));
log.info(String.format(" %d of %d images passed (%d required)",
passedCounts[x], imageFiles.length, testResult.getMustPassCount()));
int failed = imageFiles.length - passedCounts[x];
passedCounts[x], imageFiles.size(), testResult.getMustPassCount()));
int failed = imageFiles.size() - passedCounts[x];
log.info(String.format(" %d failed due to misreads, %d not detected",
misreadCounts[x], failed - misreadCounts[x]));
log.info(String.format(" %d of %d images passed with try harder (%d required)",
tryHarderCounts[x], imageFiles.length, testResult.getTryHarderCount()));
failed = imageFiles.length - tryHarderCounts[x];
tryHarderCounts[x], imageFiles.size(), testResult.getTryHarderCount()));
failed = imageFiles.size() - tryHarderCounts[x];
log.info(String.format(" %d failed due to misreads, %d not detected",
tryHaderMisreadCounts[x], failed - tryHaderMisreadCounts[x]));
totalFound += passedCounts[x] + tryHarderCounts[x];
@ -219,7 +215,7 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
totalMaxMisread += testResult.getMaxMisreads() + testResult.getMaxTryHarderMisreads();
}
int totalTests = imageFiles.length * testCount * 2;
int totalTests = imageFiles.size() * testCount * 2;
log.info(String.format("Decoded %d images out of %d (%d%%, %d required)",
totalFound, totalTests, totalFound * 100 / totalTests, totalMustPass));
if (totalFound > totalMustPass) {
@ -296,19 +292,8 @@ public abstract class AbstractBlackBoxTestCase extends Assert {
return true;
}
protected static String readFileAsString(File file, Charset charset) throws IOException {
StringBuilder result = new StringBuilder((int) file.length());
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), charset);
try {
char[] buffer = new char[256];
int charsRead;
while ((charsRead = reader.read(buffer)) > 0) {
result.append(buffer, 0, charsRead);
}
} finally {
reader.close();
}
String stringContents = result.toString();
protected static String readFileAsString(Path file, Charset charset) throws IOException {
String stringContents = new String(Files.readAllBytes(file), charset);
if (stringContents.endsWith("\n")) {
log.info("String contents of file " + file + " end with a newline. " +
"This may not be intended and cause a test failure");

View file

@ -27,8 +27,8 @@ import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
@ -80,11 +80,11 @@ public abstract class AbstractNegativeBlackBoxTestCase extends AbstractBlackBoxT
public void testBlackBox() throws IOException {
assertFalse(testResults.isEmpty());
File[] imageFiles = getImageFiles();
List<Path> imageFiles = getImageFiles();
int[] falsePositives = new int[testResults.size()];
for (File testImage : imageFiles) {
log.info(String.format("Starting %s", testImage.getAbsolutePath()));
BufferedImage image = ImageIO.read(testImage);
for (Path testImage : imageFiles) {
log.info(String.format("Starting %s", testImage));
BufferedImage image = ImageIO.read(testImage.toFile());
if (image == null) {
throw new IOException("Could not read image: " + testImage);
}
@ -114,7 +114,7 @@ public abstract class AbstractNegativeBlackBoxTestCase extends AbstractBlackBoxT
for (int x = 0; x < testResults.size(); x++) {
TestResult testResult = testResults.get(x);
log.info(String.format("Rotation %d degrees: %d of %d images were false positives (%d allowed)",
(int) testResult.getRotation(), falsePositives[x], imageFiles.length,
(int) testResult.getRotation(), falsePositives[x], imageFiles.size(),
testResult.getFalsePositivesAllowed()));
assertTrue("Rotation " + testResult.getRotation() + " degrees: Too many false positives found",
falsePositives[x] <= testResult.getFalsePositivesAllowed());

View file

@ -341,7 +341,7 @@ public final class HighLevelEncodeTestCase extends Assert {
byte[] data = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x7E, 0x7F, (byte) 0x80, (byte) 0x81, (byte) 0x82};
String expected = encodeHighLevel(new String(data, Charset.forName("ISO-8859-1")));
String expected = encodeHighLevel(new String(data, StandardCharsets.ISO-8859-1)));
String visualized = encodeHighLevel("url(data:text/plain;charset=iso-8859-1,"
+ "%00%01%02%03%04%05%06%07%08%09%0A%7E%7F%80%81%82)");
assertEquals(expected, visualized);

View file

@ -27,8 +27,10 @@
package com.google.zxing.oned.rss.expanded;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.imageio.ImageIO;
@ -51,186 +53,136 @@ public final class RSSExpandedImage2binaryTestCase extends Assert {
@Test
public void testDecodeRow2binary_1() throws Exception {
// (11)100224(17)110224(3102)000100
String path = "src/test/resources/blackbox/rssexpanded-1/1.png";
String expected = " ...X...X .X....X. .XX...X. X..X...X ...XX.X. ..X.X... ..X.X..X ...X..X. X.X....X .X....X. .....X.. X...X...";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"1.png", " ...X...X .X....X. .XX...X. X..X...X ...XX.X. ..X.X... ..X.X..X ...X..X. X.X....X .X....X. .....X.. X...X...");
}
@Test
public void testDecodeRow2binary_2() throws Exception {
// (01)90012345678908(3103)001750
String path = "src/test/resources/blackbox/rssexpanded-1/2.png";
String expected = " ..X..... ......X. .XXX.X.X .X...XX. XXXXX.XX XX.X.... .XX.XX.X .XX.";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary("2.png", " ..X..... ......X. .XXX.X.X .X...XX. XXXXX.XX XX.X.... .XX.XX.X .XX.");
}
@Test
public void testDecodeRow2binary_3() throws Exception {
// (10)12A
String path = "src/test/resources/blackbox/rssexpanded-1/3.png";
String expected = " .......X ..XX..X. X.X....X .......X ....";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary("3.png", " .......X ..XX..X. X.X....X .......X ....");
}
@Test
public void testDecodeRow2binary_4() throws Exception {
// (01)98898765432106(3202)012345(15)991231
String path = "src/test/resources/blackbox/rssexpanded-1/4.png";
String expected = " ..XXXX.X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX..XX XX.X.XXX X..XX..X .X.XXXXX XXXX";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"4.png", " ..XXXX.X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX..XX XX.X.XXX X..XX..X .X.XXXXX XXXX");
}
@Test
public void testDecodeRow2binary_5() throws Exception {
// (01)90614141000015(3202)000150
String path = "src/test/resources/blackbox/rssexpanded-1/5.png";
String expected = " ..X.X... .XXXX.X. XX..XXXX ....XX.. X....... ....X... ....X..X .XX.";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"5.png", " ..X.X... .XXXX.X. XX..XXXX ....XX.. X....... ....X... ....X..X .XX.");
}
@Test
public void testDecodeRow2binary_10() throws Exception {
// (01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456(423)0123456789012
String path = "src/test/resources/blackbox/rssexpanded-1/10.png";
String expected = " .X.XX..X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX...X XX.X.... X.X.X.X. X.X..X.X .X....X. XX...X.. ...XX.X. .XXXXXX. .X..XX.. X.X.X... .X...... XXXX.... XX.XX... XXXXX.X. ...XXXXX .....X.X ...X.... X.XXX..X X.X.X... XX.XX..X .X..X..X .X.X.X.X X.XX...X .XX.XXX. XXX.X.XX ..X.";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"10.png", " .X.XX..X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX...X XX.X.... X.X.X.X. X.X..X.X .X....X. XX...X.. ...XX.X. .XXXXXX. .X..XX.. X.X.X... .X...... XXXX.... XX.XX... XXXXX.X. ...XXXXX .....X.X ...X.... X.XXX..X X.X.X... XX.XX..X .X..X..X .X.X.X.X X.XX...X .XX.XXX. XXX.X.XX ..X.");
}
@Test
public void testDecodeRow2binary_11() throws Exception {
// (01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456
String expected = " .X.XX..X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX...X XX.X.... X.X.X.X. X.X..X.X .X....X. XX...X.. ...XX.X. .XXXXXX. .X..XX.. X.X.X... .X...... XXXX.... XX.XX... XXXXX.X. ...XXXXX .....X.X ...X.... X.XXX..X X.X.X... ....";
String path = "src/test/resources/blackbox/rssexpanded-1/11.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"11.png", " .X.XX..X XX.XXXX. .XXX.XX. XX..X... .XXXXX.. XX.X..X. ..XX...X XX.X.... X.X.X.X. X.X..X.X .X....X. XX...X.. ...XX.X. .XXXXXX. .X..XX.. X.X.X... .X...... XXXX.... XX.XX... XXXXX.X. ...XXXXX .....X.X ...X.... X.XXX..X X.X.X... ....");
}
@Test
public void testDecodeRow2binary_12() throws Exception {
// (01)98898765432106(3103)001750
String expected = " ..X..XX. XXXX..XX X.XX.XX. .X....XX XXX..XX. X..X.... .XX.XX.X .XX.";
String path = "src/test/resources/blackbox/rssexpanded-1/12.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"12.png", " ..X..XX. XXXX..XX X.XX.XX. .X....XX XXX..XX. X..X.... .XX.XX.X .XX.");
}
@Test
public void testDecodeRow2binary_13() throws Exception {
// (01)90012345678908(3922)795
String expected = " ..XX..X. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. X.X.XXXX .X..X..X ......X.";
String path = "src/test/resources/blackbox/rssexpanded-1/13.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"13.png", " ..XX..X. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. X.X.XXXX .X..X..X ......X.");
}
@Test
public void testDecodeRow2binary_14() throws Exception {
// (01)90012345678908(3932)0401234
String expected = " ..XX.X.. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. X.....X. X.....X. X.X.X.XX .X...... X...";
String path = "src/test/resources/blackbox/rssexpanded-1/14.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"14.png", " ..XX.X.. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. X.....X. X.....X. X.X.X.XX .X...... X...");
}
@Test
public void testDecodeRow2binary_15() throws Exception {
// (01)90012345678908(3102)001750(11)100312
String expected = " ..XXX... ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/15.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"15.png", " ..XXX... ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_16() throws Exception {
// (01)90012345678908(3202)001750(11)100312
String expected = " ..XXX..X ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/16.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"16.png", " ..XXX..X ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_17() throws Exception {
// (01)90012345678908(3102)001750(13)100312
String expected = " ..XXX.X. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/17.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"17.png", " ..XXX.X. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_18() throws Exception {
// (01)90012345678908(3202)001750(13)100312
String expected = " ..XXX.XX ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/18.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"18.png", " ..XXX.XX ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_19() throws Exception {
// (01)90012345678908(3102)001750(15)100312
String expected = " ..XXXX.. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/19.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"19.png", " ..XXXX.. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_20() throws Exception {
// (01)90012345678908(3202)001750(15)100312
String expected = " ..XXXX.X ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/20.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"20.png", " ..XXXX.X ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_21() throws Exception {
// (01)90012345678908(3102)001750(17)100312
String expected = " ..XXXXX. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/21.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"21.png", " ..XXXXX. ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
@Test
public void testDecodeRow2binary_22() throws Exception {
// (01)90012345678908(3202)001750(17)100312
String expected = " ..XXXXXX ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..";
String path = "src/test/resources/blackbox/rssexpanded-1/22.png";
assertCorrectImage2binary(path, expected);
assertCorrectImage2binary(
"22.png", " ..XXXXXX ........ .X..XXX. X.X.X... XX.XXXXX .XXXX.X. ..XX...X .X.....X .XX..... XXXX.X.. XX..");
}
private static void assertCorrectImage2binary(String path, String expected) throws IOException, NotFoundException {
File file = new File(path);
if (!file.exists()) {
private static void assertCorrectImage2binary(String fileName, String expected)
throws IOException, NotFoundException {
Path path = Paths.get("src/test/resources/blackbox/rssexpanded-1/").resolve(fileName);
if (!Files.exists(path)) {
// Support running from project root too
file = new File("core", path);
path = Paths.get("core").resolve(path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = ImageIO.read(path.toFile());
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
int rowNumber = binaryMap.getHeight() / 2;
BitArray row = binaryMap.getBlackRow(rowNumber, null);

View file

@ -32,8 +32,10 @@
package com.google.zxing.oned.rss.expanded;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import javax.imageio.ImageIO;
@ -62,7 +64,6 @@ public final class RSSExpandedImage2resultTestCase extends Assert {
@Test
public void testDecodeRow2result_2() throws Exception {
// (01)90012345678908(3103)001750
String path = "src/test/resources/blackbox/rssexpanded-1/2.png";
ExpandedProductParsedResult expected =
new ExpandedProductParsedResult("(01)90012345678908(3103)001750",
"90012345678908",
@ -71,19 +72,18 @@ public final class RSSExpandedImage2resultTestCase extends Assert {
ExpandedProductParsedResult.KILOGRAM,
"3", null, null, null, new HashMap<String,String>());
assertCorrectImage2result(path, expected);
assertCorrectImage2result("2.png", expected);
}
private static void assertCorrectImage2result(String path, ExpandedProductParsedResult expected)
private static void assertCorrectImage2result(String fileName, ExpandedProductParsedResult expected)
throws IOException, NotFoundException {
File file = new File(path);
if (!file.exists()) {
Path path = Paths.get("src/test/resources/blackbox/rssexpanded-1/").resolve(fileName);
if (!Files.exists(path)) {
// Support running from project root too
file = new File("core", path);
path = Paths.get("core").resolve(path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = ImageIO.read(path.toFile());
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
int rowNumber = binaryMap.getHeight() / 2;
BitArray row = binaryMap.getBlackRow(rowNumber, null);

View file

@ -27,8 +27,10 @@
package com.google.zxing.oned.rss.expanded;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
@ -51,230 +53,151 @@ public final class RSSExpandedImage2stringTestCase extends Assert {
@Test
public void testDecodeRow2string_1() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/1.png";
String expected = "(11)100224(17)110224(3102)000100";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("1.png", "(11)100224(17)110224(3102)000100");
}
@Test
public void testDecodeRow2string_2() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/2.png";
String expected = "(01)90012345678908(3103)001750";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("2.png", "(01)90012345678908(3103)001750");
}
@Test
public void testDecodeRow2string_3() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/3.png";
String expected = "(10)12A";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("3.png", "(10)12A");
}
@Test
public void testDecodeRow2string_4() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/4.png";
String expected = "(01)98898765432106(3202)012345(15)991231";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("4.png", "(01)98898765432106(3202)012345(15)991231");
}
@Test
public void testDecodeRow2string_5() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/5.png";
String expected = "(01)90614141000015(3202)000150";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("5.png", "(01)90614141000015(3202)000150");
}
@Test
public void testDecodeRow2string_7() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/7.png";
String expected = "(10)567(11)010101";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("7.png", "(10)567(11)010101");
}
@Test
public void testDecodeRow2string_10() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/10.png";
String expected = "(01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456(423)012345678901";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("10.png", expected);
}
@Test
public void testDecodeRow2string_11() throws Exception {
String expected = "(01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456";
String path = "src/test/resources/blackbox/rssexpanded-1/11.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("11.png", "(01)98898765432106(15)991231(3103)001750(10)12A(422)123(21)123456");
}
@Test
public void testDecodeRow2string_12() throws Exception {
String expected = "(01)98898765432106(3103)001750";
String path = "src/test/resources/blackbox/rssexpanded-1/12.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("12.png", "(01)98898765432106(3103)001750");
}
@Test
public void testDecodeRow2string_13() throws Exception {
String expected = "(01)90012345678908(3922)795";
String path = "src/test/resources/blackbox/rssexpanded-1/13.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("13.png", "(01)90012345678908(3922)795");
}
@Test
public void testDecodeRow2string_14() throws Exception {
String expected = "(01)90012345678908(3932)0401234";
String path = "src/test/resources/blackbox/rssexpanded-1/14.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("14.png", "(01)90012345678908(3932)0401234");
}
@Test
public void testDecodeRow2string_15() throws Exception {
String expected = "(01)90012345678908(3102)001750(11)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/15.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("15.png", "(01)90012345678908(3102)001750(11)100312");
}
@Test
public void testDecodeRow2string_16() throws Exception {
String expected = "(01)90012345678908(3202)001750(11)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/16.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("16.png", "(01)90012345678908(3202)001750(11)100312");
}
@Test
public void testDecodeRow2string_17() throws Exception {
String expected = "(01)90012345678908(3102)001750(13)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/17.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("17.png", "(01)90012345678908(3102)001750(13)100312");
}
@Test
public void testDecodeRow2string_18() throws Exception {
String expected = "(01)90012345678908(3202)001750(13)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/18.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("18.png", "(01)90012345678908(3202)001750(13)100312");
}
@Test
public void testDecodeRow2string_19() throws Exception {
String expected = "(01)90012345678908(3102)001750(15)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/19.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("19.png", "(01)90012345678908(3102)001750(15)100312");
}
@Test
public void testDecodeRow2string_20() throws Exception {
String expected = "(01)90012345678908(3202)001750(15)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/20.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("20.png", "(01)90012345678908(3202)001750(15)100312");
}
@Test
public void testDecodeRow2string_21() throws Exception {
String expected = "(01)90012345678908(3102)001750(17)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/21.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("21.png", "(01)90012345678908(3102)001750(17)100312");
}
@Test
public void testDecodeRow2string_22() throws Exception {
String expected = "(01)90012345678908(3202)001750(17)100312";
String path = "src/test/resources/blackbox/rssexpanded-1/22.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("22.png", "(01)90012345678908(3202)001750(17)100312");
}
@Test
public void testDecodeRow2string_25() throws Exception {
String expected = "(10)123";
String path = "src/test/resources/blackbox/rssexpanded-1/25.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("25.png", "(10)123");
}
@Test
public void testDecodeRow2string_26() throws Exception {
String expected = "(10)5678(11)010101";
String path = "src/test/resources/blackbox/rssexpanded-1/26.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("26.png", "(10)5678(11)010101");
}
@Test
public void testDecodeRow2string_27() throws Exception {
String expected = "(10)1098-1234";
String path = "src/test/resources/blackbox/rssexpanded-1/27.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("27.png", "(10)1098-1234");
}
@Test
public void testDecodeRow2string_28() throws Exception {
String expected = "(10)1098/1234";
String path = "src/test/resources/blackbox/rssexpanded-1/28.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("28.png", "(10)1098/1234");
}
@Test
public void testDecodeRow2string_29() throws Exception {
String expected = "(10)1098.1234";
String path = "src/test/resources/blackbox/rssexpanded-1/29.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("29.png", "(10)1098.1234");
}
@Test
public void testDecodeRow2string_30() throws Exception {
String expected = "(10)1098*1234";
String path = "src/test/resources/blackbox/rssexpanded-1/30.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("30.png", "(10)1098*1234");
}
@Test
public void testDecodeRow2string_31() throws Exception {
String expected = "(10)1098,1234";
String path = "src/test/resources/blackbox/rssexpanded-1/31.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("31.png", "(10)1098,1234");
}
@Test
public void testDecodeRow2string_32() throws Exception {
String expected = "(15)991231(3103)001750(10)12A(422)123(21)123456(423)0123456789012";
String path = "src/test/resources/blackbox/rssexpanded-1/32.png";
assertCorrectImage2string(path, expected);
assertCorrectImage2string("32.png", "(15)991231(3103)001750(10)12A(422)123(21)123456(423)0123456789012");
}
private static void assertCorrectImage2string(String path, String expected) throws IOException, NotFoundException {
File file = new File(path);
if (!file.exists()) {
private static void assertCorrectImage2string(String fileName, String expected)
throws IOException, NotFoundException {
Path path = Paths.get("src/test/resources/blackbox/rssexpanded-1/").resolve(fileName);
if (!Files.exists(path)) {
// Support running from project root too
file = new File("core", path);
path = Paths.get("core").resolve(path);
}
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
BufferedImage image = ImageIO.read(path.toFile());
BinaryBitmap binaryMap =
new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
int rowNumber = binaryMap.getHeight() / 2;
BitArray row = binaryMap.getBlackRow(rowNumber, null);

View file

@ -27,7 +27,10 @@
package com.google.zxing.oned.rss.expanded;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@ -52,15 +55,7 @@ public final class RSSExpandedInternalTestCase extends Assert {
@Test
public void testFindFinderPatterns() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/2.png";
File file = new File(path);
if (!file.exists()) {
// Support running from project root too
file = new File("core", path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = readImage("2.png");
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
int rowNumber = binaryMap.getHeight() / 2;
BitArray row = binaryMap.getBlackRow(rowNumber, null);
@ -96,15 +91,7 @@ public final class RSSExpandedInternalTestCase extends Assert {
@Test
public void testRetrieveNextPairPatterns() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/3.png";
File file = new File(path);
if (!file.exists()) {
// Support running from project root too
file = new File("core", path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = readImage("3.png");
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
int rowNumber = binaryMap.getHeight() / 2;
BitArray row = binaryMap.getBlackRow(rowNumber, null);
@ -126,15 +113,7 @@ public final class RSSExpandedInternalTestCase extends Assert {
@Test
public void testDecodeCheckCharacter() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/3.png";
File file = new File(path);
if (!file.exists()) {
// Support running from project root too
file = new File("core", path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = readImage("3.png");
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
BitArray row = binaryMap.getBlackRow(binaryMap.getHeight() / 2, null);
@ -150,15 +129,7 @@ public final class RSSExpandedInternalTestCase extends Assert {
@Test
public void testDecodeDataCharacter() throws Exception {
String path = "src/test/resources/blackbox/rssexpanded-1/3.png";
File file = new File(path);
if (!file.exists()) {
// Support running from project root too
file = new File("core", path);
}
BufferedImage image = ImageIO.read(file);
BufferedImage image = readImage("3.png");
BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
BitArray row = binaryMap.getBlackRow(binaryMap.getHeight() / 2, null);
@ -172,4 +143,15 @@ public final class RSSExpandedInternalTestCase extends Assert {
assertEquals(19, dataCharacter.getValue());
assertEquals(1007, dataCharacter.getChecksumPortion());
}
private static BufferedImage readImage(String fileName) throws IOException {
Path path = Paths.get("src/test/resources/blackbox/rssexpanded-1/").resolve(fileName);
if (!Files.exists(path)) {
// Support running from project root too
path = Paths.get("core").resolve(path);
}
return ImageIO.read(path.toFile());
}
}

View file

@ -27,8 +27,10 @@
package com.google.zxing.oned.rss.expanded;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
@ -42,12 +44,12 @@ final class TestCaseUtil {
}
private static BufferedImage getBufferedImage(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
Path file = Paths.get(path);
if (!Files.exists(file)) {
// Support running from project root too
file = new File("core", path);
file = Paths.get("core").resolve(file);
}
return ImageIO.read(file);
return ImageIO.read(file.toFile());
}
static BinaryBitmap getBinaryBitmap(String path) throws IOException {

View file

@ -29,14 +29,16 @@ import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.common.SummaryResults;
import com.google.zxing.common.TestResult;
import com.google.zxing.multi.MultipleBarcodeReader;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -53,27 +55,16 @@ import java.util.logging.Logger;
* several barcodes can be properly combined again to yield the original data content.
*
* @author Guenther Grau
*
*/
public final class PDF417BlackBox4TestCase extends AbstractBlackBoxTestCase {
private static final Logger log = Logger.getLogger(AbstractBlackBoxTestCase.class.getSimpleName());
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Charset ISO88591 = Charset.forName("ISO-8859-1");
private static final String TEST_BASE_PATH_SUFFIX = "src/test/resources/blackbox/pdf417-4";
private final PDF417Reader barcodeReader = new PDF417Reader();
private final MultipleBarcodeReader barcodeReader = new PDF417Reader();
private final List<TestResult> testResults = new ArrayList<>();
private File testBase;
public PDF417BlackBox4TestCase() {
super(TEST_BASE_PATH_SUFFIX, null, BarcodeFormat.PDF_417);
// A little workaround to prevent aggravation in my IDE
testBase = new File(TEST_BASE_PATH_SUFFIX);
if (!testBase.exists()) {
// try starting with 'core' since the test base is often given as the project root
testBase = new File("core/" + TEST_BASE_PATH_SUFFIX);
}
super("src/test/resources/blackbox/pdf417-4", null, BarcodeFormat.PDF_417);
testResults.add(new TestResult(2, 2, 0, 0, 0.0f));
}
@ -83,10 +74,10 @@ public final class PDF417BlackBox4TestCase extends AbstractBlackBoxTestCase {
testPDF417BlackBoxCountingResults(true);
}
public SummaryResults testPDF417BlackBoxCountingResults(boolean assertOnFailure) throws IOException {
SummaryResults testPDF417BlackBoxCountingResults(boolean assertOnFailure) throws IOException {
assertFalse(testResults.isEmpty());
Map<String,List<File>> imageFiles = getImageFileLists();
Map<String,List<Path>> imageFiles = getImageFileLists();
int testCount = testResults.size();
int[] passedCounts = new int[testCount];
@ -94,24 +85,26 @@ public final class PDF417BlackBox4TestCase extends AbstractBlackBoxTestCase {
int[] tryHarderCounts = new int[testCount];
int[] tryHaderMisreadCounts = new int[testCount];
for (Entry<String,List<File>> testImageGroup : imageFiles.entrySet()) {
Path testBase = getTestBase();
for (Entry<String,List<Path>> testImageGroup : imageFiles.entrySet()) {
log.fine(String.format("Starting Image Group %s", testImageGroup.getKey()));
String fileBaseName = testImageGroup.getKey();
String expectedText;
File expectedTextFile = new File(testBase, fileBaseName + ".txt");
if (expectedTextFile.exists()) {
expectedText = readFileAsString(expectedTextFile, UTF8);
Path expectedTextFile = testBase.resolve(fileBaseName + ".txt");
if (Files.exists(expectedTextFile)) {
expectedText = readFileAsString(expectedTextFile, StandardCharsets.UTF_8);
} else {
expectedTextFile = new File(testBase, fileBaseName + ".bin");
assertTrue(expectedTextFile.exists());
expectedText = readFileAsString(expectedTextFile, ISO88591);
expectedTextFile = testBase.resolve(fileBaseName + ".bin");
assertTrue(Files.exists(expectedTextFile));
expectedText = readFileAsString(expectedTextFile, StandardCharsets.ISO_8859_1);
}
for (int x = 0; x < testCount; x++) {
List<Result> results = new ArrayList<>();
for (File imageFile : testImageGroup.getValue()) {
BufferedImage image = ImageIO.read(imageFile);
for (Path imageFile : testImageGroup.getValue()) {
BufferedImage image = ImageIO.read(imageFile.toFile());
float rotation = testResults.get(x).getRotation();
BufferedImage rotatedImage = rotateImage(image, rotation);
LuminanceSource source = new BufferedImageLuminanceSource(rotatedImage);
@ -219,12 +212,12 @@ public final class PDF417BlackBox4TestCase extends AbstractBlackBoxTestCase {
return barcodeReader.decodeMultiple(source, hints);
}
private Map<String,List<File>> getImageFileLists() {
Map<String,List<File>> result = new HashMap<>();
for (File file : getImageFiles()) {
String testImageFileName = file.getName();
private Map<String,List<Path>> getImageFileLists() throws IOException {
Map<String,List<Path>> result = new HashMap<>();
for (Path file : getImageFiles()) {
String testImageFileName = file.getFileName().toString();
String fileBaseName = testImageFileName.substring(0, testImageFileName.indexOf('-'));
List<File> files = result.get(fileBaseName);
List<Path> files = result.get(fileBaseName);
if (files == null) {
files = new ArrayList<>();
result.put(fileBaseName, files);

View file

@ -18,6 +18,7 @@ package com.google.zxing.qrcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
@ -26,8 +27,10 @@ import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.EnumMap;
import java.util.Map;
@ -37,16 +40,16 @@ import java.util.Map;
*/
public final class QRCodeWriterTestCase extends Assert {
private static final String BASE_IMAGE_PATH = "src/test/resources/golden/qrcode/";
private static final Path BASE_IMAGE_PATH = Paths.get("src/test/resources/golden/qrcode/");
private static BufferedImage loadImage(String fileName) throws IOException {
File file = new File(BASE_IMAGE_PATH + fileName);
if (!file.exists()) {
Path file = BASE_IMAGE_PATH.resolve(fileName);
if (!Files.exists(file)) {
// try starting with 'core' since the test base is often given as the project root
file = new File("core/" + BASE_IMAGE_PATH + fileName);
file = Paths.get("core/").resolve(BASE_IMAGE_PATH).resolve(fileName);
}
assertTrue("Please download and install test images, and run from the 'core' directory", file.exists());
return ImageIO.read(file);
assertTrue("Please download and install test images, and run from the 'core' directory", Files.exists(file));
return ImageIO.read(file.toFile());
}
// In case the golden images are not monochromatic, convert the RGB values to greyscale.
@ -75,7 +78,7 @@ public final class QRCodeWriterTestCase extends Assert {
public void testQRCodeWriter() throws WriterException {
// The QR should be multiplied up to fit, with extra padding if necessary
int bigEnough = 256;
QRCodeWriter writer = new QRCodeWriter();
Writer writer = new QRCodeWriter();
BitMatrix matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, bigEnough,
bigEnough, null);
assertNotNull(matrix);
@ -112,7 +115,7 @@ public final class QRCodeWriterTestCase extends Assert {
Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.ERROR_CORRECTION, ecLevel);
QRCodeWriter writer = new QRCodeWriter();
Writer writer = new QRCodeWriter();
BitMatrix generatedResult = writer.encode(contents, BarcodeFormat.QR_CODE, resolution,
resolution, hints);

View file

@ -29,12 +29,11 @@ import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -73,7 +72,7 @@ public final class HtmlAssetTranslator {
"(all|lang1[,lang2 ...]) (all|file1.html[ file2.html ...])");
return;
}
File assetsDir = new File(args[0]);
Path assetsDir = Paths.get(args[0]);
Collection<String> languagesToTranslate = parseLanguagesToTranslate(assetsDir, args[1]);
List<String> restOfArgs = Arrays.asList(args).subList(2, args.length);
Collection<String> fileNamesToTranslate = parseFileNamesToTranslate(assetsDir, restOfArgs);
@ -82,84 +81,80 @@ public final class HtmlAssetTranslator {
}
}
private static Collection<String> parseLanguagesToTranslate(File assetsDir, CharSequence languageArg) {
Collection<String> languages = new ArrayList<>();
private static Collection<String> parseLanguagesToTranslate(Path assetsDir,
CharSequence languageArg) throws IOException {
if ("all".equals(languageArg)) {
FileFilter fileFilter = new FileFilter() {
Collection<String> languages = new ArrayList<>();
DirectoryStream.Filter<Path> fileFilter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(File file) {
Path path = file.toPath();
return
Files.isDirectory(path) &&
!Files.isSymbolicLink(path) &&
file.getName().startsWith("html-") &&
!"html-en".equals(file.getName());
public boolean accept(Path entry) {
return Files.isDirectory(entry) && !Files.isSymbolicLink(entry) &&
entry.getFileName().startsWith("html-") && !"html-en".equals(entry.getFileName().toString());
}
};
for (File languageDir : assetsDir.listFiles(fileFilter)) {
languages.add(languageDir.getName().substring(5));
try (DirectoryStream<Path> dirs = Files.newDirectoryStream(assetsDir, fileFilter)) {
for (Path languageDir : dirs) {
languages.add(languageDir.getFileName().toString().substring(5));
}
} else {
languages.addAll(Arrays.asList(COMMA.split(languageArg)));
}
return languages;
} else {
return Arrays.asList(COMMA.split(languageArg));
}
}
private static Collection<String> parseFileNamesToTranslate(File assetsDir, List<String> restOfArgs) {
Collection<String> fileNamesToTranslate = new ArrayList<>();
private static Collection<String> parseFileNamesToTranslate(Path assetsDir,
List<String> restOfArgs) throws IOException {
if ("all".equals(restOfArgs.get(0))) {
File htmlEnAssetDir = new File(assetsDir, "html-en");
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".html");
}
};
for (File file : htmlEnAssetDir.listFiles(fileFilter)) {
fileNamesToTranslate.add(file.getName());
}
} else {
for (String fileName : restOfArgs) {
fileNamesToTranslate.add(fileName);
Collection<String> fileNamesToTranslate = new ArrayList<>();
Path htmlEnAssetDir = assetsDir.resolve("html-en");
try (DirectoryStream<Path> files = Files.newDirectoryStream(htmlEnAssetDir, "*.html")) {
for (Path file : files) {
fileNamesToTranslate.add(file.getFileName().toString());
}
}
return fileNamesToTranslate;
} else {
return restOfArgs;
}
}
private static void translateOneLanguage(File assetsDir,
private static void translateOneLanguage(Path assetsDir,
String language,
final Collection<String> filesToTranslate) throws IOException {
File targetHtmlDir = new File(assetsDir, "html-" + language);
targetHtmlDir.mkdirs();
File englishHtmlDir = new File(assetsDir, "html-en");
Path targetHtmlDir = assetsDir.resolve("html-" + language);
Files.createDirectories(targetHtmlDir);
Path englishHtmlDir = assetsDir.resolve("html-en");
String translationTextTranslated =
StringsResourceTranslator.translateString("Translated by Google Translate.", language);
File[] sourceFiles = englishHtmlDir.listFiles(new FilenameFilter() {
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(File dir, String name) {
public boolean accept(Path entry) {
String name = entry.getFileName().toString();
return name.endsWith(".html") && (filesToTranslate.isEmpty() || filesToTranslate.contains(name));
}
});
for (File sourceFile : sourceFiles) {
};
try (DirectoryStream<Path> files = Files.newDirectoryStream(englishHtmlDir, filter)) {
for (Path sourceFile : files) {
translateOneFile(language, targetHtmlDir, sourceFile, translationTextTranslated);
}
}
}
private static void translateOneFile(String language,
File targetHtmlDir,
File sourceFile,
Path targetHtmlDir,
Path sourceFile,
String translationTextTranslated) throws IOException {
File destFile = new File(targetHtmlDir, sourceFile.getName());
Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(sourceFile);
document = builder.parse(sourceFile.toFile());
} catch (ParserConfigurationException pce) {
throw new IllegalStateException(pce);
} catch (SAXException sae) {
@ -204,7 +199,7 @@ public final class HtmlAssetTranslator {
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.writeToURI(document, destFile.toURI().toString());
writer.writeToURI(document, destFile.toUri().toString());
}
private static boolean shouldTranslate(Node node) {

View file

@ -16,24 +16,21 @@
package com.google.zxing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -53,6 +50,11 @@ import java.util.regex.Pattern;
public final class StringsResourceTranslator {
private static final String API_KEY = System.getProperty("translateAPI.key");
static {
if (API_KEY == null) {
throw new IllegalArgumentException("translateAPI.key is not specified");
}
}
private static final Pattern ENTRY_PATTERN = Pattern.compile("<string name=\"([^\"]+)\".*>([^<]+)</string>");
private static final Pattern STRINGS_FILE_NAME_PATTERN = Pattern.compile("values-(.+)");
@ -61,7 +63,7 @@ public final class StringsResourceTranslator {
private static final String APACHE_2_LICENSE =
"<!--\n" +
" Copyright (C) 2013 ZXing authors\n" +
" Copyright (C) 2014 ZXing authors\n" +
'\n' +
" Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
" you may not use this file except in compliance with the License.\n" +
@ -85,36 +87,32 @@ public final class StringsResourceTranslator {
private StringsResourceTranslator() {}
public static void main(String[] args) throws IOException {
File resDir = new File(args[0]);
File valueDir = new File(resDir, "values");
File stringsFile = new File(valueDir, "strings.xml");
Path resDir = Paths.get(args[0]);
Path valueDir = resDir.resolve("values");
Path stringsFile = valueDir.resolve("strings.xml");
Collection<String> forceRetranslation = Arrays.asList(args).subList(1, args.length);
File[] translatedValuesDirs = resDir.listFiles(new FileFilter() {
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(File file) {
Path path = file.toPath();
return
Files.isDirectory(path) &&
!Files.isSymbolicLink(path) &&
VALUES_DIR_PATTERN.matcher(file.getName()).matches();
public boolean accept(Path entry) {
return Files.isDirectory(entry) && !Files.isSymbolicLink(entry) &&
VALUES_DIR_PATTERN.matcher(entry.getFileName().toString()).matches();
}
};
try (DirectoryStream<Path> dirs = Files.newDirectoryStream(resDir, filter)) {
for (Path dir : dirs) {
translate(stringsFile, dir.resolve("strings.xml"), forceRetranslation);
}
}
});
for (File translatedValuesDir : translatedValuesDirs) {
File translatedStringsFile = new File(translatedValuesDir, "strings.xml");
translate(stringsFile, translatedStringsFile, forceRetranslation);
}
}
private static void translate(File englishFile,
File translatedFile,
private static void translate(Path englishFile,
Path translatedFile,
Collection<String> forceRetranslation) throws IOException {
Map<String, String> english = readLines(englishFile);
SortedMap<String,String> translated = readLines(translatedFile);
String parentName = translatedFile.getParentFile().getName();
Map<String,String> translated = readLines(translatedFile);
String parentName = translatedFile.getParent().getFileName().toString();
Matcher stringsFileNameMatcher = STRINGS_FILE_NAME_PATTERN.matcher(parentName);
stringsFileNameMatcher.find();
@ -126,11 +124,10 @@ public final class StringsResourceTranslator {
System.out.println("Translating " + language);
File resultTempFile = File.createTempFile(parentName, ".xml");
resultTempFile.deleteOnExit();
Path resultTempFile = Files.createTempFile(null, null);
boolean anyChange = false;
try (Writer out = Files.newBufferedWriter(resultTempFile.toPath(), StandardCharsets.UTF_8)) {
try (Writer out = Files.newBufferedWriter(resultTempFile, StandardCharsets.UTF_8)) {
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.write(APACHE_2_LICENSE);
out.write("<resources>\n");
@ -163,10 +160,9 @@ public final class StringsResourceTranslator {
if (anyChange) {
System.out.println(" Writing translations");
translatedFile.delete();
resultTempFile.renameTo(translatedFile);
Files.move(resultTempFile, translatedFile, StandardCopyOption.REPLACE_EXISTING);
} else {
resultTempFile.delete();
Files.delete(resultTempFile);
}
}
@ -180,15 +176,11 @@ public final class StringsResourceTranslator {
}
System.out.println(" Need translation for " + english);
if (API_KEY == null) {
throw new IllegalArgumentException("translateAPI.key is not specified");
}
URL translateURL = new URL(
URI translateURI = URI.create(
"https://www.googleapis.com/language/translate/v2?key=" + API_KEY + "&q=" +
URLEncoder.encode(english, "UTF-8") +
"&source=en&target=" + language);
CharSequence translateResult = fetch(translateURL);
CharSequence translateResult = new String(Files.readAllBytes(Paths.get(translateURI)), StandardCharsets.UTF_8);
Matcher m = TRANSLATE_RESPONSE_PATTERN.matcher(translateResult);
if (!m.find()) {
System.err.println("No translate result");
@ -207,36 +199,18 @@ public final class StringsResourceTranslator {
return translation;
}
private static CharSequence fetch(URL translateURL) throws IOException {
URLConnection connection = translateURL.openConnection();
connection.connect();
StringBuilder translateResult = new StringBuilder(200);
try (Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = in.read(buffer)) > 0) {
translateResult.append(buffer, 0, charsRead);
}
}
return translateResult;
}
private static SortedMap<String,String> readLines(File file) throws IOException {
SortedMap<String,String> entries = new TreeMap<>();
if (!file.exists()) {
return entries;
}
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
CharSequence line;
while ((line = reader.readLine()) != null) {
private static Map<String,String> readLines(Path file) throws IOException {
if (Files.exists(file)) {
Map<String,String> entries = new TreeMap<>();
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
Matcher m = ENTRY_PATTERN.matcher(line);
if (m.find()) {
String key = m.group(1);
String value = m.group(2);
entries.put(key, value);
entries.put(m.group(1), m.group(2));
}
}
return entries;
} else {
return Collections.emptyMap();
}
}

View file

@ -20,7 +20,7 @@ import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import java.io.File;
import java.nio.file.Paths;
import java.util.Locale;
/**
@ -90,9 +90,8 @@ public final class CommandLineEncoder {
outFileString += '.' + imageFormat.toLowerCase(Locale.ENGLISH);
}
MultiFormatWriter barcodeWriter = new MultiFormatWriter();
BitMatrix matrix = barcodeWriter.encode(contents, barcodeFormat, width, height);
MatrixToImageWriter.writeToFile(matrix, imageFormat, new File(outFileString));
BitMatrix matrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height);
MatrixToImageWriter.writeToPath(matrix, imageFormat, Paths.get(outFileString));
}
private static void printUsage() {

View file

@ -19,8 +19,11 @@ package com.google.zxing.client.j2se;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
@ -55,7 +58,7 @@ public final class CommandLineRunner {
}
Config config = new Config();
Queue<String> inputs = new ConcurrentLinkedQueue<>();
Queue<Path> inputs = new ConcurrentLinkedQueue<>();
for (String arg : args) {
String[] argValue = arg.split("=");
@ -101,7 +104,7 @@ public final class CommandLineRunner {
printUsage();
return;
}
addArgumentToInputs(arg, config, inputs);
addArgumentToInputs(Paths.get(arg), config, inputs);
break;
}
}
@ -132,20 +135,19 @@ public final class CommandLineRunner {
// Build all the inputs up front into a single flat list, so the threads can atomically pull
// paths/URLs off the queue.
private static void addArgumentToInputs(String argument, Config config, Queue<String> inputs) throws IOException {
File inputFile = new File(argument);
if (inputFile.exists()) {
if (inputFile.isDirectory()) {
for (File singleFile : inputFile.listFiles()) {
String filename = singleFile.getName().toLowerCase(Locale.ENGLISH);
private static void addArgumentToInputs(Path inputFile, Config config, Queue<Path> inputs) throws IOException {
if (Files.isDirectory(inputFile)) {
try (DirectoryStream<Path> paths = Files.newDirectoryStream(inputFile)) {
for (Path singleFile : paths) {
String filename = singleFile.getFileName().toString().toLowerCase(Locale.ENGLISH);
// Skip hidden files and directories (e.g. svn stuff).
if (filename.startsWith(".")) {
continue;
}
// Recur on nested directories if requested, otherwise skip them.
if (singleFile.isDirectory()) {
if (Files.isDirectory(singleFile)) {
if (config.isRecursive()) {
addArgumentToInputs(singleFile.getAbsolutePath(), config, inputs);
addArgumentToInputs(singleFile, config, inputs);
}
continue;
}
@ -153,13 +155,11 @@ public final class CommandLineRunner {
if (filename.endsWith(".txt") || filename.contains(".mono.png")) {
continue;
}
inputs.add(singleFile.getCanonicalPath());
inputs.add(singleFile);
}
}
} else {
inputs.add(inputFile.getCanonicalPath());
}
} else {
inputs.add(argument);
inputs.add(inputFile);
}
}

View file

@ -29,17 +29,20 @@ import com.google.zxing.common.BitArray;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Callable;
@ -51,12 +54,14 @@ import java.util.concurrent.Callable;
*/
final class DecodeWorker implements Callable<Integer> {
private static final Charset UTF8 = Charset.forName("UTF8");
private static final int RED = 0xFFFF0000;
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private final Config config;
private final Queue<String> inputs;
private final Queue<Path> inputs;
DecodeWorker(Config config, Queue<String> inputs) {
DecodeWorker(Config config, Queue<Path> inputs) {
this.config = config;
this.inputs = inputs;
}
@ -64,29 +69,28 @@ final class DecodeWorker implements Callable<Integer> {
@Override
public Integer call() throws IOException {
int successful = 0;
String input;
Path input;
while ((input = inputs.poll()) != null) {
File inputFile = new File(input);
if (inputFile.exists()) {
if (Files.exists(input)) {
if (config.isMulti()) {
Result[] results = decodeMulti(inputFile.toURI(), config.getHints());
Result[] results = decodeMulti(input.toUri(), config.getHints());
if (results != null) {
successful++;
if (config.isDumpResults()) {
dumpResultMulti(inputFile, results);
dumpResultMulti(input, results);
}
}
} else {
Result result = decode(inputFile.toURI(), config.getHints());
Result result = decode(input.toUri(), config.getHints());
if (result != null) {
successful++;
if (config.isDumpResults()) {
dumpResult(inputFile, result);
dumpResult(input, result);
}
}
}
} else {
if (decode(URI.create(input), config.getHints()) != null) {
if (decode(input.toUri(), config.getHints()) != null) {
successful++;
}
}
@ -94,41 +98,28 @@ final class DecodeWorker implements Callable<Integer> {
return successful;
}
private static void dumpResult(File input, Result result) throws IOException {
String name = input.getCanonicalPath();
private static void dumpResult(Path input, Result result) throws IOException {
String name = input.getFileName().toString();
int pos = name.lastIndexOf('.');
if (pos > 0) {
name = name.substring(0, pos);
name = name.substring(0, pos) + ".txt";
}
File dump = new File(name + ".txt");
writeStringToFile(result.getText(), dump);
Path dumpFile = input.getParent().resolve(name);
Files.write(dumpFile, Collections.singleton(result.getText()), StandardCharsets.UTF_8);
}
private static void dumpResultMulti(File input, Result[] results) throws IOException {
String name = input.getCanonicalPath();
private static void dumpResultMulti(Path input, Result[] results) throws IOException {
String name = input.getFileName().toString();
int pos = name.lastIndexOf('.');
if (pos > 0) {
name = name.substring(0, pos);
name = name.substring(0, pos) + ".txt";
}
File dump = new File(name + ".txt");
writeResultsToFile(results, dump);
}
private static void writeStringToFile(String value, File file) throws IOException {
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
out.write(value);
}
}
private static void writeResultsToFile(Result[] results, File file) throws IOException {
String newline = System.getProperty("line.separator");
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), UTF8)) {
Path dumpFile = input.getParent().resolve(name);
Collection<String> resultTexts = new ArrayList<>();
for (Result result : results) {
out.write(result.getText());
out.write(newline);
}
resultTexts.add(result.getText());
}
Files.write(dumpFile, resultTexts, StandardCharsets.UTF_8);
}
private Result decode(URI uri, Map<DecodeHintType,?> hints) throws IOException {
@ -186,8 +177,7 @@ final class DecodeWorker implements Callable<Integer> {
}
MultiFormatReader multiFormatReader = new MultiFormatReader();
GenericMultipleBarcodeReader reader = new GenericMultipleBarcodeReader(
multiFormatReader);
MultipleBarcodeReader reader = new GenericMultipleBarcodeReader(multiFormatReader);
Result[] results = reader.decodeMultiple(bitmap, hints);
if (config.isBrief()) {
@ -220,9 +210,7 @@ final class DecodeWorker implements Callable<Integer> {
* monochrome version.
*/
private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
String inputName = uri.getPath();
if (inputName.contains(".mono.png")) {
if (uri.getPath().contains(".mono.png")) {
return;
}
@ -246,19 +234,13 @@ final class DecodeWorker implements Callable<Integer> {
} catch (NotFoundException nfe) {
// If fetching the row failed, draw a red line and keep going.
int offset = y * stride + width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = 0xffff0000;
}
Arrays.fill(pixels, offset, offset + width, RED);
continue;
}
int offset = y * stride + width;
for (int x = 0; x < width; x++) {
if (row.get(x)) {
pixels[offset + x] = 0xff000000;
} else {
pixels[offset + x] = 0xffffffff;
}
pixels[offset + x] = row.get(x) ? BLACK : WHITE;
}
}
@ -268,32 +250,26 @@ final class DecodeWorker implements Callable<Integer> {
BitMatrix matrix = bitmap.getBlackMatrix();
int offset = y * stride + width * 2;
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[offset + x] = 0xff000000;
} else {
pixels[offset + x] = 0xffffffff;
}
pixels[offset + x] = matrix.get(x, y) ? BLACK : WHITE;
}
}
} catch (NotFoundException ignored) {
// continue
}
writeResultImage(stride, height, pixels, uri, inputName, ".mono.png");
writeResultImage(stride, height, pixels, uri, ".mono.png");
}
private static void writeResultImage(int stride,
int height,
int[] pixels,
URI uri,
String inputName,
String suffix) {
// Write the result
BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
result.setRGB(0, 0, stride, height, pixels, 0, stride);
// Use the current working directory for URLs
String resultName = inputName;
String resultName = uri.getPath();
if ("http".equals(uri.getScheme())) {
int pos = resultName.lastIndexOf('/');
if (pos > 0) {
@ -305,8 +281,8 @@ final class DecodeWorker implements Callable<Integer> {
resultName = resultName.substring(0, pos);
}
resultName += suffix;
try (OutputStream outStream = new FileOutputStream(resultName)) {
if (!ImageIO.write(result, "png", outStream)) {
try {
if (!ImageIO.write(result, "png", Paths.get(resultName).toFile())) {
System.err.println("Could not encode an image to " + resultName);
}
} catch (IOException ignored) {

View file

@ -27,9 +27,9 @@ import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import javax.swing.Icon;
import javax.swing.ImageIcon;
@ -77,18 +77,18 @@ public final class GUIRunner extends JFrame {
private void chooseImage() throws MalformedURLException {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(this);
File file = fileChooser.getSelectedFile();
Icon imageIcon = new ImageIcon(file.toURI().toURL());
Path file = fileChooser.getSelectedFile().toPath();
Icon imageIcon = new ImageIcon(file.toUri().toURL());
setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight() + 100);
imageLabel.setIcon(imageIcon);
String decodeText = getDecodeText(file);
textArea.setText(decodeText);
}
private static String getDecodeText(File file) {
private static String getDecodeText(Path file) {
BufferedImage image;
try {
image = ImageReader.readImage(file);
image = ImageReader.readImage(file.toUri());
} catch (IOException ioe) {
return ioe.toString();
}

View file

@ -20,7 +20,6 @@ import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URLDecoder;
@ -68,8 +67,4 @@ public final class ImageReader {
return ImageIO.read(new ByteArrayInputStream(imageBytes));
}
public static BufferedImage readImage(File file) throws IOException {
return readImage(file.toURI());
}
}

View file

@ -23,6 +23,7 @@ import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.nio.file.Path;
/**
* Writes a {@link BitMatrix} to {@link BufferedImage},
@ -62,22 +63,39 @@ public final class MatrixToImageWriter {
return image;
}
/**
* @deprecated use {@link #writeToPath(BitMatrix, String, Path)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
writeToPath(matrix, format, file.toPath());
}
/**
* Writes a {@link BitMatrix} to a file.
*
* @see #toBufferedImage(BitMatrix)
*/
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
writeToFile(matrix, format, file, DEFAULT_CONFIG);
public static void writeToPath(BitMatrix matrix, String format, Path file) throws IOException {
writeToPath(matrix, format, file, DEFAULT_CONFIG);
}
/**
* @deprecated use {@link #writeToPath(BitMatrix, String, Path, MatrixToImageConfig)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config)
throws IOException {
writeToPath(matrix, format, file.toPath(), config);
}
/**
* As {@link #writeToFile(BitMatrix, String, File)}, but allows customization of the output.
*/
public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config)
public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file)) {
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}

View file

@ -219,11 +219,8 @@ public final class DecodeServlet extends HttpServlet {
return;
}
InputStream is = null;
try (InputStream is = connection.getInputStream()) {
try {
is = connection.getInputStream();
if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
log.info("Unsuccessful return code: " + connection.getResponseCode());
response.sendRedirect("badurl.jspx");
@ -242,9 +239,7 @@ public final class DecodeServlet extends HttpServlet {
log.info(ioe.toString());
response.sendRedirect("badurl.jspx");
} finally {
if (is != null) {
consumeRemainder(is);
is.close();
}
}