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