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