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