001package ca.uhn.hl7v2.util;
002
003import ca.uhn.hl7v2.model.DataTypeException;
004import ca.uhn.hl7v2.HL7Exception;
005import ca.uhn.hl7v2.model.*;
006
007/**
008 * Tools for copying data recurvisely from one message element into another.  Currently only Types are 
009 * supported.  
010 * @author Bryan Tripp
011 */
012public class DeepCopy {
013    
014    /**
015     * Copies data from the "from" Type into the "to" Type.  Either Type may be 
016     * a Primitive, Composite, or Varies.  If a Varies is provided, the operation is 
017     * performed on the result of calling its getData() method.  A Primitive may be 
018     * copied into a Composite, in which case the value is copied into the first 
019     * component of the Composite.  A Composite may be copied into a Primitive, 
020     * in which case the first component is copied.  Given Composites with different 
021     * numbers of components, the first components are copied, up to the length 
022     * of the smaller one.
023     *
024     * @param from type to copy from
025     * @param to type to copy to
026     * @throws DataTypeException if the types are not compatible
027     */
028    public static void copy(Type from, Type to) throws DataTypeException {
029        for (int i = 1; i <= Terser.numComponents(from); i++) {
030            for (int j = 1; j <= Terser.numSubComponents(from, i); j++) {
031                String val = Terser.getPrimitive(from, i, j).getValue();
032                Terser.getPrimitive(to, i, j).setValue(val);
033            }
034        }
035    }
036
037    
038    /**
039     * Copies contents from the source segment to the destination segment.  This 
040     * method calls copy(Type, Type) on each repetition of each field (see additional 
041     * behavioural description there).  An attempt is made to copy each repetition of 
042     * each field in the source segment, regardless of whether the corresponding 
043     * destination field is repeating or even exists.
044     *
045     * @param from the segment from which data are copied 
046     * @param to the segment into which data are copied
047     * @throws HL7Exception if an error occurred while copying
048     */
049    public static void copy(Segment from, Segment to) throws HL7Exception {
050        int n = from.numFields();
051        for (int i = 1; i <= n; i++) {
052            Type[] reps = from.getField(i);
053            for (int j = 0; j < reps.length; j++) {
054                copy(reps[j], to.getField(i, j));
055            }
056        }
057    }
058}