Repository navigation
Expand file tree
/
Copy pathCaVaxRecDecoder.java
More file actions
1293 lines (1243 loc) · 40.6 KB
/
Copy pathCaVaxRecDecoder.java
File metadata and controls
1293 lines (1243 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.io.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.math.BigInteger;
import java.net.URL;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.*;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.ECPoint;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.zip.*;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.bzdev.io.CSVWriter;
import org.bzdev.io.AppendableWriter;
import org.bzdev.swing.SimpleConsole;
import org.bzdev.swing.DarkmodeMonitor;
import org.bzdev.swing.InputTablePane;
import org.bzdev.util.JSOps;
import org.bzdev.util.JSArray;
import org.bzdev.util.JSObject;
import org.bzdev.util.JSUtilities;
/**
* Class implementating a Java program to read and verify a
* California Digital COVID-19 Vaccine Record. The record
* is typically provided as a QR-Code surrounded with some
* logos and a summary of its contents. A QR-code scanner
* can convert it to its purely digital form - a URI whose
* scheme is "shc". Textually it consists of the string
* "shc:/" followed by a large number of pairs of digits,
* with a total length of roughly 1700 characters. By
* contrast, a PNG image of a screenshot of the vaccination
* record is about 176000 bytes in size, with the QR code
* along requiring roughly 155000 bytes at that resolution.
* <P>
* To compile/run, libbzdev-base.jar and the two zxing jar files
* core.js and javase.js (poorly named by their Debian packages
* as they are both placed in /usr/share/java with no indication that
* they have anything to do with zxing, Google's open-source bar-code
* class library) must be on the class path. These libraries provide
* the following:
* <UL>
* <LI><STRONG>libbzdev-base.jar</STRONG>. The org.bzdev classes for
* creating a CSV file and for processing JSON.
* <LI><STRONG>core.jar</STRONG> and <STRONG>javase.jar</STRONG>. The
* classes used to read QR bar codes.
* </UL>
* <P>
* The command-line options are
* <UL>
* <LI><STRONG>-u</STRONG>Print the URI provided by the QR codes,
* one per line.
* <LI><STRONG>-v</STRONG>Print a full description of the contents of
* a QR code, excluding the header, and indicate if the signature
* was valid or not.
* </UL>
* These two options are mutually exclusive. If neither is present, the
* output will be a summary of each QR code printed with a heading in
* CSV format, so it can be easily imported into a spread sheet or database.
* If a file name argument is '-', an image file should be read from
* standard input.
* If there are no arguments, the input is expected to be a file with one
* URI per line. Lines starting with "#' and blank lines are ignored.
* <P>
* The California digital vaccine record is based on the Smart Health
* Card standard. Unfortunately, this standard, at least what one will
* find with an initial Google search, is somewhat lacking in clarity.
* The QR code itself encodes a URI whose scheme is "shc". In the URI,
* this is followed by a colon, a "/", and a long series of pairs of digits.
* Each pair represents a number in the range [0, 99]. To turn this encoding
* int a series of ASCII characters, take the number represented by each pair
* and add 45 to it to obtain the character code of an ascii character.
* The characters that are produced will be those in a URL-safe base-64
* encoding (with some base-64 decoders, one must explicitly request url-safe
* base 64 decoding). All the characters except for two periods (".") are
* allowed characters for this encoding. The input must be split at the
* periods. This provides three components: a header, a record, and a
* signature. The signature, however, is not DER encoded, and Java's
* signing code expects DER encoded signature.
* <P>
* When base-64 decoded, the first component contains a JSON
* object with fields that specify the compression algorithm for the
* second component and type of signature, with the signature itself
* provided by the last component. When the second component is base-64
* decoded and then uncompressed, the result is a JSON object containing
* the vaccination record. To verify the signature, you have to use the
* procedure specified in RFC 7515. What is signed is the concatenation
* of the url-safe base-64 encoded header, a period, and
* the url-safe base-64 encoded compressed record. The URL
* <A HREF="https://myvaccinerecord.cdph.ca.gov/creds/.well-known/jwks.json">
* https://myvaccinerecord.cdph.ca.gov/creds/.well-known/jwks.json</A>
* contains a description of the public key needed to verify the signature
* (at the time this documentation was written, there was only one key,
* but additional keys could be added later). Also, they do not explicitly
* indicate what vaccines are used. Instead, a vaccine record consists of
* a "system" field that indicates a name space and a code that indicates
* a vaccine listed in that namespace. The codes seem to be non-negative
* integers. The web site
* <A HREF="https://www.cdc.gov/vaccines/programs/iis/COVID-19-related-codes.html>
* https://www.cdc.gov/vaccines/programs/iis/COVID-19-related-codes.html</A>
* has the vaccine codes (it lists CVX codes).
* <P>
* Because the COVID-19 pandemic should end once enough of the population
* has enough sense to get vaccinated, the implementation skips some steps
* that would be appropriate for an application whose useful life is
* longer. It uses a built-in key for speed, and if the keyid of a key
* is missing, it goes to the California Department of Public Health link
* mentioned above to update and extend the list of known keys. Nothing
* downloaded is cached. Also, because this is California-specific, no
* effort was made at internationalization: people in California who
* can run a command-line program are typically fluent in English in
* addition to whatever other languages they know, the result of a need
* for companies to hire the brightest and most highly educated people they
* can find. The extra effort needed for localizing the code would
* unfortunately take too long given only a single individual developing
* this software.
* <P>
* The method getPublicKey looks up key parameters from a key id and
* then issues the incantation that creates the public key. The method
* mkder takes a signature and DER encodes it. Both have been tested
* with a single case due to large sample of SHC QRCodes not being
* available.
*/
public class CaVaxRecDecoder {
static PrintWriter err =
new PrintWriter(new OutputStreamWriter(System.err));
// information stored at
// https://myvaccinerecord.cdph.ca.gov/creds/.well-known/jwks.json
static class KeyInfo {
String kty;
String alg;
String crv;
String x;
String y;
public KeyInfo(String kty, String alg, String crv, String x, String y) {
this.kty = kty;
this.alg = alg;
this.crv = crv;
this.x = x;
this.y = y;
}
}
static Map<String, KeyInfo> keymap = new HashMap<>();
static boolean needLoading = true;
static {
// At the time this was written, the California web site contained
// a single key. These keys should not change very often, but
// it would be worth checking periodically and updating this
// section of the code.
keymap.put("7JvktUpf1_9NPwdM-70FJT3YdyTiSe2IvmVxxgDSRb0",
new KeyInfo("EC", "ES256", "P-256",
"3dQz5ZlbazChP3U7bdqShfF0fvSXLXD9WMa1kqqH6i4",
"FV4AsWjc7ZmfhSiHsw2gjnDMKNLwNqi2jMLmJpiKWtE"));
}
static Map<String,Integer> knownISS = new LinkedHashMap<String,Integer>();
static int issCount = 0;
static void loadKeys(String iss) {
// load the keys, by default from the CA DPH web site.
// This will be called at most once for each value of iss.
try {
if (iss != null && iss.endsWith("/")) {
iss = iss.substring(0, iss.length()-1);
}
String urlString = ((iss == null)?
"https://myvaccinerecord.cdph.ca.gov/creds":
iss)
+ "/.well-known/jwks.json";
URL url = new URL(urlString);
InputStream is = url.openStream();
Object obj = JSUtilities.JSON.parse(is, "UTF-8");
if (obj instanceof JSObject) {
JSObject object = (JSObject) obj;
obj = object.get("keys");
if (obj instanceof JSArray) {
JSArray array = (JSArray) obj;
for (Object o: array) {
if (o instanceof JSObject) {
object = (JSObject) o;
String kid = object.get("kid", String.class);
String kty = object.get("kty", String.class);
String alg = object.get("alg", String.class);
String crv = object.get("crv", String.class);
String x = object.get("x", String.class);
String y = object.get("y", String.class);
keymap.put(kid,
new KeyInfo(kty, alg, crv, x, y));
}
}
}
}
knownISS.put(iss, ++issCount);
needLoading = false;
} catch (Exception e) {
err.println("cvrdecode: could not load key(s): "
+ e.getMessage());
}
}
static HashMap<String,Integer> vmap = new HashMap<>();
static {
// List of currently used vaccines and the number of doses
// required for each. This table applies to
// the system http://hl7.org/fhir/sid/cvx
// the CVX codes were taken from
// https://www.cdc.gov/vaccines/programs/iis/COVID-19-related-codes.html
vmap.put("207", 2); // Moderna
vmap.put("208", 2); // Pfizer
vmap.put("210", 2); // AstraZeneca
vmap.put("211", 2); // Novavax
vmap.put("212", 1); // Jansen (J&J)
vmap.put("213", 1); // unspecified
vmap.put("229", 1); // Moderna
vmap.put("308", 1); // Pfizer
vmap.put("310", 1); // Pfizer
vmap.put("311", 1); // Moderna
vmap.put("312", 1); // Moderna
vmap.put("313", 1); // Noravax
}
static int neededDoses(String system, String code) {
// Currently we recognize only one "system". The code
// will have to be modified if that changes at some point.
if (!system.equals("http://hl7.org/fhir/sid/cvx")) {
return -1;
}
Integer ival = vmap.get(code);
if (ival == null) return -1;
return ival;
}
static ECPublicKey getPublicKey(String iss, String kid)
throws NoSuchAlgorithmException, InvalidParameterSpecException,
InvalidKeySpecException, NoSuchProviderException,
IllegalArgumentException
{
KeyInfo info = keymap.get(kid);
if (info == null && !knownISS.containsKey(iss)) {
loadKeys(iss);
info = keymap.get(kid);
}
if (info == null) throw new IllegalArgumentException("unknown key ID");
if (!info.kty.equals("EC")) {
throw new IllegalStateException("Cannot Handle " + info.kty);
}
if (!info.alg.equals("ES256")) {
throw new IllegalStateException("Cannot Handle " + info.alg);
}
if (!info.crv.equals("P-256")) {
throw new IllegalStateException("Cannot Handle " + info.crv);
}
Base64.Decoder decoder = Base64.getUrlDecoder();
byte[] xbytes = decoder.decode(info.x);
byte[] ybytes = decoder.decode(info.y);
BigInteger x = new BigInteger(1, xbytes);
BigInteger y = new BigInteger(1, ybytes);
ECPoint ecpoint = new ECPoint(x, y);
AlgorithmParameters parameters =
AlgorithmParameters.getInstance("EC", "SunEC");
parameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameters =
parameters.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec pubSpec = new ECPublicKeySpec(ecpoint, ecParameters);
KeyFactory kf = KeyFactory.getInstance("EC");
return (ECPublicKey)kf.generatePublic(pubSpec);
}
static boolean verify(ECPublicKey key, byte[] data, byte[] signature)
throws SignatureException, NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException
{
Signature sig = Signature.getInstance("SHA256withECDSA", "SunEC");
sig.initVerify(key);
sig.update(data, 0, data.length);
return sig.verify(signature);
}
static byte[] mkder(byte[] sig) {
// The signature we get from the record is not DER encoded,
// so we have to fix it up. It consists of two 256 bit
// numbers (unsigned), and we have to add a 'zero' byte if
// the first byte is negative to prevent sign-extension from
// turning the number into a negative one.
int lenR = 0x20;
int lenS = 0x20;
if (sig[0] < 0) {
lenR++;
}
if (sig[32] < 0) {
lenS++;
}
byte[] result = new byte[6 + lenR + lenS];
int i = 0;
result[i++] = 0x30;
result[i++] = (byte)(0x04 + lenR + lenS);
result[i++] = 0x02;
result[i++] = (byte)lenR;
if (lenR > 0x20) {
result[i++] = 0;
}
System.arraycopy(sig, 0, result, i, 0x20);
i += 0x20;
result[i++] = 0x02;
result[i++] = (byte)lenS;
if (lenS > 0x20) {
result[i++] = 0x00;
}
System.arraycopy(sig, 0x20, result, i, 0x20);
i += 0x20;
if (i != result.length) {
throw new RuntimeException("DER encoding failed");
}
return result;
}
private static void printInfo(JSOps info, int depth) {
// Recursive function to walk through a tree and pretty print it.
if (info instanceof JSObject) {
if (depth == 0) {
JSObject object = (JSObject) info;
Object issObject = object.get("iss");
iss = (issObject instanceof String)? (String) issObject: null;
if (iss == null) {
throw new IllegalStateException("iss = "
+ issObject
+ " not expected");
}
}
for (Map.Entry<String,Object> entry: ((JSObject) info).entrySet()) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.print(entry.getKey() + ":");
Object value = entry.getValue();
if (value instanceof JSOps) {
System.out.println();
printInfo((JSOps) value, depth + 2);
} else {
System.out.println(" " + value);
}
}
} else if (info instanceof JSArray) {
for (Object object: (JSArray)info) {
for (int i = 0; i < depth-1; i++) {
System.out.print(" ");
}
System.out.print("-");
if (object instanceof JSArray) {
System.out.println();
printInfo((JSOps) object, depth + 2);
} else if (object instanceof JSObject) {
System.out.println();
printInfo((JSOps)object, depth + 2);
} else {
System.out.print(" ");
System.out.println(object);
}
}
} else {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.println(info);
}
}
private static void printInfo(String contents) throws IOException {
Object object = JSUtilities.JSON.parse(contents);
if (object instanceof JSOps) {
printInfo((JSOps) object, 0);
} else {
System.out.println(object);
}
}
static String iss = null;
static String kid = null;
static int issIndex = 0;
static String familyName = null;
static String givenNames = null;
static String birthDate = null;
static int dosesNeeded = -1;
static int code = -1;
static int oindex = 0;
static ArrayList<LocalDate> occurrence = new ArrayList<>();;
static boolean valid = false;
static boolean full = false;
static LocalDate latest = null;
private static void processInfo(JSOps info) throws IOException {
// traverse the JSON data structures and store the
// fields we want.
if (info instanceof JSObject) {
JSObject object = (JSObject) info;
if (object.containsKey("vc")) {
processInfo((JSOps)object.get("vc"));
} else if (object.containsKey("credentialSubject")) {
processInfo((JSOps)object.get("credentialSubject"));
} else if (object.containsKey("fhirBundle")) {
processInfo((JSOps)object.get("fhirBundle"));
} else if (object.containsKey("resource")) {
processInfo((JSOps)object.get("resource"));
} else if (object.containsKey("resourceType")) {
String rtype = object.get("resourceType", String.class);
if (rtype.equals("Bundle")) {
processInfo((JSOps)object.get("entry"));
} else if (rtype.equals("Patient")) {
JSArray array = (JSArray) object.get("name");
JSObject obj = (JSObject) array.get(0);
familyName = obj.get("family", String.class);
JSArray givens = (JSArray) obj.get("given");
givenNames = "";
for (Object sobj: givens) {
givenNames = givenNames + " " + sobj;
}
givenNames = givenNames.trim();
birthDate = object.get("birthDate", String.class);
} else if (rtype.equals("Immunization")) {
if (object.containsKey("vaccineCode")) {
JSObject vcobj = (JSObject)object.get("vaccineCode");
JSObject vobj = (JSObject)
(((JSArray)vcobj.get("coding")).get(0));
dosesNeeded = neededDoses(vobj.get("system",
String.class),
vobj.get("code",
String.class));
if (dosesNeeded == -1) {
System.err.println("Warning: cannot recognize "
+ "vaccine code "
+ vobj.get("code",
String.class));
} else {
occurrence.add(LocalDate
.parse(object
.get("occurrenceDateTime",
String.class)));
}
}
}
}
} else if (info instanceof JSArray) {
for (Object object: (JSArray)info) {
if (object instanceof JSArray) {
processInfo((JSOps) object);
} else if (object instanceof JSObject) {
processInfo((JSOps)object);
}
}
} else {
throw new IOException("cannot recognize format");
}
}
private static void processInfo(String contents) throws IOException {
// need to initialize so we don't use old data if something is
// missing.
familyName = null;
givenNames = null;
birthDate = null;
dosesNeeded = -1;
code = -1;
oindex = 0;
occurrence.clear();
valid = false;
full = false;
Object object = JSUtilities.JSON.parse(contents);
if (object instanceof JSObject) {
JSObject obj = (JSObject) object;
Object issObject = obj.get("iss");
iss = (issObject instanceof String)? (String) issObject: null;
if (iss == null) {
throw new IllegalStateException("iss = "
+ issObject
+ " not expected");
}
}
if (object instanceof JSOps) {
processInfo((JSOps) object);
} else {
throw new IOException("cannot recognize format");
}
}
/*
// The program that processes images containing QR codes.
private static final String ZBARIMG =
System.getProperty("zbarimg.path", "/usr/bin/zbarimg");
*/
static Object monitor = null; // Set & used by the GUI
static File target = null;
static File output = null;
static Vector<Vector<Object>> tableRows = null;
static JButton showTableButton = null;
static final Color PALE_YELLOW = new Color(255, 255, 200);
private static void startGUI() throws Exception {
DarkmodeMonitor.setSystemPLAF();
DarkmodeMonitor.init();
monitor = new Object();
SwingUtilities.invokeLater(() -> {
java.util.List<Image> iconList = new LinkedList<Image>();
try {
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode16.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode24.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode32.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode48.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode64.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode96.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode128.png")
))).getImage());
iconList.add((new
ImageIcon((CaVaxRecDecoder.class
.getResource("cvrdecode256.png")
))).getImage());
} catch (Exception e) {
System.err.println("initialization failed - "
+ "missing icon for iconList");
}
SimpleConsole console = SimpleConsole
.newFramedInstance(800, 600, "cvrdecode: Console", false);
err = new PrintWriter(new AppendableWriter(console));
InputTablePane.ColSpec[] spec = {
new InputTablePane.ColSpec("Family Name",
"mmmmmmmmmmmm",
String.class, null, null),
new InputTablePane.ColSpec("Given Names",
"mmmmmmmmmmmm",
String.class, null, null),
new InputTablePane.ColSpec("Birth Date",
"5555-55-55",
String.class, null, null),
new InputTablePane.ColSpec("Last Vax",
"5555-55-55",
String.class, null, null),
new InputTablePane.ColSpec("Fully Vaxxed",
"false",
String.class, null, null),
new InputTablePane.ColSpec("Valid Sig.",
"false",
String.class, null, null),
new InputTablePane.ColSpec("Source",
"mmmmmmmmmmmmmmmm",
String.class, null, null),
};
JFrame frame =
new JFrame("cvrdecode: CA Vaccine Record Decoder");
frame.setIconImages(iconList);
JPanel panel = new JPanel(new GridLayout(3, 2));
JButton runButton = new JButton("Run");
JButton setDirButton = new JButton("Set Input Directory");
JButton setOutputButton = new JButton("Set Output File");
JButton showConsoleButton = new JButton("Show Console");
runButton.setEnabled(false);
runButton.addActionListener((ae) -> {
synchronized(monitor) {
try {
monitor.notifyAll();
} catch (Exception e) {}
}
setDirButton.setEnabled(false);
setOutputButton.setEnabled(false);
showConsoleButton.setEnabled(true);
runButton.setEnabled(false);
});
FileFilter filter1 = new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return f.canRead();
} else {
String name = f.getName();
return (name.endsWith(".zip")
|| name.endsWith(".ZIP"))
&& f.canRead();
}
}
public String getDescription() {
return "Directory or ZIP file";
}
};
String cdir = System.getProperty("user.dir");
final JFileChooser fc1 = new JFileChooser(cdir);
fc1.addChoosableFileFilter(filter1);
fc1.setAcceptAllFileFilterUsed(false);
fc1.setMultiSelectionEnabled(false);
fc1.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc1.setDialogTitle("cvrdecode: Set Directory");
fc1.setApproveButtonText("Set Input Directory");
FileNameExtensionFilter filter2 =
new FileNameExtensionFilter("csv", "CSV");
final JFileChooser fc2 = new JFileChooser(cdir);
fc2.setFileFilter(filter2);
fc2.setDialogTitle("cvrdecode: Set Output File");
fc2.setApproveButtonText("Set Output File");
fc2.setAcceptAllFileFilterUsed(false);
fc2.setMultiSelectionEnabled(false);
setDirButton.addActionListener((ae) -> {
File lastTarget = target;
if (fc1.showOpenDialog(panel) ==
JFileChooser.APPROVE_OPTION) {
target = fc1.getSelectedFile();
if (target == null) {
JOptionPane
.showMessageDialog(panel,
"No directory selected",
"Error",
JOptionPane
.ERROR_MESSAGE);
target = lastTarget;
return;
}
if (output == null) {
// set only if we haven't already selected
// something.
fc2.setCurrentDirectory(target.getParentFile());
}
if (target != null) {
setDirButton.setOpaque(true);
setDirButton.setBackground(PALE_YELLOW);
} else
if (target != null && output != null) {
runButton.setEnabled(true);
}
}
});
setOutputButton.addActionListener((ae) -> {
File lastOutput = output;
if (fc2.showOpenDialog(panel) ==
JFileChooser.APPROVE_OPTION) {
output = fc2.getSelectedFile();
if (output == null) {
output = lastOutput;
JOptionPane
.showMessageDialog(panel,
"No file selected",
"Error",
JOptionPane
.ERROR_MESSAGE);
return;
}
String oname = output.getName();
if (oname == null) {
output = lastOutput;
JOptionPane
.showMessageDialog(panel,
"No file selected",
"Error",
JOptionPane
.ERROR_MESSAGE);
return;
}
int ind = oname.lastIndexOf(".");
if (ind == -1) {
output = new File(output.getParentFile(),
oname + ".csv");
} else {
String suffix = oname.substring(ind+1);
if (!(suffix.equals("csv")
|| suffix.equals("CSV"))) {
output = new File(output.getParentFile(),
oname + ".csv");
}
}
if (output != null) {
setOutputButton.setOpaque(true);
setOutputButton.setBackground(PALE_YELLOW);
}
if (target != null && output != null) {
runButton.setEnabled(true);
}
}
});
showConsoleButton.setEnabled(false);
showConsoleButton.addActionListener((ae) -> {
console.getFrame().setVisible(true);
});
showTableButton = new JButton("Show Table");
showTableButton.setEnabled(false);
showTableButton.addActionListener((ae) -> {
if (tableRows == null) return;
InputTablePane.showDialog(panel,
"crvdecode: Output Table",
spec,
tableRows,
false, false, false);
});
JButton exitButton = new JButton("Exit");
exitButton.addActionListener((ae) -> {
System.exit(0);
});
panel.add(setDirButton);
panel.add(setOutputButton);
panel.add(runButton);
panel.add(showTableButton);
panel.add(showConsoleButton);
panel.add(exitButton);
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
});
// Need to wait until the target directory and output file are set.
synchronized (monitor) {
while (target == null && output == null) {
try {
monitor.wait();
} catch (Exception e) {}
}
}
// We now have the directory to read.
}
/**
* Main entry point.
*/
public static void main(String argv[]) throws Exception {
boolean guimode = false;
ZipInputStream zis = null;
if (argv.length == 0) {
startGUI();
String[] suffixes = ImageIO.getReaderFileSuffixes();
Set<String> suffixSet = new HashSet<>();
suffixSet.add("shc");
for (String suffix: suffixes) {
suffixSet.add(suffix);
}
ArrayList<String> list = new ArrayList<>(256);
if (target.isDirectory()) {
for (File f: target.listFiles()) {
String fname = f.getName();
int ind = fname.lastIndexOf(".");
if (ind == -1) continue;
String suffix = fname.substring(ind+1);
if (suffixSet.contains(suffix)) {
list.add(f.getCanonicalPath());
}
}
argv = list.toArray(new String[list.size()]);
} else {
try {
zis = new ZipInputStream(new FileInputStream(target));
} catch (Exception ezip) {
err.println("cvrdecode:input not a zip file?");
err.flush();
return;
}
}
guimode = true;
}
boolean showJSON = false;
boolean uriMode = false;
if (argv.length > 0 && argv.length < 3 && argv[0].equals("-i")) {
// Special case: the arguments are read from standard input
// or from a single file containing shc URLs,
// probably from a file generated using the '-u' option.
// Each URI must appear on a single line. We'll simply
// re-write argv.
Charset charset = Charset.forName("UTF-8");
InputStream is = (argv.length == 1 || argv[1].equals("-"))?
System.in: new FileInputStream(new File(argv[0]));
BufferedReader r = new
BufferedReader(new InputStreamReader(is, charset), 4096);
ArrayList<String> alist = new ArrayList<>(512);
String line = null;
int linecnt = 0;
while ((line = r.readLine()) != null) {
line = line.trim();
linecnt++;
if (line.length() == 0) continue;
if (line.startsWith("#")) continue;
if (line.startsWith("shc:/")) {
alist.add(line.trim());
} else {
err.println("cvrdecode: bad input at line number "
+ linecnt);
err.flush();
}
}
argv = alist.toArray(new String[alist.size()]);
} else if (argv.length > 0 && argv.length < 3 && argv[0].equals("-z")) {
try {
zis = new ZipInputStream((argv.length == 1)? System.in:
(argv[1].equals("-"))? System.in:
new FileInputStream(argv[1]));
} catch (Exception ezis) {
err.println("crvdecode: input not a ZIP file");
err.flush();
System.exit(1);
}
} else if (argv.length > 0 && argv[0].equals("-v")) {
if (argv.length == 1) {
argv = new String[] {
"-v", "-"
};
} else if (argv.length != 2) {
err.println("cvrdecode: "
+ "only one file with -v is allowed");
err.flush();
System.exit(1);
}
showJSON = true;
} else if (argv.length > 0 && argv[0].equals("-u")) {
uriMode = true;
}
String uri;
ArrayList<String[]> list = new ArrayList<>(argv.length);
PrintWriter pw = (showJSON || uriMode)? null:
new PrintWriter(((output != null)? new FileOutputStream(output):
System.out), true, Charset.forName("UTF-8"));
CSVWriter w = (showJSON || uriMode)? null: new CSVWriter(pw, 7);
if (showJSON == false && uriMode == false) {
w.writeRow("Family Name", "Given Names", "Birth Date",
"Last Vaccination Date", "Fully Vaccinated",
"Valid Signature", "Source");
}
boolean mayHaveOptions = true;
if (zis != null) {
// image and shc files are taken from a zip file.
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) continue;
String arg = entry.getName();
long sz = entry.getSize();
uri = null;
byte[] bytes;
int offset = 0;
if (sz != -1) {
if (sz > Integer.MAX_VALUE) {
err.println("cvrdecode: zip entry too large");
err.flush();
zis.closeEntry();
continue;
}
int size = (int) sz;
bytes = new byte[size];
while (offset < size) {
int len = zis.read(bytes, offset, size-offset);
if (len == -1) {
break;
}
offset += len;
}
} else {
bytes = new byte[4048];
ByteArrayOutputStream bos =
new ByteArrayOutputStream(1<<18);
int len;
while ((len = zis.read(bytes, 0, 4048)) != -1) {
bos.write(bytes, 0, len);
}
bytes = bos.toByteArray();
// In the other branch, offset is the total length
// of the entry that was just read.
offset = bytes.length;
}
if (arg.endsWith(".shc") || arg.endsWith(".SHC")) {
uri = new String(bytes, 0, offset, "UTF-8").trim();
} else {
// assume the entry is an image
try {
InputStream in = new ByteArrayInputStream(bytes, 0,
offset);
// Read the URI from an embedded QR code
BufferedImage bufferedImage = ImageIO.read(in);
LuminanceSource source = new
BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap =
new BinaryBitmap(new HybridBinarizer(source));
uri = (new MultiFormatReader().decode(bitmap))
.getText();
} catch (Exception e) {
uri = null;
}
if (uri == null) {
err.println("cvrdecode: zip entry not readable - "
+ arg);
err.flush();
zis.closeEntry();
continue;
}
}
try {
processSHC(arg, uri, false);
} catch (Exception e) {
err.println("cvrdecode: " + e.getMessage()
+ " - " + arg);
err.flush();
zis.closeEntry();
continue;
}
// String doseString = full? "true (" + occurrence.size() + ")":
// "false";
String doseString = full? "true": "false";
int osize = occurrence.size();
if (full && dosesNeeded < osize) {
doseString = doseString + " (" + osize + ")";
}
String[] row = {familyName, givenNames, birthDate,
(latest == null)? "[no date]": latest.toString(),
doseString,
valid? "true": "false",
((issIndex == 0)? "": "[" + issIndex + "] ")
+ "zip: " + arg
};
list.add(row);
zis.closeEntry();
}
} else {
for (String arg: argv) {
if (mayHaveOptions && arg.equals("--")) {