Exemple #1
0
        public R InvokeMethod <R>(ISegment segment, string methodName, IPipelineContext context, R defaultValue)
        {
            if (segment == null)
            {
                throw new ArgumentNullException("segment");
            }
            if (methodName == null)
            {
                throw new ArgumentNullException("methodName");
            }
            if (string.IsNullOrWhiteSpace(methodName))
            {
                throw new ArgumentException("Method name cannot be empty", "methodName");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var methodToinvoke = GetMethod(segment.GetType(), methodName);

            if (methodToinvoke == null)
            {
                return(defaultValue);
            }

            var    parameters = GetParameters(methodToinvoke, context);
            object result     = methodToinvoke.Invoke(segment, parameters);

            return(result is R ? (R)result : defaultValue);
        }
Exemple #2
0
        /// <summary> Populates the given error segment with information from this Exception.</summary>
        // TODO: this is out of sync with hapi see
        // https://github.com/hapifhir/hapi-hl7v2/blob/809516e3f4851d7cd97573efb6dedf24959a1063/hapi-base/src/main/java/ca/uhn/hl7v2/AbstractHL7Exception.java#L134
        public virtual void populate(ISegment errorSegment)
        {
            //make sure it's an ERR
            if (!errorSegment.GetStructureName().Equals("ERR"))
            {
                throw new HL7Exception("Can only populate an ERR segment with an exception -- got: " +
                                       errorSegment.GetType().FullName);
            }

            var rep = errorSegment.GetField(1).Length;             //append after existing reps

            if (SegmentName != null)
            {
                Terser.Set(errorSegment, 1, rep, 1, 1, SegmentName);
            }


            if (SegmentRepetition >= 0)
            {
                Terser.Set(errorSegment, 1, rep, 2, 1, Convert.ToString(SegmentRepetition));
            }


            if (FieldPosition >= 0)
            {
                Terser.Set(errorSegment, 1, rep, 3, 1, Convert.ToString(FieldPosition));
            }

            Terser.Set(errorSegment, 1, rep, 4, 1, Convert.ToString(ErrorCode));
            // this replaces the need to connect to the database
            Terser.Set(errorSegment, 1, rep, 4, 2, ErrorCode.GetName());
            Terser.Set(errorSegment, 1, rep, 4, 3, "hl70357");
            Terser.Set(errorSegment, 1, rep, 4, 5, Message);
        }
        /// <summary> Populates the given error segment with information from this Exception.</summary>
        public virtual void populate(ISegment errorSegment)
        {
            //make sure it's an ERR
            if (!errorSegment.GetStructureName().Equals("ERR"))
            {
                throw new HL7Exception("Can only populate an ERR segment with an exception -- got: " +
                                       errorSegment.GetType().FullName);
            }

            int rep = errorSegment.GetField(1).Length;             //append after existing reps

            if (SegmentName != null)
            {
                Terser.Set(errorSegment, 1, rep, 1, 1, SegmentName);
            }

            if (SegmentRepetition >= 0)
            {
                Terser.Set(errorSegment, 1, rep, 2, 1, Convert.ToString(SegmentRepetition));
            }

            if (FieldPosition >= 0)
            {
                Terser.Set(errorSegment, 1, rep, 3, 1, Convert.ToString(FieldPosition));
            }

            Terser.Set(errorSegment, 1, rep, 4, 1, Convert.ToString(errCode));
            Terser.Set(errorSegment, 1, rep, 4, 3, "hl70357");
            Terser.Set(errorSegment, 1, rep, 4, 5, Message);

            //try to get error condition text
            try
            {
                String desc = TableRepository.Instance.getDescription(357, Convert.ToString(errCode));
                Terser.Set(errorSegment, 1, rep, 4, 2, desc);
            }
            catch (LookupException e)
            {
                ourLog.Debug("Warning: LookupException getting error condition text (are we connected to a TableRepository?)", e);
            }
            catch (InvalidOperationException e)
            {
                ourLog.Debug("Warning: InvalidOperationException getting error condition text (are we connected to a TableRepository? Is a valid ConnectionString configured?)", e);
            }
        }
Exemple #4
0
        /// <summary>   Populates the given Segment object with data from the given XML Element. </summary>
        /// <summary>   for the given Segment, or if there is an error while setting individual field
        ///             values. </summary>
        ///
        /// <param name="segmentObject">    The segment object. </param>
        /// <param name="segmentElement">   Element describing the segment. </param>

        public virtual void Parse(ISegment segmentObject, System.Xml.XmlElement segmentElement)
        {
            SupportClass.HashSetSupport done = new SupportClass.HashSetSupport();

            //        for (int i = 1; i <= segmentObject.NumFields(); i++) {
            //            String elementName = makeElementName(segmentObject, i);
            //            done.add(elementName);
            //            parseReps(segmentObject, segmentElement, elementName, i);
            //        }

            System.Xml.XmlNodeList all = segmentElement.ChildNodes;
            for (int i = 0; i < all.Count; i++)
            {
                System.String elementName = all.Item(i).Name;
                if (System.Convert.ToInt16(all.Item(i).NodeType) == (short)System.Xml.XmlNodeType.Element &&
                    !done.Contains(elementName))
                {
                    done.Add(elementName);

                    int index = elementName.IndexOf('.');
                    if (index >= 0 && elementName.Length > index)
                    {
                        //properly formatted element
                        System.String fieldNumString = elementName.Substring(index + 1);
                        int           fieldNum       = System.Int32.Parse(fieldNumString);
                        this.ParseReps(segmentObject, segmentElement, elementName, fieldNum);
                    }
                    else
                    {
                        log.Debug(
                            "Child of segment " + segmentObject.GetStructureName() + " doesn't look like a field: "
                            + elementName);
                    }
                }
            }

            //set data type of OBX-5
            if (segmentObject.GetType().FullName.IndexOf("OBX") >= 0)
            {
                Varies.fixOBX5(segmentObject, this.Factory);
            }
        }
Exemple #5
0
        /// <summary> Populates the given Segment object with data from the given XML Element.</summary>
        /// <throws>  HL7Exception if the XML Element does not have the correct name and structure. </throws>
        /// <summary>      for the given Segment, or if there is an error while setting individual field values.
        /// </summary>
        public virtual void Parse(ISegment segmentObject, XmlElement segmentElement, ParserOptions parserOptions)
        {
            parserOptions = parserOptions ?? DefaultParserOptions;

            var done = new SupportClass.HashSetSupport();

            // for (int i = 1; i <= segmentObject.NumFields(); i++) {
            //            String elementName = makeElementName(segmentObject, i);
            //            done.add(elementName);
            //            parseReps(segmentObject, segmentElement, elementName, i);
            //        }
            var all = segmentElement.ChildNodes;

            for (var i = 0; i < all.Count; i++)
            {
                var elementName = all.Item(i).Name;
                if (Convert.ToInt16(all.Item(i).NodeType) == (short)XmlNodeType.Element && !done.Contains(elementName))
                {
                    done.Add(elementName);

                    var index = elementName.IndexOf('.');
                    if (index >= 0 && elementName.Length > index)
                    {
                        // properly formatted element
                        var fieldNumString = elementName.Substring(index + 1);
                        var fieldNum       = int.Parse(fieldNumString);
                        ParseReps(segmentObject, segmentElement, elementName, fieldNum);
                    }
                    else
                    {
                        Log.Debug("Child of segment " + segmentObject.GetStructureName() + " doesn't look like a field: " + elementName);
                    }
                }
            }

            // set data type of OBX-5
            if (segmentObject.GetType().FullName.IndexOf("OBX") >= 0)
            {
                Varies.FixOBX5(segmentObject, Factory, parserOptions);
            }
        }
Exemple #6
0
        /// <summary> Parses a segment string and populates the given Segment object.  Unexpected fields are
        /// added as Varies' at the end of the segment.
        ///
        /// </summary>
        /// <throws>  HL7Exception if the given string does not contain the </throws>
        /// <summary>      given segment or if the string is not encoded properly
        /// </summary>
        public virtual void Parse(ISegment destination, System.String segment, EncodingCharacters encodingChars)
        {
            int fieldOffset = 0;

            if (IsDelimDefSegment(destination.GetStructureName()))
            {
                fieldOffset = 1;
                //set field 1 to fourth character of string
                Terser.Set(destination, 1, 0, 1, 1, System.Convert.ToString(encodingChars.FieldSeparator));
            }

            System.String[] fields = Split(segment, System.Convert.ToString(encodingChars.FieldSeparator));
            //destination.setName(fields[0]);
            for (int i = 1; i < fields.Length; i++)
            {
                System.String[] reps = Split(fields[i], System.Convert.ToString(encodingChars.RepetitionSeparator));
                if (log.DebugEnabled)
                {
                    log.Debug(reps.Length + "reps delimited by: " + encodingChars.RepetitionSeparator);
                }

                //MSH-2 will get split incorrectly so we have to fudge it ...
                bool isMSH2 = IsDelimDefSegment(destination.GetStructureName()) && i + fieldOffset == 2;
                if (isMSH2)
                {
                    reps    = new System.String[1];
                    reps[0] = fields[i];
                }

                for (int j = 0; j < reps.Length; j++)
                {
                    try
                    {
                        System.Text.StringBuilder statusMessage = new System.Text.StringBuilder("Parsing field ");
                        statusMessage.Append(i + fieldOffset);
                        statusMessage.Append(" repetition ");
                        statusMessage.Append(j);
                        log.Debug(statusMessage.ToString());
                        //parse(destination.GetField(i + fieldOffset, j), reps[j], encodingChars, false);

                        IType field = destination.GetField(i + fieldOffset, j);
                        if (isMSH2)
                        {
                            Terser.getPrimitive(field, 1, 1).Value = reps[j];
                        }
                        else
                        {
                            Parse(field, reps[j], encodingChars);
                        }
                    }
                    catch (HL7Exception e)
                    {
                        //set the field location and throw again ...
                        e.FieldPosition     = i;
                        e.SegmentRepetition = MessageIterator.getIndex(destination.ParentStructure, destination).rep;
                        e.SegmentName       = destination.GetStructureName();
                        throw e;
                    }
                }
            }

            //set data type of OBX-5
            if (destination.GetType().FullName.IndexOf("OBX") >= 0)
            {
                Varies.fixOBX5(destination, Factory);
            }
        }
Exemple #7
0
        /// <summary>
        /// Parses a segment string and populates the given Segment object.
        /// <para>
        /// Unexpected fields are added as Varies' at the end of the segment.
        /// </para>
        /// </summary>
        /// <param name="destination">Segment to parse the segment string into.</param>
        /// <param name="segment">Encoded segment.</param>
        /// <param name="encodingChars">Encoding characters to be used.</param>
        /// <param name="repetition">The repetition number of this segment within its group.</param>
        /// <param name="parserOptions">Contains configuration that will be applied when parsing.</param>
        /// <exception cref="HL7Exception">
        /// If the given string does not contain the given segment or if the string is not encoded properly.
        /// </exception>
        public virtual void Parse(ISegment destination, string segment, EncodingCharacters encodingChars, int repetition, ParserOptions parserOptions)
        {
            parserOptions = parserOptions ?? DefaultParserOptions;

            var fieldOffset = 0;

            if (IsDelimDefSegment(destination.GetStructureName()))
            {
                fieldOffset = 1;

                // set field 1 to fourth character of string
                Terser.Set(destination, 1, 0, 1, 1, Convert.ToString(encodingChars.FieldSeparator));
            }

            var fields = Split(segment, Convert.ToString(encodingChars.FieldSeparator));

            for (var i = 1; i < fields.Length; i++)
            {
                var reps = Split(fields[i], Convert.ToString(encodingChars.RepetitionSeparator));
                if (Log.DebugEnabled)
                {
                    Log.Debug(reps.Length + "reps delimited by: " + encodingChars.RepetitionSeparator);
                }

                // MSH-2 will get split incorrectly so we have to fudge it ...
                var isMSH2 = IsDelimDefSegment(destination.GetStructureName()) && i + fieldOffset == 2;
                if (isMSH2)
                {
                    reps    = new string[1];
                    reps[0] = fields[i];
                }

                for (var j = 0; j < reps.Length; j++)
                {
                    try
                    {
                        var statusMessage = $"Parsing field {i + fieldOffset} repetition {j}";
                        Log.Debug(statusMessage);

                        var field = destination.GetField(i + fieldOffset, j);
                        if (isMSH2)
                        {
                            Terser.GetPrimitive(field, 1, 1).Value = reps[j];
                        }
                        else
                        {
                            Parse(field, reps[j], encodingChars);
                        }
                    }
                    catch (HL7Exception e)
                    {
                        // set the field location and throw again ...
                        e.FieldPosition = i;
                        if (repetition > 1)
                        {
                            e.SegmentRepetition = repetition;
                        }

                        e.SegmentName = destination.GetStructureName();
                        throw;
                    }
                }
            }

            // set data type of OBX-5
            if (destination.GetType().FullName.IndexOf("OBX") >= 0)
            {
                Varies.FixOBX5(destination, Factory, parserOptions);
            }
        }
Exemple #8
0
        public static void Main(String[] args)
        {
            if (args.Length != 1)
            {
                Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file");
                Environment.Exit(1);
            }

            //read and parse message from file
            try
            {
                PipeParser   parser      = new PipeParser();
                FileInfo     messageFile = new FileInfo(args[0]);
                long         fileLength  = SupportClass.FileLength(messageFile);
                StreamReader r           = new StreamReader(messageFile.FullName, Encoding.Default);
                char[]       cbuf        = new char[(int)fileLength];
                Console.Out.WriteLine("Reading message file ... " + r.Read((Char[])cbuf, 0, cbuf.Length) + " of " + fileLength +
                                      " chars");
                r.Close();
                String   messString = Convert.ToString(cbuf);
                IMessage mess       = parser.Parse(messString);
                Console.Out.WriteLine("Got message of type " + mess.GetType().FullName);

                XMLParser xp = new AnonymousClassXMLParser();

                //loop through segment children of message, encode, print to console
                String[] structNames = mess.Names;
                for (int i = 0; i < structNames.Length; i++)
                {
                    IStructure[] reps = mess.GetAll(structNames[i]);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        if (typeof(ISegment).IsAssignableFrom(reps[j].GetType()))
                        {
                            //ignore groups
                            XmlDocument docBuilder = new XmlDocument();
                            XmlDocument doc        = new XmlDocument();                      //new doc for each segment
                            XmlElement  root       = doc.CreateElement(reps[j].GetType().FullName);
                            doc.AppendChild(root);
                            xp.Encode((ISegment)reps[j], root);
                            StringWriter out_Renamed = new StringWriter();
                            Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml);

                            Type[]   segmentConstructTypes = new Type[] { typeof(IMessage) };
                            Object[] segmentConstructArgs  = new Object[] { null };
                            ISegment s = (ISegment)reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs);
                            xp.Parse(s, root);
                            XmlDocument doc2  = new XmlDocument();
                            XmlElement  root2 = doc2.CreateElement(s.GetType().FullName);
                            doc2.AppendChild(root2);
                            xp.Encode(s, root2);
                            StringWriter out2 = new StringWriter();
                            XmlWriter    ser  = XmlWriter.Create(out2);
                            doc.WriteTo(ser);
                            if (out2.ToString().Equals(out_Renamed.ToString()))
                            {
                                Console.Out.WriteLine("Re-encode OK");
                            }
                            else
                            {
                                Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Exemple #9
0
		/// <summary> Parses a segment string and populates the given Segment object.  Unexpected fields are
		/// added as Varies' at the end of the segment.  
		/// 
		/// </summary>
		/// <throws>  HL7Exception if the given string does not contain the </throws>
		/// <summary>      given segment or if the string is not encoded properly
		/// </summary>
		public virtual void Parse(ISegment destination, String segment, EncodingCharacters encodingChars)
		{
			int fieldOffset = 0;
			if (IsDelimDefSegment(destination.GetStructureName()))
			{
				fieldOffset = 1;
				//set field 1 to fourth character of string
				Terser.Set(destination, 1, 0, 1, 1, Convert.ToString(encodingChars.FieldSeparator));
			}

			String[] fields = Split(segment, Convert.ToString(encodingChars.FieldSeparator));

			for (int i = 1; i < fields.Length; i++)
			{
				String[] reps = Split(fields[i], Convert.ToString(encodingChars.RepetitionSeparator));
				if (log.DebugEnabled)
				{
					log.Debug(reps.Length + "reps delimited by: " + encodingChars.RepetitionSeparator);
				}

				//MSH-2 will get split incorrectly so we have to fudge it ...
				bool isMSH2 = IsDelimDefSegment(destination.GetStructureName()) && i + fieldOffset == 2;
				if (isMSH2)
				{
					reps = new String[1];
					reps[0] = fields[i];
				}

				for (int j = 0; j < reps.Length; j++)
				{
					try
					{
						StringBuilder statusMessage = new StringBuilder("Parsing field ");
						statusMessage.Append(i + fieldOffset);
						statusMessage.Append(" repetition ");
						statusMessage.Append(j);
						log.Debug(statusMessage.ToString());

						IType field = destination.GetField(i + fieldOffset, j);
						if (isMSH2)
						{
							Terser.getPrimitive(field, 1, 1).Value = reps[j];
						}
						else
						{
							Parse(field, reps[j], encodingChars);
						}
					}
					catch (HL7Exception e)
					{
						//set the field location and throw again ...
						e.FieldPosition = i + fieldOffset;
						e.SegmentRepetition = MessageIterator.getIndex(destination.ParentStructure, destination).rep;
						e.SegmentName = destination.GetStructureName();
						throw;
					}
				}
			}

			//set data type of OBX-5
			if (destination.GetType().FullName.IndexOf("OBX") >= 0)
			{
				Varies.fixOBX5(destination, Factory);
			}
		}
Exemple #10
0
        /// <summary> Populates the given error segment with information from this Exception.</summary>
        public virtual void populate(ISegment errorSegment)
        {
            //make sure it's an ERR
            if (!errorSegment.GetStructureName().Equals("ERR"))
                throw new HL7Exception("Can only populate an ERR segment with an exception -- got: " + errorSegment.GetType().FullName);

            int rep = errorSegment.GetField(1).Length; //append after existing reps

            if (this.SegmentName != null)
                Terser.Set(errorSegment, 1, rep, 1, 1, this.SegmentName);

            if (this.SegmentRepetition >= 0)
                Terser.Set(errorSegment, 1, rep, 2, 1, System.Convert.ToString(this.SegmentRepetition));

            if (this.FieldPosition >= 0)
                Terser.Set(errorSegment, 1, rep, 3, 1, System.Convert.ToString(this.FieldPosition));

            Terser.Set(errorSegment, 1, rep, 4, 1, System.Convert.ToString(this.errCode));
            Terser.Set(errorSegment, 1, rep, 4, 3, "hl70357");
            Terser.Set(errorSegment, 1, rep, 4, 5, this.Message);

            //try to get error condition text
            try
            {
                System.String desc = TableRepository.Instance.getDescription(357, System.Convert.ToString(this.errCode));
                Terser.Set(errorSegment, 1, rep, 4, 2, desc);
            }
            catch (LookupException e)
            {
                ourLog.Debug("Warning: LookupException getting error condition text (are we connected to a TableRepository?)", e);
            }
        }
Exemple #11
0
		/// <summary> Populates the given Segment object with data from the given XML Element.</summary>
		/// <throws>  HL7Exception if the XML Element does not have the correct name and structure </throws>
		/// <summary>      for the given Segment, or if there is an error while setting individual field values.
		/// </summary>
		public virtual void Parse(ISegment segmentObject, XmlElement segmentElement)
		{
			SupportClass.HashSetSupport done = new SupportClass.HashSetSupport();

			//        for (int i = 1; i <= segmentObject.NumFields(); i++) {
			//            String elementName = makeElementName(segmentObject, i);
			//            done.add(elementName);
			//            parseReps(segmentObject, segmentElement, elementName, i);
			//        }

			XmlNodeList all = segmentElement.ChildNodes;
			for (int i = 0; i < all.Count; i++)
			{
				String elementName = all.Item(i).Name;
				if (Convert.ToInt16(all.Item(i).NodeType) == (short) XmlNodeType.Element && !done.Contains(elementName))
				{
					done.Add(elementName);

					int index = elementName.IndexOf('.');
					if (index >= 0 && elementName.Length > index)
					{
						//properly formatted element
						String fieldNumString = elementName.Substring(index + 1);
						int fieldNum = Int32.Parse(fieldNumString);
						ParseReps(segmentObject, segmentElement, elementName, fieldNum);
					}
					else
					{
						log.Debug("Child of segment " + segmentObject.GetStructureName() + " doesn't look like a field: " + elementName);
					}
				}
			}

			//set data type of OBX-5        
			if (segmentObject.GetType().FullName.IndexOf("OBX") >= 0)
			{
				Varies.fixOBX5(segmentObject, Factory);
			}
		}