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