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