Coverage Report - ca.uhn.hl7v2.parser.MessageIterator
 
Classes in this File Line Coverage Branch Coverage Complexity
MessageIterator
89%
111/124
91%
68/74
3.522
MessageIterator$1
100%
1/1
N/A
3.522
MessageIterator$Position
43%
13/30
0%
0/10
3.522
 
 1  
 package ca.uhn.hl7v2.parser;
 2  
 
 3  
 import java.util.ArrayList;
 4  
 import java.util.Arrays;
 5  
 import java.util.List;
 6  
 import java.util.NoSuchElementException;
 7  
 
 8  
 import org.slf4j.Logger;
 9  
 import org.slf4j.LoggerFactory;
 10  
 
 11  
 import ca.uhn.hl7v2.HL7Exception;
 12  
 import ca.uhn.hl7v2.model.Group;
 13  
 import ca.uhn.hl7v2.model.Message;
 14  
 import ca.uhn.hl7v2.model.Structure;
 15  
 
 16  
 /**
 17  
  * Iterates over all defined nodes (ie segments, groups) in a message,
 18  
  * regardless of whether they have been instantiated previously. This is a
 19  
  * tricky process, because the number of nodes is infinite, due to infinitely
 20  
  * repeating segments and groups. See <code>next()</code> for details on how
 21  
  * this is handled.
 22  
  * 
 23  
  * This implementation assumes that the first segment in each group is present
 24  
  * (as per HL7 rules). Specifically, when looking for a segment location, an
 25  
  * empty group that has a spot for the segment will be overlooked if there is
 26  
  * anything else before that spot. This may result in surprising (but sensible)
 27  
  * behaviour if a message is missing the first segment in a group.
 28  
  * 
 29  
  * @author Bryan Tripp
 30  
  */
 31  0
 public class MessageIterator implements java.util.Iterator<Structure> {
 32  
 
 33  
     private Message myMessage;
 34  
     private String myDirection;
 35  
     private boolean myNextIsSet;
 36  
     private boolean myHandleUnexpectedSegments;
 37  3391
     private List<Position> myCurrentDefinitionPath = new ArrayList<Position>();
 38  
 
 39  5
     private static final Logger log = LoggerFactory.getLogger(MessageIterator.class);
 40  
 
 41  
     /*
 42  
      * may add configurability later ... private boolean findUpToFirstRequired;
 43  
      * private boolean findFirstDescendentsOnly;
 44  
      * 
 45  
      * public static final String WHOLE_GROUP; public static final String
 46  
      * FIRST_DESCENDENTS_ONLY; public static final String UP_TO_FIRST_REQUIRED;
 47  
      */
 48  
 
 49  
     /** Creates a new instance of MessageIterator */
 50  3391
     public MessageIterator(Message start, IStructureDefinition startDefinition, String direction, boolean handleUnexpectedSegments) {
 51  3391
         this.myMessage = start;
 52  3391
         this.myDirection = direction;
 53  3391
         this.myHandleUnexpectedSegments = handleUnexpectedSegments;
 54  3391
         this.myCurrentDefinitionPath.add(new Position(startDefinition, -1));
 55  3391
     }
 56  
 
 57  
     private Position getCurrentPosition() {
 58  41026
         return getTail(myCurrentDefinitionPath);
 59  
     }
 60  
 
 61  
     private Position getTail(List<Position> theDefinitionPath) {
 62  42807
         return theDefinitionPath.get(theDefinitionPath.size() - 1);
 63  
     }
 64  
 
 65  
     private List<Position> popUntilMatchFound(List<Position> theDefinitionPath) {
 66  1781
         theDefinitionPath = new ArrayList<Position>(theDefinitionPath.subList(0, theDefinitionPath.size() - 1));
 67  
 
 68  1781
         Position newCurrentPosition = getTail(theDefinitionPath);
 69  1780
         IStructureDefinition newCurrentStructureDefinition = newCurrentPosition.getStructureDefinition();
 70  
 
 71  1780
         if (newCurrentStructureDefinition.getAllPossibleFirstChildren().contains(myDirection)) {
 72  695
             return theDefinitionPath;
 73  
         }
 74  
 
 75  1085
         if (newCurrentStructureDefinition.isFinalChildOfParent()) {
 76  440
             if (theDefinitionPath.size() > 1) {
 77  265
                 return popUntilMatchFound(theDefinitionPath); // recurse
 78  
             } else {
 79  175
                     log.debug("Popped to root of message and did not find a match for {}", myDirection);
 80  175
                 return null;
 81  
             }
 82  
         }
 83  
 
 84  645
         return theDefinitionPath;
 85  
     }
 86  
 
 87  
     /**
 88  
      * Returns true if another object exists in the iteration sequence.
 89  
      */
 90  
     public boolean hasNext() {
 91  
 
 92  23705
         log.trace("hasNext() for direction {}", myDirection);
 93  23705
         if (myDirection == null) {
 94  0
             throw new IllegalStateException("Direction not set");
 95  
         }
 96  
 
 97  61110
         while (!myNextIsSet) {
 98  
 
 99  37412
             Position currentPosition = getCurrentPosition();
 100  
 
 101  37412
             log.trace("hasNext() current position: {}", currentPosition);
 102  
 
 103  37412
             IStructureDefinition structureDefinition = currentPosition.getStructureDefinition();
 104  
             
 105  37412
             if (myMessage.getParser().getParserConfiguration().isNonGreedyMode()) {
 106  200
                     IStructureDefinition nonGreedyPosition = couldBeNotGreedy();
 107  200
                     if (nonGreedyPosition != null) {
 108  20
                             log.info("Found non greedy parsing choice, moving to {}", nonGreedyPosition.getName());
 109  60
                             while (getCurrentPosition().getStructureDefinition() != nonGreedyPosition) {
 110  40
                                     myCurrentDefinitionPath.remove(myCurrentDefinitionPath.size() - 1);
 111  
                             }
 112  
                     }
 113  
             }
 114  
             
 115  37412
             if (structureDefinition.isSegment() && structureDefinition.getName().startsWith(myDirection) && (structureDefinition.isRepeating() || currentPosition.getRepNumber() == -1)) {
 116  10666
                 myNextIsSet = true;
 117  10666
                 currentPosition.incrementRep();
 118  26746
             } else if (structureDefinition.isSegment() && structureDefinition.getNextLeaf() == null
 119  807
                     && !structureDefinition.getNamesOfAllPossibleFollowingLeaves().contains(myDirection)) {
 120  652
                 if (!myHandleUnexpectedSegments) {
 121  0
                     return false;
 122  
                 }
 123  652
                 addNonStandardSegmentAtCurrentPosition();
 124  26094
             } else if (structureDefinition.hasChildren() && structureDefinition.getAllPossibleFirstChildren().contains(myDirection) && (structureDefinition.isRepeating() || currentPosition.getRepNumber() == -1)) {
 125  8676
                 currentPosition.incrementRep();
 126  8676
                 myCurrentDefinitionPath.add(new Position(structureDefinition.getFirstChild(), -1));
 127  17418
             } else if (!structureDefinition.hasChildren() && !structureDefinition.getNamesOfAllPossibleFollowingLeaves().contains(myDirection)) {
 128  361
                 if (!myHandleUnexpectedSegments) {
 129  0
                     return false;
 130  
                 }
 131  361
                 addNonStandardSegmentAtCurrentPosition();
 132  
                 // } else if (structureDefinition.isMessage()) {
 133  
                 // if (!handleUnexpectedSegments) {
 134  
                 // return false;
 135  
                 // }
 136  
                 // addNonStandardSegmentAtCurrentPosition();
 137  17056
             } else if (structureDefinition.isFinalChildOfParent()) {
 138  1516
                 List<Position> newDefinitionPath = popUntilMatchFound(myCurrentDefinitionPath);
 139  1515
                 if (newDefinitionPath != null) {
 140  
                     // found match
 141  1340
                     myCurrentDefinitionPath = newDefinitionPath;
 142  
                 } else {
 143  175
                     if (!myHandleUnexpectedSegments) {
 144  0
                         return false;
 145  
                     }
 146  175
                     addNonStandardSegmentAtCurrentPosition();
 147  
                 }
 148  1515
             } else {
 149  15540
                 currentPosition.setStructureDefinition(structureDefinition.getNextSibling());
 150  15540
                 currentPosition.resetRepNumber();
 151  
             }
 152  
 
 153  37405
         }
 154  
 
 155  23698
         return true;
 156  
     }
 157  
 
 158  
     /**
 159  
      * @see ParserConfiguration#setNonGreedyMode(boolean)
 160  
      */
 161  
     private IStructureDefinition couldBeNotGreedy() {
 162  545
             for (int i = myCurrentDefinitionPath.size() - 1; i >= 1; i--) {
 163  365
                     Position position = myCurrentDefinitionPath.get(i);
 164  365
                     IStructureDefinition curPos = position.getStructureDefinition();
 165  365
                     if (curPos.getPosition() > 0) {
 166  260
                             IStructureDefinition parent = curPos.getParent();
 167  260
                                 if (parent.isRepeating() && parent.getAllPossibleFirstChildren().contains(myDirection)) {
 168  20
                                     return parent;
 169  
                             }
 170  
                     }
 171  
                     
 172  
             }
 173  
             
 174  180
                 return null;
 175  
         }
 176  
 
 177  
         private void addNonStandardSegmentAtCurrentPosition() throws Error {
 178  2376
             log.debug("Creating non standard segment {} on group: {}", 
 179  1188
                             myDirection, getCurrentPosition().getStructureDefinition().getParent().getName());
 180  
         
 181  
             List<Position> parentDefinitionPath;
 182  
         Group parentStructure;
 183  
         
 184  1188
         switch (myMessage.getParser().getParserConfiguration().getUnexpectedSegmentBehaviour()) {
 185  
         case ADD_INLINE:
 186  
         default:
 187  1168
                 parentDefinitionPath = new ArrayList<Position>(myCurrentDefinitionPath.subList(0, myCurrentDefinitionPath.size() - 1));
 188  1168
                 parentStructure = (Group) navigateToStructure(parentDefinitionPath);
 189  1168
                 break;
 190  
         case DROP_TO_ROOT:
 191  15
                 parentDefinitionPath = new ArrayList<Position>(myCurrentDefinitionPath.subList(0, 1));
 192  15
                 parentStructure = myMessage;
 193  15
                 myCurrentDefinitionPath = myCurrentDefinitionPath.subList(0, 2);
 194  15
                 break;
 195  
         case THROW_HL7_EXCEPTION:
 196  5
                 throw new Error(new HL7Exception("Found unknown segment: " + myDirection));
 197  
         }
 198  
         
 199  
         
 200  
         // Current position within parent
 201  1183
         Position currentPosition = getCurrentPosition();
 202  1183
                 String nameAsItAppearsInParent = currentPosition.getStructureDefinition().getNameAsItAppearsInParent();
 203  
 
 204  1183
                 int index = Arrays.asList(parentStructure.getNames()).indexOf(nameAsItAppearsInParent) + 1;
 205  
                 
 206  
         String newSegmentName;
 207  
                 
 208  
                 // Check if the structure already has a non-standard segment in the appropriate
 209  
                 // position
 210  1183
                 String[] currentNames = parentStructure.getNames();
 211  1183
                 if (index < currentNames.length && currentNames[index].startsWith(myDirection)) {
 212  10
                         newSegmentName = currentNames[index];
 213  
                 } else { 
 214  
                 try {
 215  1173
                     newSegmentName = parentStructure.addNonstandardSegment(myDirection, index);
 216  0
                 } catch (HL7Exception e) {
 217  0
                     throw new Error("Unable to add nonstandard segment " + myDirection + ": ", e);
 218  1173
                 }
 219  
             }
 220  
                 
 221  1183
         IStructureDefinition previousSibling = getCurrentPosition().getStructureDefinition();
 222  1183
         IStructureDefinition parentStructureDefinition = parentDefinitionPath.get(parentDefinitionPath.size() - 1).getStructureDefinition();
 223  1183
         NonStandardStructureDefinition nextDefinition = new NonStandardStructureDefinition(parentStructureDefinition, previousSibling, newSegmentName, index);
 224  1183
         myCurrentDefinitionPath = parentDefinitionPath;
 225  1183
         myCurrentDefinitionPath.add(new Position(nextDefinition, 0));
 226  
 
 227  1183
         myNextIsSet = true;
 228  1183
     }
 229  
 
 230  
     /**
 231  
      * <p>
 232  
      * Returns the next node in the message. Sometimes the next node is
 233  
      * ambiguous. For example at the end of a repeating group, the next node may
 234  
      * be the first segment in the next repetition of the group, or the next
 235  
      * sibling, or an undeclared segment locally added to the group's end. Cases
 236  
      * like this are disambiguated using getDirection(), which returns the name
 237  
      * of the structure that we are "iterating towards". Usually we are
 238  
      * "iterating towards" a segment of a certain name because we have a segment
 239  
      * string that we would like to parse into that node. Here are the rules:
 240  
      * </p>
 241  
      * <ol>
 242  
      * <li>If at a group, next means first child.</li>
 243  
      * <li>If at a non-repeating segment, next means next "position"</li>
 244  
      * <li>If at a repeating segment: if segment name matches direction then
 245  
      * next means next rep, otherwise next means next "position".</li>
 246  
      * <li>If at a segment within a group (not at the end of the group), next
 247  
      * "position" means next sibling</li>
 248  
      * <li>If at the end of a group: If name of group or any of its "first
 249  
      * decendents" matches direction, then next position means next rep of
 250  
      * group. Otherwise if direction matches name of next sibling of the group,
 251  
      * or any of its first descendents, next position means next sibling of the
 252  
      * group. Otherwise, next means a new segment added to the group (with a
 253  
      * name that matches "direction").</li>
 254  
      * <li>"First descendents" means first child, or first child of the first
 255  
      * child, or first child of the first child of the first child, etc.</li>
 256  
      * </ol>
 257  
      */
 258  
     public Structure next() {
 259  11849
         if (!hasNext()) {
 260  0
             throw new NoSuchElementException("No more nodes in message");
 261  
         }
 262  
 
 263  11849
         Structure currentStructure = navigateToStructure(myCurrentDefinitionPath);
 264  
 
 265  11849
         clearNext();
 266  11849
         return currentStructure;
 267  
     }
 268  
 
 269  
     private Structure navigateToStructure(List<Position> theDefinitionPath) throws Error {
 270  13017
         Structure currentStructure = null;
 271  13017
         for (Position next : theDefinitionPath) {
 272  35247
             if (currentStructure == null) {
 273  13017
                 currentStructure = myMessage;
 274  
             } else {
 275  
                 try {
 276  22230
                     IStructureDefinition structureDefinition = next.getStructureDefinition();
 277  22230
                     Group currentStructureGroup = (Group) currentStructure;
 278  22230
                     String nextStructureName = structureDefinition.getNameAsItAppearsInParent();
 279  22230
                     currentStructure = currentStructureGroup.get(nextStructureName, next.getRepNumber());
 280  0
                 } catch (HL7Exception e) {
 281  0
                     throw new Error("Failed to retrieve structure: ", e);
 282  22230
                 }
 283  
             }
 284  35247
         }
 285  13017
         return currentStructure;
 286  
     }
 287  
 
 288  
     /** Not supported */
 289  
     public void remove() {
 290  0
         throw new UnsupportedOperationException("Can't remove a node from a message");
 291  
     }
 292  
 
 293  
     public String getDirection() {
 294  0
         return this.myDirection;
 295  
     }
 296  
 
 297  
     public void setDirection(String direction) {
 298  11856
         clearNext();
 299  11856
         this.myDirection = direction;
 300  11856
     }
 301  
 
 302  
     private void clearNext() {
 303  23705
         myNextIsSet = false;
 304  23705
     }
 305  
 
 306  
     /**
 307  
      * A structure position within a message.
 308  
      */
 309  
     public static class Position {
 310  
         private IStructureDefinition myStructureDefinition;
 311  13250
         private int myRepNumber = -1;
 312  
 
 313  
         public IStructureDefinition getStructureDefinition() {
 314  66584
             return myStructureDefinition;
 315  
         }
 316  
 
 317  
         public void resetRepNumber() {
 318  15540
             myRepNumber = -1;
 319  15540
         }
 320  
 
 321  
         public void setStructureDefinition(IStructureDefinition theStructureDefinition) {
 322  15540
             myStructureDefinition = theStructureDefinition;
 323  15540
         }
 324  
 
 325  
         public int getRepNumber() {
 326  37509
             return myRepNumber;
 327  
         }
 328  
 
 329  13250
         public Position(IStructureDefinition theStructureDefinition, int theRepNumber) {
 330  13250
             myStructureDefinition = theStructureDefinition;
 331  13250
             myRepNumber = theRepNumber;
 332  13250
         }
 333  
 
 334  
         public void incrementRep() {
 335  19342
             myRepNumber++;
 336  19342
         }
 337  
 
 338  
         /** @see Object#equals */
 339  
         public boolean equals(Object o) {
 340  0
             boolean equals = false;
 341  0
             if (o != null && o instanceof Position) {
 342  0
                 Position p = (Position) o;
 343  0
                 if (p.myStructureDefinition.equals(myStructureDefinition) && p.myRepNumber == myRepNumber)
 344  0
                     equals = true;
 345  
             }
 346  0
             return equals;
 347  
         }
 348  
 
 349  
         /** @see Object#hashCode */
 350  
         public int hashCode() {
 351  0
             return myStructureDefinition.hashCode() + myRepNumber;
 352  
         }
 353  
 
 354  
         public String toString() {
 355  0
             StringBuilder ret = new StringBuilder();
 356  
 
 357  0
             if (myStructureDefinition.getParent() != null) {
 358  0
                 ret.append(myStructureDefinition.getParent().getName());
 359  
             } else {
 360  0
                 ret.append("Root");
 361  
             }
 362  
 
 363  0
             ret.append(":");
 364  0
             ret.append(myStructureDefinition.getName());
 365  0
             ret.append("(");
 366  0
             ret.append(myRepNumber);
 367  0
             ret.append(")");
 368  0
             return ret.toString();
 369  
         }
 370  
     }
 371  
 
 372  
     /**
 373  
      * Must be called after {@link #next()}
 374  
      */
 375  
     public int getNextIndexWithinParent() {
 376  0
         return getCurrentPosition().getStructureDefinition().getPosition();
 377  
     }
 378  
 }