-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathImportNarrativeDocument.java
executable file
·2599 lines (2100 loc) · 86.3 KB
/
ImportNarrativeDocument.java
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
/*******************************************************************************
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2020, Deep Blue C Technology Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*******************************************************************************/
/*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2016, Deep Blue C Technology Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package Debrief.ReaderWriter.Word;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import Debrief.GUI.Frames.Application;
import Debrief.ReaderWriter.NMEA.ImportNMEA;
import Debrief.ReaderWriter.Replay.ImportReplay;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.LightweightTrackWrapper;
import MWC.GUI.BaseLayer;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.ToolParent;
import MWC.GUI.Properties.DebriefColors;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.TacticalData.NarrativeEntry;
import MWC.TacticalData.NarrativeWrapper;
import MWC.Utilities.ReaderWriter.XML.LayerHandler;
import MWC.Utilities.TextFormatting.GMTDateFormat;
import junit.framework.TestCase;
public class ImportNarrativeDocument {
/**
* collection of fields for an FCS entry
*
* @author ian
*
*/
private static class FCSEntry {
private static String getClassified(final String input) {
String res = null;
final String regexp = "Classified (.*$)";
final Pattern pattern = Pattern.compile(regexp);
final Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
res = matcher.group(1);
}
return res;
}
/**
* get the element that starts with the provided identifier
*
* @param identifier
* @param input
* @return
*/
private static Double getElement(final String identifier, final String input) {
Double res = null;
final String regexp = identifier + "-*(\\d+\\.?\\d*)";
final Pattern pattern = Pattern.compile(regexp);
final Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
final String found = matcher.group(1);
try {
res = Double.parseDouble(found);
} catch (final NumberFormatException fe) {
// ok, we failed :-(
}
}
return res;
}
/**
* special element handler that can accommodate a range of types of units
*
* @param tidied
* @return
*/
private static WorldDistance getRange(final String input) {
final WorldDistance res;
// replace newline control characters
String tidied = input.replace("\n", "");
tidied = tidied.replace("\r", "");
final String regexp = ".*R-(?<RANGE>\\d+\\.?\\d?)(?:\\s*)(?<UNITS>\\w*?)(?:\\.|\\s).*";
final Matcher m = Pattern.compile(regexp).matcher(tidied);
if (m.matches()) {
final double range = Double.valueOf(m.group("RANGE"));
final String units = m.group("UNITS");
// ok, create the relevant object
if (units.toUpperCase().equals("KYDS")) {
res = new WorldDistance(range, WorldDistance.KYDS);
} else if (units.toUpperCase().equals("YDS")) {
res = new WorldDistance(range, WorldDistance.YARDS);
} else if (units.toUpperCase().equals("M")) {
res = new WorldDistance(range, WorldDistance.METRES);
} else {
res = null;
}
} else {
res = null;
}
return res;
}
private static String parseSource(final String str) {
// replace newline control characters
String tidied = str.replace("\n", "");
tidied = tidied.replace("\r", "");
tidied = tidied.trim();
final String regexp = ".*([A-Z]{1,4}\\d{3}|M\\d{2})(?<SOURCE>.*)B-.*";
final Matcher m = Pattern.compile(regexp).matcher(tidied);
final String res;
if (m.matches()) {
final String source = m.group("SOURCE").trim();
// ok, special processing. We're getting unpredicable extra text
// in the source field (between FCS and "B-". So
// do some inspection to decide what to show
if (source.contains("LOP")) {
res = "LOP";
} else if (source.contains("SMCS")) {
res = "SMCS";
} else if (source.contains("WECDIS")) {
res = "WECDIS";
} else if (source.contains("1936")) {
res = "1936";
} else if (source.contains("1959")) {
res = "1959";
} else if (source.contains("CMD")) {
res = "CMD";
} else if (source.contains("WECDIS")) {
res = "WECDIS";
} else if (source.toUpperCase().contains("TRIANGULATION")) {
res = "Triangulation";
} else if (source.contains("HDPR")) {
res = "HDPR";
} else {
res = source;
}
} else {
res = null;
}
return res;
}
/**
* extract the track number from the provided string
*
* @param str
* @return
*/
private static String parseTrack(final String str) {
// note: we try to match the master track first, since sometimes
// both are referred to in the FCS entry
// NOTE: if we continue to get "thrown" by multiple references in the line,
// then we should use a more prescriptive regexp, that starts with the
// FCS marker
final String shortTrackId = "(M\\d{2})";
final Pattern shortPattern = Pattern.compile(shortTrackId);
final Matcher matcher = shortPattern.matcher(str);
final String res;
if (matcher.find()) {
res = matcher.group(1);
} else {
final String longTrackId = "[A-Z]{1,4}(\\d{3})";
final Pattern longPattern = Pattern.compile(longTrackId);
final Matcher matcher1 = longPattern.matcher(str);
if (matcher1.find()) {
res = matcher1.group(1);
} else {
res = null;
}
}
return res;
}
/**
* have brg/rng as objects, so they can be null
*
*/
final Double brgDegs;
final Double rangYds;
final String tgtType;
final String contact;
final double crseDegs;
final double spdKts;
final String source;
public FCSEntry(final String msg) {
// pull out the matching strings
final Double bVal = getElement("B-", msg);
final WorldDistance rVal = getRange(msg);
final Double cVal = getElement("C-", msg);
final Double sVal = getElement("S-", msg);
// extract the classification
final String classStr = getClassified(msg);
// try to extract the track id
final String trackId = parseTrack(msg);
final String source = parseSource(msg);
this.crseDegs = cVal != null ? cVal : 0d;
this.brgDegs = bVal != null ? bVal : null;
this.rangYds = rVal != null ? rVal.getValueIn(WorldDistance.YARDS) : null;
this.spdKts = sVal != null ? sVal : 0d;
this.tgtType = classStr != null ? classStr : "N/A";
this.contact = trackId != null ? trackId : "N/A";
this.source = source != null ? source : "";
}
}
public static enum ImportNarrativeEnum {
TRIMMED_DATA(TRIMMED_DATA_STR), ALL_DATA(ALL_DATA_STR), CANCEL(CANCEL_STR);
public static ImportNarrativeEnum getByName(final String name) {
switch (name) {
case TRIMMED_DATA_STR:
return TRIMMED_DATA;
case ALL_DATA_STR:
return ALL_DATA;
default:
return CANCEL;
}
}
private String name;
ImportNarrativeEnum(final String string) {
this.name = string;
}
public String getName() {
return this.name;
}
}
public static class NarrativeHelperRetVal {
public ImportNarrativeEnum narrativeEnum;
public List<String> selectedNarrativeTypes;
}
public static interface NarrativeTypeHelper {
List<String> getSelectedNarrativeTypes(final Map<String, Integer> narrativeTypes);
}
private static class NarrEntry {
/**
* what is the last valid time we have. if time fields are missing we will
* extend from the last DTG
*/
private static Date lastDtg;
/**
* what was the last platform we read in, in case the platform is missing
*
*/
private static String lastPlatform;
/**
* what was the last entry? We remember it, so we can append ourselves to it
*
*/
private static NarrEntry lastEntry;
/**
* we've encountered circumstances where copy/paste has ended up with the day
* being earlier than the current one When we can detect this, we'll use the
* previous day.
*/
private static String lastDay;
/**
* don#t assume a decreasing day is wrong if the month has incremented
*/
private static String lastMonth;
/**
* don#t assume a decreasing day is wrong if the year has incremented
*/
private static String lastYear;
static public NarrEntry create(final String msg, final int lineNum) {
NarrEntry res = null;
try {
res = new NarrEntry(msg);
if (res.appendedToPrevious && res.text != null) {
// that's ok - we'll let the parent handle it
} else {
// just check it's valid
final boolean valid = (res.dtg != null) && (res.type != null) && (res.platform != null)
&& (res.text != null);
if (!valid) {
res = null;
}
}
} catch (final ParseException e) {
logThisError(ToolParent.WARNING, "Failed whilst parsing Word Document, at line:" + lineNum, e);
}
return res;
}
/**
* reset the static variables we use to handle missing, or mangled data
*
*/
public static void reset() {
lastDtg = null;
lastPlatform = null;
lastEntry = null;
lastDay = null;
lastMonth = null;
lastYear = null;
}
HiResDate dtg;
String type;
String platform;
String text;
boolean appendedToPrevious = false;
@SuppressWarnings("deprecation")
public NarrEntry(final String entry) throws ParseException {
final String trimmed = entry.trim();
final String[] parts = trimmed.split(",");
int ctr = 0;
// if(entry.contains("message 69"))
// {
// System.out.println("here");
// }
final boolean correctLength = parts.length > 5;
final boolean sixFigDTG = correctLength && parts[0].length() == 6 && parts[0].matches(DATE_MATCH_SIX);
final boolean fourFigDTG = correctLength && parts[0].length() == 4 && parts[0].matches(DATE_MATCH_FOUR);
final boolean hasDTG = sixFigDTG || fourFigDTG;
if (hasDTG) {
final String dtgStr;
if (fourFigDTG) {
dtgStr = parts[ctr++];
} else {
dtgStr = parts[ctr++].substring(2, 6);
}
// ok, sort out the time first
String dayStr = parts[ctr++];
final String monStr = parts[ctr++];
final String yrStr = parts[ctr++];
platform = parts[ctr++].trim();
type = parts[ctr++].trim();
/**
* special processing, to overcome problem with entries being pulled back from
* the next day. The problem has occurred when something that happened at, say
* 2345 only gets entered at 0005, so the user moves the entry back to the real
* time
*/
if (sixFigDTG) {
final int dtgDate = Integer.valueOf(parts[0].substring(0, 2));
final int hours = Integer.valueOf(parts[0].substring(2, 4));
// is this entry after 2300? (that's the usual destination)
if (hours == 23) {
final int hiddenDay = Integer.parseInt(dayStr);
if (hiddenDay == dtgDate + 1) {
// ok, the date in the hidden text is one day after
// that in 6-fix DTG. correct the date
dayStr = "" + dtgDate;
}
}
}
/**
* special processing, to overcome the previous day being used
*
*/
final boolean dayDecreased = lastDay != null && Integer.parseInt(dayStr) < Integer.parseInt(lastDay);
final boolean monthIncreased = lastMonth != null
&& Integer.parseInt(monStr) > Integer.parseInt(lastMonth);
final boolean yearIncreased = lastYear != null && Integer.parseInt(yrStr) > Integer.parseInt(lastYear);
if (dayDecreased && !monthIncreased && !yearIncreased) {
// ok, the day has dropped, but the month hasn't increased
dayStr = lastDay;
// insert warning, since this may be a mangled DTG
final String msg = "Day decreased, but month didn't increase: " + dtgStr
+ ". The previous entry may be a mangled cut/paste";
logThisError(ToolParent.ERROR, msg, null);
} else {
// it's valid, update the last day
lastDay = dayStr;
lastMonth = monStr;
lastYear = yrStr;
}
// hmm, on occasion we don't get the closing comma on the entry type
if (type.length() > 20) {
final int firstSpace = type.indexOf(" ");
// note: should actually be looking for non-alphanumeric, since it may be a tab
type = type.substring(0, firstSpace - 1);
}
final int year;
if (yrStr.length() == 2) {
final int theYear = Integer.parseInt(yrStr);
// is this from the late 80's onwards?
if (theYear > 80) {
year = 1900 + theYear;
} else {
year = 2000 + theYear;
}
} else {
year = Integer.parseInt(yrStr);
}
final int hours = Integer.parseInt(dtgStr.substring(0, 2));
final int mins = Integer.parseInt(dtgStr.substring(2, 4));
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(year, Integer.parseInt(monStr) - 1, Integer.parseInt(dayStr), hours, mins, 0);
cal.set(Calendar.MILLISECOND, 0);
dtg = new HiResDate(cal.getTime());
// ok, and the message part
final int ind = entry.indexOf(type);
text = entry.substring(ind + type.length() + 1).trim();
// remember what's happening, so we can refer back to previous entries
lastDtg = new Date(dtg.getDate().getTime());
lastPlatform = platform;
lastEntry = this;
} else {
final int firstTab = firstWhiteSpace(trimmed);
// see if the first few characters are date
final String dateStr = firstTab > 0 ? trimmed.substring(0, Math.min(trimmed.length(), firstTab))
: trimmed;
// is this all numeric
boolean probIsDate = false;
try {
if (dateStr.length() == 6 || dateStr.length() == 4) {
@SuppressWarnings("unused")
final int testInt = Integer.parseInt(dateStr);
probIsDate = true;
}
} catch (final NumberFormatException e) {
}
final boolean probHasContent = entry.length() > 8;
if (probIsDate && probHasContent) {
// yes, go for it.
// ooh, do we have some stored data?
if (lastDtg != null && lastPlatform != null) {
final String parseStr;
Integer theseDays = null;
if (dateStr.length() == 6) {
// reduce to four charts
theseDays = Integer.parseInt(dateStr.substring(0, 2));
parseStr = dateStr.substring(2, 6);
} else {
parseStr = dateStr;
}
// first try to parse it
final int hours = Integer.parseInt(parseStr.substring(0, 2));
final int mins = Integer.parseInt(parseStr.substring(2, 4));
// do some date fiddling
int daysToUse = lastDtg.getDate();
int monthToUse = lastDtg.getMonth();
int yearToUse = lastDtg.getYear();
if (theseDays != null) {
// ok, see if the day has changed
if (theseDays < daysToUse) {
// day moved backwards, we must be in a different month
if (monthToUse == 11) {
// hey, happy new year!
yearToUse++;
// set to January
monthToUse = 0;
} else {
// just increment to the next month
monthToUse++;
}
}
// ok use the new value of days
daysToUse = theseDays;
}
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1900 + yearToUse, monthToUse, daysToUse, hours, mins, 0);
cal.set(Calendar.MILLISECOND, 0);
dtg = new HiResDate(cal.getTime());
// stash the platform
platform = lastPlatform;
// and catch the rest of the text
text = trimmed.substring(dateStr.length()).trim();
final String startOfLine = text.substring(0, Math.min(20, text.length() - 1));
final String trackNum = FCSEntry.parseTrack(startOfLine);
if (trackNum != null) {
type = "FCS";
} else {
// explain we don't know what type of comment this is
type = "N/A";
}
// try to replace soft returns with hard returns
text = text.replace("\r", "\n");
// remember what's happening, so we can refer back to previous entries
lastDtg = new Date(dtg.getDate().getTime());
lastPlatform = platform;
lastEntry = this;
}
} else {
// hmm, see if it's just text. If it is, stick it on the end of the previous one
// ooh, it may be a next day marker. have a check
final DateFormat dtgBlock = new GMTDateFormat("dd MMM yy");
boolean hasDate = false;
try {
final Date scrapDate = dtgBlock.parse(trimmed);
hasDate = true;
// store the date, ready for successive lines
lastDtg = scrapDate;
// hey, maybe this is a data-file without any metadata
// give it a platform
if (lastPlatform == null) {
lastPlatform = NAME_NOT_PRESENT;
}
} catch (final ParseException e) {
// it's ok, we can silently fail
}
if (!hasDate) {
// ooh, do we have a previous one?
if (lastEntry != null) {
text = trimmed;
// now flag that we've just added ourselves to the previous one
appendedToPrevious = true;
}
}
}
}
}
}
/**
* helper that can ask the user a question
*
*/
public static interface QuestionHelper {
String askQuestion(final String title, final String message, final String defaultStr);
boolean askYes(final String title, final String message);
void showMessage(final String title, final String message);
void showMessageWithLogButton(String title, String message);
}
public static class TestImportWord extends TestCase {
private final static String dummy_doc_path = "../org.mwc.cmap.combined.feature/root_installs/sample_data/other_formats/test_narrative.doc";
private final static String valid_doc_path = "../org.mwc.cmap.combined.feature/root_installs/sample_data/other_formats/FCS_narrative.doc";
private final static String no_metadata_path = "../org.mwc.cmap.combined.feature/root_installs/sample_data/other_formats/FCS_narrative_no_metadata.doc";
private final static String ownship_track = "../org.mwc.cmap.combined.feature/root_installs/sample_data/boat1.rep";
private final static String ownship_track_test = "../org.mwc.cmap.combined.feature/root_installs/sample_data/boattest.rep";
private final static TrimNarrativeHelper only_in_period = new TrimNarrativeHelper() {
@Override
public NarrativeHelperRetVal findWhatToImport(final Map<String, Integer> narrativeTypes) {
final NarrativeHelperRetVal retVal = new NarrativeHelperRetVal();
retVal.narrativeEnum = ImportNarrativeEnum.TRIMMED_DATA;
// retVal.selectedNarrativeTypes =
// (List<String>)Arrays.asList(narrativeTypes.keySet().toArray(new
// String[narrativeTypes.size()]));
return retVal;
}
};
private final static TrimNarrativeHelper only_selected_types = new TrimNarrativeHelper() {
@Override
public NarrativeHelperRetVal findWhatToImport(final Map<String, Integer> narrativeTypes) {
final NarrativeHelperRetVal retVal = new NarrativeHelperRetVal();
retVal.narrativeEnum = ImportNarrativeEnum.ALL_DATA;
retVal.selectedNarrativeTypes = new ArrayList<>();
retVal.selectedNarrativeTypes.add("CAT COMMENT");
return retVal;
}
};
private final static TrimNarrativeHelper only_selected_trimmed_data_types = new TrimNarrativeHelper() {
@Override
public NarrativeHelperRetVal findWhatToImport(final Map<String, Integer> narrativeTypes) {
final NarrativeHelperRetVal retVal = new NarrativeHelperRetVal();
retVal.narrativeEnum = ImportNarrativeEnum.TRIMMED_DATA;
retVal.selectedNarrativeTypes = new ArrayList<>();
retVal.selectedNarrativeTypes.add("OOW COMMENT");
return retVal;
}
};
private final static TrimNarrativeHelper allow_all = new TrimNarrativeHelper() {
@Override
public NarrativeHelperRetVal findWhatToImport(final Map<String, Integer> narrativeTypes) {
final NarrativeHelperRetVal retVal = new NarrativeHelperRetVal();
retVal.narrativeEnum = ImportNarrativeEnum.ALL_DATA;
// retVal.selectedNarrativeTypes =
// (List<String>)Arrays.asList(narrativeTypes.keySet().toArray(new
// String[narrativeTypes.size()]));
return retVal;
}
};
private final static TrimNarrativeHelper cancelled_import = new TrimNarrativeHelper() {
@Override
public NarrativeHelperRetVal findWhatToImport(final Map<String, Integer> narrativeTypes) {
final NarrativeHelperRetVal retVal = new NarrativeHelperRetVal();
retVal.narrativeEnum = ImportNarrativeEnum.CANCEL;
return retVal;
}
};
public static int countLines(final String str) {
if (str == null || str.isEmpty()) {
return 0;
}
int lines = 1;
int pos = 0;
while ((pos = str.indexOf("\n", pos) + 1) != 0) {
lines++;
}
return lines;
}
private static ArrayList<String> getNarrativeStringsNoMetadata() {
final ArrayList<String> res = new ArrayList<String>();
// start with some track data
res.add("irrelevant preamble 1");
res.add("irrelevant preamble 2");
res.add("31 Dec 1995");
res.add("310504 SR023 SOURCE_A FCS B-123 R-5.1kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.");
res.add("irrelevant preamble 3");
res.add("irrelevant preamble 4");
res.add("01 Jan 1996");
res.add("010505 SR023 SOURCE_A FCS B-123 R-5.1kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.");
res.add("010506 irrelevant content 1");
res.add("010507 SR023 SOURCE_B FCS (AAAA) B-123 R-5kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.");
res.add("010508 irrelevant content 2");
res.add("010509 SR023 SOURCE_B FCS (AAAA) B-123 R-800yds C-321 S-6kts AAAAAAA. Classified AAAAAA \r BBBBBB AAAAAA.");
res.add("010608");
res.add("irrelevant postamble 3");
res.add("irrelevant postamble 4");
return res;
}
private static String[] getTrackStrings() {
final ArrayList<String> res = new ArrayList<String>();
res.add("960101 050000.000 NELSON @C 22 11 10.63 N 21 41 52.37 W 269.7 2.0 0\n");
res.add("960101 050100.000 NELSON @C 22 11 10.58 N 21 42 2.98 W 269.7 2.0 0\n");
res.add("960101 050200.000 NELSON @C 22 11 10.51 N 21 42 14.81 W 269.9 2.0 0\n");
res.add("960101 050300.000 NELSON @C 22 11 10.51 N 21 42 27.27 W 268.7 2.0 0\n");
res.add("960101 050400.000 NELSON @C 22 11 10.28 N 21 42 40.33 W 270.6 2.0 0\n");
res.add("960101 053500.000 NELSON @C 22 11 10.39 N 21 42 53.47 W 269.4 2.0 0 \n");
res.add("960101 053600.000 NELSON @C 22 11 10.26 N 21 43 6.79 W 269.0 2.0 0 \n");
res.add("960101 053700.000 NELSON @C 22 11 10.08 N 21 43 20.34 W 270.5 2.0 0 \n");
res.add("960101 054800.000 NELSON @C 22 11 10.18 N 21 43 33.68 W 269.9 2.0 0 \n");
res.add("960101 055900.000 NELSON @C 22 11 10.19 N 21 43 47.26 W 268.6 2.0 0\n");
return res.toArray(new String[] {});
}
private static StringBuilder strArrayToStream(final String[] track) {
final StringBuilder sb = new StringBuilder();
for (final String s : track) {
sb.append(s);
}
return sb;
}
public static void testAddFCSToHiddenTrack() throws InterruptedException, IOException {
final Layers tLayers = new Layers();
// start off with the ownship track
final File boatFile = new File(ownship_track);
assertTrue(boatFile.exists());
final InputStream bs = new FileInputStream(boatFile);
final ImportReplay trackImporter = new ImportReplay();
ImportReplay.initialise(new ImportReplay.testImport.TestParent(ImportReplay.IMPORT_AS_OTG, 0L));
trackImporter.importThis(ownship_track, bs, tLayers);
assertEquals("read in track", 1, tLayers.size());
// ok, now filter it to a time period
final TrackWrapper track = (TrackWrapper) tLayers.elementAt(0);
// filter the list to a period of data after the narrative cuts
track.filterListTo(new HiResDate(818749200000L), new HiResDate(818766600000L));
// now load the FCS data
final String testFile = valid_doc_path;
final File testI = new File(testFile);
assertTrue(testI.exists());
final InputStream is = new FileInputStream(testI);
final ImportNarrativeDocument importer = new ImportNarrativeDocument(tLayers);
final HWPFDocument doc = new HWPFDocument(is);
final ArrayList<String> strings = importFromWord(doc);
importer.processThese(strings);
// hmmm, how many tracks
assertEquals("got new tracks", 3, tLayers.size());
final NarrativeWrapper narrLayer = (NarrativeWrapper) tLayers.findLayer(LayerHandler.NARRATIVE_LAYER);
// correct final count
assertEquals("Got num lines", 364, narrLayer.size());
final BaseLayer fcsLayer = (BaseLayer) tLayers.findLayer(NARR_LAYER);
final Object[] solutions = fcsLayer.getData().toArray();
// hey, let's have a look them
LightweightTrackWrapper tw = (LightweightTrackWrapper) solutions[5];
assertEquals("correct name", "M01_AAAA AAAA AAA (BBBB)", tw.getName());
assertEquals("got fixes", 3, tw.numFixes());
// hey, let's have a look them
tw = (LightweightTrackWrapper) solutions[2];
assertEquals("correct name", "025_AAAA AAAA AAA (AAAA)", tw.getName());
assertEquals("got fixes", 5, tw.numFixes());
// we need to introduce a 500ms delay, so we don't use
// the cahced visible period
Thread.sleep(550);
final TimePeriod bounds = tw.getVisiblePeriod();
// in our sample data we have several FCSs at the same time,
// so we have to increment the DTG (seconds) on successive points.
// so,the dataset should end at 08:11:01 - since the last point
// had a second added.
assertEquals("correct bounds:", "Period:951212 080800 to 951212 081400", bounds.toString());
// hey, let's have a look tthem
final BaseLayer fcsNarr = (BaseLayer) tLayers.findLayer(NARR_LAYER);
final Object[] data = fcsNarr.getData().toArray();
tw = (LightweightTrackWrapper) data[3];
assertEquals("correct name", "027_AAAA AAAA AAA (AAAA)", tw.getName());
assertEquals("got fixes", 3, tw.numFixes());
}
public static void testAddFCSToTrack() throws InterruptedException, IOException {
final Layers tLayers = new Layers();
// start off with the ownship track
final File boatFile = new File(ownship_track);
assertTrue(boatFile.exists());
final InputStream bs = new FileInputStream(boatFile);
final ImportReplay trackImporter = new ImportReplay();
ImportReplay.initialise(new ImportReplay.testImport.TestParent(ImportReplay.IMPORT_AS_OTG, 0L));
trackImporter.importThis(ownship_track, bs, tLayers);
assertEquals("read in track", 1, tLayers.size());
final String testFile = valid_doc_path;
final File testI = new File(testFile);
assertTrue(testI.exists());
final InputStream is = new FileInputStream(testI);
final ImportNarrativeDocument importer = new ImportNarrativeDocument(tLayers);
final HWPFDocument doc = new HWPFDocument(is);
final ArrayList<String> strings = importFromWord(doc);
importer.processThese(strings);
// hmmm, how many tracks
assertEquals("got new tracks", 3, tLayers.size());
final NarrativeWrapper narrLayer = (NarrativeWrapper) tLayers.findLayer(LayerHandler.NARRATIVE_LAYER);
// correct final count
assertEquals("Got num lines", 364, narrLayer.size());
final BaseLayer sols = (BaseLayer) tLayers.findLayer(NARR_LAYER);
final Object[] data = sols.getData().toArray();
// hey, let's have a look them
LightweightTrackWrapper tw = (LightweightTrackWrapper) data[5];
assertEquals("correct name", "M01_AAAA AAAA AAA (BBBB)", tw.getName());
assertEquals("got fixes", 3, tw.numFixes());
// hey, let's have a look them
tw = (LightweightTrackWrapper) data[2];
assertEquals("correct name", "025_AAAA AAAA AAA (AAAA)", tw.getName());
assertEquals("got fixes", 5, tw.numFixes());
// we need to introduce a 500ms delay, so we don't use
// the cahced visible period
Thread.sleep(550);
final TimePeriod bounds = tw.getVisiblePeriod();
// in our sample data we have several FCSs at the same time,
// so we have to increment the DTG (seconds) on successive points.
// so,the dataset should end at 08:11:01 - since the last point
// had a second added.
assertEquals("correct bounds:", "Period:951212 080800 to 951212 081400", bounds.toString());
// hey, let's have a look tthem
tw = (LightweightTrackWrapper) data[3];
assertEquals("correct name", "027_AAAA AAAA AAA (AAAA)", tw.getName());
assertEquals("got fixes", 3, tw.numFixes());
}
public static void testAdvancedParseBulkFCS() throws ParseException {
final String str1 = "160504,16,08,2016,NONSUCH,FCS, SR023 SOURCE_A FCS B-123 R-5.1kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.";
final String str1a = "160504,16,08,2016,NONSUCH,FCS, SR023 SOURCE_B FCS (AAAA) B-123 R-5kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.";
final String str2 = "160504,16,08,2016,NONSUCH,FCS, SR023 SOURCE_B FCS (AAAA) B-123 R-800yds C-321 S-6kts AAAAAAA. Classified AAAAAA \r BBBBBB AAAAAA.";
final String str3 = "160504,16,08,2016,NONSUCH,FCS, SR023 SOURCE_A FCS B-123 R-800 m C-321 S-6kts AAAAAAA. Classified AAAAAA \nBBBBBB AAAAAA.";
final String str4 = "160504,16,08,2016,NONSUCH,FCS, SV023 SOURCE_A FCS B-311\u00b0 R-12.4kyds. Classified AAAAAA CCCCCC AAAAAA.";
// create mock importer
final String[] strings = new String[] { str1, str1a, str2, str3, str4 };
final ArrayList<String> strList = new ArrayList<String>(Arrays.asList(strings));
final Layers target = new Layers();
// create the ownship track
final TrackWrapper nonsuch = new TrackWrapper();
nonsuch.setName("NONSUCH");
// we also need fixes covering this period
final SimpleDateFormat df = new GMTDateFormat("MM/dd/yyyy HH:mm:ss");
final HiResDate hd1 = new HiResDate(df.parse("08/16/2016 03:00:00"));
final HiResDate hd2 = new HiResDate(df.parse("08/16/2016 08:00:00"));
final WorldLocation loc1 = new WorldLocation(1, 1, 0);
final WorldLocation loc2 = new WorldLocation(2, 2, 0);
final Fix fx1 = new Fix(hd1, loc1, 12d, 5);
final Fix fx2 = new Fix(hd2, loc2, 12d, 5);
nonsuch.addFix(new FixWrapper(fx1));
nonsuch.addFix(new FixWrapper(fx2));
target.addThisLayer(nonsuch);
final ImportNarrativeDocument importer = new ImportNarrativeDocument(target);
assertEquals("one track", 1, target.size());
importer.processThese(strList);
// check we have two tracks
assertEquals("all tracks", 3, target.size());
// check the size
final Layer t2 = target.elementAt(2);
// check t2 is narratives
assertEquals("correct name", NARR_LAYER, t2.getName());
final BaseLayer layer = (BaseLayer) t2;
final Editable sol1 = layer.first();
assertEquals("correct name", "023_SOURCE_A FCS", sol1.getName());
final Editable sol2 = layer.last();
assertEquals("correct name", "023_SOURCE_A FCS", sol1.getName());
assertEquals("correct name", "023_SOURCE_B FCS (AAAA)", sol2.getName());
// check zero depth in target track
final LightweightTrackWrapper light = (LightweightTrackWrapper) sol2;
final FixWrapper first = (FixWrapper) light.getPositionIterator().nextElement();
assertEquals("fix has zero depth", 0d, first.getDepth(), 0.0001);
}
public static void testAdvancedParseFCS() throws ParseException {
final String str1 = " SR023 SOURCE_A FCS B-123 R-5.1kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.";
final String str2 = "SR023 1936 GAINED FCS (AAAA) B-123 R-5kyds C-321 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.";
final String str3 = "M01 AAAA AAAA AAA (AAAA) B-173 R-3.7kyds C-271 S-6kts AAAAAAA. Classified AAAAAA BBBBBB AAAAAA.";
// high level test of extracting source
final String match1 = FCSEntry.parseSource(str1);
assertEquals("got source", "SOURCE_A FCS", match1);