001package org.hl7.fhir.r5.elementmodel;
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.io.ByteArrayInputStream;
033import java.io.ByteArrayOutputStream;
034import java.io.IOException;
035import java.util.ArrayList;
036import java.util.List;
037
038import org.hl7.fhir.exceptions.FHIRException;
039import org.hl7.fhir.r5.conformance.profile.ProfileUtilities;
040import org.hl7.fhir.r5.conformance.profile.ProfileUtilities.SourcedChildDefinitions;
041import org.hl7.fhir.r5.context.IWorkerContext;
042import org.hl7.fhir.r5.elementmodel.ParserBase.NamedElement;
043import org.hl7.fhir.r5.formats.IParser.OutputStyle;
044import org.hl7.fhir.r5.model.Base;
045import org.hl7.fhir.r5.model.CodeableConcept;
046import org.hl7.fhir.r5.model.Coding;
047import org.hl7.fhir.r5.model.DataType;
048import org.hl7.fhir.r5.model.ElementDefinition;
049import org.hl7.fhir.r5.model.Factory;
050import org.hl7.fhir.r5.model.Identifier;
051import org.hl7.fhir.r5.model.PrimitiveType;
052import org.hl7.fhir.r5.model.Reference;
053import org.hl7.fhir.r5.model.Resource;
054import org.hl7.fhir.r5.model.StructureDefinition;
055import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
056
057
058public class ObjectConverter  {
059
060  private IWorkerContext context;
061  private ProfileUtilities profileUtilities;
062
063  public ObjectConverter(IWorkerContext context) {
064    this.context = context;
065    profileUtilities = new ProfileUtilities(context, null, null);
066  }
067
068  public Element convert(Resource ig) throws IOException, FHIRException {
069    if (ig == null)
070      return null;
071    ByteArrayOutputStream bs = new ByteArrayOutputStream();
072    org.hl7.fhir.r5.formats.JsonParser jp = new org.hl7.fhir.r5.formats.JsonParser();
073    jp.compose(bs, ig);
074    ByteArrayInputStream bi = new ByteArrayInputStream(bs.toByteArray());
075    List<NamedElement> list = new JsonParser(context).parse(bi);
076    if (list.size() != 1) {
077      throw new FHIRException("Unable to convert because the source contains multieple resources");
078    }
079    return list.get(0).getElement();
080  }
081
082  public Element convert(Property property, DataType type) throws FHIRException {
083    return convertElement(property, type);
084  }
085  
086  private Element convertElement(Property property, Base base) throws FHIRException {
087    if (base == null)
088      return null;
089    String tn = base.fhirType();
090    StructureDefinition sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(tn, null));
091    if (sd == null)
092      throw new FHIRException("Unable to find definition for type "+tn);
093    Element res = new Element(property.getName(), property);
094    if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) 
095      res.setValue(((PrimitiveType) base).asStringValue());
096
097    SourcedChildDefinitions children = profileUtilities.getChildMap(sd, sd.getSnapshot().getElementFirstRep()); 
098    for (ElementDefinition child : children.getList()) {
099      String n = tail(child.getPath());
100      if (sd.getKind() != StructureDefinitionKind.PRIMITIVETYPE || !"value".equals(n)) {
101        Base[] values = base.getProperty(n.hashCode(), n, false);
102        if (values != null)
103          for (Base value : values) {
104            res.getChildren().add(convertElement(new Property(context, child, sd), value));
105          }
106      }
107    }
108    return res;
109  }
110
111  private String tail(String path) {
112    if (path.contains("."))
113      return path.substring(path.lastIndexOf('.')+1);
114    else
115      return path;
116  }
117
118  public DataType convertToType(Element element) throws FHIRException {
119    DataType b = new Factory().create(element.fhirType());
120    if (b instanceof PrimitiveType) {
121      ((PrimitiveType) b).setValueAsString(element.primitiveValue());
122    } else {
123      for (Element child : element.getChildren()) {
124        b.setProperty(child.getName(), convertToType(child));
125      }
126    }
127    return b;
128  }
129
130  public Resource convert(Element element) throws FHIRException {
131    ByteArrayOutputStream bo = new ByteArrayOutputStream();
132    try {
133      new JsonParser(context).compose(element, bo, OutputStyle.NORMAL, null);
134      return new org.hl7.fhir.r5.formats.JsonParser().parse(bo.toByteArray());
135    } catch (IOException e) {
136      // won't happen
137      throw new FHIRException(e);
138    }
139    
140  }
141
142  public static CodeableConcept readAsCodeableConcept(Element element) {
143    if (element == null) {
144      return null;
145    }
146    CodeableConcept cc = new CodeableConcept();
147    List<Element> list = new ArrayList<Element>();
148    element.getNamedChildren("coding", list);
149    for (Element item : list)
150      cc.addCoding(readAsCoding(item));
151    cc.setText(element.getNamedChildValue("text"));
152    return cc;
153  }
154
155  public static Coding readAsCoding(Element item) {
156    Coding c = new Coding();
157    c.setSystem(item.getNamedChildValue("system"));
158    c.setVersion(item.getNamedChildValue("version"));
159    c.setCode(item.getNamedChildValue("code"));
160    c.setDisplay(item.getNamedChildValue("display"));
161    return c;
162  }
163
164  public static Identifier readAsIdentifier(Element item) {
165    Identifier r = new Identifier();
166    r.setSystem(item.getNamedChildValue("system"));
167    r.setValue(item.getNamedChildValue("value"));
168    return r;
169  }
170
171  public static Reference readAsReference(Element item) {
172    Reference r = new Reference();
173    r.setDisplay(item.getNamedChildValue("display"));
174    r.setReference(item.getNamedChildValue("reference"));
175    r.setType(item.getNamedChildValue("type"));
176    if (!r.hasType()) {
177      Element ext = item.getExtension("http://hl7.org/fhir/4.0/StructureDefinition/extension-Reference.type");
178      if (ext != null) {
179        r.setType(ext.getChildValue("valueUri"));
180      }
181    }
182    List<Element> identifier = item.getChildrenByName("identifier");
183    if (identifier.isEmpty() == false) {
184      r.setIdentifier(readAsIdentifier(identifier.get(0)));
185    }
186    return r;
187  }
188
189}