Remove my old email address from files. Might as well save spammers the trouble.
[zxing.git] / javase / src / com / google / zxing / client / j2se / CommandLineRunner.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.j2se;
18
19 import com.google.zxing.DecodeHintType;
20 import com.google.zxing.MonochromeBitmapSource;
21 import com.google.zxing.MultiFormatReader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
24
25 import javax.imageio.ImageIO;
26 import java.awt.image.BufferedImage;
27 import java.io.File;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.OutputStreamWriter;
32 import java.io.Writer;
33 import java.net.URI;
34 import java.util.Hashtable;
35 import java.nio.charset.Charset;
36
37 /**
38  * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
39  * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
40  * request that hint. The raw text of each barcode is printed, and when running against directories,
41  * summary statistics are also displayed.</p>
42  *
43  * @author Sean Owen
44  * @author dswitkin@google.com (Daniel Switkin)
45  */
46 public final class CommandLineRunner {
47
48   private CommandLineRunner() {
49   }
50
51   public static void main(String[] args) throws Exception {
52     Hashtable<DecodeHintType, Object> hints = null;
53     boolean dumpResults = false;
54     for (String arg : args) {
55       if ("--try_harder".equals(arg)) {
56         hints = new Hashtable<DecodeHintType, Object>(3);
57         hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
58       } else if ("--dump_results".equals(arg)) {
59         dumpResults = true;
60       } else if (arg.startsWith("--")) {
61         System.out.println("Unknown command line option " + arg);
62         return;
63       }
64     }
65     for (String arg : args) {
66       if (!arg.startsWith("--")) {
67         decodeOneArgument(arg, hints, dumpResults);
68       }
69     }
70   }
71
72   private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
73       boolean dumpResults) throws Exception {
74
75     File inputFile = new File(argument);
76     if (inputFile.exists()) {
77       if (inputFile.isDirectory()) {
78         int successful = 0;
79         int total = 0;
80         for (File input : inputFile.listFiles()) {
81           String filename = input.getName().toLowerCase();
82           // Skip hidden files and text files (the latter is found in the blackbox tests).
83           if (filename.startsWith(".") || filename.endsWith(".txt")) {
84             continue;
85           }
86           Result result = decode(input.toURI(), hints);
87           if (result != null) {
88             successful++;
89             if (dumpResults) {
90               dumpResult(input, result);
91             }
92           }
93           total++;
94         }
95         System.out.println("\nDecoded " + successful + " files out of " + total +
96             " successfully (" + (successful * 100 / total) + "%)\n");
97       } else {
98         Result result = decode(inputFile.toURI(), hints);
99         if (dumpResults) {
100           dumpResult(inputFile, result);
101         }
102       }
103     } else {
104       decode(new URI(argument), hints);
105     }
106   }
107
108   private static void dumpResult(File input, Result result) throws IOException {
109     String name = input.getAbsolutePath();
110     int pos = name.lastIndexOf('.');
111     if (pos > 0) {
112       name = name.substring(0, pos);
113     }
114     File dump = new File(name + ".txt");
115     writeStringToFile(result.getText(), dump);
116   }
117
118   private static void writeStringToFile(String value, File file) throws IOException {
119     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
120     try {
121       out.write(value);
122     } finally {
123       out.close();
124     }
125   }
126
127   private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints) throws IOException {
128     BufferedImage image;
129     try {
130       image = ImageIO.read(uri.toURL());
131     } catch (IllegalArgumentException iae) {
132       throw new FileNotFoundException("Resource not found: " + uri);
133     }
134     if (image == null) {
135       System.err.println(uri.toString() + ": Could not load image");
136       return null;
137     }
138     try {
139       MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
140       Result result = new MultiFormatReader().decode(source, hints);
141       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() + "):\n" +
142           result.getText());
143       return result;
144     } catch (ReaderException e) {
145       System.out.println(uri.toString() + ": No barcode found");
146       return null;
147     }
148   }
149
150 }