001package org.hl7.fhir.r4.utils;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032import java.util.List;
033
034import org.hl7.fhir.r4.model.Bundle;
035import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
036import org.hl7.fhir.r4.model.Bundle.BundleLinkComponent;
037import org.hl7.fhir.r4.model.CodeableConcept;
038import org.hl7.fhir.r4.model.Coding;
039import org.hl7.fhir.r4.model.ContactPoint;
040import org.hl7.fhir.r4.model.ContactPoint.ContactPointSystem;
041import org.hl7.fhir.r4.model.ElementDefinition.ElementDefinitionBindingComponent;
042import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
043import org.hl7.fhir.r4.model.Meta;
044import org.hl7.fhir.r4.model.OperationOutcome;
045import org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity;
046import org.hl7.fhir.r4.model.OperationOutcome.OperationOutcomeIssueComponent;
047import org.hl7.fhir.r4.model.Reference;
048import org.hl7.fhir.r4.model.Resource;
049import org.hl7.fhir.r4.model.ResourceType;
050import org.hl7.fhir.r4.model.Type;
051import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
052import org.hl7.fhir.utilities.Utilities;
053import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
054
055/**
056 * Decoration utilities for various resource types
057 * 
058 * @author Grahame
059 *
060 */
061public class ResourceUtilities {
062
063  public final static String FHIR_LANGUAGE = "urn:ietf:bcp:47";
064
065  public static boolean isAnError(OperationOutcome error) {
066    for (OperationOutcomeIssueComponent t : error.getIssue())
067      if (t.getSeverity() == IssueSeverity.ERROR)
068        return true;
069      else if (t.getSeverity() == IssueSeverity.FATAL)
070        return true;
071    return false;
072  }
073
074  public static String getErrorDescription(OperationOutcome error) {
075    if (error.hasText() && error.getText().hasDiv())
076      return new XhtmlComposer(XhtmlComposer.XML).composePlainText(error.getText().getDiv());
077
078    StringBuilder b = new StringBuilder();
079    for (OperationOutcomeIssueComponent t : error.getIssue())
080      if (t.getSeverity() == IssueSeverity.ERROR)
081        b.append("Error:" + gen(t.getDetails()) + "\r\n");
082      else if (t.getSeverity() == IssueSeverity.FATAL)
083        b.append("Fatal:" + gen(t.getDetails()) + "\r\n");
084      else if (t.getSeverity() == IssueSeverity.WARNING)
085        b.append("Warning:" + gen(t.getDetails()) + "\r\n");
086      else if (t.getSeverity() == IssueSeverity.INFORMATION)
087        b.append("Information:" + gen(t.getDetails()) + "\r\n");
088    return b.toString();
089  }
090
091  private static String gen(CodeableConcept details) {
092    if (details.hasText()) {
093      return details.getText();
094    }
095    for (Coding c : details.getCoding()) {
096      if (c.hasDisplay()) {
097        return c.getDisplay();
098      }
099    }
100    for (Coding c : details.getCoding()) {
101      if (c.hasCode()) {
102        return c.getCode();
103      }
104    }
105    return "(no details supplied)";
106  }
107
108  public static Resource getById(Bundle feed, ResourceType type, String reference) {
109    for (BundleEntryComponent item : feed.getEntry()) {
110      if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
111        return item.getResource();
112    }
113    return null;
114  }
115
116  public static BundleEntryComponent getEntryById(Bundle feed, ResourceType type, String reference) {
117    for (BundleEntryComponent item : feed.getEntry()) {
118      if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
119        return item;
120    }
121    return null;
122  }
123
124  public static String getLink(Bundle feed, String rel) {
125    for (BundleLinkComponent link : feed.getLink()) {
126      if (link.getRelation().equals(rel))
127        return link.getUrl();
128    }
129    return null;
130  }
131
132  public static Meta meta(Resource resource) {
133    if (!resource.hasMeta())
134      resource.setMeta(new Meta());
135    return resource.getMeta();
136  }
137
138//  public static String representDataElementCollection(IWorkerContext context, Bundle bundle, boolean profileLink, String linkBase) {
139//    StringBuilder b = new StringBuilder();
140//    DataElement common = showDECHeader(b, bundle);
141//    b.append("<table class=\"grid\">\r\n"); 
142//    List<String> cols = chooseColumns(bundle, common, b, profileLink);
143//    for (BundleEntryComponent e : bundle.getEntry()) {
144//      DataElement de = (DataElement) e.getResource();
145//      renderDE(de, cols, b, profileLink, linkBase);
146//    }
147//    b.append("</table>\r\n");
148//    return b.toString();
149//  }
150//
151//  
152//  private static void renderDE(DataElement de, List<String> cols, StringBuilder b, boolean profileLink, String linkBase) {
153//    b.append("<tr>");
154//    for (String col : cols) {
155//      String v;
156//      ElementDefinition dee = de.getElement().get(0);
157//      if (col.equals("DataElement.name")) {
158//        v = de.hasName() ? Utilities.escapeXml(de.getName()) : "";
159//      } else if (col.equals("DataElement.status")) {
160//        v = de.hasStatusElement() ? de.getStatusElement().asStringValue() : "";
161//      } else if (col.equals("DataElement.code")) {
162//        v = renderCoding(dee.getCode());
163//      } else if (col.equals("DataElement.type")) {
164//        v = dee.hasType() ? Utilities.escapeXml(dee.getType().get(0).getCode()) : "";
165//      } else if (col.equals("DataElement.units")) {
166//        v = renderDEUnits(ToolingExtensions.getAllowedUnits(dee));
167//      } else if (col.equals("DataElement.binding")) {
168//        v = renderBinding(dee.getBinding());
169//      } else if (col.equals("DataElement.minValue")) {
170//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/minValue") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/minValue").asStringValue()) : "";
171//      } else if (col.equals("DataElement.maxValue")) {
172//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/maxValue") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/maxValue").asStringValue()) : "";
173//      } else if (col.equals("DataElement.maxLength")) {
174//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/maxLength") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/maxLength").asStringValue()) : "";
175//      } else if (col.equals("DataElement.mask")) {
176//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/mask") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/mask").asStringValue()) : "";
177//      } else 
178//        throw new Error("Unknown column name: "+col);
179//
180//      b.append("<td>"+v+"</td>");
181//    }
182//    if (profileLink) {
183//      b.append("<td><a href=\""+linkBase+"-"+de.getId()+".html\">Profile</a>, <a href=\"http://www.opencem.org/#/20140917/Intermountain/"+de.getId()+"\">CEM</a>");
184//      if (ToolingExtensions.hasExtension(de, ToolingExtensions.EXT_CIMI_REFERENCE)) 
185//        b.append(", <a href=\""+ToolingExtensions.readStringExtension(de, ToolingExtensions.EXT_CIMI_REFERENCE)+"\">CIMI</a>");
186//      b.append("</td>");
187//    }
188//    b.append("</tr>\r\n");
189//  }
190
191  private static String renderBinding(ElementDefinitionBindingComponent binding) {
192    // TODO Auto-generated method stub
193    return null;
194  }
195
196  private static String renderDEUnits(Type units) {
197    if (units == null || units.isEmpty())
198      return "";
199    if (units instanceof CodeableConcept)
200      return renderCodeable((CodeableConcept) units);
201    else
202      return "<a href=\"" + Utilities.escapeXml(((Reference) units).getReference()) + "\">"
203          + Utilities.escapeXml(((Reference) units).getReference()) + "</a>";
204
205  }
206
207  private static String renderCodeable(CodeableConcept units) {
208    if (units == null || units.isEmpty())
209      return "";
210    String v = renderCoding(units.getCoding());
211    if (units.hasText())
212      v = v + " " + Utilities.escapeXml(units.getText());
213    return v;
214  }
215
216  private static String renderCoding(List<Coding> codes) {
217    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
218    for (Coding c : codes)
219      b.append(renderCoding(c));
220    return b.toString();
221  }
222
223  private static String renderCoding(Coding code) {
224    if (code == null || code.isEmpty())
225      return "";
226    else
227      return "<span title=\"" + Utilities.escapeXml(code.getSystem()) + "\">" + Utilities.escapeXml(code.getCode())
228          + "</span>";
229  }
230
231//  private static List<String> chooseColumns(Bundle bundle, DataElement common, StringBuilder b, boolean profileLink) {
232//    b.append("<tr>");
233//    List<String> results = new ArrayList<String>();
234//    results.add("DataElement.name");
235//    b.append("<td width=\"250\"><b>Name</b></td>");
236//    if (!common.hasStatus()) {
237//      results.add("DataElement.status");
238//      b.append("<td><b>Status</b></td>");
239//    }
240//    if (hasCode(bundle)) {
241//      results.add("DataElement.code");
242//      b.append("<td><b>Code</b></td>");
243//    }
244//    if (!common.getElement().get(0).hasType() && hasType(bundle)) {
245//      results.add("DataElement.type");
246//      b.append("<td><b>Type</b></td>");
247//    }
248//    if (hasUnits(bundle)) {
249//      results.add("DataElement.units");
250//      b.append("<td><b>Units</b></td>");
251//    }
252//    if (hasBinding(bundle)) {
253//      results.add("DataElement.binding");
254//      b.append("<td><b>Binding</b></td>");
255//    }
256//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/minValue")) {
257//      results.add("DataElement.minValue");
258//      b.append("<td><b>Min Value</b></td>");
259//    }
260//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/maxValue")) {
261//      results.add("DataElement.maxValue");
262//      b.append("<td><b>Max Value</b></td>");
263//    }
264//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/maxLength")) {
265//      results.add("DataElement.maxLength");
266//      b.append("<td><b>Max Length</b></td>");
267//    }
268//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/mask")) {
269//      results.add("DataElement.mask");
270//      b.append("<td><b>Mask</b></td>");
271//    }
272//    if (profileLink)
273//      b.append("<td><b>Links</b></td>");
274//    b.append("</tr>\r\n");
275//    return results;
276//  }
277//
278//  private static boolean hasExtension(Bundle bundle, String url) {
279//    for (BundleEntryComponent e : bundle.getEntry()) {
280//      DataElement de = (DataElement) e.getResource();
281//      if (ToolingExtensions.hasExtension(de, url))
282//        return true;
283//    }
284//    return false;
285//  }
286//
287//  private static boolean hasBinding(Bundle bundle) {
288//    for (BundleEntryComponent e : bundle.getEntry()) {
289//      DataElement de = (DataElement) e.getResource();
290//      if (de.getElement().get(0).hasBinding())
291//        return true;
292//    }
293//    return false;
294//  }
295//
296//  private static boolean hasCode(Bundle bundle) {
297//    for (BundleEntryComponent e : bundle.getEntry()) {
298//      DataElement de = (DataElement) e.getResource();
299//      if (de.getElement().get(0).hasCode())
300//        return true;
301//    }
302//    return false;
303//  }
304//
305//  private static boolean hasType(Bundle bundle) {
306//    for (BundleEntryComponent e : bundle.getEntry()) {
307//      DataElement de = (DataElement) e.getResource();
308//      if (de.getElement().get(0).hasType())
309//        return true;
310//    }
311//    return false;
312//  }
313//
314//  private static boolean hasUnits(Bundle bundle) {
315//    for (BundleEntryComponent e : bundle.getEntry()) {
316//      DataElement de = (DataElement) e.getResource();
317//      if (ToolingExtensions.getAllowedUnits(de.getElement().get(0)) != null)
318//        return true;
319//    }
320//    return false;
321//  }
322//
323//  private static DataElement showDECHeader(StringBuilder b, Bundle bundle) {
324//    DataElement meta = new DataElement();
325//    DataElement prototype = (DataElement) bundle.getEntry().get(0).getResource();
326//    meta.setPublisher(prototype.getPublisher());
327//    meta.getContact().addAll(prototype.getContact());
328//    meta.setStatus(prototype.getStatus());
329//    meta.setDate(prototype.getDate());
330//    meta.addElement().getType().addAll(prototype.getElement().get(0).getType());
331//
332//    for (BundleEntryComponent e : bundle.getEntry()) {
333//      DataElement de = (DataElement) e.getResource();
334//      if (!Base.compareDeep(de.getPublisherElement(), meta.getPublisherElement(), false))
335//        meta.setPublisherElement(null);
336//      if (!Base.compareDeep(de.getContact(), meta.getContact(), false))
337//        meta.getContact().clear();
338//      if (!Base.compareDeep(de.getStatusElement(), meta.getStatusElement(), false))
339//        meta.setStatusElement(null);
340//      if (!Base.compareDeep(de.getDateElement(), meta.getDateElement(), false))
341//        meta.setDateElement(null);
342//      if (!Base.compareDeep(de.getElement().get(0).getType(), meta.getElement().get(0).getType(), false))
343//        meta.getElement().get(0).getType().clear();
344//    }
345//    if (meta.hasPublisher() || meta.hasContact() || meta.hasStatus() || meta.hasDate() /* || meta.hasType() */) {
346//      b.append("<table class=\"grid\">\r\n"); 
347//      if (meta.hasPublisher())
348//        b.append("<tr><td>Publisher:</td><td>"+meta.getPublisher()+"</td></tr>\r\n");
349//      if (meta.hasContact()) {
350//        b.append("<tr><td>Contacts:</td><td>");
351//        boolean firsti = true;
352//        for (ContactDetail c : meta.getContact()) {
353//          if (firsti)
354//            firsti = false;
355//          else
356//            b.append("<br/>");
357//          if (c.hasName())
358//            b.append(Utilities.escapeXml(c.getName())+": ");
359//          boolean first = true;
360//          for (ContactPoint cp : c.getTelecom()) {
361//            if (first)
362//              first = false;
363//            else
364//              b.append(", ");
365//            renderContactPoint(b, cp);
366//          }
367//        }
368//        b.append("</td></tr>\r\n");
369//      }
370//      if (meta.hasStatus())
371//        b.append("<tr><td>Status:</td><td>"+meta.getStatus().toString()+"</td></tr>\r\n");
372//      if (meta.hasDate())
373//        b.append("<tr><td>Date:</td><td>"+meta.getDateElement().asStringValue()+"</td></tr>\r\n");
374//      if (meta.getElement().get(0).hasType())
375//        b.append("<tr><td>Type:</td><td>"+renderType(meta.getElement().get(0).getType())+"</td></tr>\r\n");
376//      b.append("</table>\r\n"); 
377//    }  
378//    return meta;
379//  }
380
381  private static String renderType(List<TypeRefComponent> type) {
382    if (type == null || type.isEmpty())
383      return "";
384    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
385    for (TypeRefComponent c : type)
386      b.append(renderType(c));
387    return b.toString();
388  }
389
390  private static String renderType(TypeRefComponent type) {
391    if (type == null || type.isEmpty())
392      return "";
393    return type.getWorkingCode();
394  }
395
396  public static void renderContactPoint(StringBuilder b, ContactPoint cp) {
397    if (cp != null && !cp.isEmpty()) {
398      if (cp.getSystem() == ContactPointSystem.EMAIL)
399        b.append("<a href=\"mailto:" + cp.getValue() + "\">" + cp.getValue() + "</a>");
400      else if (cp.getSystem() == ContactPointSystem.FAX)
401        b.append("Fax: " + cp.getValue());
402      else if (cp.getSystem() == ContactPointSystem.OTHER)
403        b.append("<a href=\"" + cp.getValue() + "\">" + cp.getValue() + "</a>");
404      else
405        b.append(cp.getValue());
406    }
407  }
408}