HasMoreTokens() public method

Determines if there are more tokens to return from the source string
public HasMoreTokens ( ) : bool
return bool
        /// <summary> Reads given "property file" and sets system properties accordingly.  In the property file,
        /// there should be one property per line.  A line should consist of 1) the fully qualified property name,
        /// 2) one or more tabs, and 3) the value (everything after the first group of tabs and before any subsequent
        /// groups will be considered "the value").
        /// Lines in the file are consdidered comments if they begin with "%".
        /// </summary>
        public static void  loadProperties(System.String propertyFileName)
        {
            //open stream from given property file
            System.IO.StreamReader in_Renamed = null;
            in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).CurrentEncoding);

            System.String          line, key, value_Renamed, delim = "\t";
            SupportClass.Tokenizer tok;
            while ((line = in_Renamed.ReadLine()) != null)
            {
                //ignore comments
                if (!line.StartsWith("%"))
                {
                    key = null; value_Renamed = null;

                    //get property key and value
                    tok = new SupportClass.Tokenizer(line, delim, false);
                    if (tok.HasMoreTokens())
                    {
                        key = tok.NextToken();
                    }
                    if (tok.HasMoreTokens())
                    {
                        value_Renamed = tok.NextToken();
                    }
                }
            }
            in_Renamed.Close();
        }
		/// <summary> Reads given "property file" and sets system properties accordingly.  In the property file,
		/// there should be one property per line.  A line should consist of 1) the fully qualified property name,
		/// 2) one or more tabs, and 3) the value (everything after the first group of tabs and before any subsequent
		/// groups will be considered "the value").
		/// Lines in the file are consdidered comments if they begin with "%".
		/// </summary>
		public static void  loadProperties(System.String propertyFileName)
		{
			
			//open stream from given property file
			System.IO.StreamReader in_Renamed = null;
			in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(propertyFileName, System.Text.Encoding.Default).CurrentEncoding);
			
			System.String line, key, value_Renamed, delim = "\t";
			SupportClass.Tokenizer tok;
			while ((line = in_Renamed.ReadLine()) != null)
			{
				//ignore comments
				if (!line.StartsWith("%"))
				{
					key = null; value_Renamed = null;
					
					//get property key and value
					tok = new SupportClass.Tokenizer(line, delim, false);
					if (tok.HasMoreTokens())
						key = tok.NextToken();
					if (tok.HasMoreTokens())
						value_Renamed = tok.NextToken();
				}
			}
			in_Renamed.Close();
		}
Example #3
0
        /// <summary>Parses message and dumps contents to props, with keys in the
        /// ZYX[a]-b[c]-d-e style.
        /// </summary>
        public static bool parseMessage(System.Collections.Specialized.NameValueCollection props, System.Collections.ArrayList msgMask, System.String message)
        {
            bool ok = false;

            if (message != null)
            {
                if (props == null)
                {
                    props = new System.Collections.Specialized.NameValueCollection();
                }

                SupportClass.Tokenizer messageTokenizer = new SupportClass.Tokenizer(message, segmentSeparators);
                if (messageTokenizer.HasMoreTokens())
                {
                    System.String           firstSegment  = messageTokenizer.NextToken();
                    NuGenEncodingCharacters encodingChars = new NuGenEncodingCharacters('0', "0000");
                    if (parseMSHSegmentWhole(props, msgMask, encodingChars, firstSegment))
                    {
                        ok = true;
                        System.Collections.SortedList segmentId2nextRepIdx = new System.Collections.SortedList();
                        segmentId2nextRepIdx[new System.Text.StringBuilder("MSH").ToString()] = 1;
                        // in case we find another MSH segment, heh.
                        while (messageTokenizer.HasMoreTokens())
                        {
                            parseSegmentWhole(props, segmentId2nextRepIdx, msgMask, encodingChars, messageTokenizer.NextToken());
                        }
                    }
                }
            }
            return(ok);
        }
Example #4
0
        private static RootRef parseGuide(System.String theSpec)
        {
            SupportClass.Tokenizer lines = new SupportClass.Tokenizer(theSpec, "\r", false);
            RootRef result = new RootRef();

            System.Collections.ArrayList ancestry = new System.Collections.ArrayList();
            ancestry.Add(result);
            System.Collections.IDictionary successors = new System.Collections.Hashtable();

            StructRef previous = result;

            while (lines.HasMoreTokens())
            {
                System.String          line    = lines.NextToken();
                SupportClass.Tokenizer parts   = new SupportClass.Tokenizer(line, "\t ", false);
                System.String          segName = parts.NextToken();
                System.String          path    = parts.HasMoreTokens()?parts.NextToken():"";
                parts = new SupportClass.Tokenizer(path, ":", false);
                path  = parts.HasMoreTokens()?parts.NextToken():null;

                int[] fields = getFieldList(parts.HasMoreTokens()?parts.NextToken():"");

                if (segName.Equals("}"))
                {
                    StructRef parent = (StructRef)SupportClass.StackSupport.Pop(ancestry);
                    if (parent.ChildName != null && parent.RelativePath.IndexOf('*') >= 0)
                    {
                        //repeating group
                        previous.setSuccessor(parent.ChildName, parent);
                    }
                }
                else
                {
                    bool      isSegment   = !(segName.Equals("{"));
                    StructRef ref_Renamed = new StructRef((StructRef)ancestry[ancestry.Count - 1], path, isSegment, fields);
                    if (isSegment)
                    {
                        previous.setSuccessor(segName, ref_Renamed);
                        if (path.IndexOf('*') >= 0)
                        {
                            ref_Renamed.setSuccessor(segName, ref_Renamed);
                        }
                        setGroupSuccessors(successors, segName);
                    }
                    else
                    {
                        successors[previous] = ref_Renamed;
                    }
                    if (!isSegment)
                    {
                        ancestry.Add(ref_Renamed);
                    }
                    previous = ref_Renamed;
                }
            }

            return(result);
        }
Example #5
0
        /// <summary> Returns the segment specified in the given segment_path_spec. </summary>
        public virtual ISegment GetSegment(string segSpec)
        {
            ISegment seg = null;

            if (segSpec.Substring(0, 1 - 0).Equals("/"))
            {
                Finder.Reset();
            }

            var tok    = new SupportClass.Tokenizer(segSpec, "/", false);
            var finder = Finder;

            while (tok.HasMoreTokens())
            {
                var pathSpec = tok.NextToken();
                var ps       = ParsePathSpec(pathSpec);
                if (tok.HasMoreTokens())
                {
                    ps.IsGroup = true;
                }
                else
                {
                    ps.IsGroup = false;
                }

                if (ps.IsGroup)
                {
                    IGroup g = null;
                    if (ps.Find)
                    {
                        g = finder.FindGroup(ps.Pattern, ps.Rep);
                    }
                    else
                    {
                        g = finder.GetGroup(ps.Pattern, ps.Rep);
                    }

                    finder = new SegmentFinder(g);
                }
                else
                {
                    if (ps.Find)
                    {
                        seg = finder.FindSegment(ps.Pattern, ps.Rep);
                    }
                    else
                    {
                        seg = finder.GetSegment(ps.Pattern, ps.Rep);
                    }
                }
            }

            return(seg);
        }
Example #6
0
        /// <summary> Returns the segment specified in the given segment_path_spec. </summary>
        public virtual ISegment getSegment(String segSpec)
        {
            ISegment seg = null;

            if (segSpec.Substring(0, (1) - (0)).Equals("/"))
            {
                Finder.reset();
            }

            SupportClass.Tokenizer tok    = new SupportClass.Tokenizer(segSpec, "/", false);
            SegmentFinder          finder = Finder;

            while (tok.HasMoreTokens())
            {
                String   pathSpec = tok.NextToken();
                PathSpec ps       = parsePathSpec(pathSpec);
                if (tok.HasMoreTokens())
                {
                    ps.isGroup = true;
                }
                else
                {
                    ps.isGroup = false;
                }

                if (ps.isGroup)
                {
                    IGroup g = null;
                    if (ps.find)
                    {
                        g = finder.findGroup(ps.pattern, ps.rep);
                    }
                    else
                    {
                        g = finder.getGroup(ps.pattern, ps.rep);
                    }
                    finder = new SegmentFinder(g);
                }
                else
                {
                    if (ps.find)
                    {
                        seg = finder.findSegment(ps.pattern, ps.rep);
                    }
                    else
                    {
                        seg = finder.getSegment(ps.pattern, ps.rep);
                    }
                }
            }

            return(seg);
        }
        /// <summary> Returns the query portion of the URL, broken up into individual key/value
        /// pairs. Does NOT unescape the keys and values.
        /// </summary>
        public virtual LinkedHashMap getParameterMap()
        {
            LinkedHashMap map;

            SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&");             //$NON-NLS-1$
            // multiply by 2 to create a sufficiently large HashMap
            map = new LinkedHashMap(tokens.Count * 2);

            while (tokens.HasMoreTokens())
            {
                String nameValuePair = tokens.NextToken();
                String name          = nameValuePair;
                String value         = "";         //$NON-NLS-1$
                int    equalsIndex   = nameValuePair.IndexOf('=');
                if (equalsIndex != -1)
                {
                    name = nameValuePair.Substring(0, (equalsIndex) - (0));
                    if (name.Length > 0)
                    {
                        value = nameValuePair.Substring(equalsIndex + 1);
                    }
                }
                map.Add(name, value);
            }

            return(map);
        }
Example #8
0
        private static int[] getFieldList(System.String theSpec)
        {
            SupportClass.Tokenizer   tok       = new SupportClass.Tokenizer(theSpec, ",", false);
            System.Collections.IList fieldList = new System.Collections.ArrayList(30);
            while (tok.HasMoreTokens())
            {
                System.String token = tok.NextToken();
                int           index = token.IndexOf('-');
                if (index >= 0)
                {
                    //it's a range
                    int start = System.Int32.Parse(token.Substring(0, (index) - (0)));
                    int end   = System.Int32.Parse(token.Substring(index + 1));
                    for (int i = start; i <= end; i++)
                    {
                        fieldList.Add((System.Int32)i);
                    }
                }
                else
                {
                    fieldList.Add(System.Int32.Parse(token));
                }
            }

            int[] result = new int[fieldList.Count];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = ((System.Int32)fieldList[i]);
            }

            return(result);
        }
Example #9
0
        /// <summary> Extracts selected fields from a message.
        ///
        /// </summary>
        /// <param name="theMessageText">an unparsed message from which to get fields
        /// </param>
        /// <param name="thePathSpecs">Terser-like paths to fields in the message.  See documentation
        /// for Terser.  These paths are identical except that they start with the segment
        /// name (search flags and group names are to be omitted as they are not relevant
        /// with unparsed ER7 messages).
        /// </param>
        /// <returns> field values corresponding to the given paths
        /// </returns>
        /// <throws>  HL7Exception </throws>
        public static System.String[] getFields(System.String theMessageText, System.String[] thePathSpecs)
        {
            NuGenDatumPath[] paths = new NuGenDatumPath[thePathSpecs.Length];
            for (int i = 0; i < thePathSpecs.Length; i++)
            {
                SupportClass.Tokenizer tok     = new SupportClass.Tokenizer(thePathSpecs[i], "-", false);
                System.String          segSpec = tok.NextToken();
                tok = new SupportClass.Tokenizer(segSpec, "()", false);
                System.String segName = tok.NextToken();
                if (segName.Length != 3)
                {
                    throw new NuGenHL7Exception("In field path, " + segName + " is not a valid segment name");
                }
                int segRep = 0;
                if (tok.HasMoreTokens())
                {
                    System.String rep = tok.NextToken();
                    try
                    {
                        segRep = System.Int32.Parse(rep);
                    }
                    catch (System.FormatException e)
                    {
                        throw new NuGenHL7Exception("In field path, segment rep" + rep + " is not valid", e);
                    }
                }

                int[] indices = Terser.getIndices(thePathSpecs[i]);
                paths[i] = new NuGenDatumPath();
                paths[i].add(segName).add(segRep);
                paths[i].add(indices[0]).add(indices[1]).add(indices[2]).add(indices[3]);
            }
            return(getFields(theMessageText, paths));
        }
Example #10
0
        /// <summary> Creates the given directory if it does not exist.</summary>
        public static System.IO.FileInfo makeDirectory(System.String directory)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(directory, "\\/", false);

            System.IO.FileInfo currDir = null;
            while (tok.HasMoreTokens())
            {
                System.String thisDirName = tok.NextToken();

                currDir = new System.IO.FileInfo(currDir.FullName + "\\" + thisDirName);                 //if currDir null, defaults to 1 arg call

                bool tmpBool;
                if (System.IO.File.Exists(currDir.FullName))
                {
                    tmpBool = true;
                }
                else
                {
                    tmpBool = System.IO.Directory.Exists(currDir.FullName);
                }
                if (!tmpBool)
                {
                    //create
                    System.IO.Directory.CreateDirectory(currDir.FullName);
                    ;
                }
                else if (System.IO.File.Exists(currDir.FullName))
                {
                    throw new System.IO.IOException("Can't create directory " + thisDirName + " - file with same name exists.");
                }
            }

            return(currDir);
        }
		} //end method
		
		/// <summary> Checks a code for an exact match, and using certain sequences where some 
		/// characters are wildcards (e.g. HL7nnnn).  If the pattern contains one of 
		/// " or ", " OR ", or "," each operand is checked.
		/// </summary>
		private bool checkCode(System.String code, System.String pattern)
		{
			bool match = false;
			//mod by Neal acharya - Do full match on with the pattern.  If code matches pattern then return true
			//else parse pattern to look for wildcard characters
			if (code.Equals(pattern))
			{
				match = true;
			}
			//end if 
			else
			{
				if (pattern.IndexOf(' ') >= 0 || pattern.IndexOf(',') >= 0)
				{
					SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pattern, ", ", false);
					while (tok.HasMoreTokens() && !match)
					{
						System.String t = tok.NextToken();
						if (!t.ToUpper().Equals("or".ToUpper()))
							match = checkCode(code, t);
					} //end while
				}
				//end if
				else
				{
					if (code.Equals(pattern))
					{
						match = true;
					}
				} //end else
			} //end else 
			return match;
		} //end method
Example #12
0
        /// <summary>recursively tokenize "guts" (a segment, or part of one) into tokens,
        /// according to separators (aka delimiters) which are different at each level
        /// of recursion, and to a recursive depth which is discovered through "handler"
        /// via handler.delim(int) and handler.specDepth()  As tokens are found, they
        /// are reported to handler via handler.putDatum(), which presumably stashes them
        /// away somewhere.  We tell the handler about the location in the message via
        /// putDatum()'s key argument, which is a List of Integers representing the
        /// position in the parse tree (size() == depth of recursion).
        /// TODO: say more.
        /// </summary>
        protected internal static void  parseSegmentGuts(NuGenER7.Handler handler, System.String guts, System.Collections.ArrayList nodeKey)
        {
            char thisDepthsDelim = handler.delim(nodeKey.Count - 1);

            //nodeKey.add(new Integer(0)); // will change nodeKey back before function exits

            SupportClass.Tokenizer gutsTokenizer = new SupportClass.Tokenizer(guts, System.Convert.ToString(thisDepthsDelim), true);
            while (gutsTokenizer.HasMoreTokens())
            {
                System.String gutsToken = gutsTokenizer.NextToken();

                if (gutsToken[0] == thisDepthsDelim)
                {
                    // gutsToken is all delims -- skipping over as many fields or
                    // components or whatevers as there are characters in the token:
                    int oldvalue = ((System.Int32)nodeKey[nodeKey.Count - 1]);
                    nodeKey[nodeKey.Count - 1] = (System.Int32)(oldvalue + gutsToken.Length);
                }
                else
                {
                    if (nodeKey.Count < handler.specDepth())
                    {
                        nodeKey.Add(0);
                        parseSegmentGuts(handler, gutsToken, nodeKey);
                        SupportClass.SetCapacity(nodeKey, nodeKey.Count - 1);
                    }
                    else
                    {
                        handler.putDatum(nodeKey, gutsToken);
                    }
                }
            }
            //nodeKey.setSize(nodeKey.size()-1); // undoing add done at top of this func
        }
Example #13
0
		/// <summary> Extracts selected fields from a message.  
		/// 
		/// </summary>
		/// <param name="theMessageText">an unparsed message from which to get fields 
		/// </param>
		/// <param name="thePathSpecs">Terser-like paths to fields in the message.  See documentation
		/// for Terser.  These paths are identical except that they start with the segment
		/// name (search flags and group names are to be omitted as they are not relevant 
		/// with unparsed ER7 messages).  
		/// </param>
		/// <returns> field values corresponding to the given paths
		/// </returns>
		/// <throws>  HL7Exception </throws>
		public static System.String[] getFields(System.String theMessageText, System.String[] thePathSpecs)
		{
			NuGenDatumPath[] paths = new NuGenDatumPath[thePathSpecs.Length];
			for (int i = 0; i < thePathSpecs.Length; i++)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePathSpecs[i], "-", false);
				System.String segSpec = tok.NextToken();
				tok = new SupportClass.Tokenizer(segSpec, "()", false);
				System.String segName = tok.NextToken();
				if (segName.Length != 3)
				{
					throw new NuGenHL7Exception("In field path, " + segName + " is not a valid segment name");
				}
				int segRep = 0;
				if (tok.HasMoreTokens())
				{
					System.String rep = tok.NextToken();
					try
					{
						segRep = System.Int32.Parse(rep);
					}
					catch (System.FormatException e)
					{
						throw new NuGenHL7Exception("In field path, segment rep" + rep + " is not valid", e);
					}
				}
				
				int[] indices = Terser.getIndices(thePathSpecs[i]);
				paths[i] = new NuGenDatumPath();
				paths[i].add(segName).add(segRep);
				paths[i].add(indices[0]).add(indices[1]).add(indices[2]).add(indices[3]);
			}
			return getFields(theMessageText, paths);
		}
Example #14
0
        /// <summary> Returns a String representing the encoding of the given message, if
        /// the encoding is recognized.  For example if the given message appears
        /// to be encoded using HL7 2.x XML rules then "XML" would be returned.
        /// If the encoding is not recognized then null is returned.  That this
        /// method returns a specific encoding does not guarantee that the
        /// message is correctly encoded (e.g. well formed XML) - just that
        /// it is not encoded using any other encoding than the one returned.
        /// </summary>
        public override string GetEncoding(string message)
        {
            string encoding = null;

            // quit if the string is too short
            if (message.Length < 4)
            {
                return(null);
            }

            // see if it looks like this message is | encoded ...
            var ok = true;

            // string should start with "MSH"
            if (!message.StartsWith("MSH"))
            {
                return(null);
            }

            // 4th character of each segment should be field delimiter
            var fourthChar = message[3];
            var st         = new SupportClass.Tokenizer(message, Convert.ToString(SegDelim), false);

            while (st.HasMoreTokens())
            {
                var x = st.NextToken();
                if (x.Length > 0)
                {
                    if (char.IsWhiteSpace(x[0]))
                    {
                        x = StripLeadingWhitespace(x);
                    }

                    if (x.Length >= 4 && x[3] != fourthChar)
                    {
                        return(null);
                    }
                }
            }

            // should be at least 11 field delimiters (because MSH-12 is required)
            var nextFieldDelimLoc = 0;

            for (var i = 0; i < 11; i++)
            {
                nextFieldDelimLoc = message.IndexOf((char)fourthChar, nextFieldDelimLoc + 1);
                if (nextFieldDelimLoc < 0)
                {
                    return(null);
                }
            }

            if (ok)
            {
                encoding = "VB";
            }

            return(encoding);
        }
Example #15
0
 private void addDictRefedAnnotation(IChemObject object_Renamed, System.String type, System.String values)
 {
     SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(values, ",");
     while (tokenizer.HasMoreTokens())
     {
         System.String token = tokenizer.NextToken();
         object_Renamed.setProperty(new DictRef("macie:" + type, token), token);
         //logger.debug("Added dict ref ", token, " to ", object_Renamed.GetType().FullName);
     }
 }
Example #16
0
        /// <summary>
        /// Given a Terser path, returns an array containing field num, field rep,
        /// component, and subcomponent.
        /// </summary>
        public static int[] GetIndices(string spec)
        {
            var tok = new SupportClass.Tokenizer(spec, "-", false);

            tok.NextToken(); // skip over segment
            if (!tok.HasMoreTokens())
            {
                throw new HL7Exception("Must specify field in spec " + spec, ErrorCode.APPLICATION_INTERNAL_ERROR);
            }

            int[] ret = null;
            try
            {
                var fieldSpec = new SupportClass.Tokenizer(tok.NextToken(), "()", false);
                var fieldNum  = int.Parse(fieldSpec.NextToken());
                var fieldRep  = 0;
                if (fieldSpec.HasMoreTokens())
                {
                    fieldRep = int.Parse(fieldSpec.NextToken());
                }

                var component = 1;
                if (tok.HasMoreTokens())
                {
                    component = int.Parse(tok.NextToken());
                }

                var subcomponent = 1;
                if (tok.HasMoreTokens())
                {
                    subcomponent = int.Parse(tok.NextToken());
                }

                var result = new int[] { fieldNum, fieldRep, component, subcomponent };
                ret = result;
            }
            catch (FormatException)
            {
                throw new HL7Exception("Invalid integer in spec " + spec, ErrorCode.APPLICATION_INTERNAL_ERROR);
            }

            return(ret);
        }
        /// <summary> Create a string array from a string separated by delim
        /// *
        /// </summary>
        /// <param name="line">the line to split
        /// </param>
        /// <param name="delim">the delimter to split by
        /// </param>
        /// <returns>a string array of the split fields
        ///
        /// </returns>
        public static String[] split(String line, String delim)
        {
            ArrayList list = new ArrayList();

            SupportClass.Tokenizer t = new SupportClass.Tokenizer(line, delim);
            while (t.HasMoreTokens())
            {
                list.Add(t.NextToken());
            }
            return((String[])list.ToArray(typeof(String)));
        }
Example #18
0
        ///
        ///	 <summary> * add - adds a number list to the already existing number list
        ///	 *  </summary>
        ///	 * <param name="s"> the given string
        ///	 *  </param>
        ///	 * <exception cref="FormatException"> - if the String has not a valid format </exception>
        ///
        public virtual void Add(string s)
        {
            //StringTokenizer sToken = new StringTokenizer(s, JDFConstants.BLANK);
            SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(s, JDFConstants.BLANK);

            while (sToken.HasMoreTokens())
            {
                string t = sToken.NextToken().Trim();
                m_numList.Add(t);
            }
        }
Example #19
0
        public static string[] Split(string line, string delim)
        {
            ArrayList arrayList = new ArrayList();

            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line, delim);
            while (tokenizer.HasMoreTokens())
            {
                arrayList.Add(tokenizer.NextToken());
            }
            return((string[])arrayList.ToArray(typeof(string)));
        }
Example #20
0
        /// <summary>
        /// Given a Terser path, returns an array containing field num, field rep, component, and
        /// subcomponent.
        /// </summary>
        ///
        /// <exception cref="HL7Exception"> Thrown when a HL 7 error condition occurs. </exception>
        ///
        /// <param name="spec"> The specifier. </param>
        ///
        /// <returns>   An array of int. </returns>

        public static int[] getIndices(System.String spec)
        {
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "-", false);
            tok.NextToken(); //skip over segment
            if (!tok.HasMoreTokens())
            {
                throw new HL7Exception("Must specify field in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            int[] ret = null;
            try
            {
                SupportClass.Tokenizer fieldSpec = new SupportClass.Tokenizer(tok.NextToken(), "()", false);
                int fieldNum = System.Int32.Parse(fieldSpec.NextToken());
                int fieldRep = 0;
                if (fieldSpec.HasMoreTokens())
                {
                    fieldRep = System.Int32.Parse(fieldSpec.NextToken());
                }

                int component = 1;
                if (tok.HasMoreTokens())
                {
                    component = System.Int32.Parse(tok.NextToken());
                }

                int subcomponent = 1;
                if (tok.HasMoreTokens())
                {
                    subcomponent = System.Int32.Parse(tok.NextToken());
                }
                int[] result = { fieldNum, fieldRep, component, subcomponent };
                ret = result;
            }
            catch (System.FormatException)
            {
                throw new HL7Exception("Invalid integer in spec " + spec, HL7Exception.APPLICATION_INTERNAL_ERROR);
            }

            return(ret);
        }
Example #21
0
        public static string RemoveAndHump(string data, string replaceThis)
        {
            StringBuilder stringBuilder = new StringBuilder();

            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(data, replaceThis);
            while (tokenizer.HasMoreTokens())
            {
                string data2 = tokenizer.NextToken();
                stringBuilder.Append(StringUtils.CapitalizeFirstLetter(data2));
            }
            return(stringBuilder.ToString());
        }
Example #22
0
        /// <summary>
        /// Load a properties file from the templatePath defined in the
        /// generator. As the templatePath can contains multiple paths,
        /// it will cycle through them to find the file. The first file
        /// that can be successfully loaded is considered. (kind of
        /// like the java classpath), it is done to clone the Velocity
        /// process of loading templates.
        /// </summary>
        /// <param name="propertiesFile">the properties file to load. It must be
        /// a relative pathname.
        /// </param>
        /// <returns>a properties instance loaded with the properties from
        /// the file. If no file can be found it returns an empty instance.
        /// </returns>
        protected internal virtual ExtendedProperties loadFromTemplatePath(System.String propertiesFile)
        {
            ExtendedProperties properties = new ExtendedProperties();

            System.String templatePath = Generator.Instance.TemplatePath;

            // We might have something like the following:
            //
            // #set ($dbprops = $properties.load("$generator.templatePath/path/props")
            //
            // as we have in Torque but we want people to start using
            //
            // #set ($dbprops = $properties.load("path/props")
            //
            // so that everything works from the filesystem or from
            // a JAR. So the actual Generator.getTemplatePath()
            // is not deprecated but it's use in templates
            // should be.
            SupportClass.Tokenizer st = new SupportClass.Tokenizer(templatePath, ",");
            while (st.HasMoreTokens())
            {
                System.String templateDir = st.NextToken();
                try {
                    // If the properties file is being pulled from the
                    // file system and someone is using the method whereby
                    // the properties file is assumed to be in the template
                    // path and they are simply using:
                    //
                    // #set ($dbprops = $properties.load("props") (1)
                    //
                    // than we have to tack on the templatePath in order
                    // for the properties file to be found. We want (1)
                    // to work whether the generation is being run from
                    // the file system or from a JAR file.
                    System.String fullPath = propertiesFile;

                    // FIXME probably not that clever since there could be
                    // a mix of file separators and the test will fail :-(
                    if (!fullPath.StartsWith(templateDir))
                    {
                        fullPath = templateDir + "\\" + propertiesFile;
                    }

                    properties.Load(new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                    // first pick wins, we don't need to go further since
                    // we found a valid file.
                    break;
                } catch (System.Exception) {
                    // do nothing
                }
            }
            return(properties);
        }
		/// <summary> <p>A convenience method for binding applications to an <code>ApplicationRouter</code>
		/// Information about bindings is read from a file at a specified URL.  Each line in the 
		/// file should have the following format (entries TAB delimited):</p>
		/// 
		/// <p>message_type &#009; trigger_event &#009; processing_id &#009; version_id &#009; app_class</p>
		/// 
		/// <p>Note that the first four fields can be the wildcard "*", which means any.</p>
		/// 
		/// <p>For example, if you write an Application called org.yourorganiztion.ADTProcessor
		/// that processes several types of ADT messages, and another called 
		/// org.yourorganization.ResultProcessor that processes result messages, you might have a 
		/// file that looks like this: </p>
		/// 
		/// <p>ADT &#009; * &#009; * &#009; * &#009; org.yourorganization.ADTProcessor<br>
		/// ORU &#009; R01 &#009; * &#009; * &#009; org.yourorganization.ResultProcessor</p>
		/// 
		/// <p>Each class listed in this file must implement either Genetibase.NuGenHL7.app.Application or 
		/// Genetibase.NuGenHL7.protocol.ReceivingApplication, and must have a zero-argument constructor.</p>
		/// 
		/// </summary>
		/// <param name="theRouter">the <code>ApplicationRouter</code> on which to make the binding
		/// </param>
		/// <param name="theSource">a URL pointing to the bindings file 
		/// </param>
		public static void  loadApplications(NuGenApplicationRouter theRouter, System.Uri theSource)
		{
			
			if (theSource == null)
			{
				throw new NuGenHL7Exception("Can't load application bindings: the given URL is null");
			}
			
			System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).CurrentEncoding);
			System.String line = null;
			while ((line = in_Renamed.ReadLine()) != null)
			{
				//parse application registration information 
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(line, "\t", false);
				System.String type = null, event_Renamed = null, procId = null, verId = null, className = null;
				
				if (tok.HasMoreTokens())
				{
					//skip blank lines 
					try
					{
						type = tok.NextToken();
						event_Renamed = tok.NextToken();
						procId = tok.NextToken();
						verId = tok.NextToken();
						className = tok.NextToken();
					}
					catch (System.ArgumentOutOfRangeException)
					{
						throw new NuGenHL7Exception("Can't register applications from " + theSource.ToString() + ". The line '" + line + "' is not of the form: message_type [tab] trigger_event " + "[tab] processing ID [tab] version ID [tab] application_class. " + "*** NOTE TWO NEW FIELDS AS OF HAPI 0.5 ****. ", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
					}
					
					System.Type appClass = System.Type.GetType(className); //may throw ClassNotFoundException 
					System.Object appObject = System.Activator.CreateInstance(appClass);
					NuGenReceivingApplication app = null;
					if (appObject is NuGenReceivingApplication)
					{
						app = (NuGenReceivingApplication) appObject;
					}
					else if (appObject is Application)
					{
						app = new NuGenAppWrapper((Application) appObject);
					}
					else
					{
						throw new NuGenHL7Exception("The specified class, " + appClass.FullName + ", doesn't implement Application or ReceivingApplication.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
					}
					
					Genetibase.NuGenHL7.protocol.AppRoutingData rd = new NuGenAppRoutingDataImpl(type, event_Renamed, procId, verId);
					theRouter.bindApplication(rd, app);
				}
			}
		}
Example #24
0
        public static string RemoveUnderScores(string data)
        {
            StringBuilder stringBuilder = new StringBuilder();

            SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(data, "_");
            while (tokenizer.HasMoreTokens())
            {
                string data2 = tokenizer.NextToken();
                stringBuilder.Append(StringUtils.FirstLetterCaps(data2));
            }
            return(stringBuilder.ToString());
        }
Example #25
0
        /// <summary> <p>A convenience method for binding applications to an <code>ApplicationRouter</code>
        /// Information about bindings is read from a file at a specified URL.  Each line in the
        /// file should have the following format (entries TAB delimited):</p>
        ///
        /// <p>message_type &#009; trigger_event &#009; processing_id &#009; version_id &#009; app_class</p>
        ///
        /// <p>Note that the first four fields can be the wildcard "*", which means any.</p>
        ///
        /// <p>For example, if you write an Application called org.yourorganiztion.ADTProcessor
        /// that processes several types of ADT messages, and another called
        /// org.yourorganization.ResultProcessor that processes result messages, you might have a
        /// file that looks like this: </p>
        ///
        /// <p>ADT &#009; * &#009; * &#009; * &#009; org.yourorganization.ADTProcessor<br>
        /// ORU &#009; R01 &#009; * &#009; * &#009; org.yourorganization.ResultProcessor</p>
        ///
        /// <p>Each class listed in this file must implement either Genetibase.NuGenHL7.app.Application or
        /// Genetibase.NuGenHL7.protocol.ReceivingApplication, and must have a zero-argument constructor.</p>
        ///
        /// </summary>
        /// <param name="theRouter">the <code>ApplicationRouter</code> on which to make the binding
        /// </param>
        /// <param name="theSource">a URL pointing to the bindings file
        /// </param>
        public static void  loadApplications(NuGenApplicationRouter theRouter, System.Uri theSource)
        {
            if (theSource == null)
            {
                throw new NuGenHL7Exception("Can't load application bindings: the given URL is null");
            }

            System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(System.Net.WebRequest.Create(theSource).GetResponse().GetResponseStream(), System.Text.Encoding.Default).CurrentEncoding);
            System.String          line       = null;
            while ((line = in_Renamed.ReadLine()) != null)
            {
                //parse application registration information
                SupportClass.Tokenizer tok = new SupportClass.Tokenizer(line, "\t", false);
                System.String          type = null, event_Renamed = null, procId = null, verId = null, className = null;

                if (tok.HasMoreTokens())
                {
                    //skip blank lines
                    try
                    {
                        type          = tok.NextToken();
                        event_Renamed = tok.NextToken();
                        procId        = tok.NextToken();
                        verId         = tok.NextToken();
                        className     = tok.NextToken();
                    }
                    catch (System.ArgumentOutOfRangeException)
                    {
                        throw new NuGenHL7Exception("Can't register applications from " + theSource.ToString() + ". The line '" + line + "' is not of the form: message_type [tab] trigger_event " + "[tab] processing ID [tab] version ID [tab] application_class. " + "*** NOTE TWO NEW FIELDS AS OF HAPI 0.5 ****. ", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    System.Type               appClass  = System.Type.GetType(className);      //may throw ClassNotFoundException
                    System.Object             appObject = System.Activator.CreateInstance(appClass);
                    NuGenReceivingApplication app       = null;
                    if (appObject is NuGenReceivingApplication)
                    {
                        app = (NuGenReceivingApplication)appObject;
                    }
                    else if (appObject is Application)
                    {
                        app = new NuGenAppWrapper((Application)appObject);
                    }
                    else
                    {
                        throw new NuGenHL7Exception("The specified class, " + appClass.FullName + ", doesn't implement Application or ReceivingApplication.", NuGenHL7Exception.APPLICATION_INTERNAL_ERROR);
                    }

                    Genetibase.NuGenHL7.protocol.AppRoutingData rd = new NuGenAppRoutingDataImpl(type, event_Renamed, procId, verId);
                    theRouter.bindApplication(rd, app);
                }
            }
        }
Example #26
0
 public static System.String nextToken(SupportClass.Tokenizer st)
 {
     System.String t = st.NextToken().Trim();
     if (t.Equals("\t"))
     {
         t = "";
     }
     if (st.HasMoreTokens())
     {
         st.NextToken();
     }
     return(t);
 }
Example #27
0
 //extracts LP# of label between first '{' and first '}', or -1 if there isn't one
 private int getLoopPointReference(System.String thePath)
 {
     SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePath, "{}", false);
     if (thePath.IndexOf('{') >= 0 && tok.HasMoreTokens())
     {
         System.String ref_Renamed = tok.NextToken();
         return((System.Int32)myLoopPointNames[ref_Renamed]);
     }
     else
     {
         return(-1);
     }
 }
Example #28
0
		public FileExtFilter(System.String descroot, System.String suffixes)
		{
			//UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'"
			exts = new List<String>();
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(suffixes, ";");
			while (tok.HasMoreTokens())
				exts.Add(tok.NextToken());
			
			descr = descroot + " (";
			for (int n = 0; n < exts.Count; n++)
				descr = descr + (n > 0?" ":"") + "*" + exts[n];
			descr = descr + ")";
		}
Example #29
0
        ///
        ///     <summary> * Method setAllStrings - put a separated string into the vString<br>
        ///     *                        e.g.  "asdf asdf asdf asdf" </summary>
        ///     * <param name="strIn">  separated string </param>
        ///     * <param name="strSep"> string separator </param>
        ///
        public virtual void setAllStrings(string strIn, string strSep)
        {
            if ((strIn != null) && (strSep != null))
            {
                this.Clear();
                //StringTokenizer sToken = new StringTokenizer (strIn, strSep);
                SupportClass.Tokenizer sToken = new SupportClass.Tokenizer(strIn, strSep);

                while (sToken.HasMoreTokens())
                {
                    this.Add(sToken.NextToken());
                }
            }
        }
Example #30
0
        /// <returns>s the message structure from MSH-9-3
        /// </returns>
        private System.Object[] getStructure(System.String msh9, char compSep)
        {
            System.String structure     = null;
            System.String event_Renamed = null;

            System.String[]        components = new System.String[3];
            SupportClass.Tokenizer tok        = new SupportClass.Tokenizer(msh9, System.Convert.ToString(compSep), true);
            for (int i = 0; tok.HasMoreTokens() && i < components.Length;)
            {
                System.String token = tok.NextToken();
                if (token[0] == compSep)
                {
                    i++;
                }
                else
                {
                    components[i] = token;
                }
            }

            bool explicitlyDefined = (components[2] == null)?false:true;

            if (explicitlyDefined)
            {
                structure = components[2];
            }
            else if (components[0] != null && components[0].Equals("ACK"))
            {
                structure = "ACK";
            }
            else if (components[0] != null && components[1] != null)
            {
                structure = components[0] + "_" + components[1];
            }
            else
            {
                throw new NuGenHL7Exception("Can't determine message structure from MSH-9: " + msh9, NuGenHL7Exception.UNSUPPORTED_MESSAGE_TYPE);
            }

            if (components[1] == null)
            {
                event_Renamed = components[0];
            }
            else
            {
                event_Renamed = components[0] + "^" + components[1];
            }

            return(new System.Object[] { event_Renamed, structure, (Boolean)explicitlyDefined });
        }
Example #31
0
        /// <summary> Encodes the given message and compares it to the given string.  Any differences
        /// are noted in the file [hapi.home]/parse_check.txt.  Ignores extra field delimiters.
        /// </summary>
        public static void  checkParse(System.String originalMessageText, Message parsedMessage, Parser parser)
        {
            System.String newMessageText = parser.encode(parsedMessage);


            if (!originalMessageText.Equals(newMessageText))
            {
                //check each segment
                SupportClass.Tokenizer       tok = new SupportClass.Tokenizer(originalMessageText, "\r");
                System.Collections.ArrayList one = new System.Collections.ArrayList();
                while (tok.HasMoreTokens())
                {
                    System.String seg = tok.NextToken();
                    if (seg.Length > 4)
                    {
                        one.Add(seg);
                    }
                }
                tok = new SupportClass.Tokenizer(newMessageText, "\r");
                System.Collections.ArrayList two = new System.Collections.ArrayList();
                while (tok.HasMoreTokens())
                {
                    System.String seg = tok.NextToken();
                    if (seg.Length > 4)
                    {
                        two.Add(stripExtraDelimiters(seg, seg[3]));
                    }
                }

                if (one.Count != two.Count)
                {
                }
                else
                {
                    //check each segment
                    for (int i = 0; i < one.Count; i++)
                    {
                        System.String origSeg = (System.String)one[i];
                        System.String newSeg  = (System.String)two[i];
                        if (!origSeg.Equals(newSeg))
                        {
                        }
                    }
                }
            }
            else
            {
            }
        }
Example #32
0
	/// <summary>
	/// Load a properties file from the templatePath defined in the
	/// generator. As the templatePath can contains multiple paths,
	/// it will cycle through them to find the file. The first file
	/// that can be successfully loaded is considered. (kind of
	/// like the java classpath), it is done to clone the Velocity
	/// process of loading templates.
	/// </summary>
	/// <param name="propertiesFile">the properties file to load. It must be
	/// a relative pathname.
	/// </param>
	/// <returns>a properties instance loaded with the properties from
	/// the file. If no file can be found it returns an empty instance.
	/// </returns>
	protected internal virtual ExtendedProperties loadFromTemplatePath(System.String propertiesFile) {
	    ExtendedProperties properties = new ExtendedProperties();
	    System.String templatePath = Generator.Instance.TemplatePath;

	    // We might have something like the following:
	    //
	    // #set ($dbprops = $properties.load("$generator.templatePath/path/props")
	    //
	    // as we have in Torque but we want people to start using
	    //
	    // #set ($dbprops = $properties.load("path/props")
	    //
	    // so that everything works from the filesystem or from
	    // a JAR. So the actual Generator.getTemplatePath()
	    // is not deprecated but it's use in templates
	    // should be.
	    SupportClass.Tokenizer st = new SupportClass.Tokenizer(templatePath, ",");
	    while (st.HasMoreTokens()) {
		System.String templateDir = st.NextToken();
		try {
		    // If the properties file is being pulled from the
		    // file system and someone is using the method whereby
		    // the properties file is assumed to be in the template
		    // path and they are simply using:
		    //
		    // #set ($dbprops = $properties.load("props") (1)
		    //
		    // than we have to tack on the templatePath in order
		    // for the properties file to be found. We want (1)
		    // to work whether the generation is being run from
		    // the file system or from a JAR file.
		    System.String fullPath = propertiesFile;

		    // FIXME probably not that clever since there could be
		    // a mix of file separators and the test will fail :-(
		    if (!fullPath.StartsWith(templateDir)) {
			fullPath = templateDir + "\\" + propertiesFile;
		    }

		    properties.Load(new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
		    // first pick wins, we don't need to go further since
		    // we found a valid file.
		    break;
		} catch (System.Exception) {
		    // do nothing
		}
	    }
	    return properties;
	}
Example #33
0
        /// <summary>  Description of the Method
        ///
        /// </summary>
        /// <param name="smiles">                     Description of the Parameter
        /// </param>
        /// <returns>                             Description of the Return Value
        /// </returns>
        /// <exception cref="InvalidSmilesException"> Description of the Exception
        /// </exception>
        public virtual Reaction parseReactionSmiles(System.String smiles)
        {
            SupportClass.Tokenizer tokenizer      = new SupportClass.Tokenizer(smiles, ">");
            System.String          reactantSmiles = tokenizer.NextToken();
            System.String          agentSmiles    = "";
            System.String          productSmiles  = tokenizer.NextToken();
            if (tokenizer.HasMoreTokens())
            {
                agentSmiles   = productSmiles;
                productSmiles = tokenizer.NextToken();
            }

            Reaction reaction = new Reaction();

            // add reactants
            IMolecule       reactantContainer = parseSmiles(reactantSmiles);
            ISetOfMolecules reactantSet       = ConnectivityChecker.partitionIntoMolecules(reactantContainer);

            IMolecule[] reactants = reactantSet.Molecules;
            for (int i = 0; i < reactants.Length; i++)
            {
                reaction.addReactant(reactants[i]);
            }

            // add reactants
            if (agentSmiles.Length > 0)
            {
                IMolecule       agentContainer = parseSmiles(agentSmiles);
                ISetOfMolecules agentSet       = ConnectivityChecker.partitionIntoMolecules(agentContainer);
                IMolecule[]     agents         = agentSet.Molecules;
                for (int i = 0; i < agents.Length; i++)
                {
                    reaction.addAgent(agents[i]);
                }
            }

            // add products
            IMolecule       productContainer = parseSmiles(productSmiles);
            ISetOfMolecules productSet       = ConnectivityChecker.partitionIntoMolecules(productContainer);

            IMolecule[] products = productSet.Molecules;
            for (int i = 0; i < products.Length; i++)
            {
                reaction.addProduct(products[i]);
            }

            return(reaction);
        }
Example #34
0
        /// <summary> <p>
        /// 'Camels Hump' replacement.
        /// </p>
        /// *
        /// <p>
        /// Remove one string from another string but leave the capitalization of the
        /// other letters unchanged.
        /// </p>
        /// *
        /// <p>
        /// For example, removing "_" from <code>foo_barBar</code> becomes <code>FooBarBar</code>.
        /// </p>
        /// *
        /// </summary>
        /// <param name="data">string to hump
        /// </param>
        /// <param name="replaceThis">string to be replaced
        /// </param>
        /// <returns>String
        ///
        /// </returns>
        static public System.String removeAndHump(System.String data, System.String replaceThis)
        {
            System.String             temp        = null;
            System.Text.StringBuilder out_Renamed = new System.Text.StringBuilder();
            temp = data;

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, replaceThis);

            while (st.HasMoreTokens())
            {
                System.String element = (System.String)st.NextToken();
                out_Renamed.Append(capitalizeFirstLetter(element));
            } //while

            return(out_Renamed.ToString());
        }
Example #35
0
        /// <summary> <p>
        /// Remove underscores from a string and replaces first
        /// letters with capitals.  Other letters are changed to lower case.
        /// </p>
        /// *
        /// <p>
        /// For example <code>foo_bar</code> becomes <code>FooBar</code>
        /// but <code>foo_barBar</code> becomes <code>FooBarbar</code>.
        /// </p>
        /// *
        /// </summary>
        /// <param name="data">string to remove underscores from.
        /// </param>
        /// <returns>String
        /// </returns>
        /// <deprecated>Use the org.apache.commons.util.StringUtils class
        /// instead.  Using its firstLetterCaps() method in conjunction
        /// with a StringTokenizer will achieve the same result.
        ///
        /// </deprecated>
        static public System.String removeUnderScores(System.String data)
        {
            System.String             temp        = null;
            System.Text.StringBuilder out_Renamed = new System.Text.StringBuilder();
            temp = data;

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, "_");

            while (st.HasMoreTokens())
            {
                System.String element = (System.String)st.NextToken();
                out_Renamed.Append(firstLetterCaps(element));
            }

            return(out_Renamed.ToString());
        }
Example #36
0
        /// <summary> Locates the member via a dotted name starting at the given id.
        /// It will traverse any and all proto chains if necc. to find the name.
        /// </summary>
        internal virtual Value locate(int startingId, String dottedName, bool traverseProto)
        {
            if (dottedName == null)
            {
                return(null);
            }
            // first rip apart the dottedName
            SupportClass.Tokenizer names = new SupportClass.Tokenizer(dottedName, ".");             //$NON-NLS-1$
            Value val = Session.getValue(startingId);

            while (names.HasMoreTokens() && val != null)
            {
                val = locateForNamed(val.Id, names.NextToken(), traverseProto).getValue();
            }
            return(val);
        }
		/// <summary> Encodes the given message and compares it to the given string.  Any differences
		/// are noted in the file [hapi.home]/parse_check.txt.  Ignores extra field delimiters.
		/// </summary>
		public static void  checkParse(System.String originalMessageText, Message parsedMessage, Parser parser)
		{
			System.String newMessageText = parser.encode(parsedMessage);
			
			
			if (!originalMessageText.Equals(newMessageText))
			{
				//check each segment
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(originalMessageText, "\r");
				System.Collections.ArrayList one = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						one.Add(seg);
				}
				tok = new SupportClass.Tokenizer(newMessageText, "\r");
				System.Collections.ArrayList two = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						two.Add(stripExtraDelimiters(seg, seg[3]));
				}
				
				if (one.Count != two.Count)
				{
				}
				else
				{
					//check each segment
					for (int i = 0; i < one.Count; i++)
					{
						System.String origSeg = (System.String) one[i];
						System.String newSeg = (System.String) two[i];
						if (!origSeg.Equals(newSeg))
						{
						}
					}
				}
			}
			else
			{
			}
			
		}
Example #38
0
        /// <summary> Write COM marker segment(s) to the codestream.
        /// 
        /// <p>This marker is currently written in main header and indicates the
        /// JJ2000 encoder's version that has created the codestream.</p>
        /// 
        /// </summary>
        private void writeCOM()
        {
            // JJ2000 COM marker segment
            if (enJJ2KMarkSeg)
            {
                System.String str = "Created by: CSJ2K version " + JJ2KInfo.version;
                int markSegLen; // the marker segment length

                // COM marker
                hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                // Calculate length: Lcom(2) + Rcom (2) + string's length;
                markSegLen = 2 + 2 + str.Length;
                hbuf.Write((System.Int16) markSegLen);

                // Rcom
                hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin) values)

                byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                for (int i = 0; i < chars.Length; i++)
                {
                    hbuf.Write((byte) chars[i]);
                }
            }
            // other COM marker segments
            if (otherCOMMarkSeg != null)
            {
                SupportClass.Tokenizer stk = new SupportClass.Tokenizer(otherCOMMarkSeg, "#");
                while (stk.HasMoreTokens())
                {
                    System.String str = stk.NextToken();
                    int markSegLen; // the marker segment length

                    // COM marker
                    hbuf.Write((System.Int16) CSJ2K.j2k.codestream.Markers.COM);

                    // Calculate length: Lcom(2) + Rcom (2) + string's length;
                    markSegLen = 2 + 2 + str.Length;
                    hbuf.Write((System.Int16) markSegLen);

                    // Rcom
                    hbuf.Write((System.Int16) 1); // General use (IS 8859-15:1999(Latin)
                    // values)

                    byte[] chars = System.Text.Encoding.UTF8.GetBytes(str);
                    for (int i = 0; i < chars.Length; i++)
                    {
                        hbuf.Write((byte) chars[i]);
                    }
                }
            }
        }
			//extracts LP# of label between first '{' and first '}', or -1 if there isn't one
			private int getLoopPointReference(System.String thePath)
			{
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(thePath, "{}", false);
				if (thePath.IndexOf('{') >= 0 && tok.HasMoreTokens())
				{
					System.String ref_Renamed = tok.NextToken();
					return ((System.Int32) myLoopPointNames[ref_Renamed]);
				}
				else
				{
					return - 1;
				}
			}
		/// <param name="theMessage">an HL7 message from which data are to be queried 
		/// </param>
		/// <param name="theQuery">the query (see class docs for syntax)
		/// </param>
		/// <returns> data from the message that are selected by the query 
		/// </returns>
		public static NuGenMessageQuery.Result query(Message theMessage, System.String theQuery)
		{
			System.Collections.Specialized.NameValueCollection clauses = getClauses(theQuery);
			
			//parse select clause
			SupportClass.Tokenizer select = new SupportClass.Tokenizer(clauses.Get("select"), ", ", false);
			System.Collections.ArrayList fieldPaths = new System.Collections.ArrayList(10);
			System.Collections.Hashtable names = new System.Collections.Hashtable(10);
			while (select.HasMoreTokens())
			{
				System.String token = select.NextToken();
				if (token.Equals("as"))
				{
					if (!select.HasMoreTokens())
					{
						throw new System.ArgumentException("Keyword 'as' must be followed by a field label");
					}
					names[select.NextToken()] = (System.Int32) (fieldPaths.Count - 1);
				}
				else
				{
					fieldPaths.Add(token);
				}
			}
			
			//parse loop clause 
			SupportClass.Tokenizer loop = new SupportClass.Tokenizer(clauses["loop"] == null?"":clauses["loop"], ",", false);
			System.Collections.ArrayList loopPoints = new System.Collections.ArrayList(10);
			System.Collections.Hashtable loopPointNames = new System.Collections.Hashtable(10);
			while (loop.HasMoreTokens())
			{
				System.String pointDecl = loop.NextToken();
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(pointDecl, "=", false);
				System.String name = tok.NextToken().Trim();
				System.String path = tok.NextToken().Trim();
				loopPoints.Add(path);
				loopPointNames[name] = (System.Int32) (loopPoints.Count - 1);
			}
			
			//parse where clause 
			//TODO: this will do for now but it should really be evaluated like an expression 
			//rather than a list  
			SupportClass.Tokenizer where = new SupportClass.Tokenizer(clauses["where"] == null?"":clauses["where"], ",", false);
			System.Collections.ArrayList filters = new System.Collections.ArrayList();
			while (where.HasMoreTokens())
			{
				filters.Add(where.NextToken());
			}
			System.String[] filterPaths = new System.String[filters.Count];
			System.String[] filterPatterns = new System.String[filters.Count];
			bool[] exactFlags = new bool[filters.Count];
			
			for (int i = 0; i < filters.Count; i++)
			{
				exactFlags[i] = true;
				System.String filter = (System.String) filters[i];
				System.String[] parts = splitFromEnd(filter, "=");
				if (parts[1] != null)
				{
					parts[1] = parts[1].Substring(1);
				}
				else
				{
					exactFlags[i] = false;
					parts = splitFromEnd(filter, "like");
					parts[1] = parts[1].Substring(4);
				}
				filterPaths[i] = parts[0].Trim();
				parts[1] = parts[1].Trim();
				filterPatterns[i] = parts[1].Substring(1, (parts[1].Length - 1) - (1));
			}

            String[] retVal1 = new String[loopPoints.Count];
            loopPoints.CopyTo(retVal1);

            String[] retVal2 = new String[fieldPaths.Count];
            fieldPaths.CopyTo(retVal2);

			return new ResultImpl(theMessage, retVal1, loopPointNames, retVal2, names, filterPaths, filterPatterns, exactFlags);
		}
Example #41
0
		/// <summary> Constructs a new 'ForwCompTransfSpec' for the specified number of
		/// components and tiles, the wavelet filters type and the parameter of the
		/// option 'Mct'. This constructor is called by the encoder. It also checks
		/// that the arguments belong to the recognized arguments list.
		/// 
		/// <p>This constructor chose the component transformation type depending
		/// on the wavelet filters : RCT with w5x3 filter and ICT with w9x7
		/// filter. Note: All filters must use the same data type.</p>
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="wfs">The wavelet filter specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public ForwCompTransfSpec(int nt, int nc, byte type, AnWTFilterSpec wfs, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Mct");
			
			if (param == null)
			{
				// The option has not been specified
				
				// If less than three component, do not use any component
				// transformation 
				if (nc < 3)
				{
					setDefault("none");
					return ;
				}
				// If the compression is lossless, uses RCT
				else if (pl.getBooleanParameter("lossless"))
				{
					setDefault("rct");
					return ;
				}
				else
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three first components use the same filters
					bool reject = false;
					for (int c = 1; c < 3; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setDefault("none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setDefault("ict");
						}
						else
						{
							setDefault("rct");
						}
					}
				}
				
				// Each tile receives a component transform specification
				// according the type of wavelet filters that are used by the
				// three first components
				for (int t = 0; t < nt; t++)
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the
			// specification
			//System.Boolean value_Renamed;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						throw new System.ArgumentException("Component specific " + " parameters" + " not allowed with " + "'-Mct' option");
					
					default: 
						if (word.Equals("off"))
						{
							if (curSpecType == SPEC_DEF)
							{
								setDefault("none");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
									if (tileSpec[i])
									{
										setTileDef(i, "none");
									}
							}
						}
						else if (word.Equals("on"))
						{
							if (nc < 3)
							{
								throw new System.ArgumentException("Cannot use component" + " transformation on a " + "image with less than " + "three components");
							}
							
							if (curSpecType == SPEC_DEF)
							{
								// Set arbitrarily the default
								// value to RCT (later will be found the suitable
								// component transform for each tile)
								setDefault("rct");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
								{
									if (tileSpec[i])
									{
										if (getFilterType(i, wfs) == CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3)
										{
											setTileDef(i, "rct");
										}
										else
										{
											setTileDef(i, "ict");
										}
									}
								}
							}
						}
						else
						{
							throw new System.ArgumentException("Default parameter of " + "option Mct not" + " recognized: " + param);
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				// If not, set arbitrarily the default value to 'none' but
				// specifies explicitely a default value for each tile depending
				// on the wavelet transform that is used
				setDefault("none");
				
				for (int t = 0; t < nt; t++)
				{
					if (isTileSpecified(t))
					{
						continue;
					}
					
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
			}
			
			// Check validity of component transformation of each tile compared to
			// the filter used.
			for (int t = nt - 1; t >= 0; t--)
			{
				
				if (((System.String) getTileDef(t)).Equals("none"))
				{
					// No comp. transf is used. No check is needed
					continue;
				}
				else if (((System.String) getTileDef(t)).Equals("rct"))
				{
					// Tile is using Reversible component transform
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // OK
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // Must use ICT
							if (isTileSpecified(t))
							{
								// User has requested RCT -> Error
								throw new System.ArgumentException("Cannot use RCT " + "with 9x7 filter " + "in tile " + t);
							}
							else
							{
								// Specify ICT for this tile
								setTileDef(t, "ict");
							}
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
				else
				{
					// ICT
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // Must use RCT
							if (isTileSpecified(t))
							{
								// User has requested ICT -> Error
								throw new System.ArgumentException("Cannot use ICT " + "with filter 5x3 " + "in tile " + t);
							}
							else
							{
								setTileDef(t, "rct");
							}
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // OK
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
			}
		}
Example #42
0
        /// <summary> Constructs a new 'QuantStepSizeSpec' for the specified number of
        /// components and tiles and the arguments of "-Qstep" option.
        /// 
        /// </summary>
        /// <param name="nt">The number of tiles
        /// 
        /// </param>
        /// <param name="nc">The number of components
        /// 
        /// </param>
        /// <param name="type">the type of the specification module i.e. tile specific,
        /// component specific or both.
        /// 
        /// </param>
        /// <param name="pl">The ParameterList
        /// 
        /// </param>
        public QuantStepSizeSpec(int nt, int nc, byte type, ParameterList pl)
            : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Qstep");
            if (param == null)
            {
                throw new System.ArgumentException("Qstep option not specified");
            }

            // Parse argument
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            System.String word; // current word
            byte curSpecType = SPEC_DEF; // Specification type of the
            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            bool[] compSpec = null; // Components concerned by the specification
            System.Single value_Renamed; // value of the current step size

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken().ToLower();

                switch (word[0])
                {

                    case 't':  // Tiles specification
                        tileSpec = parseIdx(word, nTiles);
                        if (curSpecType == SPEC_COMP_DEF)
                            curSpecType = SPEC_TILE_COMP;
                        else
                            curSpecType = SPEC_TILE_DEF;
                        break;

                    case 'c':  // Components specification
                        compSpec = parseIdx(word, nComp);
                        if (curSpecType == SPEC_TILE_DEF)
                            curSpecType = SPEC_TILE_COMP;
                        else
                            curSpecType = SPEC_COMP_DEF;
                        break;

                    default:  // Step size value
                        try
                        {
                            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                            value_Renamed = System.Single.Parse(word);
                        }
                        catch (System.FormatException e)
                        {
                            throw new System.ArgumentException("Bad parameter for " + "-Qstep option : " + word);
                        }

                        //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                        if ((float) value_Renamed <= 0.0f)
                        {
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            throw new System.ArgumentException("Normalized base step " + "must be positive : " + value_Renamed);
                        }

                        if (curSpecType == SPEC_DEF)
                        {
                            setDefault((System.Object) value_Renamed);
                        }
                        else if (curSpecType == SPEC_TILE_DEF)
                        {
                            for (int i = tileSpec.Length - 1; i >= 0; i--)
                                if (tileSpec[i])
                                {
                                    setTileDef(i, (System.Object) value_Renamed);
                                }
                        }
                        else if (curSpecType == SPEC_COMP_DEF)
                        {
                            for (int i = compSpec.Length - 1; i >= 0; i--)
                                if (compSpec[i])
                                {
                                    setCompDef(i, (System.Object) value_Renamed);
                                }
                        }
                        else
                        {
                            for (int i = tileSpec.Length - 1; i >= 0; i--)
                            {
                                for (int j = compSpec.Length - 1; j >= 0; j--)
                                {
                                    if (tileSpec[i] && compSpec[j])
                                    {
                                        setTileCompVal(i, j, (System.Object) value_Renamed);
                                    }
                                }
                            }
                        }

                        // Re-initialize
                        curSpecType = SPEC_DEF;
                        tileSpec = null;
                        compSpec = null;
                        break;

                }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, it takes
                // the default value defined in ParameterList
                if (ndefspec != 0)
                {
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    setDefault((System.Object) System.Single.Parse(pl.DefaultParameterList.getParameter("Qstep")));
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {

                        case SPEC_TILE_DEF:
                            for (int c = nc - 1; c >= 0; c--)
                            {
                                if (specValType[0][c] == SPEC_TILE_DEF)
                                    specValType[0][c] = SPEC_DEF;
                            }
                            tileDef[0] = null;
                            break;

                        case SPEC_COMP_DEF:
                            for (int t = nt - 1; t >= 0; t--)
                            {
                                if (specValType[t][0] == SPEC_COMP_DEF)
                                    specValType[t][0] = SPEC_DEF;
                            }
                            compDef[0] = null;
                            break;

                        case SPEC_TILE_COMP:
                            specValType[0][0] = SPEC_DEF;
                            tileCompVal["t0c0"] = null;
                            break;
                        }
                }
            }
        }
Example #43
0
		/// <summary> Encodes the given message and compares it to the given string.  Any differences
		/// are noted in the file [hapi.home]/parse_check.txt.  Ignores extra field delimiters.
		/// </summary>
		private void  checkParse(System.String originalMessageText, Message parsedMessage, Parser parser)
		{
			System.String newMessageText = parser.encode(parsedMessage);
			
			checkWriter.Write("******************* Comparing Messages ****************\r\n");
			checkWriter.Write("Original:           " + originalMessageText + "\r\n");
			checkWriter.Write("Parsed and Encoded: " + newMessageText + "\r\n");
			
			if (!originalMessageText.Equals(newMessageText))
			{
				//check each segment
				SupportClass.Tokenizer tok = new SupportClass.Tokenizer(originalMessageText, "\r");
				System.Collections.ArrayList one = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						one.Add(seg);
				}
				tok = new SupportClass.Tokenizer(newMessageText, "\r");
				System.Collections.ArrayList two = new System.Collections.ArrayList();
				while (tok.HasMoreTokens())
				{
					System.String seg = tok.NextToken();
					if (seg.Length > 4)
						two.Add(stripExtraDelimiters(seg, seg[3]));
				}
				
				if (one.Count != two.Count)
				{
					checkWriter.Write("Warning: inbound and parsed messages have different numbers of segments: \r\n");
					checkWriter.Write("Original: " + originalMessageText + "\r\n");
					checkWriter.Write("Parsed:   " + newMessageText + "\r\n");
				}
				else
				{
					//check each segment
					for (int i = 0; i < one.Count; i++)
					{
						System.String origSeg = (System.String) one[i];
						System.String newSeg = (System.String) two[i];
						if (!origSeg.Equals(newSeg))
						{
							checkWriter.Write("Warning: inbound and parsed message segment differs: \r\n");
							checkWriter.Write("Original: " + origSeg + "\r\n");
							checkWriter.Write("Parsed: " + newSeg + "\r\n");
						}
					}
				}
			}
			else
			{
				checkWriter.Write("No differences found\r\n");
			}
			
			checkWriter.Write("********************  End Comparison  ******************\r\n");
			checkWriter.Flush();
		}
Example #44
0
		/// <summary> Constructs a new 'QuantTypeSpec' for the specified number of components
		/// and tiles and the arguments of "-Qtype" option. This constructor is
		/// called by the encoder.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public QuantTypeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qtype");
			if (param == null)
			{
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault("reversible");
				}
				else
				{
					setDefault("expounded");
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecValType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						
						if (curSpecValType == SPEC_COMP_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						
						if (curSpecValType == SPEC_TILE_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_COMP_DEF;
						}
						break;
					
					case 'r': 
					// reversible specification
					case 'd': 
					// derived quantization step size specification
					case 'e':  // expounded quantization step size specification
						if (!word.ToUpper().Equals("reversible".ToUpper()) && !word.ToUpper().Equals("derived".ToUpper()) && !word.ToUpper().Equals("expounded".ToUpper()))
						{
							throw new System.ArgumentException("Unknown parameter " + "for " + "'-Qtype' option: " + word);
						}
						
						if (pl.getBooleanParameter("lossless") && (word.ToUpper().Equals("derived".ToUpper()) || word.ToUpper().Equals("expounded".ToUpper())))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "quantization with " + "'-lossless' option");
						}
						
						if (curSpecValType == SPEC_DEF)
						{
							// Default specification
							setDefault(word);
						}
						else if (curSpecValType == SPEC_TILE_DEF)
						{
							// Tile default specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								if (tileSpec[i])
								{
									setTileDef(i, word);
								}
							}
						}
						else if (curSpecValType == SPEC_COMP_DEF)
						{
							// Component default specification 
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, word);
								}
						}
						else
						{
							// Tile-component specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, word);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecValType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Unknown parameter for " + "'-Qtype' option: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, the
				// quantization type is 'reversible' (if '-lossless' is specified)
				// or 'expounded' (if not). 
				if (ndefspec != 0)
				{
					if (pl.getBooleanParameter("lossless"))
					{
						setDefault("reversible");
					}
					else
					{
						setDefault("expounded");
					}
				}
				else
				{
					// All tile-component have been specified, takes arbitrarily
					// the first tile-component value as default and modifies the
					// specification type of all tile-component sharing this
					// value.
					setDefault(getTileCompVal(0, 0));
					
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Example #45
0
        /// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary>
        private Asn1Tagged parseFilterComp()
        {
            Asn1Tagged tag = null;
            int filterComp = ft.OpOrAttr;

            switch (filterComp)
            {

                case AND:
                case OR:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false);
                    break;

                case NOT:
                    tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true);
                    break;

                default:
                    int filterType = ft.FilterType;
                    System.String value_Renamed = ft.Value;

                    switch (filterType)
                    {

                        case GREATER_OR_EQUAL:
                        case LESS_OR_EQUAL:
                        case APPROX_MATCH:
                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            break;

                        case EQUALITY_MATCH:
                            if (value_Renamed.Equals("*"))
                            {
                                // present
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false);
                            }
                            else if (value_Renamed.IndexOf((System.Char) '*') != - 1)
                            {
                                // substrings parse:
                                //    [initial], *any*, [final] into an Asn1SequenceOf
                                SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*", true);
            //								SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true);
                                Asn1SequenceOf seq = new Asn1SequenceOf(5);
                                int tokCnt = sub.Count;
                                int cnt = 0;

                                System.String lastTok = new System.Text.StringBuilder("").ToString();

                                while (sub.HasMoreTokens())
                                {
                                    System.String subTok = sub.NextToken();
                                    cnt++;
                                    if (subTok.Equals("*"))
                                    {
                                        // if previous token was '*', and since the current
                                        // token is a '*', we need to insert 'any'
                                        if (lastTok.Equals(subTok))
                                        {
                                            // '**'
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false));
                                        }
                                    }
                                    else
                                    {
                                        // value (RfcLdapString)
                                        if (cnt == 1)
                                        {
                                            // initial
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else if (cnt < tokCnt)
                                        {
                                            // any
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                        else
                                        {
                                            // final
                                            seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false));
                                        }
                                    }
                                    lastTok = subTok;
                                }

                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false);
                            }
                            else
                            {
                                // simple
                                tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
                            }
                            break;

                        case EXTENSIBLE_MATCH:
                            System.String type = null, matchingRule = null;
                            bool dnAttributes = false;
            //							SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true);
                            SupportClass.Tokenizer st = new SupportClass.Tokenizer(ft.Attr, ":");//, true);

                            bool first = true;
                            while (st.HasMoreTokens())
                            {
                                System.String s = st.NextToken().Trim();
                                if (first && !s.Equals(":"))
                                {
                                    type = s;
                                }
                                // dn must be lower case to be considered dn of the Entry.
                                else if (s.Equals("dn"))
                                {
                                    dnAttributes = true;
                                }
                                else if (!s.Equals(":"))
                                {
                                    matchingRule = s;
                                }
                                first = false;
                            }

                            tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((System.Object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((System.Object) type == null)?null:new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), (dnAttributes == false)?null:new Asn1Boolean(true)), false);
                            break;
                        }
                    break;

            }
            return tag;
        }
		/// <summary> Returns the query portion of the URL, broken up into individual key/value
		/// pairs. Does NOT unescape the keys and values.
		/// </summary>
		public virtual LinkedHashMap getParameterMap()
		{
            LinkedHashMap map;
			
			SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(Query, "?&"); //$NON-NLS-1$
			// multiply by 2 to create a sufficiently large HashMap
			map = new LinkedHashMap(tokens.Count * 2);
			
			while (tokens.HasMoreTokens())
			{
				String nameValuePair = tokens.NextToken();
				String name = nameValuePair;
				String value = ""; //$NON-NLS-1$
				int equalsIndex = nameValuePair.IndexOf('=');
				if (equalsIndex != - 1)
				{
					name = nameValuePair.Substring(0, (equalsIndex) - (0));
					if (name.Length > 0)
					{
						value = nameValuePair.Substring(equalsIndex + 1);
					}
				}
				map.Add(name, value);
			}
			
			return map;
		}
Example #47
0
        private static Regex compilePattern(System.String pattern, System.String escape)
        {
            // In JMS the wildcard characters are '_' (match any single character) and
            // '%' (match zero or more characters). In regular expressions the equivalent
            // wildcard characters are '.' and '*'.
            // We have to convert JMS wildcard characters in the pattern to regexp wildcard
            // characters taking care of the escape character.
            System.String regExp = null;
            System.Text.StringBuilder buf = new System.Text.StringBuilder();
            if ((System.Object) escape == null)
            {
                // No escape character - simply replace JMS wildcards with
                // regular expression wildcards
                for (SupportClass.Tokenizer strTok = new SupportClass.Tokenizer(pattern.Replace('_', '.'), "%"); strTok.HasMoreTokens(); )
                {
                    buf.Append(strTok.NextToken());
                }
                regExp = buf.ToString();
            }
            else
            {
                char esc = escape[0];
                for (int i = 0; i < pattern.Length; ++i)
                {
                    char nextChar = pattern[i];

                    if (nextChar != esc)
                    {
                        // Not an escape character - simply replace JMS wildcard characters with
                        // regular expression wildcard characters

                        if (nextChar == '_')
                            buf.Append('.');
                        else if (nextChar == '%')
                            buf.Append(".*");
                        else
                            buf.Append(nextChar);
                    }
                    else
                    {
                        // Escape character - replace user-defined escape character with
                        // regular expression escape character. Copy the character after
                        // the escape character as is since it is being escaped

                        buf.Append('\\');
                        ++i;
                        if (i < pattern.Length)
                        {
                            buf.Append(pattern[i]);
                        }
                    }
                }
                regExp = buf.ToString();
            }
            return new Regex(regExp.ToString());
        }
Example #48
0
		//*************************************************************************
		// connect methods
		//*************************************************************************
		
		/// <summary> 
		/// Connects to the specified host and port.
		/// 
		/// If this LdapConnection object represents an open connection, the
		/// connection is closed first before the new connection is opened.
		/// At this point, there is no authentication, and any operations are
		/// conducted as an anonymous client.
		/// 
		///  When more than one host name is specified, each host is contacted
		/// in turn until a connection can be established.
		/// 
		/// </summary>
		/// <param name="host">A host name or a dotted string representing the IP address
		/// of a host running an Ldap server. It may also
		/// contain a list of host names, space-delimited. Each host
		/// name can include a trailing colon and port number.
		/// 
		/// </param>
		/// <param name="port">The TCP or UDP port number to connect to or contact.
		/// The default Ldap port is 389. The port parameter is
		/// ignored for any host hame which includes a colon and
		/// port number.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// 
		/// </exception>
		public virtual void  Connect(System.String host, int port)
		{
			// connect doesn't affect other clones
			// If not a clone, destroys old connection.
			// Step through the space-delimited list
			SupportClass.Tokenizer hostList = new SupportClass.Tokenizer(host, " ");
			System.String address = null;
			
			int specifiedPort;
			int colonIndex; //after the colon is the port
			while (hostList.HasMoreTokens())
			{
				try
				{
					specifiedPort = port;
					address = hostList.NextToken();
					colonIndex = address.IndexOf((System.Char) ':');
					if (colonIndex != - 1 && colonIndex + 1 != address.Length)
					{
						//parse Port out of address
						try
						{
							specifiedPort = System.Int32.Parse(address.Substring(colonIndex + 1));
							address = address.Substring(0, (colonIndex) - (0));
						}
						catch (System.Exception e)
						{
							throw new System.ArgumentException(ExceptionMessages.INVALID_ADDRESS);
						}
					}
					// This may return a different conn object
					// Disassociate this clone with the underlying connection.
					conn = conn.destroyClone(true);
					conn.connect(address, specifiedPort);
					break;
				}
				catch (LdapException LE)
				{
					if (!hostList.HasMoreTokens())
						throw LE;
				}
			}
			return ;
		}
Example #49
0
        /// <summary>Gets path information from a path spec. </summary>
        private PathSpec parsePathSpec(System.String spec)
        {
            PathSpec ps = new PathSpec(this);

            if (spec.StartsWith("."))
            {
                ps.find = true;
                spec = spec.Substring(1);
            }
            else
            {
                ps.find = false;
            }

            if (spec.Length == 0)
            {
                throw new HL7Exception("Invalid path (some path element is either empty or contains only a dot)");
            }
            SupportClass.Tokenizer tok = new SupportClass.Tokenizer(spec, "()", false);
            ps.pattern = tok.NextToken();
            if (tok.HasMoreTokens())
            {
                System.String repString = tok.NextToken();
                try
                {
                    ps.rep = System.Int32.Parse(repString);
                }
                catch (System.FormatException)
                {
                    throw new HL7Exception(repString + " is not a valid rep #", HL7Exception.APPLICATION_INTERNAL_ERROR);
                }
            }
            else
            {
                ps.rep = 0;
            }
            return ps;
        }
Example #50
0
		/// <summary> Constructs a new 'AnWTFilterSpec' for the specified number of
		/// components and tiles.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="qts">Quantization specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl):base(nt, nc, type)
		{
			
			// Check parameters
			pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo));
			
			System.String param = pl.getParameter("Ffilters");
			bool isFilterSpecified = true;
			
			// No parameter specified
			if (param == null)
			{
				isFilterSpecified = false;
				
				// If lossless compression, uses the reversible filters in each
				// tile-components 
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault(parseFilters(REV_FILTER_STR));
					return ;
				}
				
				// If no filter is specified through the command-line, use
				// REV_FILTER_STR or NON_REV_FILTER_STR according to the
				// quantization type
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						switch (qts.getSpecValType(t, c))
						{
							
							case SPEC_DEF: 
								if (getDefault() == null)
								{
									if (pl.getBooleanParameter("lossless"))
										setDefault(parseFilters(REV_FILTER_STR));
									if (((System.String) qts.getDefault()).Equals("reversible"))
									{
										setDefault(parseFilters(REV_FILTER_STR));
									}
									else
									{
										setDefault(parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_DEF;
								break;
							
							case SPEC_COMP_DEF: 
								if (!isCompSpecified(c))
								{
									if (((System.String) qts.getCompDef(c)).Equals("reversible"))
									{
										setCompDef(c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setCompDef(c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_COMP_DEF;
								break;
							
							case SPEC_TILE_DEF: 
								if (!isTileSpecified(t))
								{
									if (((System.String) qts.getTileDef(t)).Equals("reversible"))
									{
										setTileDef(t, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileDef(t, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_DEF;
								break;
							
							case SPEC_TILE_COMP: 
								if (!isTileCompSpecified(t, c))
								{
									if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
									{
										setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_COMP;
								break;
							
							default: 
								throw new System.ArgumentException("Unsupported " + "specification " + "type");
							
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			AnWTFilter[][] filter;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't': 
					// Tiles specification
					case 'T':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c': 
					// Components specification
					case 'C':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					case 'w': 
					// WT filters specification
					case 'W':  // WT filters specification
						if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper()))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option");
						}
						
						filter = parseFilters(word);
						if (curSpecType == SPEC_DEF)
						{
							setDefault(filter);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, filter);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, filter);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, filter);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Bad construction for " + "parameter: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					if (((System.String) qts.getDefault()).Equals("reversible"))
						setDefault(parseFilters(REV_FILTER_STR));
					else
						setDefault(parseFilters(NON_REV_FILTER_STR));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
			
			// Check consistency between filter and quantization type
			// specification
			for (int t = nt - 1; t >= 0; t--)
			{
				for (int c = nc - 1; c >= 0; c--)
				{
					// Reversible quantization
					if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
					{
						// If filter is reversible, it is OK
						if (isReversible(t, c))
							continue;
						
						// If no filter has been defined, use reversible filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
						}
						else
						{
							// Non reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line.");
						}
					}
					else
					{
						// No reversible quantization
						// No reversible filter -> OK
						if (!isReversible(t, c))
							continue;
						
						// If no filter has been specified, use non-reversible
						// filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
						}
						else
						{
							// Reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line");
						}
					}
				}
			}
		}
Example #51
0
		/// <summary> Constructs a new 'IntegerSpec' for the specified number of tiles and
		/// components, the allowed specifications type and the ParameterList
		/// instance. This constructor is normally called at encoder side and parse
		/// arguments of specified option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">The allowed specifications type
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		/// <param name="optName">The name of the option to process
		/// 
		/// </param>
		public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName):base(nt, nc, type)
		{
			
			System.Int32 value_Renamed;
			System.String param = pl.getParameter(optName);
			
			if (param == null)
			{
				// No parameter specified
				param = pl.DefaultParameterList.getParameter(optName);
				try
				{
					setDefault((System.Object) System.Int32.Parse(param));
				}
				catch (System.FormatException)
				{
					throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					default: 
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word);
						}
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					param = pl.DefaultParameterList.getParameter(optName);
					try
					{
						setDefault((System.Object) System.Int32.Parse(param));
					}
					catch (System.FormatException)
					{
						throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
					}
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Example #52
0
		/// <summary> Extracts the subtypes from the specified attribute name.
		/// 
		/// For example, if the attribute name is cn;lang-ja;phonetic,
		/// this method returns an array containing lang-ja and phonetic.
		/// 
		/// </summary>
		/// <param name="attrName">  Name of the attribute from which to extract
		/// the subtypes.
		/// 
		/// </param>
		/// <returns> An array subtypes or null if the attribute has none.
		/// 
		/// @throws IllegalArgumentException if attrName is null
		/// </returns>
		public static System.String[] getSubtypes(System.String attrName)
		{
			if ((System.Object) attrName == null)
			{
				throw new System.ArgumentException("Attribute name cannot be null");
			}
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";");
			System.String[] subTypes = null;
			int cnt = st.Count;
			if (cnt > 0)
			{
				st.NextToken(); // skip over basename
				subTypes = new System.String[cnt - 1];
				int i = 0;
				while (st.HasMoreTokens())
				{
					subTypes[i++] = st.NextToken();
				}
			}
			return subTypes;
		}
		/// <summary> Returns a String representing the encoding of the given message, if
		/// the encoding is recognized.  For example if the given message appears
		/// to be encoded using HL7 2.x XML rules then "XML" would be returned.
		/// If the encoding is not recognized then null is returned.  That this
		/// method returns a specific encoding does not guarantee that the
		/// message is correctly encoded (e.g. well formed XML) - just that
		/// it is not encoded using any other encoding than the one returned.
		/// </summary>
		public override System.String getEncoding(System.String message)
		{
			System.String encoding = null;
			
			//quit if the string is too short
			if (message.Length < 4)
				return null;
			
			//see if it looks like this message is | encoded ...
			bool ok = true;
			
			//string should start with "MSH"
			if (!message.StartsWith("MSH"))
				return null;
			
			//4th character of each segment should be field delimiter
			char fourthChar = message[3];
			SupportClass.Tokenizer st = new SupportClass.Tokenizer(message, System.Convert.ToString(segDelim), false);
			while (st.HasMoreTokens())
			{
				System.String x = st.NextToken();
				if (x.Length > 0)
				{
					if (System.Char.IsWhiteSpace(x[0]))
						x = stripLeadingWhitespace(x);
					if (x.Length >= 4 && x[3] != fourthChar)
						return null;
				}
			}
			
			//should be at least 11 field delimiters (because MSH-12 is required)
			int nextFieldDelimLoc = 0;
			for (int i = 0; i < 11; i++)
			{
				nextFieldDelimLoc = message.IndexOf((System.Char) fourthChar, nextFieldDelimLoc + 1);
				if (nextFieldDelimLoc < 0)
					return null;
			}
			
			if (ok)
				encoding = "VB";
			
			return encoding;
		}
Example #54
0
		/// <summary> This function parses the values given for the ROIs with the argument
		/// -Rroi. Currently only circular and rectangular ROIs are supported.
		/// 
		/// <p>A rectangular ROI is indicated by a 'R' followed the coordinates for
		/// the upper left corner of the ROI and then its width and height.</p>
		/// 
		/// <p>A circular ROI is indicated by a 'C' followed by the coordinates of
		/// the circle center and then the radius.</p>
		/// 
		/// <p>Before the R and C values, the component that are affected by the
		/// ROI are indicated.</p>
		/// 
		/// </summary>
		/// <param name="roiopt">The info on the ROIs
		/// 
		/// </param>
		/// <param name="nc">number of components
		/// 
		/// </param>
		/// <param name="roiVector">The vcector containing the ROI parsed from the cmd line
		/// 
		/// </param>
		/// <returns> The ROIs specified in roiopt
		/// 
		/// </returns>
		protected internal static System.Collections.ArrayList parseROIs(System.String roiopt, int nc, System.Collections.ArrayList roiVector)
		{
			//ROI[] ROIs;
			ROI roi;
			SupportClass.Tokenizer stok;
			//char tok;
			int nrOfROIs = 0;
			//char c;
			int ulx, uly, w, h, x, y, rad; // comp removed
			bool[] roiInComp = null;
			
			stok = new SupportClass.Tokenizer(roiopt);
			
			System.String word;
			while (stok.HasMoreTokens())
			{
				word = stok.NextToken();
				
				switch (word[0])
				{
					
					case 'c':  // Components specification
						roiInComp = ModuleSpec.parseIdx(word, nc);
						break;
					
					case 'R':  // Rectangular ROI to be read
						nrOfROIs++;
						try
						{
							word = stok.NextToken();
							ulx = (System.Int32.Parse(word));
							word = stok.NextToken();
							uly = (System.Int32.Parse(word));
							word = stok.NextToken();
							w = (System.Int32.Parse(word));
							word = stok.NextToken();
							h = (System.Int32.Parse(word));
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "'-Rroi R' option : " + word);
						}
						catch (System.ArgumentOutOfRangeException)
						{
							throw new System.ArgumentException("Wrong number of " + "parameters for  " + "h'-Rroi R' option.");
						}
						
						// If the ROI is component-specific, check which comps.
						if (roiInComp != null)
							for (int i = 0; i < nc; i++)
							{
								if (roiInComp[i])
								{
									roi = new ROI(i, ulx, uly, w, h);
									roiVector.Add(roi);
								}
							}
						else
						{
							// Otherwise add ROI for all components
							for (int i = 0; i < nc; i++)
							{
								roi = new ROI(i, ulx, uly, w, h);
								roiVector.Add(roi);
							}
						}
						break;
					
					case 'C':  // Circular ROI to be read
						nrOfROIs++;
						
						try
						{
							word = stok.NextToken();
							x = (System.Int32.Parse(word));
							word = stok.NextToken();
							y = (System.Int32.Parse(word));
							word = stok.NextToken();
							rad = (System.Int32.Parse(word));
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "'-Rroi C' option : " + word);
						}
						catch (System.ArgumentOutOfRangeException)
						{
							throw new System.ArgumentException("Wrong number of " + "parameters for " + "'-Rroi C' option.");
						}
						
						// If the ROI is component-specific, check which comps.
						if (roiInComp != null)
							for (int i = 0; i < nc; i++)
							{
								if (roiInComp[i])
								{
									roi = new ROI(i, x, y, rad);
									roiVector.Add(roi);
								}
							}
						else
						{
							// Otherwise add ROI for all components
							for (int i = 0; i < nc; i++)
							{
								roi = new ROI(i, x, y, rad);
								roiVector.Add(roi);
							}
						}
						break;
					
					case 'A':  // ROI wth arbitrary shape
						nrOfROIs++;
						
						System.String filename;
						ImgReaderPGM maskPGM = null;
						
						try
						{
							filename = stok.NextToken();
						}
						catch (System.ArgumentOutOfRangeException)
						{
							throw new System.ArgumentException("Wrong number of " + "parameters for " + "'-Rroi A' option.");
						}
						try
						{
							maskPGM = new ImgReaderPGM(filename);
						}
						catch (System.IO.IOException)
						{
							throw new System.ApplicationException("Cannot read PGM file with ROI");
						}
						
						// If the ROI is component-specific, check which comps.
						if (roiInComp != null)
							for (int i = 0; i < nc; i++)
							{
								if (roiInComp[i])
								{
									roi = new ROI(i, maskPGM);
									roiVector.Add(roi);
								}
							}
						else
						{
							// Otherwise add ROI for all components
							for (int i = 0; i < nc; i++)
							{
								roi = new ROI(i, maskPGM);
								roiVector.Add(roi);
							}
						}
						break;
					
					default: 
						throw new System.ApplicationException("Bad parameters for ROI nr " + roiVector.Count);
					
				}
			}
			
			return roiVector;
		}
Example #55
0
		/// <summary> Constructs a new 'GuardBitsSpec' for the specified number of components
		/// and tiles and the arguments of "-Qguard_bits" option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public GuardBitsSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qguard_bits");
			if (param == null)
			{
				throw new System.ArgumentException("Qguard_bits option not " + "specified");
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			System.Int32 value_Renamed; // value of the guard bits
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					default:  // Step size value
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "-Qguard_bits option" + " : " + word);
						}
						
						if ((float) value_Renamed <= 0.0f)
						{
							throw new System.ArgumentException("Guard bits value " + "must be positive : " + value_Renamed);
						}
						
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					setDefault((System.Object) System.Int32.Parse(pl.DefaultParameterList.getParameter("Qguard_bits")));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
		/// <summary> Splits the given composite string into an array of components using the given
		/// delimiter.
		/// </summary>
		public static System.String[] split(System.String composite, System.String delim)
		{
			System.Collections.ArrayList components = new System.Collections.ArrayList();
			
			//defend against evil nulls
			if (composite == null)
				composite = "";
			if (delim == null)
				delim = "";
			
			SupportClass.Tokenizer tok = new SupportClass.Tokenizer(composite, delim, true);
			bool previousTokenWasDelim = true;
			while (tok.HasMoreTokens())
			{
				System.String thisTok = tok.NextToken();
				if (thisTok.Equals(delim))
				{
					if (previousTokenWasDelim)
						components.Add(null);
					previousTokenWasDelim = true;
				}
				else
				{
					components.Add(thisTok);
					previousTokenWasDelim = false;
				}
			}
			
			System.String[] ret = new System.String[components.Count];
			for (int i = 0; i < components.Count; i++)
			{
				ret[i] = ((System.String) components[i]);
			}
			
			return ret;
		}
		/// <summary> Locates the member via a dotted name starting at the given id.
		/// It will traverse any and all proto chains if necc. to find the name.
		/// </summary>
		internal virtual Value locate(int startingId, String dottedName, bool traverseProto)
		{
			if (dottedName == null) return null;
			// first rip apart the dottedName
			SupportClass.Tokenizer names = new SupportClass.Tokenizer(dottedName, "."); //$NON-NLS-1$
			Value val = Session.getValue(startingId);
            while (names.HasMoreTokens() && val != null)
            {
                val = locateForNamed(val.Id, names.NextToken(), traverseProto).getValue();
            }
			return val;
		}
Example #58
0
		/// <summary> Creates a new CBlkSizeSpec object for the specified number of tiles and
		/// components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public CBlkSizeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			bool firstVal = true;
			System.String param = pl.getParameter(optName);
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //  i, xIdx removed
			System.String word = null; // current word
			System.String errMsg = null;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						System.Int32[] dim = new System.Int32[2];
						// Get code-block's width
						try
						{
							dim[0] = System.Int32.Parse(word);
							// Check that width is not >
							// StdEntropyCoderOptions.MAX_CB_DIM
							if (dim[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that width is not <
							// StdEntropyCoderOptions.MIN_CB_DIM
							if (dim[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that width is a power of 2
							if (dim[0] != (1 << MathUtil.log2(dim[0])))
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width must be a power of 2";
								throw new System.ArgumentException(errMsg);
							}
						}
						catch (System.FormatException)
						{
							errMsg = "'" + optName + "' option : the code-block's " + "width could not be parsed.";
							throw new System.ArgumentException(errMsg);
						}
						// Get the next word in option
						try
						{
							word = stk.NextToken();
						}
						catch (System.ArgumentOutOfRangeException)
						{
							errMsg = "'" + optName + "' option : could not parse the " + "code-block's height";
							throw new System.ArgumentException(errMsg);
						}
						// Get the code-block's height
						try
						{
							dim[1] = System.Int32.Parse(word);
							// Check that height is not >
							// StdEntropyCoderOptions.MAX_CB_DIM
							if (dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that height is not <
							// StdEntropyCoderOptions.MIN_CB_DIM
							if (dim[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that height is a power of 2
							if (dim[1] != (1 << MathUtil.log2(dim[1])))
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height must be a power of 2";
								throw new System.ArgumentException(errMsg);
							}
							// Check that the code-block 'area' (i.e. width*height) is
							// not greater than StdEntropyCoderOptions.MAX_CB_AREA
							if (dim[0] * dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA)
							{
								errMsg = "'" + optName + "' option : The " + "code-block's area (i.e. width*height) " + "cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA;
								throw new System.ArgumentException(errMsg);
							}
						}
						catch (System.FormatException)
						{
							errMsg = "'" + optName + "' option : the code-block's height " + "could not be parsed.";
							throw new System.ArgumentException(errMsg);
						}
						
						// Store the maximum dimensions if necessary
						if (dim[0] > maxCBlkWidth)
						{
							maxCBlkWidth = dim[0];
						}
						
						if (dim[1] > maxCBlkHeight)
						{
							maxCBlkHeight = dim[1];
						}
						
						if (firstVal)
						{
							// This is the first time a value is given so we set it as
							// the default one 
							setDefault((System.Object) (dim));
							firstVal = false;
						}
						
						switch (curSpecType)
						{
							
							case SPEC_DEF: 
								setDefault((System.Object) (dim));
								break;
							
							case SPEC_TILE_DEF: 
								for (ti = tileSpec.Length - 1; ti >= 0; ti--)
								{
									if (tileSpec[ti])
									{
										setTileDef(ti, (System.Object) (dim));
									}
								}
								break;
							
							case SPEC_COMP_DEF: 
								for (ci = compSpec.Length - 1; ci >= 0; ci--)
								{
									if (compSpec[ci])
									{
										setCompDef(ci, (System.Object) (dim));
									}
								}
								break;
							
							default: 
								for (ti = tileSpec.Length - 1; ti >= 0; ti--)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (tileSpec[ti] && compSpec[ci])
										{
											setTileCompVal(ti, ci, (System.Object) (dim));
										}
									}
								}
								break;
							
						}
						break;
					
				} // end switch
			}
		}
Example #59
0
		/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles
		/// and components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl):base(nt, nc, type)
		{
			
			this.dls = dls;
			
			// The precinct sizes are stored in a 2 elements vector array, the
			// first element containing a vector for the precincts width for each
			// resolution level and the second element containing a vector for the
			// precincts height for each resolution level. The precincts sizes are
			// specified from the highest resolution level to the lowest one
			// (i.e. 0).  If there are less elements than the number of
			// decomposition levels, the last element is used for all remaining
			// resolution levels (i.e. if the precincts sizes are specified only
			// for resolutions levels 5, 4 and 3, then the precincts size for
			// resolution levels 2, 1 and 0 will be the same as the size used for
			// resolution level 3).
			
			// Boolean used to know if we were previously reading a precinct's 
			// size or if we were reading something else.
			bool wasReadingPrecinctSize = false;
			
			System.String param = pl.getParameter(optName);
			
			// Set precinct sizes to default i.e. 2^15 =
			// Markers.PRECINCT_PARTITION_DEF_SIZE
			System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2];
			tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
			tmpv[0].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
			tmpv[1].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			setDefault(tmpv);
			
			if (param == null)
			{
				// No precinct size specified in the command line so we do not try 
				// to parse it.
				return ;
			}
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //i, xIdx removed
			
			bool endOfParamList = false;
			System.String word = null; // current word
			System.Int32 w, h;
			System.String errMsg = null;
			
			while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList)
			{
				
				System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy
				
				// We do not read the next token if we were reading a precinct's
				// size argument as we have already read the next token into word.
				if (!wasReadingPrecinctSize)
				{
					word = stk.NextToken();
				}
				
				wasReadingPrecinctSize = false;
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						
						// Initialises Vector objects
						v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
						v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
						
						while (true)
						{
							
							// Now get the precinct dimensions
							try
							{
								// Get precinct width
								w = System.Int32.Parse(word);
								
								// Get next word in argument list
								try
								{
									word = stk.NextToken();
								}
								catch (System.ArgumentOutOfRangeException)
								{
									errMsg = "'" + optName + "' option : could not " + "parse the precinct's width";
									throw new System.ArgumentException(errMsg);
								}
								// Get precinct height
								h = System.Int32.Parse(word);
								if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h)))
								{
									errMsg = "Precinct dimensions must be powers of 2";
									throw new System.ArgumentException(errMsg);
								}
							}
							catch (System.FormatException)
							{
								errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed.";
								throw new System.ArgumentException(errMsg);
							}
							// Store packet's dimensions in Vector arrays
							v[0].Add(w);
							v[1].Add(h);
							
							// Try to get the next token
							if (stk.HasMoreTokens())
							{
								word = stk.NextToken();
								if (!System.Char.IsDigit(word[0]))
								{
									// The next token does not start with a digit so
									// it is not a precinct's size argument. We set
									// the wasReadingPrecinctSize booleen such that we
									// know that we don't have to read another token
									// and check for the end of the parameters list.
									wasReadingPrecinctSize = true;
									
									if (curSpecType == SPEC_DEF)
									{
										setDefault(v);
									}
									else if (curSpecType == SPEC_TILE_DEF)
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											if (tileSpec[ti])
											{
												setTileDef(ti, v);
											}
										}
									}
									else if (curSpecType == SPEC_COMP_DEF)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (compSpec[ci])
											{
												setCompDef(ci, v);
											}
										}
									}
									else
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											for (ci = compSpec.Length - 1; ci >= 0; ci--)
											{
												if (tileSpec[ti] && compSpec[ci])
												{
													setTileCompVal(ti, ci, v);
												}
											}
										}
									}
									// Re-initialize
									curSpecType = SPEC_DEF;
									tileSpec = null;
									compSpec = null;
									
									// Go back to 'normal' parsing
									break;
								}
								else
								{
									// Next token starts with a digit so read it
								}
							}
							else
							{
								// We have reached the end of the parameters list so
								// we store the last precinct's sizes and we stop
								if (curSpecType == SPEC_DEF)
								{
									setDefault(v);
								}
								else if (curSpecType == SPEC_TILE_DEF)
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										if (tileSpec[ti])
										{
											setTileDef(ti, v);
										}
									}
								}
								else if (curSpecType == SPEC_COMP_DEF)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (compSpec[ci])
										{
											setCompDef(ci, v);
										}
									}
								}
								else
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (tileSpec[ti] && compSpec[ci])
											{
												setTileCompVal(ti, ci, v);
											}
										}
									}
								}
								endOfParamList = true;
								break;
							}
						} // while (true)
						break;
					
				} // switch
			} // while
		}
Example #60
0
        /// <summary> Creates a new ProgressionSpec object for the specified number of tiles,
        /// components and the ParameterList instance.
        /// 
        /// </summary>
        /// <param name="nt">The number of tiles
        /// 
        /// </param>
        /// <param name="nc">The number of components
        /// 
        /// </param>
        /// <param name="nl">The number of layer
        /// 
        /// </param>
        /// <param name="dls">The number of decomposition levels specifications
        /// 
        /// </param>
        /// <param name="type">the type of the specification module. The ProgressionSpec
        /// class should only be used only with the type ModuleSpec.SPEC_TYPE_TILE.
        /// 
        /// </param>
        /// <param name="pl">The ParameterList instance
        /// 
        /// </param>
        public ProgressionSpec(int nt, int nc, int nl, IntegerSpec dls, byte type, ParameterList pl)
            : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Aptype");
            Progression[] prog;
            int mode = - 1;

            if (param == null)
            {
                // No parameter specified
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }

                if (mode == - 1)
                {
                    System.String errMsg = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType = SPEC_DEF; // Specification type of the
            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            System.String word = null; // current word
            System.String errMsg2 = null; // Error message
            bool needInteger = false; // True if an integer value is expected
            int intType = 0; // Type of read integer value (0=index of first
            // resolution level, 1= index of first component, 2=index of first
            // layer not included, 3= index of first resolution level not
            // included, 4= index of  first component not included
            System.Collections.Generic.List<Progression> progression = new List<Progression>(10);
            int tmp = 0;
            Progression curProg = null;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {

                    case 't':
                        // If progression were previously found, store them
                        if (progression.Count > 0)
                        {
                            // Ensure that all information has been taken
                            curProg.ce = nc;
                            curProg.lye = nl;
                            curProg.re = dls.Max + 1;
                            prog = new Progression[progression.Count];
                            progression.CopyTo(prog);
                            if (curSpecType == SPEC_DEF)
                            {
                                setDefault(prog);
                            }
                            else if (curSpecType == SPEC_TILE_DEF)
                            {
                                for (int i = tileSpec.Length - 1; i >= 0; i--)
                                    if (tileSpec[i])
                                    {
                                        setTileDef(i, prog);
                                    }
                            }
                        }
                        progression.Clear();
                        intType = - 1;
                        needInteger = false;

                        // Tiles specification
                        tileSpec = parseIdx(word, nTiles);
                        curSpecType = SPEC_TILE_DEF;
                        break;

                    default:
                        // Here, words is either a Integer (progression bound index)
                        // or a String (progression order type). This is determined by
                        // the value of needInteger.
                        if (needInteger)
                        {
                            // Progression bound info
                            try
                            {
                                tmp = (System.Int32.Parse(word));
                            }
                            catch (System.FormatException e)
                            {
                                // Progression has missing parameters
                                throw new System.ArgumentException("Progression " + "order" + " specification " + "has missing " + "parameters: " + param);
                            }

                            switch (intType)
                            {

                                case 0:  // cs
                                    if (tmp < 0 || tmp > (dls.Max + 1))
                                        throw new System.ArgumentException("Invalid res_start " + "in '-Aptype'" + " option: " + tmp);
                                    curProg.rs = tmp; break;

                                case 1:  // rs
                                    if (tmp < 0 || tmp > nc)
                                    {
                                        throw new System.ArgumentException("Invalid comp_start " + "in '-Aptype' " + "option: " + tmp);
                                    }
                                    curProg.cs = tmp; break;

                                case 2:  // lye
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid layer_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nl)
                                    {
                                        tmp = nl;
                                    }
                                    curProg.lye = tmp; break;

                                case 3:  // ce
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid res_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > (dls.Max + 1))
                                    {
                                        tmp = dls.Max + 1;
                                    }
                                    curProg.re = tmp; break;

                                case 4:  // re
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid comp_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nc)
                                    {
                                        tmp = nc;
                                    }
                                    curProg.ce = tmp; break;
                                }

                            if (intType < 4)
                            {
                                intType++;
                                needInteger = true;
                                break;
                            }
                            else if (intType == 4)
                            {
                                intType = 0;
                                needInteger = false;
                                break;
                            }
                            else
                            {
                                throw new System.InvalidOperationException("Error in usage of 'Aptype' " + "option: " + param);
                            }
                        }

                        if (!needInteger)
                        {
                            // Progression type info
                            mode = checkProgMode(word);
                            if (mode == - 1)
                            {
                                errMsg2 = "Unknown progression type : '" + word + "'";
                                throw new System.ArgumentException(errMsg2);
                            }
                            needInteger = true;
                            intType = 0;
                            if (progression.Count == 0)
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            else
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            progression.Add(curProg);
                        }
                        break;

                } // switch
            } // while

            if (progression.Count == 0)
            {
                // No progression defined
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }
                if (mode == - 1)
                {
                    errMsg2 = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg2);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            // Ensure that all information has been taken
            curProg.ce = nc;
            curProg.lye = nl;
            curProg.re = dls.Max + 1;

            // Store found progression
            prog = new Progression[progression.Count];
            progression.CopyTo(prog);

            if (curSpecType == SPEC_DEF)
            {
                setDefault(prog);
            }
            else if (curSpecType == SPEC_TILE_DEF)
            {
                for (int i = tileSpec.Length - 1; i >= 0; i--)
                    if (tileSpec[i])
                    {
                        setTileDef(i, prog);
                    }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, they
                // receive the default progressiveness.
                if (ndefspec != 0)
                {
                    if (pl.getParameter("Rroi") == null)
                    {
                        mode = checkProgMode("res");
                    }
                    else
                    {
                        mode = checkProgMode("layer");
                    }
                    if (mode == - 1)
                    {
                        errMsg2 = "Unknown progression type : '" + param + "'";
                        throw new System.ArgumentException(errMsg2);
                    }
                    prog = new Progression[1];
                    prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                    setDefault(prog);
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {

                        case SPEC_TILE_DEF:
                            for (int c = nc - 1; c >= 0; c--)
                            {
                                if (specValType[0][c] == SPEC_TILE_DEF)
                                    specValType[0][c] = SPEC_DEF;
                            }
                            tileDef[0] = null;
                            break;

                        case SPEC_COMP_DEF:
                            for (int t = nt - 1; t >= 0; t--)
                            {
                                if (specValType[t][0] == SPEC_COMP_DEF)
                                    specValType[t][0] = SPEC_DEF;
                            }
                            compDef[0] = null;
                            break;

                        case SPEC_TILE_COMP:
                            specValType[0][0] = SPEC_DEF;
                            tileCompVal["t0c0"] = null;
                            break;
                        }
                }
            }
        }