-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathProgram.cs
1367 lines (1174 loc) · 49.2 KB
/
Program.cs
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
extern alias stu3;
extern alias r4;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using CsvHelper;
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Model;
using stu3::Hl7.Fhir.Rest;
using r4::Hl7.Fhir.Rest;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Specification.Source;
using stu3::Hl7.Fhir.Specification.Terminology;
using r4::Hl7.Fhir.Specification.Terminology;
using Hl7.Fhir.Utility;
using stu3::Hl7.Fhir.Validation;
using r4::Hl7.Fhir.Validation;
using Hl7.FhirPath;
using Qml.Net;
using Qml.Net.Runtimes;
using TextCopy;
using Task = System.Threading.Tasks.Task;
using System.Globalization;
using System.Net.Http;
using Newtonsoft.Json.Linq;
class Program
{
[Signal("validationStarted")]
[Signal("examplesLoaded")]
[Signal("updateAvailable", NetVariantType.String)]
public class AppModel : IDisposable
{
private static AppModel _instance;
public static AppModel Instance => _instance ?? (_instance = new AppModel());
public static bool HasInstance => _instance != null;
public AppModel()
{
_instance = this;
}
public void Dispose()
{
if (_validatorCancellationSource != null)
{
_validatorCancellationSource.Dispose();
_validatorCancellationSource = null;
}
GC.SuppressFinalize(this);
}
public enum ResourceFormat
{
Xml = 1,
Json = 2,
Unknown = 3
}
// this only gets populated on use, so it's OK to setup beforehand
private readonly Hl7.Fhir.Specification.Source.IResourceResolver _coreSourceStu3 = new Hl7.Fhir.Specification.Source.CachedResolver(new stu3.Hl7.Fhir.Specification.Source.ZipSource(Path.Combine(Extensions.GetApplicationLocation(), "specification_Fhir3_0.zip")));
private readonly Hl7.Fhir.Specification.Source.IResourceResolver _coreSourceR4 = new Hl7.Fhir.Specification.Source.CachedResolver(new r4.Hl7.Fhir.Specification.Source.ZipSource(Path.Combine(Extensions.GetApplicationLocation(), "specification_Fhir4_0.zip")));
private Hl7.Fhir.Specification.Source.IResourceResolver _combinedSource;
// ReSharper disable MemberCanBePrivate.Global
#region QML-accessible properties
private ResourceFormat _instanceFormat;
private string _validateButtonText = "Validate";
[NotifySignal]
public string ValidateButtonText
{
get => _validateButtonText;
set => this.SetProperty(ref _validateButtonText, value);
}
private string _applicationVersion = Assembly.GetEntryAssembly().GetName().Version.ToString();
[NotifySignal]
public string ApplicationVersion
{
get => _applicationVersion;
set => this.SetProperty(ref _applicationVersion, value);
}
private string _noJavaInstall = "No Java install detected - Java validator couldn't run. Would you like to install Java?";
[NotifySignal]
public string NoJavaInstall
{
get => _noJavaInstall;
set => this.SetProperty(ref _noJavaInstall, value);
}
private string _javaInstallLink = "https://adoptium.net/releases.html?variant=openjdk16&jvmVariant=hotspot";
[NotifySignal]
public string JavaInstallLink
{
get => _javaInstallLink;
set => this.SetProperty(ref _javaInstallLink, value);
}
private string _scopeDirectory;
[NotifySignal]
public string ScopeDirectory
{
get => _scopeDirectory;
set
{
_scopeDirectory = value;
this.ActivateProperty(x => x.ScopeDirectory);
if (_scopeDirectory == null)
{
return;
}
if (FhirVersion == "STU3")
{
var directorySource = new CachedResolver(
new stu3.Hl7.Fhir.Specification.Source.DirectorySource(_scopeDirectory, new stu3.Hl7.Fhir.Specification.Source.DirectorySourceSettings { IncludeSubDirectories = true }));
// Finally, we combine both sources, so we will find profiles both from the core zip as well as from the directory.
// By mentioning the directory source first, anything in the user directory will override what is in the core zip.
_combinedSource = new Hl7.Fhir.Specification.Source.MultiResolver(directorySource, _coreSourceStu3);
}
else
{
var directorySource = new CachedResolver(
new r4.Hl7.Fhir.Specification.Source.DirectorySource(_scopeDirectory, new r4.Hl7.Fhir.Specification.Source.DirectorySourceSettings { IncludeSubDirectories = true }));
_combinedSource = new Hl7.Fhir.Specification.Source.MultiResolver(directorySource, _coreSourceR4);
}
}
}
private string _resourceText;
[NotifySignal]
public string ResourceText
{
get => _resourceText;
set
{
if (_resourceText == value)
{
return;
}
_resourceText = value;
UpdateResourceType(_resourceText);
this.ActivateProperty(x => x.ResourceText);
}
}
private string _resourceFont;
[NotifySignal]
public string ResourceFont
{
get => _resourceFont;
set
{
if (_resourceFont == value)
{
return;
}
_resourceFont = value;
this.ActivateProperty(x => x.ResourceFont);
}
}
private string _terminologyService = "https://tx.fhir.org/r3";
[NotifySignal]
public string TerminologyService
{
get => _terminologyService;
set
{
if (_terminologyService == value)
{
return;
}
_terminologyService = value;
this.ActivateProperty(x => x.TerminologyService);
}
}
// TODO replace with Firely SDK enum. Can be STU3 or R4
// TODO also map to the terminologyService and java validator command line properly
private string _fhirVersion = "STU3";
[NotifySignal]
public string FhirVersion
{
get => _fhirVersion;
set
{
if (_fhirVersion == value)
{
return;
}
if (TerminologyService.EndsWith("r3", StringComparison.CurrentCultureIgnoreCase) ||
TerminologyService.EndsWith("r4", StringComparison.CurrentCultureIgnoreCase))
{
TerminologyService = TerminologyService.Remove(TerminologyService.Length - 2);
TerminologyService = value
switch
{
"STU3" => TerminologyService + "r3",
"R4" => TerminologyService + "r4",
_ => TerminologyService,
};
}
_fhirVersion = value;
this.ActivateProperty(x => x.FhirVersion);
// reset stu3/r4 spec + folder we're validating against
ScopeDirectory = ScopeDirectory;
}
}
private bool _validatingDotnet;
[NotifySignal]
public bool ValidatingDotnet
{
get => _validatingDotnet;
set => this.SetProperty(ref _validatingDotnet, value);
}
private bool _validatingJava;
[NotifySignal]
public bool ValidatingJava
{
get => _validatingJava;
set => this.SetProperty(ref _validatingJava, value);
}
private List<Issue> _javaIssues = new List<Issue>();
[NotifySignal]
public List<Issue> JavaIssues
{
get => _javaIssues;
set => this.SetProperty(ref _javaIssues, value);
}
private List<Issue> _dotnetIssues = new List<Issue>();
[NotifySignal]
public List<Issue> DotnetIssues
{
get => _dotnetIssues;
set => this.SetProperty(ref _dotnetIssues, value);
}
// exposes examples to QML
private List<Example> _examples = new List<Example>();
[NotifySignal]
public List<Example> Examples
{
get => _examples;
set => this.SetProperty(ref _examples, value);
}
// loads examples from disk
public class DiskExample
{
public string Filename { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
private bool _javaValidationCrashed;
[NotifySignal]
public bool JavaValidationCrashed
{
get => _javaValidationCrashed;
set => this.SetProperty(ref _javaValidationCrashed, value);
}
private bool _animateQml = true;
/// <summary>Set to false to suppress animations in QML</summary>
[NotifySignal]
public bool AnimateQml
{
get => _animateQml;
set => this.SetProperty(ref _animateQml, value);
}
private ValidationResult _javaResult = new ValidationResult();
[NotifySignal]
public ValidationResult JavaResult
{
get => _javaResult;
set => this.SetProperty(ref _javaResult, value);
}
private ValidationResult _dotnetResult = new ValidationResult();
[NotifySignal]
public ValidationResult DotnetResult
{
get => _dotnetResult;
set => this.SetProperty(ref _dotnetResult, value);
}
#endregion
private readonly string RepoOrg = "health-validator";
private readonly string RepoName = "Hammer";
private ITypedElement _parsedResource;
private CancellationTokenSource _validatorCancellationSource;
private readonly List<Process> _validatorProcesses = new List<Process>();
private void ResetResults()
{
JavaIssues = new List<Issue>();
DotnetIssues = new List<Issue>();
JavaValidationCrashed = false;
}
public enum ValidatorType { Dotnet = 1, Java = 2 }
public class ValidationResult
{
private ValidatorType _validatorType;
[NotifySignal]
public ValidatorType ValidatorType
{
get => _validatorType;
set => this.SetProperty(ref _validatorType, value);
}
private List<Issue> _issues = new List<Issue>();
[NotifySignal]
public List<Issue> Issues
{
get => _issues;
set => this.SetProperty(ref _issues, value);
}
private int _errorCount;
[NotifySignal]
public int ErrorCount
{
get => _errorCount;
set => this.SetProperty(ref _errorCount, value);
}
private int _warningCount;
[NotifySignal]
public int WarningCount
{
get => _warningCount;
set => this.SetProperty(ref _warningCount, value);
}
}
// not a struct due to https://github.com/qmlnet/qmlnet/issues/135
public class Issue
{
private string _severity;
[NotifySignal]
public string Severity
{
get => _severity;
set => this.SetProperty(ref _severity, value);
}
private string _text;
[NotifySignal]
public string Text
{
get => _text;
set => this.SetProperty(ref _text, value);
}
private string _location;
[NotifySignal]
public string Location
{
get => _location;
set => this.SetProperty(ref _location, value);
}
private int _lineNumber;
[NotifySignal]
public int LineNumber
{
get => _lineNumber;
set => this.SetProperty(ref _lineNumber, value);
}
private int _linePosition;
[NotifySignal]
public int LinePosition
{
get => _linePosition;
set => this.SetProperty(ref _linePosition, value);
}
}
public class Example
{
private string _filepath;
[NotifySignal]
public string Filepath
{
get => _filepath;
set => this.SetProperty(ref _filepath, value);
}
private string _title;
[NotifySignal]
public string Title
{
get => _title;
set => this.SetProperty(ref _title, value);
}
private string _description;
[NotifySignal]
public string Description
{
get => _description;
set => this.SetProperty(ref _description, value);
}
}
private class MarkdownIssue
{
public string Severity;
public string Text;
public string Location;
}
public ResourceFormat InstanceFormat
{
get => _instanceFormat;
set
{
_instanceFormat = value;
switch (_instanceFormat)
{
case ResourceFormat.Xml:
ValidateButtonText = "Validate (xml)";
break;
case ResourceFormat.Json:
ValidateButtonText = "Validate (json)";
break;
case ResourceFormat.Unknown:
ValidateButtonText = "Validate";
break;
}
}
}
private bool terminologyDisabled()
{
string[] disabledTerminology = {"don't check with any server", "n/a", "off", "none"};
return disabledTerminology.Contains(TerminologyService, StringComparer.OrdinalIgnoreCase);
}
private string getJavaTxString()
{
if (terminologyDisabled())
{
return "n/a";
}
return TerminologyService;
}
private bool useDotnetExternalTx()
{
if (!terminologyDisabled())
{
return true;
}
return false;
}
private List<Issue> convertIssues(List<OperationOutcome.IssueComponent> issues)
{
List<Issue> convertedIssues = new List<Issue>();
foreach (var issue in issues)
{
var simplifiedIssue = new Issue
{
Severity = issue.Severity.ToString().ToLowerInvariant(),
Text = issue.Details?.Text ?? issue.Diagnostics ?? "(no details)",
Location = String.Join(" via ", issue.Location)
};
convertedIssues.Add(simplifiedIssue);
// read Java details
var javaLineNumber = issue.GetIntegerExtension("http://hl7.org/fhir/StructureDefinition/operationoutcome-issue-line");
var javaLinePosition = issue.GetIntegerExtension("http://hl7.org/fhir/StructureDefinition/operationoutcome-issue-col");
if (javaLineNumber.HasValue && javaLinePosition.HasValue)
{
simplifiedIssue.LineNumber = javaLineNumber.Value;
simplifiedIssue.LinePosition = javaLinePosition.Value;
continue;
}
// read .NET details
var serializationDetails = GetPositionInfo(issue);
if (serializationDetails == null)
{
continue;
}
simplifiedIssue.LineNumber = serializationDetails.LineNumber;
simplifiedIssue.LinePosition = serializationDetails.LinePosition;
}
return convertedIssues;
}
private IPositionInfo GetPositionInfo(OperationOutcome.IssueComponent issue)
{
IPositionInfo serializationDetails;
if (!issue.Location.Any())
{
return null;
}
var location = SanitizeLocation(issue.Location.First());
if (location == null)
{
return null;
}
List<ITypedElement> elementWithError = null;
try
{
elementWithError = _parsedResource.Select(location).ToList();
}
catch (FormatException)
{
// if the FHIRPath is invalid, don't return position info for it
}
if (elementWithError == null || !elementWithError.Any())
{
return null;
}
switch (InstanceFormat)
{
case ResourceFormat.Json:
serializationDetails = elementWithError.First().GetJsonSerializationDetails();
break;
case ResourceFormat.Xml:
serializationDetails = elementWithError.First().GetXmlSerializationDetails();
break;
case ResourceFormat.Unknown:
return null;
default:
return null;
}
return serializationDetails;
}
private static MatchCollection ExtractLocation(string rawLocation)
{
const string pattern = @"([^\(]+)";
return Regex.Matches(rawLocation, pattern);
}
private static MatchCollection ExtractReleaseVersion(string rawVersion)
{
const string pattern = @"Hammer-(.+)$";
return Regex.Matches(rawVersion, pattern);
}
///<summary>Trims Java FHIRpath of its position information, which isn't always correct
/// we have to compute it ourselves for .NET, might as well do it for Java</summary>
private string SanitizeLocation(string rawLocation)
{
// heuristic for the Java validator
if (rawLocation == "(document)")
{
return _parsedResource.Name;
}
var matches = ExtractLocation(rawLocation);
if (!matches.Any())
{
return null;
}
var location = matches.First().Groups[0].ToString().Trim();
return location;
}
public bool LoadResourceFile(string text)
{
if (text == null)
{
Console.Error.WriteLine("LoadResourceFile: no text passed");
return false;
}
// input already pruned - accept as-is
if (!text.StartsWith("file://", StringComparison.InvariantCulture))
{
ResourceText = text;
return true;
}
var filePath = text;
// Windows can use three leading slashes, while others can use two
// examples load with just two on windows as well - so simpler to
// try both variants
filePath = filePath.RemovePrefix("file:///");
filePath = filePath.RemovePrefix("file://");
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
filePath = filePath.Prepend("/");
}
filePath = filePath.Replace("\r", "", StringComparison.InvariantCulture)
.Replace("\n", "", StringComparison.InvariantCulture);
filePath = Uri.UnescapeDataString(filePath);
Console.WriteLine($"Loading '{filePath}'...");
if (!File.Exists(filePath))
{
Console.WriteLine($"File to load doesn't actually exist: {filePath}");
return false;
}
ResourceText = File.ReadAllText(filePath);
if (ScopeDirectory == null)
{
ScopeDirectory = Path.GetDirectoryName(filePath);
}
return true;
}
public void LoadScopeDirectory(string text)
{
// input already pruned - accept as-is
if (!text.StartsWith("file://", StringComparison.InvariantCulture))
{
ScopeDirectory = text;
return;
}
var filePath = text;
filePath = filePath.RemovePrefix(RuntimeInformation
.IsOSPlatform(OSPlatform.Windows) ? "file:///" : "file://");
filePath = filePath.Replace("\r", "", StringComparison.InvariantCulture)
.Replace("\n", "", StringComparison.InvariantCulture);
filePath = Uri.UnescapeDataString(filePath);
ScopeDirectory = filePath;
}
public void UpdateResourceType(string resourcetext)
{
var text = resourcetext;
if (!String.IsNullOrEmpty(text))
{
if (SerializationUtil.ProbeIsXml(text))
InstanceFormat = ResourceFormat.Xml;
else if (SerializationUtil.ProbeIsJson(text))
InstanceFormat = ResourceFormat.Json;
else
InstanceFormat = ResourceFormat.Unknown;
}
else
InstanceFormat = ResourceFormat.Unknown;
}
public async Task copyToClipboard(string message)
{
await ClipboardService.SetTextAsync(message);
}
public async Task CopyValidationReportCsv()
{
using var writer = new StringWriter();
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
// write fields out manually since we need to add the engine type column
csv.WriteField("Severity");
csv.WriteField("Text");
csv.WriteField("Location");
csv.WriteField("Validator engine");
csv.NextRecord();
foreach (var issue in DotnetIssues)
{
csv.WriteField(issue.Severity);
csv.WriteField(issue.Text);
csv.WriteField(issue.Location);
csv.WriteField(".NET");
csv.NextRecord();
}
foreach (var issue in JavaIssues)
{
csv.WriteField(issue.Severity);
csv.WriteField(issue.Text);
csv.WriteField(issue.Location);
csv.WriteField("Java");
csv.NextRecord();
}
await ClipboardService.SetTextAsync(writer.ToString());
}
public async Task CopyValidationReportMarkdown()
{
List<MarkdownIssue> ConvertToMarkdown(List<Issue> rawIssues)
{
var markdownIssues = new List<MarkdownIssue> { };
foreach (var issue in rawIssues)
{
markdownIssues.Add(new MarkdownIssue()
{
Severity = issue.Severity,
Text = issue.Text,
Location = (issue.LineNumber == 0 && issue.LinePosition == 0) ?
"" :
$"{issue.Location} (line {issue.LineNumber}:{issue.LinePosition})"
});
}
return markdownIssues;
}
var report = "";
if (!ValidatingDotnet)
{
report += $@"**.NET Validator**
{ConvertToMarkdown(DotnetIssues).ToMarkdownTable()}
";
}
if (!ValidatingJava)
{
report += $@"** Java Validator**
{ConvertToMarkdown(JavaIssues).ToMarkdownTable()}
";
}
await ClipboardService.SetTextAsync(report);
}
private stu3.Hl7.Fhir.Validation.Validator CreateValidatorStu3(stu3.Hl7.Fhir.Rest.FhirClient fhirClient = null)
{
var resolver = _combinedSource ?? _coreSourceStu3;
var localTerminology = new stu3.Hl7.Fhir.Specification.Terminology.LocalTerminologyService(resolver.AsAsync());
var externalTerminology = (fhirClient != null) ? new stu3.Hl7.Fhir.Specification.Terminology.ExternalTerminologyService(fhirClient) : null;
var combinedTerminology = (fhirClient != null) ? new stu3.Hl7.Fhir.Specification.Terminology.FallbackTerminologyService(localTerminology, externalTerminology) : null;
var settings = new stu3.Hl7.Fhir.Validation.ValidationSettings
{
ResourceResolver = _combinedSource ?? _coreSourceStu3,
GenerateSnapshot = true,
EnableXsdValidation = true,
Trace = false,
ResolveExternalReferences = true,
TerminologyService = combinedTerminology
};
return new stu3.Hl7.Fhir.Validation.Validator(settings);
}
private r4.Hl7.Fhir.Validation.Validator CreateValidatorR4(r4.Hl7.Fhir.Rest.FhirClient fhirClient = null)
{
var resolver = _combinedSource ?? _coreSourceR4;
var localTerminology = new r4.Hl7.Fhir.Specification.Terminology.LocalTerminologyService(resolver.AsAsync());
var externalTerminology = (fhirClient != null) ? new r4.Hl7.Fhir.Specification.Terminology.ExternalTerminologyService(fhirClient) : null;
var combinedTerminology = (fhirClient != null) ? new r4.Hl7.Fhir.Specification.Terminology.FallbackTerminologyService(localTerminology, externalTerminology) : null;
var settings = new r4.Hl7.Fhir.Validation.ValidationSettings
{
ResourceResolver = _combinedSource ?? _coreSourceR4,
GenerateSnapshot = true,
EnableXsdValidation = true,
Trace = false,
ResolveExternalReferences = true,
TerminologyService = combinedTerminology
};
return new r4.Hl7.Fhir.Validation.Validator(settings);
}
public OperationOutcome ValidateWithDotnet(CancellationToken token)
{
Console.WriteLine("Beginning .NET validation");
try
{
OperationOutcome result;
Stopwatch sw = new Stopwatch();
sw.Start();
ISourceNode untyped;
if (InstanceFormat == ResourceFormat.Xml)
{
untyped = FhirXmlNode.Parse(ResourceText, new FhirXmlParsingSettings { PermissiveParsing = true });
}
else if (InstanceFormat == ResourceFormat.Json)
{
untyped = FhirJsonNode.Parse(ResourceText, settings: new FhirJsonParsingSettings { AllowJsonComments = true });
}
else
{
throw new Exception("This resource format isn't recognised");
}
if (FhirVersion == "STU3")
{
var summaryProviderStu3 = new stu3.Hl7.Fhir.Specification.StructureDefinitionSummaryProvider(_combinedSource ?? _coreSourceStu3);
_parsedResource = untyped.ToTypedElement(summaryProviderStu3);
using var fhirClient = useDotnetExternalTx() ? new stu3.Hl7.Fhir.Rest.FhirClient(TerminologyService) : null;
var validator = CreateValidatorStu3(useDotnetExternalTx() ? fhirClient : null);
result = validator.Validate(_parsedResource);
}
else
{
var summaryProviderR4 = new r4.Hl7.Fhir.Specification.StructureDefinitionSummaryProvider(_combinedSource ?? _coreSourceR4);
_parsedResource = untyped.ToTypedElement(summaryProviderR4);
using var fhirClient = useDotnetExternalTx() ? new r4.Hl7.Fhir.Rest.FhirClient(TerminologyService) : null;
var validator = CreateValidatorR4(useDotnetExternalTx() ? fhirClient : null);
result = validator.Validate(_parsedResource);
}
sw.Stop();
token.ThrowIfCancellationRequested();
Console.WriteLine($".NET validation performed in {sw.ElapsedMilliseconds}ms");
return result;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
var result = new OperationOutcome();
result.Issue.Add(new OperationOutcome.IssueComponent
{
Severity = OperationOutcome.IssueSeverity.Error,
Diagnostics = $"{ex.GetType().Name}: {ex.Message}",
Code = OperationOutcome.IssueType.Exception
});
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(ex.Message);
errorWriter.WriteLine(ex.StackTrace);
return result;
}
}
private static string SerializeResource(string resourceText, ResourceFormat instanceFormat)
{
var fileName = $"{Path.GetTempFileName()}.{(instanceFormat == ResourceFormat.Json ? "json" : "xml")}";
File.WriteAllText(fileName, resourceText);
return fileName;
}
// in case the Java validator crashes (which it can if it doesn't like something),
// it won't produce an OperationOutcome for us - take what we've got and make one ourselves
private static OperationOutcome ConvertJavaStdout(string output)
{
var result = new OperationOutcome();
result.Issue.Add(new OperationOutcome.IssueComponent
{
Severity = OperationOutcome.IssueSeverity.Error,
Details = new CodeableConcept
{
Text = output
},
Code = OperationOutcome.IssueType.Processing
});
return result;
}
// credit: https://github.com/dotnet/runtime/issues/13051#issuecomment-514774802
public static class Extensions
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern uint GetModuleFileName(IntPtr hModule, System.Text.StringBuilder lpFilename, int nSize);
const int MAX_PATH = 255;
// reports the location of our application when running from Hammer.exe and the like
private static string GetExecutablePath()
{
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
var sb = new System.Text.StringBuilder(MAX_PATH);
GetModuleFileName(IntPtr.Zero, sb, MAX_PATH);
return Path.GetDirectoryName(sb.ToString());
}
else
{
return Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
}
}
// reports the location of our application when running from Hammer.dll
private static string GetDllPath()
{
return Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
}
public static string GetApplicationLocation()
{
string executablePath = GetExecutablePath();
string dllPath = GetDllPath();
return (File.Exists(Path.Combine(executablePath, "Main.qml"))) ? executablePath : dllPath;
}
}
public OperationOutcome ValidateWithJava(CancellationToken token)
{
var resourcePath = SerializeResource(ResourceText, InstanceFormat);
var validatorPath = Path.Combine(Extensions.GetApplicationLocation(), "org.hl7.fhir.validator.jar");
var scopeArgument = string.IsNullOrEmpty(ScopeDirectory) ? "" : $" -ig \"{ScopeDirectory}\"";
var outputJson = $"{Path.GetTempFileName()}.json";
var finalArguments = $"-jar {validatorPath} -version {(FhirVersion == "STU3" ? "3.0" : "4.0")} -tx \"{getJavaTxString()}\"{scopeArgument} -output {outputJson} {resourcePath}";
Console.WriteLine($"Beginning Java validation: java {finalArguments}");
OperationOutcome result;
var sw = new Stopwatch();
sw.Start();
string validatorOutput, resultText;
using var validator = new Process();
_validatorProcesses.Add(validator);
validator.StartInfo.FileName = "java";
validator.StartInfo.Arguments = finalArguments;
validator.StartInfo.UseShellExecute = false;
validator.StartInfo.RedirectStandardOutput = true;
validator.StartInfo.RedirectStandardError = true;
validator.StartInfo.CreateNoWindow = true;
try
{
validator.Start();
validatorOutput = validator.StandardOutput.ReadToEnd();
validatorOutput += validator.StandardError.ReadToEnd();
validator.WaitForExit();
}
catch (Exception ex)
{
result = new OperationOutcome();
if (ex.Message == "The system cannot find the file specified" ||
ex.Message == "No such file or directory")
{
result.Issue.Add(new OperationOutcome.IssueComponent
{
Severity = OperationOutcome.IssueSeverity.Error,
Diagnostics = AppModel.Instance.NoJavaInstall,
Code = OperationOutcome.IssueType.Exception
});
}
else
{
result.Issue.Add(new OperationOutcome.IssueComponent
{
Severity = OperationOutcome.IssueSeverity.Error,