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