001package org.hl7.fhir.r5.utils;
002
003import org.hl7.fhir.r5.model.Base;
004import org.hl7.fhir.r5.model.Element;
005import org.hl7.fhir.r5.model.Property;
006import org.hl7.fhir.r5.model.Resource;
007import org.hl7.fhir.r5.utils.ElementVisitor.ElementVisitorInstruction;
008
009public class ElementVisitor {
010
011  public enum ElementVisitorInstruction {
012    VISIT_CHILDREN, NO_VISIT_CHILDREN;
013  }
014
015  public interface IElementVisitor {
016    public ElementVisitorInstruction visit(Object context, Resource resource);
017    public ElementVisitorInstruction visit(Object context, Element element);
018  }
019
020  private IElementVisitor visitor;
021  
022  public ElementVisitor(IElementVisitor visitor) {
023    this.visitor = visitor;
024  }
025
026  private void visitBase(Object context, Base base) {
027    for (Property p : base.children()) {
028      if (p.hasValues()) {
029        for (Base b : p.getValues()) {
030          if (b instanceof Resource) {
031            visit(context, (Resource) b);
032          } else {
033            visit(context, (Element) b);
034          }
035        }
036      }
037    }
038  }
039
040  public void visit(Object context, Resource res) {
041    ElementVisitorInstruction c = visitor.visit(context, res);
042    if (c == ElementVisitorInstruction.VISIT_CHILDREN) {
043      visitBase(context, res);
044    }
045  }
046
047  public void visit(Object context, Element e) {
048    ElementVisitorInstruction c = visitor.visit(context, e);
049    if (c == ElementVisitorInstruction.VISIT_CHILDREN) {
050      visitBase(context, e);
051    }
052  }
053
054}