/
Publisher.java
6423 lines (5785 loc) · 269 KB
/
Publisher.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
package org.hl7.fhir.igtools.publisher;
/*-
* #%L
* org.hl7.fhir.publisher.core
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.awt.EventQueue;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.UIManager;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.codec.Charsets;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.SystemUtils;
import org.hl7.fhir.convertors.IGR2ConvertorAdvisor;
import org.hl7.fhir.convertors.R2016MayToR4Loader;
import org.hl7.fhir.convertors.R2016MayToR5Loader;
import org.hl7.fhir.convertors.R2ToR4Loader;
import org.hl7.fhir.convertors.R2ToR5Loader;
import org.hl7.fhir.convertors.R3ToR4Loader;
import org.hl7.fhir.convertors.R3ToR5Loader;
import org.hl7.fhir.convertors.R4ToR5Loader;
import org.hl7.fhir.convertors.TerminologyClientFactory;
import org.hl7.fhir.convertors.VersionConvertorAdvisor40;
import org.hl7.fhir.convertors.VersionConvertorAdvisor50;
import org.hl7.fhir.convertors.VersionConvertor_10_40;
import org.hl7.fhir.convertors.VersionConvertor_10_50;
import org.hl7.fhir.convertors.VersionConvertor_14_30;
import org.hl7.fhir.convertors.VersionConvertor_14_40;
import org.hl7.fhir.convertors.VersionConvertor_14_50;
import org.hl7.fhir.convertors.VersionConvertor_30_40;
import org.hl7.fhir.convertors.VersionConvertor_30_50;
import org.hl7.fhir.convertors.VersionConvertor_40_50;
import org.hl7.fhir.exceptions.DefinitionException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.exceptions.PathEngineException;
import org.hl7.fhir.igtools.publisher.FetchedFile.FetchedBundleType;
import org.hl7.fhir.igtools.publisher.IFetchFile.FetchState;
import org.hl7.fhir.igtools.publisher.Publisher.ListItemEntry;
import org.hl7.fhir.igtools.publisher.Publisher.ListViewSorterById;
import org.hl7.fhir.igtools.publisher.utils.IGRegistryMaintainer;
import org.hl7.fhir.igtools.publisher.utils.IGReleaseUpdater;
import org.hl7.fhir.igtools.publisher.utils.IGReleaseUpdater.ServerType;
import org.hl7.fhir.igtools.publisher.utils.IGReleaseVersionDeleter;
import org.hl7.fhir.igtools.renderers.BaseRenderer;
import org.hl7.fhir.igtools.renderers.CodeSystemRenderer;
import org.hl7.fhir.igtools.renderers.JsonXhtmlRenderer;
import org.hl7.fhir.igtools.renderers.StructureDefinitionRenderer;
import org.hl7.fhir.igtools.renderers.StructureMapRenderer;
import org.hl7.fhir.igtools.renderers.ValidationPresenter;
import org.hl7.fhir.igtools.renderers.ValueSetRenderer;
import org.hl7.fhir.igtools.renderers.XmlXHtmlRenderer;
import org.hl7.fhir.igtools.spreadsheets.IgSpreadsheetParser;
import org.hl7.fhir.igtools.templates.Template;
import org.hl7.fhir.igtools.templates.TemplateManager;
import org.hl7.fhir.igtools.ui.GraphicalPublisher;
import org.hl7.fhir.r4.formats.FormatUtilities;
import org.hl7.fhir.r5.conformance.ConstraintJavaGenerator;
import org.hl7.fhir.r5.conformance.ProfileUtilities;
import org.hl7.fhir.r5.context.IWorkerContext;
import org.hl7.fhir.r5.context.IWorkerContext.ILoggingService;
import org.hl7.fhir.r5.context.IWorkerContext.ValidationResult;
import org.hl7.fhir.r5.context.SimpleWorkerContext;
import org.hl7.fhir.r5.elementmodel.Element;
import org.hl7.fhir.r5.elementmodel.Manager.FhirFormat;
import org.hl7.fhir.r5.elementmodel.ObjectConverter;
import org.hl7.fhir.r5.elementmodel.ParserBase.ValidationPolicy;
import org.hl7.fhir.r5.elementmodel.TurtleParser;
import org.hl7.fhir.r5.formats.IParser.OutputStyle;
import org.hl7.fhir.r5.formats.JsonParser;
import org.hl7.fhir.r5.formats.XmlParser;
import org.hl7.fhir.r5.model.Base;
import org.hl7.fhir.r5.model.Bundle;
import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r5.model.Bundle.BundleType;
import org.hl7.fhir.r5.model.CapabilityStatement;
import org.hl7.fhir.r5.model.CodeSystem;
import org.hl7.fhir.r5.model.CodeableConcept;
import org.hl7.fhir.r5.model.Coding;
import org.hl7.fhir.r5.model.ConceptMap;
import org.hl7.fhir.r5.model.Constants;
import org.hl7.fhir.r5.model.ContactDetail;
import org.hl7.fhir.r5.model.ContactPoint;
import org.hl7.fhir.r5.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.r5.model.DateTimeType;
import org.hl7.fhir.r5.model.DomainResource;
import org.hl7.fhir.r5.model.ElementDefinition;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent;
import org.hl7.fhir.r5.model.Enumeration;
import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
import org.hl7.fhir.r5.model.Enumerations.PublicationStatus;
import org.hl7.fhir.r5.model.ExpressionNode;
import org.hl7.fhir.r5.model.Extension;
import org.hl7.fhir.r5.model.FhirPublication;
import org.hl7.fhir.r5.model.ImplementationGuide;
import org.hl7.fhir.r5.model.ImplementationGuide.GuidePageGeneration;
import org.hl7.fhir.r5.model.ImplementationGuide.GuideParameterCode;
import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionGroupingComponent;
import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionPageComponent;
import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionParameterComponent;
import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDefinitionResourceComponent;
import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDependsOnComponent;
import org.hl7.fhir.r5.model.ImplementationGuide.SPDXLicense;
import org.hl7.fhir.r5.model.ListResource;
import org.hl7.fhir.r5.model.ListResource.ListEntryComponent;
import org.hl7.fhir.r5.model.MetadataResource;
import org.hl7.fhir.r5.model.Parameters;
import org.hl7.fhir.r5.model.PrimitiveType;
import org.hl7.fhir.r5.model.Reference;
import org.hl7.fhir.r5.model.Resource;
import org.hl7.fhir.r5.model.ResourceFactory;
import org.hl7.fhir.r5.model.ResourceType;
import org.hl7.fhir.r5.model.StringType;
import org.hl7.fhir.r5.model.StructureDefinition;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionContextComponent;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.r5.model.StructureMap;
import org.hl7.fhir.r5.model.StructureMap.StructureMapModelMode;
import org.hl7.fhir.r5.model.StructureMap.StructureMapStructureComponent;
import org.hl7.fhir.r5.model.TypeDetails;
import org.hl7.fhir.r5.model.UriType;
import org.hl7.fhir.r5.model.ValueSet;
import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
import org.hl7.fhir.r5.openapi.OpenApiGenerator;
import org.hl7.fhir.r5.openapi.Writer;
import org.hl7.fhir.r5.terminologies.TerminologyServiceOptions;
import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
import org.hl7.fhir.r5.test.utils.ToolsHelper;
import org.hl7.fhir.r5.utils.EOperationOutcome;
import org.hl7.fhir.r5.utils.FHIRPathEngine;
import org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext;
import org.hl7.fhir.r5.utils.IGHelper;
import org.hl7.fhir.r5.utils.IResourceValidator;
import org.hl7.fhir.r5.utils.LiquidEngine;
import org.hl7.fhir.r5.utils.NPMPackageGenerator;
import org.hl7.fhir.r5.utils.NPMPackageGenerator.Category;
import org.hl7.fhir.r5.utils.NarrativeGenerator;
import org.hl7.fhir.r5.utils.NarrativeGenerator.ILiquidTemplateProvider;
import org.hl7.fhir.r5.utils.NarrativeGenerator.IReferenceResolver;
import org.hl7.fhir.r5.utils.NarrativeGenerator.ITypeParser;
import org.hl7.fhir.r5.utils.NarrativeGenerator.ResourceWithReference;
import org.hl7.fhir.r5.utils.StructureMapUtilities;
import org.hl7.fhir.r5.utils.StructureMapUtilities.StructureMapAnalysis;
import org.hl7.fhir.r5.utils.ToolingExtensions;
import org.hl7.fhir.r5.utils.client.FHIRToolingClient;
import org.hl7.fhir.r5.utils.formats.Turtle;
import org.hl7.fhir.r5.validation.CodeSystemValidator;
import org.hl7.fhir.r5.validation.InstanceValidator;
import org.hl7.fhir.r5.validation.ProfileValidator;
import org.hl7.fhir.utilities.CSFile;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.IniFile;
import org.hl7.fhir.utilities.JsonMerger;
import org.hl7.fhir.utilities.MarkDownProcessor;
import org.hl7.fhir.utilities.MarkDownProcessor.Dialect;
import org.hl7.fhir.utilities.StandardsStatus;
import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.VersionUtil;
import org.hl7.fhir.utilities.ZipGenerator;
import org.hl7.fhir.utilities.cache.NpmPackage;
import org.hl7.fhir.utilities.cache.PackageCacheManager;
import org.hl7.fhir.utilities.cache.PackageGenerator.PackageType;
import org.hl7.fhir.utilities.json.JSONUtil;
import org.hl7.fhir.utilities.json.JsonTrackingParser;
import org.hl7.fhir.utilities.cache.ToolsVersion;
import org.hl7.fhir.utilities.validation.ValidationMessage;
import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
import org.hl7.fhir.utilities.validation.ValidationMessage.Source;
import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* Implementation Guide Publisher
*
* If you want to use this inside a FHIR server, and not to access content
* on a local folder, provide your own implementation of the file fetcher
*
* rough sequence of activities:
*
* load the context using the internal validation pack
* connect to the terminology service
*
* parse the implementation guide
* find all the source files and determine the resource type
* load resources in this order:
* naming system
* code system
* value set
* data element?
* structure definition
* concept map
* structure map
*
* validate all source files (including the IG itself)
*
* for each source file:
* generate all outputs
*
* generate summary file
*
* Documentation: see http://wiki.hl7.org/index.php?title=IG_Publisher_Documentation
*
* @author Grahame Grieve
*
*/
public class Publisher implements IWorkerContext.ILoggingService, IReferenceResolver {
public class IGPublisherHostServices implements IEvaluationContext {
@Override
public Base resolveConstant(Object appContext, String name, boolean beforeContext) throws PathEngineException {
// if ("id".equals(name))
return null;
// throw new NotImplementedException("Not done yet @ IGPublisherHostServices.resolveConstant("+appContext.toString()+", \""+name+"\")");
}
@Override
public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException {
throw new NotImplementedException("Not done yet (IGPublisherHostServices.resolveConstantType)");
}
@Override
public boolean log(String argument, List<Base> focus) {
return false;
}
@Override
public FunctionDetails resolveFunction(String functionName) {
throw new NotImplementedException("Not done yet (IGPublisherHostServices.resolveFunction)");
}
@Override
public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException {
throw new NotImplementedException("Not done yet (IGPublisherHostServices.checkFunction)");
}
@Override
public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters) {
throw new NotImplementedException("Not done yet (IGPublisherHostServices.executeFunction)");
}
@Override
public Base resolveReference(Object appContext, String url) {
if (appContext instanceof Element) {
Element bnd = (Element) appContext;
if (bnd.fhirType().equals("Bundle")) {
for (Element be : bnd.getChildrenByName("entry")) {
Element res = be.getNamedChild("resource");
if (res != null) {
String fullUrl = be.getChildValue("fullUrl");
String rt = res.fhirType();
String id = res.getChildValue("id");
if (url.equals(fullUrl))
return res;
if (url.equals(rt+"/"+id))
return res;
}
}
}
}
if (Utilities.isAbsoluteUrl(url)) {
if (url.startsWith(igpkp.getCanonical())) {
url = url.substring(igpkp.getCanonical().length());
if (url.startsWith("/"))
url = url.substring(1);
} else
return null;;
}
for (FetchedFile f : fileList) {
for (FetchedResource r : f.getResources()) {
if (r.getElement() != null && url.equals(r.getElement().fhirType()+"/"+r.getId()))
return r.getElement();
}
}
return null;
}
@Override
public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException {
IResourceValidator val = context.newValidator();
List<ValidationMessage> valerrors = new ArrayList<ValidationMessage>();
if (item instanceof Resource) {
val.validate(appContext, valerrors, (Resource) item, url);
boolean ok = true;
for (ValidationMessage v : valerrors)
ok = ok && v.getLevel().isError();
return ok;
}
throw new NotImplementedException("Not done yet (IGPublisherHostServices.conformsToProfile), when item is element");
}
}
public class TypeParserR2 implements ITypeParser {
@Override
public Base parseType(String xml, String type) throws IOException, FHIRException {
org.hl7.fhir.dstu2.model.Type t = new org.hl7.fhir.dstu2.formats.XmlParser().parseType(xml, type);
return new VersionConvertor_10_50(null).convertType(t);
}
}
public class TypeParserR14 implements ITypeParser {
@Override
public Base parseType(String xml, String type) throws IOException, FHIRException {
org.hl7.fhir.dstu2016may.model.Type t = new org.hl7.fhir.dstu2016may.formats.XmlParser().parseType(xml, type);
return VersionConvertor_14_50.convertType(t);
}
}
public class TypeParserR3 implements ITypeParser {
@Override
public Base parseType(String xml, String type) throws IOException, FHIRException {
org.hl7.fhir.dstu3.model.Type t = new org.hl7.fhir.dstu3.formats.XmlParser().parseType(xml, type);
return VersionConvertor_30_50.convertType(t);
}
}
public class TypeParserR4 implements ITypeParser {
@Override
public Base parseType(String xml, String type) throws IOException, FHIRException {
org.hl7.fhir.r4.model.Type t = new org.hl7.fhir.r4.formats.XmlParser().parseType(xml, type);
return VersionConvertor_40_50.convertType(t);
}
}
public enum IGBuildMode { MANUAL, AUTOBUILD, WEBSERVER, PUBLICATION }
public enum LinkTargetType {
}
public enum CacheOption {
LEAVE, CLEAR_ERRORS, CLEAR_ALL;
}
public static final boolean USE_COMMONS_EXEC = true;
public enum GenerationTool {
Jekyll
}
private static final String IG_NAME = "!ig!";
private static final String REDIRECT_SOURCE = "<html>\r\n<head>\r\n<meta http-equiv=\"Refresh\" content=\"0; url=site/index.html\"/>\r\n</head>\r\n"+
"<body>\r\n<p>See here: <a href=\"site/index.html\">this link</a>.</p>\r\n</body>\r\n</html>\r\n";
private String configFile;
private String sourceDir;
private String destDir;
private FHIRToolingClient webTxServer;
private static String txServer = "http://tx.fhir.org";
// private static String txServer = "http://local.fhir.org:960";
private String igPack = "";
private boolean watch;
private boolean debug;
private boolean isChild;
private boolean cacheVersion;
private boolean appendTrailingSlashInDataFile;
private Publisher childPublisher = null;
private String childOutput = "";
private GenerationTool tool;
private boolean genExampleNarratives = true;
private List<String> resourceDirs = new ArrayList<String>();
private List<String> pagesDirs = new ArrayList<String>();
private String tempDir;
private String outputDir;
private String specPath;
private String qaDir;
private String version;
private List<String> suppressedMessages = new ArrayList<String>();
private String igName;
private IGBuildMode mode; // for the IG publication infrastructure
private IFetchFile fetcher = new SimpleFetcher(this);
private SimpleWorkerContext context; //
private InstanceValidator validator;
private ProfileValidator pvalidator;
private CodeSystemValidator csvalidator;
private IGKnowledgeProvider igpkp;
private List<SpecMapManager> specMaps = new ArrayList<SpecMapManager>();
private boolean first;
private Map<String, SpecificationPackage> specifications;
private Map<ImplementationGuideDefinitionResourceComponent, FetchedFile> fileMap = new HashMap<ImplementationGuideDefinitionResourceComponent, FetchedFile>();
private Map<String, FetchedFile> altMap = new HashMap<String, FetchedFile>();
private List<FetchedFile> fileList = new ArrayList<FetchedFile>();
private List<FetchedFile> changeList = new ArrayList<FetchedFile>();
private List<String> fileNames = new ArrayList<String>();
private Map<String, FetchedFile> relativeNames = new HashMap<String, FetchedFile>();
private Set<String> bndIds = new HashSet<String>();
private List<Resource> loaded = new ArrayList<Resource>();
private ImplementationGuide sourceIg;
private ImplementationGuide publishedIg;
private List<ValidationMessage> errors = new ArrayList<ValidationMessage>();
private Calendar execTime = Calendar.getInstance();
private Set<String> otherFilesStartup = new HashSet<String>();
private Set<String> otherFilesRun = new HashSet<String>();
private Set<String> regenList = new HashSet<String>();
private StringBuilder filelog;
private Set<String> allOutputs = new HashSet<String>();
private Set<FetchedResource> examples = new HashSet<FetchedResource>();
private HashMap<String, FetchedResource> resources = new HashMap<String, FetchedResource>();
private HashMap<String, ImplementationGuideDefinitionPageComponent> igPages = new HashMap<String, ImplementationGuideDefinitionPageComponent>();
private List<String> logOptions = new ArrayList<String>();
private List<String> listedURLExemptions = new ArrayList<String>();
private String jekyllCommand = "jekyll";
private boolean makeQA = true;
private long globalStart;
private ILoggingService logger = this;
private HTLMLInspector inspector;
private List<String> prePagesDirs = new ArrayList<String>();
private HashMap<String, PreProcessInfo> preProcessInfo = new HashMap<String, PreProcessInfo>();
private String historyPage;
private String vsCache;
private String adHocTmpDir;
private NarrativeGenerator gen;
private String businessVersion;
private CacheOption cacheOption;
private List<CodeableConcept> jurisdictions;
private String configFileRootPath;
private MarkDownProcessor markdownEngine;
private List<ValueSet> expansions = new ArrayList<>();
private String npmName;
private NPMPackageGenerator npm;
private PackageCacheManager pcm;
private JsonArray buildInfo;
private TemplateManager templateManager;
private String rootDir;
private String templatePck;
private boolean templateLoaded ;
private String packagesFolder;
private String targetOutput;
private String targetOutputNested;
private String folderToDelete;
private String specifiedVersion;
private NpmPackage packge;
private String txLog;
private boolean includeHeadings;
private String openApiTemplate;
private Map<String, String> extraTemplates = new HashMap<>();
private String license;
private String htmlTemplate;
private String mdTemplate;
private boolean brokenLinksError;
private String nestedIgConfig;
private String igArtifactsPage;
private String nestedIgOutput;
private boolean genExamples;
private boolean doTransforms;
private List<String> spreadsheets = new ArrayList<>();
private List<String> bundles = new ArrayList<>();
private IGPublisherLiquidTemplateServices templateProvider;
private List<NpmPackage> npmList = new ArrayList<>();
private String repoRoot;
private ValidationServices validationFetcher;
private Template template;
private boolean igMode;
private boolean isBuildingTemplate;
private JsonObject templateInfo;
private ExtensionTracker extensionTracker;
private class PreProcessInfo {
private String xsltName;
private byte[] xslt;
private String relativePath;
public PreProcessInfo(String xsltName, String relativePath) throws IOException {
this.xsltName = xsltName;
if (xsltName!=null)
this.xslt = TextFile.fileToBytes(xsltName);
this.relativePath = relativePath;
}
public boolean hasXslt() {
return xslt!=null;
}
public byte[] getXslt() {
return xslt;
}
public boolean hasRelativePath() {
return relativePath != null && !relativePath.isEmpty();
}
public String getRelativePath() {
return relativePath;
}
}
public void execute() throws Exception {
globalStart = System.nanoTime();
initialize();
if (isBuildingTemplate) {
packageTemplate();
} else {
log("Load Content");
try {
createIg();
} catch (Exception e) {
recordOutcome(e, null);
throw e;
}
if (watch) {
first = false;
log("Watching for changes on a 5sec cycle");
while (watch) { // terminated externally
Thread.sleep(5000);
if (load()) {
log("Processing changes to "+Integer.toString(changeList.size())+(changeList.size() == 1 ? " file" : " files")+" @ "+genTime());
long startTime = System.nanoTime();
loadConformance();
generateNarratives();
checkDependencies();
validate();
generate();
clean();
long endTime = System.nanoTime();
processTxLog(Utilities.path(destDir != null ? destDir : outputDir, "qa-tx.html"));
ValidationPresenter val = new ValidationPresenter(version, businessVersion, igpkp, childPublisher == null? null : childPublisher.getIgpkp(), outputDir, npmName, childPublisher == null? null : childPublisher.npmName,
new BallotChecker(repoRoot).check(igpkp.getCanonical(), npmName, businessVersion, historyPage, version), VersionUtil.getVersionString());
log("Finished. "+presentDuration(endTime - startTime)+". Validation output in "+val.generate(sourceIg.getName(), errors, fileList, Utilities.path(destDir != null ? destDir : outputDir, "qa.html"), suppressedMessages));
recordOutcome(null, val);
}
}
} else
log("Done");
}
if (templateLoaded && new File(rootDir).exists())
Utilities.clearDirectory(Utilities.path(rootDir, "template"));
if (folderToDelete != null) {
try {
Utilities.clearDirectory(folderToDelete);
new File(folderToDelete).delete();
} catch (Throwable e) {
// nothing
}
}
}
private void packageTemplate() throws IOException {
Utilities.createDirectory(outputDir);
long startTime = System.nanoTime();
JsonObject j = new JsonObject();
j.addProperty("url", templateInfo.get("canonical").getAsString());
j.addProperty("package-id", templateInfo.get("name").getAsString());
j.addProperty("ig-ver", templateInfo.get("version").getAsString());
j.addProperty("date", new SimpleDateFormat("EEE, dd MMM, yyyy HH:mm:ss Z", new Locale("en", "US")).format(execTime.getTime()));
j.addProperty("version", Constants.VERSION);
j.addProperty("tool", Constants.VERSION+" ("+ToolsVersion.TOOLS_VERSION+")");
try {
File od = new File(outputDir);
FileUtils.cleanDirectory(od);
npm = new NPMPackageGenerator(Utilities.path(outputDir, "package.tgz"), templateInfo);
npm.loadFiles(rootDir, new File(rootDir), ".git", "output", "package");
npm.finish();
TextFile.stringToFile(makeTemplateIndexPage(), Utilities.path(outputDir, "index.html"));
TextFile.stringToFile(makeTemplateQAPage(), Utilities.path(outputDir, "qa.html"));
if (mode != IGBuildMode.AUTOBUILD) {
pcm.addPackageToCache(templateInfo.get("name").getAsString(), templateInfo.get("version").getAsString(), new FileInputStream(npm.filename()));
pcm.addPackageToCache(templateInfo.get("name").getAsString(), "dev", new FileInputStream(npm.filename()));
}
} catch (Exception e) {
e.printStackTrace();
j.addProperty("exception", e.getMessage());
}
long endTime = System.nanoTime();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(j);
TextFile.stringToFile(json, Utilities.path(outputDir, "qa.json"));
// registeringg the package locally
log("Finished. "+presentDuration(endTime - startTime)+". Output in "+outputDir);
}
private String makeTemplateIndexPage() {
String page = "<!DOCTYPE HTML><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"><head><title>Template Page</title></head><body><p><b>Template {{npm}}</b></p><p>You can <a href=\"package.tgz\">download the template</a>, though you should not need to; just refer to the template as {{npm}} in your IG configuration.</p></body></html>";
return page.replace("{{npm}}", templateInfo.get("name").getAsString());
}
private String makeTemplateQAPage() {
String page = "<!DOCTYPE HTML><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"><head><title>Template QA Page</title></head><body><p><b>Template {{npm}}</b></p><p>You can <a href=\"package.tgz\">download the template</a>, though you should not need to; just refer to the template as {{npm}} in your IG configuration.</p></body></html>";
return page.replace("{{npm}}", templateInfo.get("name").getAsString());
}
private void processTxLog(String path) throws FileNotFoundException, IOException {
if (txLog != null) {
String tx = TextFile.fileToString(txLog);
PrintStream f = new PrintStream(new FileOutputStream(path));
String title = "Terminology Server Log";
f.println("<html><head><title>"+title+"</title></head><body><h2>"+title+"</h2>");
f.print(tx);
f.println("</head></html>");
}
}
public void createIg() throws Exception, IOException, EOperationOutcome, FHIRException {
load();
long startTime = System.nanoTime();
log("Processing Conformance Resources");
loadConformance();
log("Generating Narratives");
generateNarratives();
log("Validating Resources");
try {
validate();
} catch (Exception ex){
log(ex.toString());
throw(ex);
}
log("Generating Outputs in "+outputDir);
generate();
long endTime = System.nanoTime();
clean();
ValidationPresenter val = new ValidationPresenter(version, businessVersion, igpkp, childPublisher == null? null : childPublisher.getIgpkp(), outputDir, npmName, childPublisher == null? null : childPublisher.npmName,
new BallotChecker(repoRoot).check(igpkp.getCanonical(), npmName, businessVersion, historyPage, version), VersionUtil.getVersionString());
if (isChild()) {
log("Finished. "+presentDuration(endTime - startTime));
} else {
processTxLog(Utilities.path(destDir != null ? destDir : outputDir, "qa-tx.html"));
log("Finished. "+presentDuration(endTime - startTime)+". Validation output in "+val.generate(sourceIg.getName(), errors, fileList, Utilities.path(destDir != null ? destDir : outputDir, "qa.html"), suppressedMessages));
}
recordOutcome(null, val);
}
private void recordOutcome(Exception ex, ValidationPresenter val) {
try {
JsonObject j = new JsonObject();
if (sourceIg != null) {
j.addProperty("url", sourceIg.getUrl());
j.addProperty("name", sourceIg.getName());
}
if (publishedIg != null && publishedIg.hasPackageId()) {
j.addProperty("package-id", publishedIg.getPackageId());
j.addProperty("ig-ver", publishedIg.getVersion());
}
j.addProperty("date", new SimpleDateFormat("EEE, dd MMM, yyyy HH:mm:ss Z", new Locale("en", "US")).format(execTime.getTime()));
if (val != null) {
j.addProperty("errs", val.getErr());
j.addProperty("warnings", val.getWarn());
j.addProperty("hints", val.getInfo());
}
if (ex != null)
j.addProperty("exception", ex.getMessage());
j.addProperty("version", version);
if (templatePck != null)
j.addProperty("template", templatePck);
j.addProperty("tool", Constants.VERSION+" ("+ToolsVersion.TOOLS_VERSION+")");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(j);
TextFile.stringToFile(json, Utilities.path(destDir != null ? destDir : outputDir, "qa.json"));
} catch (Exception e) {
// nothing at all
}
}
public CacheOption getCacheOption() {
return cacheOption;
}
public void setCacheOption(CacheOption cacheOption) {
this.cacheOption = cacheOption;
}
@Override
public ResourceWithReference resolve(String url) {
String[] parts = url.split("\\/");
if (parts.length != 2)
return null;
for (FetchedFile f : fileList) {
for (FetchedResource r : f.getResources()) {
if (r.getElement() != null && r.getElement().fhirType().equals(parts[0]) && r.getId().equals(parts[1])) {
String path = igpkp.getLinkFor(r);
return new ResourceWithReference(path, gen.new ResourceWrapperMetaElement(r.getElement()));
}
}
}
for (SpecMapManager sp : specMaps) {
String fp = sp.getBase()+"/"+url;
String path;
try {
path = sp.getPath(fp);
} catch (Exception e) {
path = null;
}
if (path != null)
return new ResourceWithReference(path, null);
}
return null;
}
private void generateNarratives() throws Exception {
dlog(LogCategory.PROGRESS, "gen narratives");
for (FetchedFile f : fileList) {
System.out.println(f.getName());
for (FetchedResource r : f.getResources()) {
if (r.getExampleUri()==null || genExampleNarratives) {
dlog(LogCategory.PROGRESS, "narrative for "+f.getName()+" : "+r.getId());
if (r.getResource() != null && isConvertableResource(r.getResource().fhirType())) {
boolean regen = false;
gen.setDefinitionsTarget(igpkp.getDefinitionsName(r));
if (r.getResource() instanceof DomainResource && !(((DomainResource) r.getResource()).hasText() && ((DomainResource) r.getResource()).getText().hasDiv()))
regen = gen.generate((DomainResource) r.getResource(), otherFilesStartup);
if (r.getResource() instanceof Bundle)
regen = gen.generate((Bundle) r.getResource(), false, otherFilesStartup);
if (regen)
r.setElement(convertToElement(r.getResource()));
} else {
if ("http://hl7.org/fhir/StructureDefinition/DomainResource".equals(r.getElement().getProperty().getStructure().getBaseDefinition()) && !hasNarrative(r.getElement())) {
gen.generate(r.getElement(), true, getTypeLoader(f,r));
} else if (r.getElement().fhirType().equals("Bundle")) {
for (Element e : r.getElement().getChildrenByName("entry")) {
Element res = e.getNamedChild("resource");
if (res!=null && "http://hl7.org/fhir/StructureDefinition/DomainResource".equals(res.getProperty().getStructure().getBaseDefinition()) && !hasNarrative(res)) {
gen.generate(gen.new ResourceContext(r.getElement(), res), res, true, getTypeLoader(f,r));
}
}
}
}
} else {
dlog(LogCategory.PROGRESS, "skipped narrative for "+f.getName()+" : "+r.getId());
}
}
}
}
private boolean isConvertableResource(String t) {
return Utilities.existsInList(t, "StructureDefinition", "ValueSet", "CodeSystem", "Conformance", "CapabilityStatement",
"ConceptMap", "OperationOutcome", "CompartmentDefinition", "OperationDefinition", "ImplementationGuide");
}
private ITypeParser getTypeLoader(FetchedFile f, FetchedResource r) throws Exception {
String ver = r.getConfig() == null ? null : ostr(r.getConfig(), "version");
if (ver == null)
ver = version; // fall back to global version
if (ver.equals("3.0.1") || ver.equals("3.0.0")) {
return new TypeParserR3();
} else if (ver.equals("4.0.0")) {
return new TypeParserR4();
} else if (ver.equals("1.4.0")) {
return new TypeParserR14();
} else if (ver.equals("1.0.2")) {
return new TypeParserR2();
} else if (ver.equals(Constants.VERSION)) {
return null;
} else
throw new FHIRException("Unsupported version "+ver);
}
private void log(LogCategory progress, String message) {
log(message);
}
private boolean hasNarrative(Element element) {
return element.hasChild("text") && element.getNamedChild("text").hasChild("div");
}
private void clean() throws Exception {
for (Resource r : loaded)
context.dropResource(r);
for (FetchedFile f : fileList)
f.dropSource();
if (destDir != null) {
if (!(new File(destDir).exists()))
Utilities.createDirectory(destDir);
Utilities.copyDirectory(outputDir, destDir, null);
}
}
private String genTime() {
return new SimpleDateFormat("EEE, MMM d, yyyy HH:mmZ", new Locale("en", "US")).format(execTime.getTime());
}
private String genDate() {
return new SimpleDateFormat("dd/MM/yyyy", new Locale("en", "US")).format(execTime.getTime());
}
private void checkDependencies() {
// first, we load all the direct dependency lists
for (FetchedFile f : fileList)
if (f.getDependencies() == null)
loadDependencyList(f);
// now, we keep adding to the change list till there's no change
boolean changed;
do {
changed = false;
for (FetchedFile f : fileList) {
if (!changeList.contains(f)) {
boolean dep = false;
for (FetchedFile d : f.getDependencies())
if (changeList.contains(d))
dep = true;
if (dep) {
changeList.add(f);
changed = true;
}
}
}
} while (changed);
}
private void loadDependencyList(FetchedFile f) {
f.setDependencies(new ArrayList<FetchedFile>());
for (FetchedResource r : f.getResources()) {
if (r.getElement().fhirType().equals("ValueSet"))
loadValueSetDependencies(f, r);
else if (r.getElement().fhirType().equals("StructureDefinition"))
loadProfileDependencies(f, r);
else
; // all other resource types don't have dependencies that we care about for rendering purposes
}
}
private void loadValueSetDependencies(FetchedFile f, FetchedResource r) {
ValueSet vs = (ValueSet) r.getResource();
for (ConceptSetComponent cc : vs.getCompose().getInclude()) {
for (UriType vsi : cc.getValueSet()) {
FetchedFile fi = getFileForUri(vsi.getValue());
if (fi != null)
f.getDependencies().add(fi);
}
}
for (ConceptSetComponent cc : vs.getCompose().getExclude()) {
for (UriType vsi : cc.getValueSet()) {
FetchedFile fi = getFileForUri(vsi.getValue());
if (fi != null)
f.getDependencies().add(fi);
}
}
for (ConceptSetComponent vsc : vs.getCompose().getInclude()) {
FetchedFile fi = getFileForUri(vsc.getSystem());
if (fi != null)
f.getDependencies().add(fi);
}
for (ConceptSetComponent vsc : vs.getCompose().getExclude()) {
FetchedFile fi = getFileForUri(vsc.getSystem());
if (fi != null)
f.getDependencies().add(fi);
}
}
private FetchedFile getFileForFile(String path) {
for (FetchedFile f : fileList) {
if (f.getPath().equals(path))
return f;
}
return null;
}
private FetchedFile getFileForUri(String uri) {
for (FetchedFile f : fileList) {
if (getResourceForUri(f, uri) != null)
return f;
}
return null;
}
private FetchedResource getResourceForUri(FetchedFile f, String uri) {
for (FetchedResource r : f.getResources()) {
if (r.getResource() != null && r.getResource() instanceof MetadataResource) {
MetadataResource bc = (MetadataResource) r.getResource();
if (bc.getUrl() != null && bc.getUrl().equals(uri))
return r;
}
}
return null;
}
private FetchedResource getResourceForRef(FetchedFile f, String ref) {
for (FetchedResource r : f.getResources()) {
if ((r.fhirType()+"/"+r.getId()).equals(ref))
return r;
}
for (FetchedFile f1 : fileList) {