コード例 #1
0
ファイル: MessageValidator.cs プロジェクト: erdemsarigh/nhapi
        /// <summary>   Validates the given message. </summary>
        ///
        /// <exception cref="HL7Exception"> Thrown when a HL 7 error condition occurs. </exception>
        ///
        /// <param name="message">  a parsed message to validate (note that MSH-9-1 and MSH-9-2 must be
        ///                         valued) </param>
        ///
        /// <returns>   true if the message is OK. </returns>

        public virtual bool validate(IMessage message)
        {
            Terser t = new Terser(message);

            IMessageRule[] rules = this.myContext.getMessageRules(message.Version, t.Get("MSH-9-1"), t.Get("MSH-9-2"));

            ValidationException toThrow = null;
            bool result = true;

            for (int i = 0; i < rules.Length; i++)
            {
                ValidationException[] ex = rules[i].test(message);
                for (int j = 0; j < ex.Length; j++)
                {
                    result = false;
                    ourLog.Error("Invalid message", ex[j]);
                    if (this.failOnError && toThrow == null)
                    {
                        toThrow = ex[j];
                    }
                }
            }

            if (toThrow != null)
            {
                throw new HL7Exception("Invalid message", toThrow);
            }

            return(result);
        }
コード例 #2
0
 public static void Main(String[] args)
 {
     try
     {
         OdbcConnection conn = Instance.Connection;
         DbCommand      stmt = TransactionManager.manager.CreateStatement(conn);
         DbCommand      temp_OleDbCommand;
         temp_OleDbCommand             = stmt;
         temp_OleDbCommand.CommandText = "select * from TableValues";
         DbDataReader rs = temp_OleDbCommand.ExecuteReader();
         while (rs.Read())
         {
             Object tabNum = rs.GetValue(1 - 1);
             Object val    = rs.GetValue(3 - 1);
             Object desc   = rs.GetValue(4 - 1);
             Console.Out.WriteLine("Table: " + tabNum + " Value: " + val + " Description: " + desc);
         }
     }
     catch (DbException e)
     {
         log.Error("test msg!!", e);
     }
     catch (Exception e)
     {
         log.Error("test msg!!", e);
     }
 }
コード例 #3
0
 public static void Main(System.String[] args)
 {
     try
     {
         System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
         System.Data.OleDb.OleDbCommand    stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
         System.Data.OleDb.OleDbCommand    temp_OleDbCommand;
         temp_OleDbCommand             = stmt;
         temp_OleDbCommand.CommandText = "select * from TableValues";
         System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
         while (rs.Read())
         {
             System.Object tabNum = rs.GetValue(1 - 1);
             System.Object val    = rs.GetValue(3 - 1);
             System.Object desc   = rs.GetValue(4 - 1);
             System.Console.Out.WriteLine("Table: " + tabNum + " Value: " + val + " Description: " + desc);
         }
     }
     catch (System.Data.OleDb.OleDbException e)
     {
         log.Error("test msg!!", e);
     }
     catch (System.Exception e)
     {
         log.Error("test msg!!", e);
     }
 }
コード例 #4
0
        /// <summary>Parses a primitive type by filling it with text child, if any </summary>
        private void ParsePrimitive(IPrimitive datatypeObject, XmlElement datatypeElement)
        {
            XmlNodeList children = datatypeElement.ChildNodes;
            int         c        = 0;
            bool        full     = false;

            while (c < children.Count && !full)
            {
                XmlNode child = children.Item(c++);
                if (Convert.ToInt16(child.NodeType) == (short)XmlNodeType.Text)
                {
                    try
                    {
                        if (child.Value != null && !child.Value.Equals(""))
                        {
                            if (KeepAsOriginal(child.ParentNode))
                            {
                                datatypeObject.Value = child.Value;
                            }
                            else
                            {
                                datatypeObject.Value = RemoveWhitespace(child.Value);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        log.Error("Error parsing primitive value from TEXT_NODE", e);
                    }
                    full = true;
                }
            }
        }
コード例 #5
0
        /// <summary> Returns the index of the given structure as a child of the
        /// given parent.  Returns null if the child isn't found.
        /// </summary>
        public static Index getIndex(IGroup parent, IStructure child)
        {
            Index index = null;

            System.String[] names = parent.Names;
            for (int i = 0; i < names.Length; i++)
            {
                if (names[i].StartsWith(child.GetStructureName()))
                {
                    try
                    {
                        IStructure[] reps = parent.GetAll(names[i]);
                        for (int j = 0; j < reps.Length; j++)
                        {
                            if (child == reps[j])
                            {
                                index = new Index(names[i], j);
                                break;
                            }
                        }
                    }
                    catch (HL7Exception e)
                    {
                        log.Error("", e);
                        throw new System.ApplicationException("Internal HL7Exception finding structure index: " + e.Message);
                    }
                }
            }
            return(index);
        }
コード例 #6
0
        /// <summary> Returns the component (or sub-component, as the case may be) at the given
        /// index.  If it does not exist, it is added as an "extra component".
        /// If comp > 1 is requested from a Varies with GenericPrimitive data, the
        /// data is set to GenericComposite (this avoids the creation of a chain of
        /// ExtraComponents on GenericPrimitives).
        /// Components are numbered from 1.
        /// </summary>
        private static IType getComponent(IType type, int comp)
        {
            IType ret = null;

            if (typeof(Varies).IsAssignableFrom(type.GetType()))
            {
                Varies v = (Varies)type;

                try
                {
                    if (comp > 1 && typeof(GenericPrimitive).IsAssignableFrom(v.Data.GetType()))
                    {
                        v.Data = new GenericComposite(v.Message);
                    }
                }
                catch (DataTypeException de)
                {
                    String message = "Unexpected exception copying data to generic composite: " + de.Message;
                    log.Error(message, de);
                    throw new ApplicationException(message);
                }

                ret = getComponent(v.Data, comp);
            }
            else
            {
                if (typeof(IPrimitive).IsAssignableFrom(type.GetType()) && comp == 1)
                {
                    ret = type;
                }
                else if (typeof(GenericComposite).IsAssignableFrom(type.GetType()) ||
                         (typeof(IComposite).IsAssignableFrom(type.GetType()) && comp <= numStandardComponents(type)))
                {
                    //note that GenericComposite can return components > number of standard components

                    try
                    {
                        ret = ((IComposite)type)[comp - 1];
                    }
                    catch (Exception e)
                    {
                        //TODO:  This may not be the write exception type:  Error() was originally thrown, but was not in project.
                        throw new ApplicationException(
                                  "Internal error: HL7Exception thrown on getComponent(x) where x < # standard components.", e);
                    }
                }
                else
                {
                    ret = type.ExtraComponents.getComponent(comp - numStandardComponents(type) - 1);
                }
            }
            return(ret);
        }
コード例 #7
0
ファイル: MessageGenerator.cs プロジェクト: erdemsarigh/nhapi
        /// <summary>
        /// Creates source code for a specific message structure and writes it under the specified
        /// directory. throws IllegalArgumentException if there is no message structure for this message
        /// in the normative database.
        /// </summary>
        ///
        /// <param name="message">          The message. </param>
        /// <param name="baseDirectory">    Pathname of the base directory. </param>
        /// <param name="chapter">          The chapter. </param>
        /// <param name="version">          The version. </param>

        public static void make(
            System.String message,
            System.String baseDirectory,
            System.String chapter,
            System.String version)
        {
            try
            {
                SegmentDef[] segments = getSegments(message, version);
                //System.out.println("Making: " + message + " with " + segments.length + " segments (not writing message code - just groups)");

                GroupDef        group    = GroupGenerator.getGroupDef(segments, null, baseDirectory, version, message);
                IStructureDef[] contents = group.Structures;

                //make base directory
                if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
                {
                    baseDirectory = baseDirectory + "/";
                }

                System.IO.FileInfo targetDir =
                    SourceGenerator.makeDirectory(
                        baseDirectory + PackageManager.GetVersionPackagePath(version) + "Message");
                System.Console.Out.WriteLine("Writing " + message + " to " + targetDir.FullName);
                using (
                    System.IO.StreamWriter out_Renamed =
                        new System.IO.StreamWriter(targetDir.FullName + "/" + message + ".cs"))
                {
                    out_Renamed.Write(makePreamble(contents, message, chapter, version));
                    out_Renamed.Write(makeConstructor(contents, message, version));
                    for (int i = 0; i < contents.Length; i++)
                    {
                        out_Renamed.Write(GroupGenerator.makeAccessor(group, i));
                    }

                    //add implementation of model.control interface, if any
                    out_Renamed.Write("}\r\n"); //End class
                    out_Renamed.Write("}\r\n"); //End namespace
                }
            }
            catch (System.Exception e)
            {
                log.Error("Error while creating source code", e);

                log.Warn(
                    "Warning: could not write source code for message structure " + message + " - "
                    + e.GetType().FullName + ": " + e.Message);
            }
        }
コード例 #8
0
ファイル: PipeParser.cs プロジェクト: tristanwilson111/nHapi
        public static String Encode(ISegment source, EncodingCharacters encodingChars)
        {
            StringBuilder result = new StringBuilder();

            result.Append(source.GetStructureName());
            result.Append(encodingChars.FieldSeparator);

            //start at field 2 for MSH segment because field 1 is the field delimiter
            int startAt = 1;

            if (IsDelimDefSegment(source.GetStructureName()))
            {
                startAt = 2;
            }

            //loop through fields; for every field delimit any repetitions and add field delimiter after ...
            int numFields = source.NumFields();

            for (int i = startAt; i <= numFields; i++)
            {
                try
                {
                    IType[] reps = source.GetField(i);
                    for (int j = 0; j < reps.Length; j++)
                    {
                        String fieldText = Encode(reps[j], encodingChars);
                        //if this is MSH-2, then it shouldn't be escaped, so unescape it again
                        if (IsDelimDefSegment(source.GetStructureName()) && i == 2)
                        {
                            fieldText = Escape.unescape(fieldText, encodingChars);
                        }
                        result.Append(fieldText);
                        if (j < reps.Length - 1)
                        {
                            result.Append(encodingChars.RepetitionSeparator);
                        }
                    }
                }
                catch (HL7Exception e)
                {
                    log.Error("Error while encoding segment: ", e);
                }
                result.Append(encodingChars.FieldSeparator);
            }

            //strip trailing delimiters ...
            return(StripExtraDelimiters(result.ToString(), encodingChars.FieldSeparator));
        }
コード例 #9
0
        /// <summary> Creates source code for a specific message structure and
        /// writes it under the specified directory.
        /// throws IllegalArgumentException if there is no message structure
        /// for this message in the normative database.
        /// </summary>
        public static void Make(string message, string baseDirectory, string chapter, string version)
        {
            try
            {
                var segments = GetSegments(message, version);

                // System.out.println("Making: " + message + " with " + segments.length + " segments (not writing message code - just groups)");
                var group = GroupGenerator.GetGroupDef(segments, null, baseDirectory, version, message);
                var contents = group.Structures;

                // make base directory
                if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
                {
                    baseDirectory += Path.DirectorySeparatorChar;
                }

                var targetDir =
                    SourceGenerator.MakeDirectory(
                        Path.Combine(baseDirectory, PackageManager.GetVersionPackagePath(version), "Message"));

                var targetFile = Path.Combine(targetDir.FullName, $"{message}.cs");

                var stringBuilder = new StringBuilder();

                stringBuilder.Append(MakePreamble(contents, message, chapter, version));
                stringBuilder.Append(MakeConstructor(contents, message, version));
                for (var i = 0; i < contents.Length; i++)
                {
                    var groupAccessor = GroupGenerator.MakeAccessor(@group, i);
                    stringBuilder.Append(groupAccessor);
                }

                // add implementation of model.control interface, if any
                stringBuilder.Append("}\r\n"); // End class
                stringBuilder.Append("}\r\n"); // End namespace

                FileAbstraction.WriteAllBytes(targetFile, Encoding.UTF8.GetBytes(stringBuilder.ToString()));
            }
            catch (Exception e)
            {
                Log.Error("Error while creating source code", e);

                Log.Warn("Warning: could not write source code for message structure " + message + " - " + e.GetType().FullName +
                            ": " + e.Message);
            }
        }
コード例 #10
0
        /// <summary> Called from GetField(...) methods.  If a field has been requested that
        /// doesn't exist (eg GetField(15) when only 10 fields in segment) adds Varies
        /// fields to the end of the segment up to the required number.
        /// </summary>
        private void ensureEnoughFields(int fieldRequested)
        {
            int fieldsToAdd = fieldRequested - this.NumFields();

            if (fieldsToAdd < 0)
            {
                fieldsToAdd = 0;
            }

            try
            {
                for (int i = 0; i < fieldsToAdd; i++)
                {
                    this.add(typeof(Varies), false, 0, 65536, null); //using 65536 following example of OBX-5
                }
            }
            catch (HL7Exception e)
            {
                log.Error("Can't create additional generic fields to handle request for field " + fieldRequested, e);
            }
        }
コード例 #11
0
ファイル: GroupGenerator.cs プロジェクト: erichwu/nHapi
        /// <summary> Given a list of structures and the position of a SegmentDef that
        /// indicates the start of a group (ie "{" or "["), returns the position
        /// of the corresponding end of the group.  Nested group markers are ignored.
        /// </summary>
        /// <throws>  IllegalArgumentException if groupStart is out of range or does not  </throws>
        /// <summary>      point to a group opening marker.
        /// </summary>
        /// <throws>  HL7Exception if the end of the group is not found or if other pairs  </throws>
        /// <summary>      are not properly nested inside this one.
        /// </summary>
        public static int findGroupEnd(IStructureDef[] structures, int groupStart)
        {
            //  {} is rep; [] is optionality
            String endMarker = null;

            try
            {
                String startMarker = structures[groupStart].Name;
                if (startMarker.Equals("["))
                {
                    endMarker = "]";
                }
                else if (startMarker.Equals("{"))
                {
                    endMarker = "}";
                }
                else if (startMarker.Equals("[{"))
                {
                    endMarker = "}]";
                }
                else
                {
                    log.Error("Problem starting at " + groupStart);
                    for (int i = 0; i < structures.Length; i++)
                    {
                        log.Error("Structure " + i + ": " + structures[i].Name);
                    }
                    throw new ArgumentException("The segment " + startMarker + " does not begin a group - must be [ or {");
                }
            }
            catch (IndexOutOfRangeException)
            {
                throw new ArgumentException("The given start location is out of bounds");
            }

            //loop, increment and decrement opening and closing markers until we get back to 0
            String segName = null;
            int    offset  = 0;

            try
            {
                int nestedInside = 1;
                while (nestedInside > 0)
                {
                    offset++;
                    segName = structures[groupStart + offset].Name;
                    if (segName.Equals("{") || segName.Equals("[") || segName.Equals("[{"))
                    {
                        nestedInside++;
                    }
                    else if (segName.Equals("}") || segName.Equals("]") || segName.Equals("}]"))
                    {
                        nestedInside--;
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                throw new HL7Exception("Couldn't find end of group", ErrorCode.APPLICATION_INTERNAL_ERROR);
            }
            if (!endMarker.Equals(segName))
            {
                throw new HL7Exception("Group markers are not nested properly", ErrorCode.APPLICATION_INTERNAL_ERROR);
            }
            return(groupStart + offset);
        }