001package org.hl7.fhir.utilities.validation;
002
003import java.text.ParseException;
004import java.text.SimpleDateFormat;
005import java.util.ArrayList;
006import java.util.Objects;
007
008/*
009  Copyright (c) 2011+, HL7, Inc.
010  All rights reserved.
011
012  Redistribution and use in source and binary forms, with or without modification, 
013  are permitted provided that the following conditions are met:
014
015 * Redistributions of source code must retain the above copyright notice, this 
016     list of conditions and the following disclaimer.
017 * Redistributions in binary form must reproduce the above copyright notice, 
018     this list of conditions and the following disclaimer in the documentation 
019     and/or other materials provided with the distribution.
020 * Neither the name of HL7 nor the names of its contributors may be used to 
021     endorse or promote products derived from this software without specific 
022     prior written permission.
023
024  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
025  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
026  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
027  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
028  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
029  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
030  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
031  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
032  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
033  POSSIBILITY OF SUCH DAMAGE.
034
035 */
036
037
038
039/*
040 Copyright (c) 2011+, HL7, Inc
041 All rights reserved.
042
043 Redistribution and use in source and binary forms, with or without modification, 
044 are permitted provided that the following conditions are met:
045
046 * Redistributions of source code must retain the above copyright notice, this 
047 list of conditions and the following disclaimer.
048 * Redistributions in binary form must reproduce the above copyright notice, 
049 this list of conditions and the following disclaimer in the documentation 
050 and/or other materials provided with the distribution.
051 * Neither the name of HL7 nor the names of its contributors may be used to 
052 endorse or promote products derived from this software without specific 
053 prior written permission.
054
055 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
056 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
057 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
058 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
059 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
060 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
061 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
062 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
063 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
064 POSSIBILITY OF SUCH DAMAGE.
065
066 */
067
068import java.util.Comparator;
069import java.util.Date;
070import java.util.List;
071
072import lombok.Getter;
073import org.apache.commons.lang3.builder.ToStringBuilder;
074import org.apache.commons.lang3.builder.ToStringStyle;
075import org.hl7.fhir.exceptions.FHIRException;
076import org.hl7.fhir.utilities.Utilities;
077
078public class ValidationMessage implements Comparator<ValidationMessage>, Comparable<ValidationMessage>
079{
080
081  public enum Source {
082    ExampleValidator, 
083    ProfileValidator, 
084    ResourceValidator, 
085    InstanceValidator,
086    MatchetypeValidator,
087    Template,
088    Schema, 
089    Schematron, 
090    Publisher, 
091    LinkChecker,
092    Ontology, 
093    ProfileComparer, 
094    TerminologyEngine,
095    QuestionnaireResponseValidator, 
096    IPAValidator
097  }
098
099  public enum IssueSeverity {
100    /**
101     * The issue caused the action to fail, and no further checking could be performed.
102     */
103    FATAL, 
104    /**
105     * The issue is sufficiently important to cause the action to fail.
106     */
107    ERROR, 
108    /**
109     * The issue is not important enough to cause the action to fail, but may cause it to be performed suboptimally or in a way that is not as desired.
110     */
111    WARNING, 
112    /**
113     * The issue has no relation to the degree of success of the action.
114     */
115    INFORMATION, 
116    /**
117     * added to help the parsers with the generic types
118     */
119    NULL;
120    public static IssueSeverity fromCode(String codeString) throws FHIRException {
121      if (codeString == null || "".equals(codeString))
122        return null;
123      if ("fatal".equals(codeString))
124        return FATAL;
125      if ("error".equals(codeString))
126        return ERROR;
127      if ("warning".equals(codeString))
128        return WARNING;
129      if ("information".equals(codeString))
130        return INFORMATION;
131      else
132        throw new FHIRException("Unknown IssueSeverity code '"+codeString+"'");
133    }
134    public String toCode() {
135      switch (this) {
136      case FATAL: return "fatal";
137      case ERROR: return "error";
138      case WARNING: return "warning";
139      case INFORMATION: return "information";
140      case NULL: return null;
141      default: return "?";
142      }
143    }
144    public String getSystem() {
145      switch (this) {
146      case FATAL: return "http://hl7.org/fhir/issue-severity";
147      case ERROR: return "http://hl7.org/fhir/issue-severity";
148      case WARNING: return "http://hl7.org/fhir/issue-severity";
149      case INFORMATION: return "http://hl7.org/fhir/issue-severity";
150      case NULL: return null;
151      default: return "?";
152      }
153    }
154    public String getDefinition() {
155      switch (this) {
156      case FATAL: return "The issue caused the action to fail, and no further checking could be performed.";
157      case ERROR: return "The issue is sufficiently important to cause the action to fail.";
158      case WARNING: return "The issue is not important enough to cause the action to fail, but may cause it to be performed suboptimally or in a way that is not as desired.";
159      case INFORMATION: return "The issue has no relation to the degree of success of the action.";
160      case NULL: return null;
161      default: return "?";
162      }
163    }
164    public String getDisplay() {
165      switch (this) {
166      case FATAL: return "Fatal";
167      case ERROR: return "Error";
168      case WARNING: return "Warning";
169      case INFORMATION: return "Information";
170      case NULL: return null;
171      default: return "?";
172      }
173    }
174    public boolean isError() {
175      return this == FATAL || this == ERROR;
176    }
177    public boolean isHint() {
178      return this == INFORMATION;
179    }
180    
181    public static IssueSeverity max(IssueSeverity l1, IssueSeverity l2) {
182      switch (l1) {
183      case ERROR:
184        return l1 == FATAL ? FATAL : ERROR;
185      case FATAL:
186        return FATAL;
187      case INFORMATION:
188        return l2;
189      case NULL:
190        return l2;
191      case WARNING:
192        return l2 == INFORMATION ? WARNING : l2;
193      }
194      return null;
195    }
196    public String toShortCode() {
197      switch (this) {
198      case FATAL: return "fatal";
199      case ERROR: return "error";
200      case WARNING: return "warn";
201      case INFORMATION: return "info";
202      case NULL: return null;
203      default: return "?";
204      }
205    }
206  }
207
208  public enum IssueType {
209    /**
210     * Content invalid against the specification or a profile.
211     */
212    INVALID, 
213    DELETED,
214    /**
215     * A structural issue in the content such as wrong namespace, or unable to parse the content completely, or invalid json syntax.
216     */
217    STRUCTURE, 
218    /**
219     * A required element is missing.
220     */
221    REQUIRED, 
222    /**
223     * An element value is invalid.
224     */
225    VALUE, 
226    /**
227     * A content validation rule failed - e.g. a schematron rule.
228     */
229    INVARIANT, 
230    /**
231     * An authentication/authorization/permissions issue of some kind.
232     */
233    SECURITY, 
234    /**
235     * The client needs to initiate an authentication process.
236     */
237    LOGIN, 
238    /**
239     * The user or system was not able to be authenticated (either there is no process, or the proferred token is unacceptable).
240     */
241    MULTIPLEMATCHES,
242    UNKNOWN, 
243    /**
244     * User session expired; a login may be required.
245     */
246    EXPIRED, 
247    /**
248     * The user does not have the rights to perform this action.
249     */
250    FORBIDDEN, 
251    /**
252     * Some information was not or may not have been returned due to business rules, consent or privacy rules, or access permission constraints.  This information may be accessible through alternate processes.
253     */
254    SUPPRESSED, 
255    /**
256     * Processing issues. These are expected to be final e.g. there is no point resubmitting the same content unchanged.
257     */
258    PROCESSING, 
259    /**
260     * The resource or profile is not supported.
261     */
262    NOTSUPPORTED, 
263    /**
264     * An attempt was made to create a duplicate record.
265     */
266    DUPLICATE, 
267    /**
268     * The reference provided was not found. In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the content is not found further into the application architecture.
269     */
270    NOTFOUND, 
271    /**
272     * Provided content is too long (typically, this is a denial of service protection type of error).
273     */
274    TOOLONG, 
275    /**
276     * The code or system could not be understood, or it was not valid in the context of a particular ValueSet.code.
277     */
278    CODEINVALID, 
279    /**
280     * An extension was found that was not acceptable, could not be resolved, or a modifierExtension was not recognized.
281     */
282    EXTENSION, 
283    /**
284     * The operation was stopped to protect server resources; e.g. a request for a value set expansion on all of SNOMED CT.
285     */
286    TOOCOSTLY, 
287    /**
288     * The content/operation failed to pass some business rule, and so could not proceed.
289     */
290    BUSINESSRULE, 
291    /**
292     * Content could not be accepted because of an edit conflict (i.e. version aware updates) (In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the conflict is discovered further into the application architecture.)
293     */
294    CONFLICT, 
295    /**
296     * Not all data sources typically accessed could be reached, or responded in time, so the returned information may not be complete.
297     */
298    INCOMPLETE, 
299    /**
300     * Transient processing issues. The system receiving the error may be able to resubmit the same content once an underlying issue is resolved.
301     */
302    TRANSIENT, 
303    /**
304     * A resource/record locking failure (usually in an underlying database).
305     */
306    LOCKERROR, 
307    /**
308     * The persistent store is unavailable; e.g. the database is down for maintenance or similar action.
309     */
310    NOSTORE, 
311    /**
312     * An unexpected internal error has occurred.
313     */
314    EXCEPTION, 
315    /**
316     * An internal timeout has occurred.
317     */
318    TIMEOUT, 
319    /**
320     * The system is not prepared to handle this request due to load management.
321     */
322    THROTTLED, 
323    /**
324     * A message unrelated to the processing success of the completed operation (examples of the latter include things like reminders of password expiry, system maintenance times, etc.).
325     */
326    INFORMATIONAL, 
327    /**
328     * added to help the parsers with the generic types
329     */
330    NULL;
331    public static IssueType fromCode(String codeString) throws FHIRException {
332      if (codeString == null || "".equals(codeString))
333        return null;
334      if ("invalid".equals(codeString))
335        return INVALID;
336      if ("structure".equals(codeString))
337        return STRUCTURE;
338      if ("required".equals(codeString))
339        return REQUIRED;
340      if ("value".equals(codeString))
341        return VALUE;
342      if ("invariant".equals(codeString))
343        return INVARIANT;
344      if ("security".equals(codeString))
345        return SECURITY;
346      if ("login".equals(codeString))
347        return LOGIN;
348      if ("unknown".equals(codeString))
349        return UNKNOWN;
350      if ("expired".equals(codeString))
351        return EXPIRED;
352      if ("forbidden".equals(codeString))
353        return FORBIDDEN;
354      if ("suppressed".equals(codeString))
355        return SUPPRESSED;
356      if ("processing".equals(codeString))
357        return PROCESSING;
358      if ("not-supported".equals(codeString))
359        return NOTSUPPORTED;
360      if ("duplicate".equals(codeString))
361        return DUPLICATE;
362      if ("not-found".equals(codeString))
363        return NOTFOUND;
364      if ("too-long".equals(codeString))
365        return TOOLONG;
366      if ("code-invalid".equals(codeString))
367        return CODEINVALID;
368      if ("extension".equals(codeString))
369        return EXTENSION;
370      if ("too-costly".equals(codeString))
371        return TOOCOSTLY;
372      if ("business-rule".equals(codeString))
373        return BUSINESSRULE;
374      if ("conflict".equals(codeString))
375        return CONFLICT;
376      if ("incomplete".equals(codeString))
377        return INCOMPLETE;
378      if ("transient".equals(codeString))
379        return TRANSIENT;
380      if ("lock-error".equals(codeString))
381        return LOCKERROR;
382      if ("no-store".equals(codeString))
383        return NOSTORE;
384      if ("exception".equals(codeString))
385        return EXCEPTION;
386      if ("timeout".equals(codeString))
387        return TIMEOUT;
388      if ("throttled".equals(codeString))
389        return THROTTLED;
390      if ("informational".equals(codeString))
391        return INFORMATIONAL;
392      else
393        throw new FHIRException("Unknown IssueType code '"+codeString+"'");
394    }
395    public String toCode() {
396      switch (this) {
397      case INVALID: return "invalid";
398      case STRUCTURE: return "structure";
399      case REQUIRED: return "required";
400      case VALUE: return "value";
401      case INVARIANT: return "invariant";
402      case SECURITY: return "security";
403      case LOGIN: return "login";
404      case UNKNOWN: return "unknown";
405      case EXPIRED: return "expired";
406      case FORBIDDEN: return "forbidden";
407      case SUPPRESSED: return "suppressed";
408      case PROCESSING: return "processing";
409      case NOTSUPPORTED: return "not-supported";
410      case DUPLICATE: return "duplicate";
411      case NOTFOUND: return "not-found";
412      case TOOLONG: return "too-long";
413      case CODEINVALID: return "code-invalid";
414      case EXTENSION: return "extension";
415      case TOOCOSTLY: return "too-costly";
416      case BUSINESSRULE: return "business-rule";
417      case CONFLICT: return "conflict";
418      case INCOMPLETE: return "incomplete";
419      case TRANSIENT: return "transient";
420      case LOCKERROR: return "lock-error";
421      case NOSTORE: return "no-store";
422      case EXCEPTION: return "exception";
423      case TIMEOUT: return "timeout";
424      case THROTTLED: return "throttled";
425      case INFORMATIONAL: return "informational";
426      case NULL: return null;
427      default: return "?";
428      }
429    }
430    public String getSystem() {
431      switch (this) {
432      case INVALID: return "http://hl7.org/fhir/issue-type";
433      case STRUCTURE: return "http://hl7.org/fhir/issue-type";
434      case REQUIRED: return "http://hl7.org/fhir/issue-type";
435      case VALUE: return "http://hl7.org/fhir/issue-type";
436      case INVARIANT: return "http://hl7.org/fhir/issue-type";
437      case SECURITY: return "http://hl7.org/fhir/issue-type";
438      case LOGIN: return "http://hl7.org/fhir/issue-type";
439      case UNKNOWN: return "http://hl7.org/fhir/issue-type";
440      case EXPIRED: return "http://hl7.org/fhir/issue-type";
441      case FORBIDDEN: return "http://hl7.org/fhir/issue-type";
442      case SUPPRESSED: return "http://hl7.org/fhir/issue-type";
443      case PROCESSING: return "http://hl7.org/fhir/issue-type";
444      case NOTSUPPORTED: return "http://hl7.org/fhir/issue-type";
445      case DUPLICATE: return "http://hl7.org/fhir/issue-type";
446      case NOTFOUND: return "http://hl7.org/fhir/issue-type";
447      case TOOLONG: return "http://hl7.org/fhir/issue-type";
448      case CODEINVALID: return "http://hl7.org/fhir/issue-type";
449      case EXTENSION: return "http://hl7.org/fhir/issue-type";
450      case TOOCOSTLY: return "http://hl7.org/fhir/issue-type";
451      case BUSINESSRULE: return "http://hl7.org/fhir/issue-type";
452      case CONFLICT: return "http://hl7.org/fhir/issue-type";
453      case INCOMPLETE: return "http://hl7.org/fhir/issue-type";
454      case TRANSIENT: return "http://hl7.org/fhir/issue-type";
455      case LOCKERROR: return "http://hl7.org/fhir/issue-type";
456      case NOSTORE: return "http://hl7.org/fhir/issue-type";
457      case EXCEPTION: return "http://hl7.org/fhir/issue-type";
458      case TIMEOUT: return "http://hl7.org/fhir/issue-type";
459      case THROTTLED: return "http://hl7.org/fhir/issue-type";
460      case INFORMATIONAL: return "http://hl7.org/fhir/issue-type";
461      case NULL: return null;
462      default: return "?";
463      }
464    }
465    public String getDefinition() {
466      switch (this) {
467      case INVALID: return "Content invalid against the specification or a profile.";
468      case STRUCTURE: return "A structural issue in the content such as wrong namespace, or unable to parse the content completely, or invalid json syntax.";
469      case REQUIRED: return "A required element is missing.";
470      case VALUE: return "An element value is invalid.";
471      case INVARIANT: return "A content validation rule failed - e.g. a schematron rule.";
472      case SECURITY: return "An authentication/authorization/permissions issue of some kind.";
473      case LOGIN: return "The client needs to initiate an authentication process.";
474      case UNKNOWN: return "The user or system was not able to be authenticated (either there is no process, or the proferred token is unacceptable).";
475      case EXPIRED: return "User session expired; a login may be required.";
476      case FORBIDDEN: return "The user does not have the rights to perform this action.";
477      case SUPPRESSED: return "Some information was not or may not have been returned due to business rules, consent or privacy rules, or access permission constraints.  This information may be accessible through alternate processes.";
478      case PROCESSING: return "Processing issues. These are expected to be final e.g. there is no point resubmitting the same content unchanged.";
479      case NOTSUPPORTED: return "The resource or profile is not supported.";
480      case DUPLICATE: return "An attempt was made to create a duplicate record.";
481      case NOTFOUND: return "The reference provided was not found. In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the content is not found further into the application architecture.";
482      case TOOLONG: return "Provided content is too long (typically, this is a denial of service protection type of error).";
483      case CODEINVALID: return "The code or system could not be understood, or it was not valid in the context of a particular ValueSet.code.";
484      case EXTENSION: return "An extension was found that was not acceptable, could not be resolved, or a modifierExtension was not recognized.";
485      case TOOCOSTLY: return "The operation was stopped to protect server resources; e.g. a request for a value set expansion on all of SNOMED CT.";
486      case BUSINESSRULE: return "The content/operation failed to pass some business rule, and so could not proceed.";
487      case CONFLICT: return "Content could not be accepted because of an edit conflict (i.e. version aware updates) (In a pure RESTful environment, this would be an HTTP 404 error, but this code may be used where the conflict is discovered further into the application architecture.)";
488      case INCOMPLETE: return "Not all data sources typically accessed could be reached, or responded in time, so the returned information may not be complete.";
489      case TRANSIENT: return "Transient processing issues. The system receiving the error may be able to resubmit the same content once an underlying issue is resolved.";
490      case LOCKERROR: return "A resource/record locking failure (usually in an underlying database).";
491      case NOSTORE: return "The persistent store is unavailable; e.g. the database is down for maintenance or similar action.";
492      case EXCEPTION: return "An unexpected internal error has occurred.";
493      case TIMEOUT: return "An internal timeout has occurred.";
494      case THROTTLED: return "The system is not prepared to handle this request due to load management.";
495      case INFORMATIONAL: return "A message unrelated to the processing success of the completed operation (examples of the latter include things like reminders of password expiry, system maintenance times, etc.).";
496      case NULL: return null;
497      default: return "?";
498      }
499    }
500    public String getDisplay() {
501      switch (this) {
502      case INVALID: return "Invalid Content";
503      case STRUCTURE: return "Structural Issue";
504      case REQUIRED: return "Required element missing";
505      case VALUE: return "Element value invalid";
506      case INVARIANT: return "Validation rule failed";
507      case SECURITY: return "Security Problem";
508      case LOGIN: return "Login Required";
509      case UNKNOWN: return "Unknown User";
510      case EXPIRED: return "Session Expired";
511      case FORBIDDEN: return "Forbidden";
512      case SUPPRESSED: return "Information  Suppressed";
513      case PROCESSING: return "Processing Failure";
514      case NOTSUPPORTED: return "Content not supported";
515      case DUPLICATE: return "Duplicate";
516      case NOTFOUND: return "Not Found";
517      case TOOLONG: return "Content Too Long";
518      case CODEINVALID: return "Invalid Code";
519      case EXTENSION: return "Unacceptable Extension";
520      case TOOCOSTLY: return "Operation Too Costly";
521      case BUSINESSRULE: return "Business Rule Violation";
522      case CONFLICT: return "Edit Version Conflict";
523      case INCOMPLETE: return "Incomplete Results";
524      case TRANSIENT: return "Transient Issue";
525      case LOCKERROR: return "Lock Error";
526      case NOSTORE: return "No Store Available";
527      case EXCEPTION: return "Exception";
528      case TIMEOUT: return "Timeout";
529      case THROTTLED: return "Throttled";
530      case INFORMATIONAL: return "Informational Note";
531      case NULL: return null;
532      default: return "?";
533      }
534    }
535  }
536
537
538  private Source source;
539  private String server;
540  private int line;
541  private int col;
542  private String location; // fhirPath
543  private String message;
544  private String messageId; // source, for grouping
545  private IssueType type;
546  private IssueSeverity level;
547  private String html;
548  private String locationLink;
549  private String txLink;
550  public String sliceHtml;
551  private boolean slicingHint;
552  private boolean signpost;
553  private boolean criticalSignpost;
554  private Date ruleDate;
555  public static final String NO_RULE_DATE = null;
556  private boolean matched; // internal use counting matching filters
557  private boolean ignorableError;
558  private String invId;
559  private String comment;
560  private List<ValidationMessage> sliceInfo;
561  private int count;
562
563  @Getter private String diagnostics;
564
565  /**
566   * Constructor
567   */
568  public ValidationMessage() {
569    // nothing
570  }
571
572  public ValidationMessage(Source source, IssueType type, String path, String message, IssueSeverity level) {
573    this();
574    this.line = -1;
575    this.col = -1;
576    this.location = path;
577    if (message == null)
578      throw new Error("message is null");
579    this.message = message;
580    this.html = Utilities.escapeXml(message);
581    this.level = level;
582    this.source = source;
583    this.type = type;
584    if (level == IssueSeverity.NULL)
585      determineLevel(path);
586    if (type == null)
587      throw new Error("A type must be provided");
588  }
589
590  public ValidationMessage(Source source, IssueType type, int line, int col, String path, String message, IssueSeverity level) {
591    this();
592    this.line = line;
593    this.col = col;
594    this.location = path;
595    this.message = message;
596    this.html = Utilities.escapeXml(message);
597    this.level = level;
598    this.source = source;
599    this.type = type;
600    if (level == IssueSeverity.NULL)
601      determineLevel(path);
602    if (type == null)
603      throw new Error("A type must be provided");
604  }
605
606  public ValidationMessage(Source source, IssueType type, String path, String message, String html, IssueSeverity level) {
607    this();
608    this.line = -1;
609    this.col = -1;
610    this.location = path;
611    if (message == null)
612      throw new Error("message is null");
613    this.message = message;
614    this.html = html;
615    this.level = level;
616    this.source = source;
617    this.type = type;
618    if (level == IssueSeverity.NULL)
619      determineLevel(path);
620    if (type == null)
621      throw new Error("A type must be provided");
622  }
623
624  public ValidationMessage(Source source, IssueType type, int line, int col, String path, String message, String html, IssueSeverity level) {
625    this();
626    this.line = line;
627    this.col = col;
628    this.location = path;
629    if (message == null)
630      throw new Error("message is null");
631    this.message = message;
632    this.html = html;
633    this.level = level;
634    this.source = source;
635    this.type = type;
636    if (level == IssueSeverity.NULL)
637      determineLevel(path);
638    if (type == null)
639      throw new Error("A type must be provided");
640  }
641
642  private IssueSeverity determineLevel(String path) {
643    if (isGrandfathered(path))
644      return IssueSeverity.WARNING;
645    else
646      return IssueSeverity.ERROR;
647  }
648
649  private boolean isGrandfathered(String path) {
650    if (path.startsWith("xds-documentmanifest."))
651      return true;
652    if (path.startsWith("observation-device-metric-devicemetricobservation."))
653      return true;
654    if (path.startsWith("medicationadministration-immunization-vaccine."))
655      return true;
656    if (path.startsWith("elementdefinition-de-dataelement."))
657      return true;
658    if (path.startsWith("dataelement-sdc-sdcelement."))
659      return true;
660    if (path.startsWith("questionnaireresponse-sdc-structureddatacaptureanswers."))
661      return true;
662    if (path.startsWith("valueset-sdc-structureddatacapturevalueset."))
663      return true;
664    if (path.startsWith("dataelement-sdc-de-sdcelement."))
665      return true;
666    if (path.startsWith("do-uslab-uslabdo."))
667      return true;
668    if (path.startsWith("."))
669      return true;
670    if (path.startsWith("."))
671      return true;
672    if (path.startsWith("."))
673      return true;
674    if (path.startsWith("."))
675      return true;
676
677    return false;
678  }
679
680  public String getMessage() {
681    return message+showCount();
682  }
683  
684  private String showCount() {
685    return count == 0 ? "" : " (also in "+count+" other files)";
686  }
687
688  public ValidationMessage setMessage(String message) {
689    this.message = message;
690    return this;
691  }
692
693  public IssueSeverity getLevel() {
694    return level;
695  }
696  public ValidationMessage setLevel(IssueSeverity level) {
697    this.level = level;
698    return this;
699  }
700
701  public Source getSource() {
702    return source;
703  }
704  public ValidationMessage setSource(Source source) {
705    this.source = source;
706    return this;
707  }
708
709  public int getLine() {
710    return line;
711  }
712
713  public void setLine(int theLine) {
714    line = theLine;
715  }
716
717  public int getCol() {
718    return col;
719  }
720
721  public void setCol(int theCol) {
722    col = theCol;
723  }
724
725  public String getLocation() {
726    return location;
727  }
728  public ValidationMessage setLocation(String location) {
729    this.location = location;
730    return this;
731  }
732
733  public IssueType getType() {
734    return type;
735  }
736
737  public ValidationMessage setType(IssueType type) {
738    this.type = type;
739    return this;
740  }
741
742  public String summary() {
743    return level.toString()+" @ "+location+(line>= 0 && col >= 0 ? " (line "+Integer.toString(line)+", col"+Integer.toString(col)+"): " : ": ") +message+showCount() +(server != null ? " (src = "+server+")" : "");
744  }
745
746  public String summaryNoLevel() {
747    return location+(line>= 0 && col >= 0 ? " (line "+Integer.toString(line)+", col"+Integer.toString(col)+"): " : ": ") +message+showCount() +(server != null ? " (src = "+server+")" : "");
748  }
749
750
751  public String toXML() {
752    return "<message source=\"" + source + "\" line=\"" + line + "\" col=\"" + col + "\" location=\"" + Utilities.escapeXml(location) + "\" type=\"" + type + "\" level=\"" + level + "\" display=\"" + Utilities.escapeXml(getDisplay()) + "\" ><plain>" + Utilities.escapeXml(message)+showCount() + "</plain><html>" + html + "</html></message>";
753  }
754
755  public String getHtml() {
756    return (html == null ? Utilities.escapeXml(message) : html)+showCount();
757  }
758
759  public String getDisplay() {
760    return level + ": " + (location==null || location.isEmpty() ? "" : (location + ": ")) + message+showCount();
761  }
762
763  /**
764   * Returns a representation of this ValidationMessage suitable for logging. The values of
765   * most of the internal fields are included, so this may not be suitable for display to 
766   * an end user.
767   */
768  @Override
769  public String toString() {
770    ToStringBuilder b = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
771    b.append("level", level);
772    b.append("type", type);
773    b.append("location", location);
774    b.append("message", message+showCount());
775    return b.build();
776  }
777
778  @Override
779  public boolean equals(Object o) {
780    return (
781      this.getMessage() != null && this.getMessage().equals(((ValidationMessage)o).getMessage()))
782      && (this.getLocation() != null && this.getLocation().equals(((ValidationMessage)o).getLocation()));
783  }
784
785  @Override
786  public int compare(ValidationMessage x, ValidationMessage y) {
787    String sx = x.getLevel().getDisplay() + x.getType().getDisplay() + String.format("%06d", x.getLine()) + x.getMessage();
788    String sy = y.getLevel().getDisplay() + y.getType().getDisplay() + String.format("%06d", y.getLine()) + y.getMessage();
789    return sx.compareTo(sy);
790  }  
791
792  @Override
793  public int compareTo(ValidationMessage y) {
794    return compare(this, y);
795  }
796
797  public String getLocationLink() {
798    return locationLink;
799  }
800
801  public ValidationMessage setLocationLink(String locationLink) {
802    this.locationLink = locationLink;
803    return this;
804  }
805
806  public String getTxLink() {
807    return txLink;
808  }
809
810  public ValidationMessage setTxLink(String txLink) {
811    this.txLink = txLink;
812    return this;
813  }
814
815  public void setHtml(String html) {
816    this.html = html;
817  }
818
819  public boolean isSlicingHint() {
820    return slicingHint;
821  }
822
823  public ValidationMessage setSlicingHint(boolean slicingHint) {
824    this.slicingHint = slicingHint;
825    return this;
826  }
827
828  public String getSliceHtml() {
829    return sliceHtml;
830  }
831
832  public ValidationMessage setSliceHtml(String sliceHtml, List<ValidationMessage> info) {
833    this.sliceHtml = sliceHtml;
834    if (info != null) {
835      if (this.sliceInfo == null) {
836        this.sliceInfo = new ArrayList<ValidationMessage>();
837      }
838      this.sliceInfo.addAll(info);
839    }
840    return this;
841  }
842
843  public String getMessageId() {
844    return messageId;
845  }
846
847  public ValidationMessage setMessageId(String messageId) {
848    this.messageId = messageId;
849    return this;
850  }
851
852  public boolean isSignpost() {
853    return signpost;
854  }
855
856  public ValidationMessage setSignpost(boolean signpost) {
857    this.signpost = signpost;
858    return this;
859  }
860
861  public boolean isCriticalSignpost() {
862    return criticalSignpost;
863  }
864
865  public ValidationMessage setCriticalSignpost(boolean criticalSignpost) {
866    this.criticalSignpost = criticalSignpost;
867    return this;
868  }
869
870  public Date getRuleDate() {
871    return ruleDate;
872  }
873
874  public ValidationMessage setRuleDate(Date ruleDate) {
875    this.ruleDate = ruleDate;
876    return this;
877  }
878
879
880  public ValidationMessage setRuleDate(String value) {
881    if (value == null) {
882      ruleDate = null;
883    } else {
884      Date d = null;
885      try {
886        d = new SimpleDateFormat("yyyy-MM-dd").parse(value);
887      } catch (ParseException e) {
888        e.printStackTrace();
889      }
890      ruleDate = d;
891    }
892    return this;
893  }
894
895  public boolean isError() {
896    return level == IssueSeverity.ERROR || level == IssueSeverity.FATAL;
897  }
898
899  public boolean isMatched() {
900    return matched;
901  }
902
903  public void setMatched(boolean matched) {
904    this.matched = matched;
905  }
906
907  public boolean isIgnorableError() {
908    return ignorableError;
909  }
910
911  public ValidationMessage setIgnorableError(boolean ignorableError) {
912    this.ignorableError = ignorableError;
913    return this;
914  }
915
916  public boolean matches(ValidationMessage other) {
917    if (location == null) {
918      if (other.location != null) {
919        return false;
920      }
921    } else {
922      String l1 = preprocessLocation(location);
923      String l2 = preprocessLocation(other.location);
924      if (!l1.equals(l2)) {
925        return false;
926      }
927    }
928    if (message == null) {
929      if (other.message != null) {
930        return false;
931      }
932    } else if (!message.equals(other.message)) {
933      return false;
934    }
935    if (messageId == null) {
936      if (other.messageId != null) {
937        return false;
938      }
939    } else if (!messageId.equals(other.messageId)) {
940      return false;
941    }
942    if (type != other.type) {
943      return false;
944    }
945    if (level != other.level) {
946      return false;
947    }
948    return true;
949  }
950
951  private String preprocessLocation(String loc) {
952    // some locations are prefixes with a location but they're not different since the location is fixed where .match is called from 
953    if (loc.contains(": ")) {
954      return loc.substring(loc.indexOf(": ")+2);
955    }
956    return loc;
957  }
958
959  public String getInvId() {
960    return invId;
961  }
962
963  public ValidationMessage setInvId(String invId) {
964    this.invId = invId;
965    return this;
966  }
967
968  public String getComment() {
969    return comment;
970  }
971
972  public void setComment(String comment) {
973    this.comment = comment;
974  }
975
976  public List<ValidationMessage> getSliceInfo() {
977    return sliceInfo;
978  }
979
980  public void setSliceInfo(List<ValidationMessage> sliceInfo) {
981    this.sliceInfo = sliceInfo;
982  }
983
984  public String getServer() {
985    return server;
986  }
987
988  public void setServer(String server) {
989    this.server = server;
990  }
991
992  public void incCount() {
993    count++;
994  }
995
996  public boolean containsText(List<String> fragements) {
997    for (String s : fragements) {
998      if ((getMessage() != null && getMessage().contains(s)) || (getMessageId() != null && getMessageId().contains(s))) {
999        return true;
1000      }
1001    }
1002    return false;
1003  }
1004
1005  public boolean hasSliceInfo() {
1006    return sliceInfo != null && !sliceInfo.isEmpty();
1007  }
1008
1009  public boolean preciseMatch(ValidationMessage other) {
1010    if (other == null) {
1011      return false;
1012    }
1013
1014    // Compare source
1015    if (this.source != other.source) {
1016      return false;
1017    }
1018
1019    // Compare server
1020    if (!Objects.equals(this.server, other.server)) {
1021      return false;
1022    }
1023
1024    // Compare line
1025    if (this.line != other.line) {
1026      return false;
1027    }
1028
1029    // Compare col
1030    if (this.col != other.col) {
1031      return false;
1032    }
1033
1034    // Compare location
1035    if (!Objects.equals(this.location, other.location)) {
1036      return false;
1037    }
1038
1039    // Compare message
1040    if (!Objects.equals(this.message, other.message)) {
1041      return false;
1042    }
1043
1044    // Compare messageId
1045    if (!Objects.equals(this.messageId, other.messageId)) {
1046      return false;
1047    }
1048
1049    // Compare type
1050    if (this.type != other.type) {
1051      return false;
1052    }
1053
1054    // Compare level
1055    if (this.level != other.level) {
1056      return false;
1057    }
1058
1059    // Compare html
1060    if (!Objects.equals(this.html, other.html)) {
1061      return false;
1062    }
1063
1064    // Compare locationLink
1065    if (!Objects.equals(this.locationLink, other.locationLink)) {
1066      return false;
1067    }
1068
1069    // Compare txLink
1070    if (!Objects.equals(this.txLink, other.txLink)) {
1071      return false;
1072    }
1073
1074    // Compare sliceHtml
1075    if (!Objects.equals(this.sliceHtml, other.sliceHtml)) {
1076      return false;
1077    }
1078
1079    // Compare slicingHint
1080    if (this.slicingHint != other.slicingHint) {
1081      return false;
1082    }
1083
1084    // Compare signpost
1085    if (this.signpost != other.signpost) {
1086      return false;
1087    }
1088
1089    // Compare criticalSignpost
1090    if (this.criticalSignpost != other.criticalSignpost) {
1091      return false;
1092    }
1093
1094    // Compare ruleDate
1095    if (!Objects.equals(this.ruleDate, other.ruleDate)) {
1096      return false;
1097    }
1098
1099    // Compare matched
1100    if (this.matched != other.matched) {
1101      return false;
1102    }
1103
1104    // Compare ignorableError
1105    if (this.ignorableError != other.ignorableError) {
1106      return false;
1107    }
1108
1109    // Compare invId
1110    if (!Objects.equals(this.invId, other.invId)) {
1111      return false;
1112    }
1113
1114    // Compare comment
1115    if (!Objects.equals(this.comment, other.comment)) {
1116      return false;
1117    }
1118
1119    // Compare sliceInfo
1120    if (!Objects.equals(this.sliceInfo, other.sliceInfo)) {
1121      return false;
1122    }
1123
1124
1125    return true;
1126  }
1127
1128  public ValidationMessage setDiagnostics(String diagnostics) {
1129    this.diagnostics = diagnostics;
1130    return this;
1131  }
1132}