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    boolean first = true;
080    for (OperationOutcomeIssueComponent t : error.getIssue()) {
081      if (first) first = false; else b.append("\r\n");
082      String txt = t.hasDetails() && t.getDetails().hasText() ?
083            t.getDetails().getText()
084            : t.hasDiagnostics() ? t.getDiagnostics() : gen(t.getDetails());
085      if (t.getSeverity() == IssueSeverity.ERROR)
086        b.append("Error: " + txt);
087      else if (t.getSeverity() == IssueSeverity.FATAL)
088        b.append("Fatal: " + txt);
089      else if (t.getSeverity() == IssueSeverity.WARNING)
090        b.append("Warning: " + txt);
091      else if (t.getSeverity() == IssueSeverity.INFORMATION)
092        b.append("Information: " + txt);
093    }
094    return b.toString();
095  }
096
097  private static String gen(CodeableConcept details) {
098    if (details.hasText()) {
099      return details.getText();
100    }
101    for (Coding c : details.getCoding()) {
102      if (c.hasDisplay()) {
103        return c.getDisplay();
104      }
105    }
106    for (Coding c : details.getCoding()) {
107      if (c.hasCode()) {
108        return c.getCode();
109      }
110    }
111    return "(no details supplied)";
112  }
113
114  public static Resource getById(Bundle feed, ResourceType type, String reference) {
115    for (BundleEntryComponent item : feed.getEntry()) {
116      if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
117        return item.getResource();
118    }
119    return null;
120  }
121
122  public static BundleEntryComponent getEntryById(Bundle feed, ResourceType type, String reference) {
123    for (BundleEntryComponent item : feed.getEntry()) {
124      if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
125        return item;
126    }
127    return null;
128  }
129
130  public static String getLink(Bundle feed, String rel) {
131    for (BundleLinkComponent link : feed.getLink()) {
132      if (link.getRelation().equals(rel))
133        return link.getUrl();
134    }
135    return null;
136  }
137
138  public static Meta meta(Resource resource) {
139    if (!resource.hasMeta())
140      resource.setMeta(new Meta());
141    return resource.getMeta();
142  }
143
144//  public static String representDataElementCollection(IWorkerContext context, Bundle bundle, boolean profileLink, String linkBase) {
145//    StringBuilder b = new StringBuilder();
146//    DataElement common = showDECHeader(b, bundle);
147//    b.append("<table class=\"grid\">\r\n"); 
148//    List<String> cols = chooseColumns(bundle, common, b, profileLink);
149//    for (BundleEntryComponent e : bundle.getEntry()) {
150//      DataElement de = (DataElement) e.getResource();
151//      renderDE(de, cols, b, profileLink, linkBase);
152//    }
153//    b.append("</table>\r\n");
154//    return b.toString();
155//  }
156//
157//  
158//  private static void renderDE(DataElement de, List<String> cols, StringBuilder b, boolean profileLink, String linkBase) {
159//    b.append("<tr>");
160//    for (String col : cols) {
161//      String v;
162//      ElementDefinition dee = de.getElement().get(0);
163//      if (col.equals("DataElement.name")) {
164//        v = de.hasName() ? Utilities.escapeXml(de.getName()) : "";
165//      } else if (col.equals("DataElement.status")) {
166//        v = de.hasStatusElement() ? de.getStatusElement().asStringValue() : "";
167//      } else if (col.equals("DataElement.code")) {
168//        v = renderCoding(dee.getCode());
169//      } else if (col.equals("DataElement.type")) {
170//        v = dee.hasType() ? Utilities.escapeXml(dee.getType().get(0).getCode()) : "";
171//      } else if (col.equals("DataElement.units")) {
172//        v = renderDEUnits(ToolingExtensions.getAllowedUnits(dee));
173//      } else if (col.equals("DataElement.binding")) {
174//        v = renderBinding(dee.getBinding());
175//      } else if (col.equals("DataElement.minValue")) {
176//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/minValue") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/minValue").asStringValue()) : "";
177//      } else if (col.equals("DataElement.maxValue")) {
178//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/maxValue") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/maxValue").asStringValue()) : "";
179//      } else if (col.equals("DataElement.maxLength")) {
180//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/maxLength") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/maxLength").asStringValue()) : "";
181//      } else if (col.equals("DataElement.mask")) {
182//        v = ToolingExtensions.hasExtension(de, "http://hl7.org/fhir/StructureDefinition/mask") ? Utilities.escapeXml(ToolingExtensions.readPrimitiveExtension(de, "http://hl7.org/fhir/StructureDefinition/mask").asStringValue()) : "";
183//      } else 
184//        throw new Error("Unknown column name: "+col);
185//
186//      b.append("<td>"+v+"</td>");
187//    }
188//    if (profileLink) {
189//      b.append("<td><a href=\""+linkBase+"-"+de.getId()+".html\">Profile</a>, <a href=\"http://www.opencem.org/#/20140917/Intermountain/"+de.getId()+"\">CEM</a>");
190//      if (ToolingExtensions.hasExtension(de, ToolingExtensions.EXT_CIMI_REFERENCE)) 
191//        b.append(", <a href=\""+ToolingExtensions.readStringExtension(de, ToolingExtensions.EXT_CIMI_REFERENCE)+"\">CIMI</a>");
192//      b.append("</td>");
193//    }
194//    b.append("</tr>\r\n");
195//  }
196
197  private static String renderBinding(ElementDefinitionBindingComponent binding) {
198    // TODO Auto-generated method stub
199    return null;
200  }
201
202  private static String renderDEUnits(Type units) {
203    if (units == null || units.isEmpty())
204      return "";
205    if (units instanceof CodeableConcept)
206      return renderCodeable((CodeableConcept) units);
207    else
208      return "<a href=\"" + Utilities.escapeXml(((Reference) units).getReference()) + "\">"
209          + Utilities.escapeXml(((Reference) units).getReference()) + "</a>";
210
211  }
212
213  private static String renderCodeable(CodeableConcept units) {
214    if (units == null || units.isEmpty())
215      return "";
216    String v = renderCoding(units.getCoding());
217    if (units.hasText())
218      v = v + " " + Utilities.escapeXml(units.getText());
219    return v;
220  }
221
222  private static String renderCoding(List<Coding> codes) {
223    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
224    for (Coding c : codes)
225      b.append(renderCoding(c));
226    return b.toString();
227  }
228
229  private static String renderCoding(Coding code) {
230    if (code == null || code.isEmpty())
231      return "";
232    else
233      return "<span title=\"" + Utilities.escapeXml(code.getSystem()) + "\">" + Utilities.escapeXml(code.getCode())
234          + "</span>";
235  }
236
237//  private static List<String> chooseColumns(Bundle bundle, DataElement common, StringBuilder b, boolean profileLink) {
238//    b.append("<tr>");
239//    List<String> results = new ArrayList<String>();
240//    results.add("DataElement.name");
241//    b.append("<td width=\"250\"><b>Name</b></td>");
242//    if (!common.hasStatus()) {
243//      results.add("DataElement.status");
244//      b.append("<td><b>Status</b></td>");
245//    }
246//    if (hasCode(bundle)) {
247//      results.add("DataElement.code");
248//      b.append("<td><b>Code</b></td>");
249//    }
250//    if (!common.getElement().get(0).hasType() && hasType(bundle)) {
251//      results.add("DataElement.type");
252//      b.append("<td><b>Type</b></td>");
253//    }
254//    if (hasUnits(bundle)) {
255//      results.add("DataElement.units");
256//      b.append("<td><b>Units</b></td>");
257//    }
258//    if (hasBinding(bundle)) {
259//      results.add("DataElement.binding");
260//      b.append("<td><b>Binding</b></td>");
261//    }
262//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/minValue")) {
263//      results.add("DataElement.minValue");
264//      b.append("<td><b>Min Value</b></td>");
265//    }
266//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/maxValue")) {
267//      results.add("DataElement.maxValue");
268//      b.append("<td><b>Max Value</b></td>");
269//    }
270//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/maxLength")) {
271//      results.add("DataElement.maxLength");
272//      b.append("<td><b>Max Length</b></td>");
273//    }
274//    if (hasExtension(bundle, "http://hl7.org/fhir/StructureDefinition/mask")) {
275//      results.add("DataElement.mask");
276//      b.append("<td><b>Mask</b></td>");
277//    }
278//    if (profileLink)
279//      b.append("<td><b>Links</b></td>");
280//    b.append("</tr>\r\n");
281//    return results;
282//  }
283//
284//  private static boolean hasExtension(Bundle bundle, String url) {
285//    for (BundleEntryComponent e : bundle.getEntry()) {
286//      DataElement de = (DataElement) e.getResource();
287//      if (ToolingExtensions.hasExtension(de, url))
288//        return true;
289//    }
290//    return false;
291//  }
292//
293//  private static boolean hasBinding(Bundle bundle) {
294//    for (BundleEntryComponent e : bundle.getEntry()) {
295//      DataElement de = (DataElement) e.getResource();
296//      if (de.getElement().get(0).hasBinding())
297//        return true;
298//    }
299//    return false;
300//  }
301//
302//  private static boolean hasCode(Bundle bundle) {
303//    for (BundleEntryComponent e : bundle.getEntry()) {
304//      DataElement de = (DataElement) e.getResource();
305//      if (de.getElement().get(0).hasCode())
306//        return true;
307//    }
308//    return false;
309//  }
310//
311//  private static boolean hasType(Bundle bundle) {
312//    for (BundleEntryComponent e : bundle.getEntry()) {
313//      DataElement de = (DataElement) e.getResource();
314//      if (de.getElement().get(0).hasType())
315//        return true;
316//    }
317//    return false;
318//  }
319//
320//  private static boolean hasUnits(Bundle bundle) {
321//    for (BundleEntryComponent e : bundle.getEntry()) {
322//      DataElement de = (DataElement) e.getResource();
323//      if (ToolingExtensions.getAllowedUnits(de.getElement().get(0)) != null)
324//        return true;
325//    }
326//    return false;
327//  }
328//
329//  private static DataElement showDECHeader(StringBuilder b, Bundle bundle) {
330//    DataElement meta = new DataElement();
331//    DataElement prototype = (DataElement) bundle.getEntry().get(0).getResource();
332//    meta.setPublisher(prototype.getPublisher());
333//    meta.getContact().addAll(prototype.getContact());
334//    meta.setStatus(prototype.getStatus());
335//    meta.setDate(prototype.getDate());
336//    meta.addElement().getType().addAll(prototype.getElement().get(0).getType());
337//
338//    for (BundleEntryComponent e : bundle.getEntry()) {
339//      DataElement de = (DataElement) e.getResource();
340//      if (!Base.compareDeep(de.getPublisherElement(), meta.getPublisherElement(), false))
341//        meta.setPublisherElement(null);
342//      if (!Base.compareDeep(de.getContact(), meta.getContact(), false))
343//        meta.getContact().clear();
344//      if (!Base.compareDeep(de.getStatusElement(), meta.getStatusElement(), false))
345//        meta.setStatusElement(null);
346//      if (!Base.compareDeep(de.getDateElement(), meta.getDateElement(), false))
347//        meta.setDateElement(null);
348//      if (!Base.compareDeep(de.getElement().get(0).getType(), meta.getElement().get(0).getType(), false))
349//        meta.getElement().get(0).getType().clear();
350//    }
351//    if (meta.hasPublisher() || meta.hasContact() || meta.hasStatus() || meta.hasDate() /* || meta.hasType() */) {
352//      b.append("<table class=\"grid\">\r\n"); 
353//      if (meta.hasPublisher())
354//        b.append("<tr><td>Publisher:</td><td>"+meta.getPublisher()+"</td></tr>\r\n");
355//      if (meta.hasContact()) {
356//        b.append("<tr><td>Contacts:</td><td>");
357//        boolean firsti = true;
358//        for (ContactDetail c : meta.getContact()) {
359//          if (firsti)
360//            firsti = false;
361//          else
362//            b.append("<br/>");
363//          if (c.hasName())
364//            b.append(Utilities.escapeXml(c.getName())+": ");
365//          boolean first = true;
366//          for (ContactPoint cp : c.getTelecom()) {
367//            if (first)
368//              first = false;
369//            else
370//              b.append(", ");
371//            renderContactPoint(b, cp);
372//          }
373//        }
374//        b.append("</td></tr>\r\n");
375//      }
376//      if (meta.hasStatus())
377//        b.append("<tr><td>Status:</td><td>"+meta.getStatus().toString()+"</td></tr>\r\n");
378//      if (meta.hasDate())
379//        b.append("<tr><td>Date:</td><td>"+meta.getDateElement().asStringValue()+"</td></tr>\r\n");
380//      if (meta.getElement().get(0).hasType())
381//        b.append("<tr><td>Type:</td><td>"+renderType(meta.getElement().get(0).getType())+"</td></tr>\r\n");
382//      b.append("</table>\r\n"); 
383//    }  
384//    return meta;
385//  }
386
387  private static String renderType(List<TypeRefComponent> type) {
388    if (type == null || type.isEmpty())
389      return "";
390    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
391    for (TypeRefComponent c : type)
392      b.append(renderType(c));
393    return b.toString();
394  }
395
396  private static String renderType(TypeRefComponent type) {
397    if (type == null || type.isEmpty())
398      return "";
399    return type.getWorkingCode();
400  }
401
402  public static void renderContactPoint(StringBuilder b, ContactPoint cp) {
403    if (cp != null && !cp.isEmpty()) {
404      if (cp.getSystem() == ContactPointSystem.EMAIL)
405        b.append("<a href=\"mailto:" + cp.getValue() + "\">" + cp.getValue() + "</a>");
406      else if (cp.getSystem() == ContactPointSystem.FAX)
407        b.append("Fax: " + cp.getValue());
408      else if (cp.getSystem() == ContactPointSystem.OTHER)
409        b.append("<a href=\"" + cp.getValue() + "\">" + cp.getValue() + "</a>");
410      else
411        b.append(cp.getValue());
412    }
413  }
414}