Exemplo n.º 1
0
        /// <summary>
        /// Returns an INodeIterator instance that iterates the children
        /// of the current node; otherwise, <c>Null</c>.
        /// </summary>
        /// <returns></returns>
        public override INodeIterator GetChildren()
        {
            SifVersion version = Version;


            // Get all of the Element fields and children that match the
            // NodeTest into a list
            SifFormatter    formatter = Adk.Dtd.GetFormatter(version);
            IList <Element> elements  = formatter.GetContent(fSifElement, version);

            if (elements.Count == 0)
            {
                return(null);
            }
            else if (elements.Count == 1)
            {
                Element singleChild = elements[0];
                if (singleChild is SimpleField)
                {
                    return(new SingleNodeIterator(SimpleFieldPointer.Create(this, (SimpleField)singleChild)));
                }
                else
                {
                    return(new SingleNodeIterator(Create(this, (SifElement)singleChild, version)));
                }
            }


            return(new AdkElementIterator(this, elements));
        }
Exemplo n.º 2
0
        public override INodePointer CreateChild(SifXPathContext context, string name, int i)
        {
            SifVersion   version    = Version;
            IElementDef  subEleDef  = GetChildDef(name);
            SifFormatter formatter  = Adk.Dtd.GetFormatter(version);
            SifElement   sifElement = (SifElement)fElement;

            // Check to see if this child has a render surrogate defined
            IRenderSurrogate rs = subEleDef.GetVersionInfo(version).GetSurrogate();

            if (rs != null)
            {
                return(rs.CreateChild(this, formatter, version, context));
            }

            if (subEleDef.Field)
            {
                SifSimpleType ssf = subEleDef.TypeConverter.GetSifSimpleType(null);
                SimpleField   sf  = formatter.SetField(sifElement, subEleDef, ssf, version);
                return(SimpleFieldPointer.Create(this, sf));
            }
            else
            {
                SifElement newEle = SifElement.Create(sifElement, subEleDef);
                formatter.AddChild(sifElement, newEle, version);
                return(new SifElementPointer(this, newEle, version));
            }
        }
Exemplo n.º 3
0
        public void testConvertRefIdtoUUID()
        {
            String adkGuid = "F81D4FAE7DEC11D0A76500A0C91E6BF6";
            Guid?  guid    = SifFormatter.SifRefIDToGuid(adkGuid);

            Assert.AreEqual(new Guid("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), guid.Value, "match");
        }
Exemplo n.º 4
0
        private void AckPush(SIF_Ack ack,
                             AdkHttpResponse response)
        {
            try {
                //  Set SIF_Ack / SIF_Header fields
                SIF_Header hdr = ack.Header;
                hdr.SIF_Timestamp = DateTime.Now;

                hdr.SIF_MsgId    = SifFormatter.GuidToSifRefID(Guid.NewGuid());
                hdr.SIF_SourceId = this.Zone.Agent.Id;

                ack.LogSend(this.Zone.Log);

                response.ContentType = SifIOFormatter.CONTENTTYPE;
                // TODO: This code may need to change. The ADKHttpResponse should not automatically set the content length
                // and other implementations will not do so.
                SifWriter w = new SifWriter(response.GetResponseStream());
                w.Write(ack);
                w.Flush();
            }
            catch (Exception thr) {
                Console.Out.WriteLine
                    ("HttpProtocolHandler failed to send SIF_Ack for pushed message (zone=" +
                    this.Zone.ZoneId + "): " + thr);
                throw new AdkHttpException
                          (AdkHttpStatusCode.ServerError_500_Internal_Server_Error, thr.Message, thr);
            }
        }
Exemplo n.º 5
0
        public void testConvertUUIDToRefId()
        {
            String str     = "f81d4fae-7dec-11d0-a765-00a0c91e6bf6";
            Guid   guid    = new Guid(str);
            String adkGuid = SifFormatter.GuidToSifRefID(guid);

            assertRefId(adkGuid);
            Assert.AreEqual("F81D4FAE7DEC11D0A76500A0C91E6BF6", adkGuid, "match");
        }
Exemplo n.º 6
0
        public bool ReadRaw(XmlReader reader,
                            SifVersion version,
                            SifElement parent,
                            SifFormatter formatter)
        {
            string name = reader.LocalName;

            if (name.Equals(fDateElement))
            {
                String   dateValue = ConsumeElementTextValue(reader, version);
                DateTime?date      = formatter.ToDate(dateValue);
                if (date.HasValue)
                {
                    DateTime    tsValue  = date.Value;
                    SifDateTime dateTime = new SifDateTime(tsValue);
                    parent.SetField(dateTime.CreateField(parent, fElementDef));
                }
            }
            else if (name.Equals(fTimeElement))
            {
                String   timeValue = ConsumeElementTextValue(reader, version);
                DateTime?time      = formatter.ToTime(timeValue);
                if (time.HasValue)
                {
                    DateTime val = time.Value;
                    // See if the Timestamp field already exists on the parent
                    SimpleField timeStampField = parent.GetField(fElementDef);
                    if (timeStampField == null)
                    {
                        // Doesn't exist, create it
                        SifDateTime dateTime = new SifDateTime(val);
                        parent.SetField(dateTime.CreateField(parent, fElementDef));
                    }
                    else
                    {
                        // Exists, update the time portion of the date
                        SifDateTime sdt = (SifDateTime)timeStampField.SifValue;
                        if (sdt != null && sdt.Value.HasValue)
                        {
                            DateTime tsValue = sdt.Value.Value;
                            tsValue = tsValue.Add(val.TimeOfDay);
                            sdt     = new SifDateTime(tsValue);
                            // Overwrite the current value
                            parent.SetField(sdt.CreateField(parent, fElementDef));
                        }
                    }
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 7
0
        private void assertBooleanParsing(SifFormatter formatter, String stringValue, Boolean value)
        {
            Console.WriteLine("Testing Boolean parse of '" + stringValue + "' using " + formatter.ToString());
            Boolean?testValue = formatter.ToBool(stringValue);

            Assertion.AssertEquals("Boolean Value", value, testValue);
            Assertion.AssertEquals("String Value", stringValue, formatter.ToString(value));

            testValue = formatter.ToBool(null);
            Assertion.AssertNull("Boolean value should be null", testValue);
        }
Exemplo n.º 8
0
        private void assertintParsing(SifFormatter formatter, String stringValue, int value)
        {
            Console.WriteLine("Testing int parse of '" + stringValue + "' using " + formatter.ToString());
            int?testValue = formatter.ToInt(stringValue);

            Assertion.AssertEquals("int Value", value, testValue);
            Assertion.AssertEquals("String Value", stringValue, formatter.ToString(value));

            testValue = formatter.ToInt(null);
            Assertion.AssertNull("int value should be null", testValue);
        }
Exemplo n.º 9
0
        private void assertFloatParsing(SifFormatter formatter, String stringValue, float value)
        {
            Console.WriteLine("Testing Float parse of '" + stringValue + "' using " + formatter.ToString());
            float?testValue = formatter.ToFloat(stringValue);

            Assert.AreEqual(value, testValue);
            Assert.AreEqual(stringValue, formatter.ToString(value), "String Value");

            testValue = formatter.ToFloat(null);
            Assert.IsFalse(testValue.HasValue, "Float value should be null");
        }
Exemplo n.º 10
0
 /// <summary>
 /// Writes a SIF 1.x &lt;SIF_Time&gt; element
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="formatter"></param>
 /// <param name="elementName"></param>
 /// <param name="time"></param>
 public static void WriteSIFTime(
     XmlWriter writer,
     SifFormatter formatter,
     String elementName,
     DateTime time )
 {
     String xmlTime = formatter.ToTimeString( time );
     writer.WriteStartElement( elementName );
     writer.WriteAttributeString( "Zone", Sif1xFormatter.FormatTimeZone( time ) );
     writer.WriteValue( xmlTime );
     writer.WriteEndElement();
 }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a child element, if supported by this node
        /// </summary>
        /// <param name="parentPointer"></param>
        /// <param name="formatter"></param>
        /// <param name="version"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public INodePointer CreateChild(INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                        SifXPathContext context)
        {
            // 1) Create an instance of the SimpleField with a null value (It's assigned later)

            //
            // STEP 2
            // Find the actual field to set the value to
            //
            SifElement parent        = (SifElement)((SifElementPointer)parentPointer).Element;
            SifElement targetElement = parent;

            if (!fElementDef.Field)
            {
                //	This indicates a child SifElement that needs to be created
                targetElement = SifElement.Create(parent, fElementDef);

                formatter.AddChild(parent, targetElement, version);
            }

            IElementDef fieldDef = null;

            if (fValueXpath.Equals("."))
            {
                fieldDef = fElementDef;
            }
            else
            {
                String fieldName = fValueXpath;
                if (fValueXpath.StartsWith("@"))
                {
                    fieldName = fValueXpath.Substring(1);
                }
                fieldDef = Adk.Dtd.LookupElementDef(fElementDef, fieldName);
            }


            if (fieldDef == null)
            {
                throw new ArgumentException("Support for value path {" + fValueXpath +
                                            "} is not supported by XPathSurrogate.");
            }

            SifSimpleType ssf = fieldDef.TypeConverter.GetSifSimpleType(null);
            SimpleField   sf  = ssf.CreateField(targetElement, fieldDef);

            targetElement.SetField(sf);


            // 2) built out a fake set of node pointers representing the SIF 1.5r1 path and
            //    return the root pointer from that stack
            return(BuildLegacyPointers(parentPointer, sf));
        }
Exemplo n.º 12
0
        private void AssertTimeParsing(DateTime?assertedDateTime, SifFormatter formatter, string test, String statement)
        {
            DateTime?parsedValue;

            parsedValue = formatter.ToTime(test);
            Console.WriteLine(statement);
            Console.WriteLine("parsing: " + test);
            Console.WriteLine("Asserted: {0} : {1}", assertedDateTime.Value, assertedDateTime.Value.ToFileTimeUtc());
            Console.WriteLine("Parsed: {0} : {1}", parsedValue.Value, parsedValue.Value.ToFileTimeUtc());
            Console.WriteLine();
            assertTimes(statement, assertedDateTime, parsedValue);
        }
Exemplo n.º 13
0
        private void AssertDateParsing(SifFormatter formatter, String stringValue, Calendar value)
        {
            Console.WriteLine("Testing Date parse of '" + stringValue + "' using " + formatter.ToString());
            //Calendar testValue = formatter.ToDate(stringValue);
            DateTime testValue = (DateTime)formatter.ToDate(stringValue);

            Assertion.AssertEquals("Date Value", value, testValue);
            Assertion.AssertEquals("String Value", stringValue, (String)formatter.ToDateString(testValue));

            testValue = (DateTime)formatter.ToDate(null);
            Assertion.AssertNull("Date value should be null", testValue);
        }
Exemplo n.º 14
0
        public void RenderRaw(XmlWriter writer,
                              SifVersion version,
                              Element o,
                              SifFormatter formatter)
        {
            String  elementName = fElementDef.Name;
            SifTime time        = (SifTime)o.SifValue;

            if (time.Value.HasValue)
            {
                WriteSIFTime(writer, formatter, elementName, time.Value.Value);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Writes a SIF 1.x &lt;SIF_Time&gt; element
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="formatter"></param>
        /// <param name="elementName"></param>
        /// <param name="time"></param>
        public static void WriteSIFTime(
            XmlWriter writer,
            SifFormatter formatter,
            String elementName,
            DateTime time)
        {
            String xmlTime = formatter.ToTimeString(time);

            writer.WriteStartElement(elementName);
            writer.WriteAttributeString("Zone", Sif1xFormatter.FormatTimeZone(time));
            writer.WriteValue(xmlTime);
            writer.WriteEndElement();
        }
Exemplo n.º 16
0
        public void RenderRaw(XmlWriter writer,
                              SifVersion version,
                              Element o,
                              SifFormatter formatter)
        {
            DateTime?timeStamp = ((SifDateTime)o.SifValue).Value;

            if (timeStamp.HasValue)
            {
                String xmlDate = formatter.ToDateString(timeStamp);
                WriteSimpleElement(writer, fDateElement, xmlDate);
                SIFTimeSurrogate.WriteSIFTime(writer, formatter, fTimeElement, timeStamp.Value);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a child element, if supported by this node
        /// </summary>
        /// <param name="parentPointer"></param>
        /// <param name="formatter"></param>
        /// <param name="version"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public INodePointer CreateChild( INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                         SifXPathContext context )
        {
            // 1) Create an instance of the SimpleField with a null value (It's assigned later)

            //
            // STEP 2
            // Find the actual field to set the value to
            //
            SifElement parent = (SifElement) ((SifElementPointer) parentPointer).Element;
            SifElement targetElement = parent;

            if ( !fElementDef.Field )
            {
                //	This indicates a child SifElement that needs to be created
                targetElement = SifElement.Create( parent, fElementDef );

                formatter.AddChild( parent, targetElement, version );
            }

            IElementDef fieldDef = null;
            if ( fValueXpath.Equals( "." ) )
            {
                fieldDef = fElementDef;
            }
            else
            {
                String fieldName = fValueXpath;
                if ( fValueXpath.StartsWith( "@" ) )
                {
                    fieldName = fValueXpath.Substring( 1 );
                }
                fieldDef = Adk.Dtd.LookupElementDef( fElementDef, fieldName );
            }

            if ( fieldDef == null )
            {
                throw new ArgumentException( "Support for value path {" + fValueXpath +
                                             "} is not supported by XPathSurrogate." );
            }

            SifSimpleType ssf = fieldDef.TypeConverter.GetSifSimpleType( null );
            SimpleField sf = ssf.CreateField( targetElement, fieldDef );
            targetElement.SetField( sf );

            // 2) built out a fake set of node pointers representing the SIF 1.5r1 path and
            //    return the root pointer from that stack
            return BuildLegacyPointers( parentPointer, sf );
        }
Exemplo n.º 18
0
 /// <summary>
 /// Gets the default value
 /// </summary>
 /// <param name="converter">The type converter to use</param>
 /// <param name="formatter">The formatter to use for the version of SIF</param>
 /// <returns></returns>
 public SifSimpleType GetDefaultValue(TypeConverter converter, SifFormatter formatter)
 {
     if (fDefValue != null && converter != null)
     {
         try
         {
             return(converter.Parse(formatter, fDefValue));
         }
         catch (AdkParsingException adkpe)
         {
             throw new AdkMappingException(adkpe.Message, null, adkpe);
         }
     }
     return(null);
 }
Exemplo n.º 19
0
        public bool ReadRaw(XmlReader reader,
                            SifVersion version,
                            SifElement parent,
                            SifFormatter formatter)
        {
            String elementName = fElementDef.Name;

            if (!reader.LocalName.Equals(elementName))
            {
                return(false);
            }

            String value = ConsumeElementTextValue(reader, version);

            if (value != null && value.Length > 0)
            {
                DateTime?time    = formatter.ToTime(value);
                SifTime  sifTime = new SifTime(time);
                parent.SetField(sifTime.CreateField(parent, fElementDef));
            }
            return(true);
        }
Exemplo n.º 20
0
        public bool ReadRaw(
            XmlReader reader,
            SifVersion version,
            SifElement parent,
            SifFormatter formatter )
        {
            String value = null;
            //
            // STEP 1
            // Determine if this surrogate can handle the parsing of this node.
            // Retrieve the node value as a string
            //

            String[] xPathParts = fLegacyXpath.Split( '/' );
            XmlNodeType eventType = reader.NodeType;
            String localName = reader.LocalName;
            if ( eventType == XmlNodeType.Element &&
                 localName.Equals( xPathParts[0] ) )
            {
                try
                {
                    int currentSegment = 0;
                    int lastSegment = xPathParts.Length - 1;
                    if ( xPathParts[lastSegment].StartsWith( "@" ) )
                    {
                        lastSegment--;
                    }
                    while ( currentSegment < lastSegment )
                    {
                        reader.Read();
                        currentSegment++;

                        if ( !reader.LocalName.Equals( xPathParts[currentSegment] ) )
                        {
                            ThrowParseException
                                ( "Element {" + reader.LocalName +
                                  "} is not supported by XPathSurrogate path " + fLegacyXpath,
                                  version );
                        }
                    }

                    // New we are at the last segment in the XPath, and the XMLStreamReader
                    // should be positioned on the proper node. The last segment is either
                    // an attribute or an element, which need to be read differently
                    String finalSegment = xPathParts[xPathParts.Length - 1];
                    if ( finalSegment.StartsWith( "@" ) )
                    {
                        value = reader.GetAttribute( finalSegment.Substring( 1 ) );
                    }
                    else
                    {
                        value = ReadElementTextValue( reader );
                    }

                    // Note: Unlike the Java ADK, Surrogates in the the .NET ADK do not have to worry about
                    // completely consuming the XMLElement and advancing to the next tag. The .NET
                    // Surrogates are handed a reader that only allows reading the current node and
                    // the parent reader is automatically advanced when the surrogate is done.
                }
                catch ( Exception xse )
                {
                    ThrowParseException( xse, reader.LocalName, version );
                }
            }
            else
            {
                // No match was found
                return false;
            }

            //
            // STEP 2
            // Find the actual field to set the value to
            //
            IElementDef fieldDef;
            SifElement targetElement = parent;
            if ( fValueXpath.Equals( "." ) && fElementDef.Field )
            {
                fieldDef = fElementDef;
            }
            else
            {
                //	This indicates a child SifElement that needs to be created
                try
                {
                    targetElement = SifElement.Create( parent, fElementDef );
                }
                catch ( AdkSchemaException adkse )
                {
                    ThrowParseException( adkse, reader.LocalName, version );
                }

                formatter.AddChild( parent, targetElement, version );

                if ( fValueXpath.Equals( "." ) )
                {
                    fieldDef = fElementDef;
                }
                else
                {
                    String fieldName = fValueXpath;
                    if ( fValueXpath.StartsWith( "@" ) )
                    {
                        fieldName = fValueXpath.Substring( 1 );
                    }
                    fieldDef = Adk.Dtd.LookupElementDef( fElementDef, fieldName );
                }
            }

            if ( fieldDef == null )
            {
                throw new InvalidOperationException
                    ( "Support for value path {" + fValueXpath +
                      "} is not supported by XPathSurrogate." );
            }

            //
            // STEP 3
            // Set the value to the field
            //
            TypeConverter converter = fieldDef.TypeConverter;
            if ( converter == null )
            {
                // TODO: Determine if we should be automatically creating a converter
                // for elementDefs that don't have one, or whether we should just throw the
                // spurious data away.
                converter = SifTypeConverters.STRING;
            }
            SifSimpleType data = converter.Parse( formatter, value );
            targetElement.SetField( fieldDef, data );

            return true;
        }
Exemplo n.º 21
0
        private void RunLengthTest(Stream[] payloads, bool error, bool replace, SifVersion version)
        {
            // This test loosely emulates what ResponseDelivery does when it builds up the MessageStreamer class
            //  Prepare SIF_Response
            SIF_Response rsp = new SIF_Response();

            rsp.SIF_MorePackets  = "No";
            rsp.SIF_RequestMsgId = "12345123451234512345";
            rsp.SIF_PacketNumber = 1;

            rsp.SifVersion = version;

            //  Write an empty "<SIF_ObjectData> </SIFObjectData>" for the
            //  MessageStreamer to fill in. If this is an errorPacket, the empty
            //  element is required per SIF Specifications.
            SIF_ObjectData placeholder = new SIF_ObjectData();

            placeholder.TextValue = " ";
            rsp.SIF_ObjectData    = placeholder;

            if (error)
            {
                SIF_Error err = new SIF_Error();
                err.TextValue = " ";
                rsp.SIF_Error = err;
            }


            //  Assign values to message header - this is usually done by
            //  MessageDispatcher.send() but because we're preparing a SIF_Response
            //  output stream we need to do it manually
            SIF_Header hdr = rsp.Header;

            hdr.SIF_Timestamp     = DateTime.Now;
            hdr.SIF_MsgId         = SifFormatter.GuidToSifRefID(Guid.NewGuid());
            hdr.SIF_SourceId      = "UnitTest";
            hdr.SIF_DestinationId = "123451234512345";

            //  Write SIF_Response -- without its SIF_ObjectData payload -- to a buffer
            using (MemoryStream envelope = new MemoryStream())
            {
                SifWriter writer = new SifWriter(envelope);
                writer.Write(rsp);
                writer.Flush();

                envelope.Seek(0, SeekOrigin.Begin);
                StreamReader reader      = new StreamReader(envelope, Encoding.UTF8);
                String       envelopeStr = reader.ReadToEnd();
                Console.Out.WriteLine(envelopeStr);

                envelope.Seek(0, SeekOrigin.Begin);

                using (
                    MessageStreamer ms =
                        new MessageStreamer(envelope, payloads, error ? "<SIF_Error>" : "<SIF_ObjectData>", replace))
                {
                    AssertMessageStreamer(ms, version);
                }
                envelope.Close();
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Creates a child element, if supported by this node
 /// </summary>
 /// <param name="parentPointer"></param>
 /// <param name="formatter"></param>
 /// <param name="version"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public INodePointer CreateChild(INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                 SifXPathContext context)
 {
     // TODO Auto-generated method stub
     return(null);
 }
Exemplo n.º 23
0
        public void RenderRaw(
            XmlWriter writer,
            SifVersion version,
            Element o,
            SifFormatter formatter )
        {
            SifSimpleType value;
            // Read the value out of the source object
            if ( fValueXpath.StartsWith( "." ) )
            {
                value = o.SifValue;
            }
            else
            {
                IElementDef valueDef = null;
                if ( o is SifElement )
                {
                    valueDef = Adk.Dtd.LookupElementDefBySQP( o.ElementDef, fValueXpath );
                }
                if ( valueDef == null )
                {
                    throw new InvalidOperationException
                        ( "Support for value path {" + fValueXpath +
                          "} is not supported by XPathSurrogate." );
                }
                SimpleField field = ((SifElement) o).GetField( valueDef );
                if ( field == null )
                {
                    return;
                }
                value = field.SifValue;
            }

            if ( value == null )
            {
                return;
            }

            String[] xPathParts = fLegacyXpath.Split( '/' );
            int currentSegment = 0;
            // Build the path
            while ( currentSegment < xPathParts.Length - 1 )
            {
                writer.WriteStartElement( xPathParts[currentSegment] );
                currentSegment++;
            }

            String finalSegment = xPathParts[currentSegment];
            if ( finalSegment.StartsWith( "@" ) )
            {
                writer.WriteAttributeString(
                    finalSegment.Substring( 1 ),
                    value.ToString( formatter ) );
            }
            else
            {
                // Note: finalSegment can be equal to ".", which
                // signals to render the text only
                if ( finalSegment.Length > 1 )
                {
                    writer.WriteStartElement( finalSegment );
                    currentSegment++;
                }
                writer.WriteValue( value.ToString( formatter ) );
            }

            currentSegment--;
            // unwind the path
            while ( currentSegment > -1 )
            {
                writer.WriteEndElement();
                currentSegment--;
            }
        }
Exemplo n.º 24
0
        public void RenderRaw(
            XmlWriter writer,
            SifVersion version,
            Element o,
            SifFormatter formatter)
        {
            SifSimpleType value;

            // Read the value out of the source object
            if (fValueXpath.StartsWith("."))
            {
                value = o.SifValue;
            }
            else
            {
                IElementDef valueDef = null;
                if (o is SifElement)
                {
                    valueDef = Adk.Dtd.LookupElementDefBySQP(o.ElementDef, fValueXpath);
                }
                if (valueDef == null)
                {
                    throw new InvalidOperationException
                              ("Support for value path {" + fValueXpath +
                              "} is not supported by XPathSurrogate.");
                }
                SimpleField field = ((SifElement)o).GetField(valueDef);
                if (field == null)
                {
                    return;
                }
                value = field.SifValue;
            }

            if (value == null)
            {
                return;
            }

            String[] xPathParts     = fLegacyXpath.Split('/');
            int      currentSegment = 0;

            // Build the path
            while (currentSegment < xPathParts.Length - 1)
            {
                writer.WriteStartElement(xPathParts[currentSegment]);
                currentSegment++;
            }

            String finalSegment = xPathParts[currentSegment];

            if (finalSegment.StartsWith("@"))
            {
                writer.WriteAttributeString(
                    finalSegment.Substring(1),
                    value.ToString(formatter));
            }
            else
            {
                // Note: finalSegment can be equal to ".", which
                // signals to render the text only
                if (finalSegment.Length > 1)
                {
                    writer.WriteStartElement(finalSegment);
                    currentSegment++;
                }
                writer.WriteValue(value.ToString(formatter));
            }

            currentSegment--;
            // unwind the path
            while (currentSegment > -1)
            {
                writer.WriteEndElement();
                currentSegment--;
            }
        }
Exemplo n.º 25
0
        public bool ReadRaw( XmlReader reader,
                             SifVersion version,
                             SifElement parent,
                             SifFormatter formatter )
        {
            String elementName = fElementDef.Name;
            if ( !reader.LocalName.Equals( elementName ) )
            {
                return false;
            }

            String value = ConsumeElementTextValue( reader, version );

            if ( value != null && value.Length > 0 )
            {
                DateTime? time = formatter.ToTime( value );
                SifTime sifTime = new SifTime( time );
                parent.SetField( sifTime.CreateField( parent, fElementDef ) );
            }
            return true;
        }
Exemplo n.º 26
0
 public void RenderRaw( XmlWriter writer,
                        SifVersion version,
                        Element o,
                        SifFormatter formatter )
 {
     DateTime? timeStamp = ((SifDateTime) o.SifValue).Value;
     if ( timeStamp.HasValue )
     {
         String xmlDate = formatter.ToDateString( timeStamp );
         WriteSimpleElement( writer, fDateElement, xmlDate );
         SIFTimeSurrogate.WriteSIFTime( writer, formatter, fTimeElement, timeStamp.Value );
     }
 }
Exemplo n.º 27
0
 /// <summary>
 /// Creates a child element, if supported by this node
 /// </summary>
 /// <param name="parentPointer"></param>
 /// <param name="formatter"></param>
 /// <param name="version"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public INodePointer CreateChild( INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                  SifXPathContext context )
 {
     return null;
 }
Exemplo n.º 28
0
        /// <summary>
        /// Create all elements and attributes referenced by the XPath-like query string.
        /// </summary>
        /// <param name="relativeTo">The element that is the starting point of the path</param>
        /// <param name="query">The xPath query to build out</param>
        /// <param name="valueBuilder">The class to use for</param>
        /// <param name="version">The version of SIF for which this mapping operation is being evaluated</param>
        /// <param name="textFormatter">The SIFFormatter instance used to parse strings into strongly-typed data values.
        /// For many uses of this API, this formatter is equivalent to Adk.TextFormatter</param>
        /// <param name="pathFormatter">The SIFFormatter instance used for setting child SIFElements on their parents.
        /// This formatter may be different than the text formatter. The text formatter is, for
        /// compatibility's sake defaulted to SIF 1.x. However, the path formatter must be 
        /// correct for the mappings path being evaluated. </param>
        /// <returns></returns>
        public Element CreateElementOrAttributeFromXPath(
            SifElement relativeTo,
            String query,
            IValueBuilder valueBuilder,
            SifVersion version,
            SifFormatter textFormatter,
            SifFormatter pathFormatter)
        {
            int i = query.IndexOf('/');
            String currentSegment;
            String nextSegment = null;
            if (i == -1)
            {
                currentSegment = query;
            }
            else
            {
                currentSegment = query.Substring(0, i);
                nextSegment = query.Substring(i + 1);
            }
            Element result = _xpathBuild(relativeTo,
                                          new StringBuilder(),
                                          currentSegment,
                                          nextSegment,
                                          null,
                                          valueBuilder,
                                          version,
                                          textFormatter,
                                          pathFormatter);

            return result;
        }
Exemplo n.º 29
0
        /// <summary>
        /// Renders a SIFRefId as a Guid datatype
        /// </summary>
        /// <param name="sifRefId"></param>
        /// <returns></returns>
        public String RenderGuid(String sifRefId)
        {
            Guid?g = SifFormatter.SifRefIDToGuid(sifRefId);

            return(fQuoteCharacter + g.Value.ToString("B") + fQuoteCharacter);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a child element and sets the text value
        /// </summary>
        /// <param name="relativeTo">The parent SIFElement to add the new element to</param>
        /// <param name="tag">The tag name of the element</param>
        /// <param name="valueBuilder">The ValueBuilder instance to use to evaluate macros</param>
        /// <param name="version">The version of SIF for which this mapping operation is being evaluated</param>
        /// <param name="textFormatter">The SIFFormatter instance used to parse strings into strongly-typed data values.
        /// For many uses of this API, this formatter is equivalent to Adk.TextFormatter</param>
        /// <param name="pathFormatter">The SIFFormatter instance used for setting child SIFElements on their parents.
        /// This formatter may be different than the text formatter. The text formatter is, for
        /// compatibility's sake defaulted to SIF 1.x. However, the path formatter must be 
        /// correct for the mappings path being evaluated.</param>
        /// <returns></returns>
        private SifElement _createChild(
            SifElement relativeTo,
            String tag,
            IValueBuilder valueBuilder,
            SifVersion version,
            SifFormatter textFormatter,
            SifFormatter pathFormatter)
        {
            string _tag = tag;
            string assignValue = null;
            int eq = tag.IndexOf('=');
            if (eq != -1)
            {
                _tag = tag.Substring(0, (eq) - (0));
                string str = tag.Substring(eq + 1);
                assignValue = valueBuilder == null ? str : valueBuilder.Evaluate(str);
            }

            //  Lookup the IElementDef
            IElementDef def = Adk.Dtd.LookupElementDef(relativeTo.ElementDef, _tag);
            if (def == null)
            {
                def = Adk.Dtd.LookupElementDef(_tag);
            }
            if (def == null)
            {
                throw new AdkSchemaException(_tag + " is not a recognized element or attribute of " + relativeTo.Tag);
            }

            try
            {
                TypeConverter defConverter = def.TypeConverter;
                if (defConverter == null)
                {
                    defConverter = SifTypeConverters.STRING;
                }
                if (def.Field)
                {
                    SimpleField field = defConverter.ParseField(relativeTo, def, textFormatter, assignValue);
                    relativeTo.SetField(field);
                }
                else
                {
                    //  Create element instance

                    SifElement ele = (SifElement)ClassFactory.CreateInstance(def.FQClassName);
                    ele.ElementDef = def;
                    pathFormatter.AddChild(relativeTo, ele, version);
                    if (assignValue != null)
                    {
                        // TODO: THis needs to be done using the type converter
                        ele.TextValue = assignValue;
                    }

                    return ele;
                }
            }
            catch (TypeLoadException tle)
            {
                throw new SystemException(
                    "The " + def.Package +
                    " Sdo module is not loaded (ensure the Adk is initialized to load this module)", tle);
            }
            catch (Exception thr)
            {
                throw new SystemException(
                    "Failed to create an instance of the " + def.ClassName + " class from the " + def.Package +
                    " Sdo module: ", thr);
            }

            return null;
        }
Exemplo n.º 31
0
 /// <summary>
 /// Creates a child element, if supported by this node
 /// </summary>
 /// <param name="parentPointer"></param>
 /// <param name="formatter"></param>
 /// <param name="version"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public INodePointer CreateChild(INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                 SifXPathContext context)
 {
     return(null);
 }
Exemplo n.º 32
0
        public bool ReadRaw(
            XmlReader reader,
            SifVersion version,
            SifElement parent,
            SifFormatter formatter)
        {
            String value = null;

            //
            // STEP 1
            // Determine if this surrogate can handle the parsing of this node.
            // Retrieve the node value as a string
            //

            String[]    xPathParts = fLegacyXpath.Split('/');
            XmlNodeType eventType  = reader.NodeType;
            String      localName  = reader.LocalName;

            if (eventType == XmlNodeType.Element &&
                localName.Equals(xPathParts[0]))
            {
                try
                {
                    int currentSegment = 0;
                    int lastSegment    = xPathParts.Length - 1;
                    if (xPathParts[lastSegment].StartsWith("@"))
                    {
                        lastSegment--;
                    }
                    while (currentSegment < lastSegment)
                    {
                        reader.Read();
                        currentSegment++;

                        if (!reader.LocalName.Equals(xPathParts[currentSegment]))
                        {
                            ThrowParseException
                                ("Element {" + reader.LocalName +
                                "} is not supported by XPathSurrogate path " + fLegacyXpath,
                                version);
                        }
                    }

                    // New we are at the last segment in the XPath, and the XMLStreamReader
                    // should be positioned on the proper node. The last segment is either
                    // an attribute or an element, which need to be read differently
                    String finalSegment = xPathParts[xPathParts.Length - 1];
                    if (finalSegment.StartsWith("@"))
                    {
                        value = reader.GetAttribute(finalSegment.Substring(1));
                    }
                    else
                    {
                        value = ReadElementTextValue(reader);
                    }

                    // Note: Unlike the Java ADK, Surrogates in the the .NET ADK do not have to worry about
                    // completely consuming the XMLElement and advancing to the next tag. The .NET
                    // Surrogates are handed a reader that only allows reading the current node and
                    // the parent reader is automatically advanced when the surrogate is done.
                }
                catch (Exception xse)
                {
                    ThrowParseException(xse, reader.LocalName, version);
                }
            }
            else
            {
                // No match was found
                return(false);
            }

            //
            // STEP 2
            // Find the actual field to set the value to
            //
            IElementDef fieldDef;
            SifElement  targetElement = parent;

            if (fValueXpath.Equals(".") && fElementDef.Field)
            {
                fieldDef = fElementDef;
            }
            else
            {
                //	This indicates a child SifElement that needs to be created
                try
                {
                    targetElement = SifElement.Create(parent, fElementDef);
                }
                catch (AdkSchemaException adkse)
                {
                    ThrowParseException(adkse, reader.LocalName, version);
                }

                formatter.AddChild(parent, targetElement, version);

                if (fValueXpath.Equals("."))
                {
                    fieldDef = fElementDef;
                }
                else
                {
                    String fieldName = fValueXpath;
                    if (fValueXpath.StartsWith("@"))
                    {
                        fieldName = fValueXpath.Substring(1);
                    }
                    fieldDef = Adk.Dtd.LookupElementDef(fElementDef, fieldName);
                }
            }

            if (fieldDef == null)
            {
                throw new InvalidOperationException
                          ("Support for value path {" + fValueXpath +
                          "} is not supported by XPathSurrogate.");
            }


            //
            // STEP 3
            // Set the value to the field
            //
            TypeConverter converter = fieldDef.TypeConverter;

            if (converter == null)
            {
                // TODO: Determine if we should be automatically creating a converter
                // for elementDefs that don't have one, or whether we should just throw the
                // spurious data away.
                converter = SifTypeConverters.STRING;
            }
            SifSimpleType data = converter.Parse(formatter, value);

            targetElement.SetField(fieldDef, data);

            return(true);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Sends a specific packet to the zone
        /// </summary>
        /// <param name="file"></param>
        /// <param name="morePackets"></param>
        protected internal virtual void SendPacket(FileInfo file,
                                                   bool morePackets)
        {
            long extraBytes = 0;

            ResponsePacketInfo responsePacket = DeserializeResponseFileName(file.Name);

            /*	If we're processing SIF_ReportObject responses, read the ReportInfo
             *	data from the "requestMsgId.rpt" file
             *
             *  TT 894 - If a SIFException is thrown after the ReportInfo is set on
             *  the ReportObjectStream, then we don't want to include that ReportInfo
             *  in the packet with the error.  In that case, rptInfoReader will be
             *  null and will not be included in the list of payloads below.
             */

            FileStream rptInfoStream = null;

            if (fSrc == ResponseDeliveryType.SIFReportObject && !responsePacket.errorPacket)
            {
                try {
                    FileInfo f =
                        new FileInfo
                            (fWorkDir + Path.DirectorySeparatorChar.ToString() + responsePacket.destinationId + "." +
                            responsePacket.requestMsgId + ".rpt");
                    rptInfoStream = f.OpenRead();
                    extraBytes    = f.Length;
                }
                catch (FileNotFoundException fnfe) {
                    fZone.Log.Debug
                        ("Error sending SIF_ReportObject packet #" + responsePacket.packetNumber + (morePackets ? "" : " (last packet)") + ", file not found: " + fnfe.Message);
                }
            }

            if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
            {
                fZone.Log.Debug
                    ("Sending " + (responsePacket.errorPacket ? "SIF_Error response" : "SIF_Response") +
                    " packet #" + responsePacket.packetNumber +
                    (morePackets ? "" : " (last packet)"));
            }

            //  Prepare SIF_Response
            SIF_Response rsp = new SIF_Response();

            rsp.SetSIF_MorePackets(morePackets ? YesNo.YES : YesNo.NO);
            rsp.SIF_RequestMsgId = responsePacket.requestMsgId;
            rsp.SIF_PacketNumber = responsePacket.packetNumber;

            //  The SIF_Response is rendered in the same version of SIF as the original SIF_Request
            rsp.SifVersion = responsePacket.version;

            if (responsePacket.errorPacket)
            {
                //  Write an empty "<SIF_Error> </SIF_Error>" for the MessageStreamer
                //  to replace
                SIF_Error err = new SIF_Error();
                err.TextValue = " ";
                rsp.SIF_Error = err;
            }

            if (!responsePacket.errorPacket || responsePacket.version.Major == 1)
            {
                //  Write an empty "<SIF_ObjectData> </SIFObjectData>" for the
                //  MessageStreamer to fill in. If this is an errorPacket, the empty
                //  element is required per the SIF 1.x Specifications, but disallowed
                // in SIF 2.x.
                SIF_ObjectData placeholder = new SIF_ObjectData();
                placeholder.TextValue = " ";
                rsp.SIF_ObjectData    = placeholder;
            }


            //  Assign values to message header - this is usually done by
            //  MessageDispatcher.send() but because we're preparing a SIF_Response
            //  output stream we need to do it manually
            SIF_Header hdr = rsp.Header;

            hdr.SIF_Timestamp     = DateTime.Now;
            hdr.SIF_MsgId         = SifFormatter.GuidToSifRefID(Guid.NewGuid());
            hdr.SIF_SourceId      = fZone.Agent.Id;
            hdr.SIF_Security      = fZone.Dispatcher.secureChannel();
            hdr.SIF_DestinationId = responsePacket.destinationId;

            //  Write SIF_Response -- without its SIF_ObjectData payload -- to a buffer
            using (MemoryStream envelope = new MemoryStream()) {
                SifWriter writer = new SifWriter(envelope);
                writer.Write(rsp);
                writer.Flush();
                envelope.Seek(0, SeekOrigin.Begin);

                FileStream fs = file.OpenRead();
                try {
                    //  Send the SIF_Response as a stream
                    Stream [] payloads;
                    if (fSrc == ResponseDeliveryType.Generic)
                    {
                        payloads = new Stream [] { fs };
                    }
                    else
                    {
                        if (rptInfoStream != null)
                        {
                            payloads = new Stream [] { rptInfoStream, fs };
                        }
                        else
                        {
                            payloads = new Stream [] { fs };
                        }
                    }

                    using (MessageStreamer ms = new MessageStreamer
                                                (
                               envelope,
                               payloads,
                               responsePacket.errorPacket ? "<SIF_Error>" : "<SIF_ObjectData>", responsePacket.errorPacket))
                    {
                        if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
                        {
                            fZone.Log.Debug("Send SIF_Response");
                        }
                        if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0)
                        {
                            fZone.Log.Debug("  MsgId: " + rsp.MsgId);
                        }

                        SIF_Ack ack;
                        using (IMessageInputStream ackStream = fZone.ProtocolHandler.Send(ms)) {
                            ack =
                                (SIF_Ack)
                                fParser.Parse
                                    (ackStream.GetInputStream(), fZone, SifParserFlags.None);
                        }
                        if (ack != null)
                        {
                            ack.LogRecv(fZone.Log);
                        }
                    }

                    //  If we get here, the message was sent successfully
                    envelope.Close();

                    for (int i = 0; i < payloads.Length; i++)
                    {
                        payloads[i].Close();
                    }
                    fs.Close();

                    if (DELETE_ON_SUCCESS && file.Exists)
                    {
                        file.Delete();
                    }
                }
                catch (AdkException adke) {
                    AdkUtils._throw(adke, fZone.Log);
                }
                catch (Exception e) {
                    AdkUtils._throw
                        (new AdkException("Failed to send SIF_Response: " + e, fZone), fZone.Log);
                }
                finally {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    if (rptInfoStream != null)
                    {
                        rptInfoStream.Close();
                    }
                }
            }
        }
Exemplo n.º 34
0
        public bool ReadRaw( XmlReader reader,
                             SifVersion version,
                             SifElement parent,
                             SifFormatter formatter )
        {
            string name = reader.LocalName;

            if ( name.Equals( fDateElement ) )
            {
                String dateValue = ConsumeElementTextValue( reader, version );
                DateTime? date = formatter.ToDate( dateValue );
                if ( date.HasValue )
                {
                    DateTime tsValue = date.Value;
                    SifDateTime dateTime = new SifDateTime( tsValue );
                    parent.SetField( dateTime.CreateField( parent, fElementDef ) );
                }
            }
            else if ( name.Equals( fTimeElement ) )
            {
                String timeValue = ConsumeElementTextValue( reader, version );
                DateTime? time = formatter.ToTime( timeValue );
                if ( time.HasValue )
                {
                    DateTime val = time.Value;
                    // See if the Timestamp field already exists on the parent
                    SimpleField timeStampField = parent.GetField( fElementDef );
                    if ( timeStampField == null )
                    {
                        // Doesn't exist, create it
                        SifDateTime dateTime = new SifDateTime( val );
                        parent.SetField( dateTime.CreateField( parent, fElementDef ) );
                    }
                    else
                    {
                        // Exists, update the time portion of the date
                        SifDateTime sdt = (SifDateTime) timeStampField.SifValue;
                        if ( sdt != null && sdt.Value.HasValue )
                        {
                            DateTime tsValue = sdt.Value.Value;
                            tsValue = tsValue.Add( val.TimeOfDay );
                            sdt = new SifDateTime( tsValue );
                            // Overwrite the current value
                            parent.SetField( sdt.CreateField( parent, fElementDef ) );
                        }
                    }
                }
            }
            else
            {
                return false;
            }

            return true;
        }
Exemplo n.º 35
0
 public void RenderRaw( XmlWriter writer,
                        SifVersion version,
                        Element o,
                        SifFormatter formatter )
 {
     String elementName = fElementDef.Name;
     SifTime time = (SifTime) o.SifValue;
     if ( time.Value.HasValue )
     {
         WriteSIFTime( writer, formatter, elementName, time.Value.Value );
     }
 }
Exemplo n.º 36
0
        /// <summary>  Recursively builds elements and attributes relative to a SifElement.</summary>
        /// <param name="relativeTo">The SifElement this iteration is relative to. For the
        /// first call to this method, the <i>relativeTo</i> parameter is usually
        /// a SifDataObject such as StudentPersonal to which the XPath query
        /// string is relative. With each subsequent call it is the SifElement
        /// or SimpleField that was previously processed.</param>
        /// <param name="path">A running path of the segments processed thus far; an empty
        /// StringBuffer should be passed to this parameter the first time the
        /// method is called </param>
        /// <param name="curSegment">The current segment of the path that is being processed.
        /// For the first call to this method, the <i>curSegment</i> should be
        /// the portion of the XPath query string up to the first forward slash,
        /// exclusive.</param>
        /// <param name="nextSegment">The remaining portion of the path to be processed.
        /// For the first call to this method, the <i>nextSegment</i> should be
        /// the portion of the XPath query string following the first forward
        /// slash.</param>
        /// <param name="prevAttributes">An optional array of attribute values that were
        /// used to construct an Element in the processing of the last segment.
        /// The array is comprised of attribute name and value pairs such that
        /// element N is an attribute name and N+1 is its value. For the first
        /// call to this method, the array should be null. For subsequent calls,
        /// it should be null unless an Element was constructed from attribute
        /// values.</param>
        /// <param name="version">The version of SIF for which this mapping operation is being evaluated</param>
        /// <param name="textFormatter">The SIFFormatter instance used to parse strings into strongly-typed data values.
        /// For many uses of this API, this formatter is equivalent to ADK.TextFormatter</param>
        /// <param name="pathFormatter">The SIFFormatter instance used for setting child SIFElements on their parents.
        /// This formatter may be different than the text formatter. The text formatter is, for
        /// compatibility's sake defaulted to SIF 1.x. However, the path formatter must be 
        /// correct for the mappings path being evaluated.</param>
        /// <param name="valueBuilder"></param>
        /// <returns> The Element satisfying the query, or <c>null</c> if no
        /// match was found (unless the <i>create</i> parameter is true). If the
        /// query resolves to an attribute, a SimpleField object is returned. If
        /// it resolves to an element, a SifElement object is returned. In both
        /// cases the caller can obtain the text value of the attribute or
        /// element by calling its <c>TextValue</c> Property.
        /// </returns>
        private Element _xpathBuild(
            SifElement relativeTo,
            StringBuilder path,
            string curSegment,
            string nextSegment,
            string[] prevAttributes,
            IValueBuilder valueBuilder,
            SifVersion version,
            SifFormatter textFormatter,
            SifFormatter pathFormatter)
        {
            string[] _prevAttributes = null;
            SifElement nextEle = null;

            int asgnEq = curSegment.LastIndexOf('=');
            int attr = curSegment.LastIndexOf('@', asgnEq == -1 ? curSegment.Length - 1 : asgnEq - 1);
            int bracket = curSegment.IndexOf('[');
            if (bracket != -1)
            {
                if (attr == -1)
                {
                    throw new AdkSchemaException("Invalid query: \"" + curSegment +
                                                  "\" must be in the form [@Attr='value1','value2',...]");
                }

                string subEleTag = curSegment.Substring(0, (bracket) - (0));

                int lastBracket = curSegment.LastIndexOf(']');
                string[] attrList = curSegment.Substring(bracket + 1, (lastBracket) - (bracket + 1)).Split(',');
                _prevAttributes = new string[attrList.Length * 2];
                int _prevI = 0;

                for (int a = 0; a < attrList.Length; a++)
                {
                    string _curSegment = attrList[a];

                    //  Determine the value of the attribute
                    int eq = _curSegment.IndexOf("=");
                    string val = _curSegment.Substring(eq + 1);
                    string v = null;
                    if (val[0] == '\'')
                    {
                        int end = val.IndexOf('\'', 1);
                        if (end != -1)
                        {
                            v = valueBuilder == null
                                    ? val.Substring(1, (end) - (1))
                                    : valueBuilder.Evaluate(val.Substring(1, (end) - (1)));
                        }
                    }

                    if (v == null)
                    {
                        throw new AdkSchemaException("Attribute value (" + val +
                                                      ") must be in the form @Attribute='value'");
                    }

                    string attrName = _curSegment.Substring(1, (eq) - (1));

                    _prevAttributes[_prevI++] = attrName;
                    _prevAttributes[_prevI++] = v;

                    if (nextEle == null)
                    {
                        //
                        //  Look at all of the peer elements to determine if any have the
                        //  attribute value set. If so, return it; otherwise create a new
                        //  instance of the element with the attribute set. For example, if
                        //  curSegment is "Address[@Type='M']", we must look at all of the
                        //  Address children of relativeTo in order to determine if any
                        //  currently exist with a Type field set to a value of 'M'. If one
                        //  does, then it already exists and there is nothing to do; if
                        //  not found, however, a new Address child must be added with a
                        //  Type field of 'M'.
                        //

                        //  Lookup the IElementDef of relativeTo
                        IElementDef subEleDef = Adk.Dtd.LookupElementDef(relativeTo.ElementDef, subEleTag);
                        if (subEleDef == null)
                        {
                            subEleDef = Adk.Dtd.LookupElementDef(subEleTag);
                            if (subEleDef == null)
                            {
                                throw new AdkSchemaException(subEleTag + " is not a recognized attribute of " +
                                                              relativeTo.Tag);
                            }
                        }

                        bool repeatable = subEleDef.IsRepeatable(relativeTo.SifVersion);

                        SifElementList peers = relativeTo.GetChildList(subEleDef);

                        if (curSegment.IndexOf("+]") == -1)
                        {
                            //
                            //  Determine if relatSifElementListiveTo has any children that already
                            //  define this attribute/value; if not, create a new instance.
                            //  If subEleDef is not repeatable, however, we cannot add
                            //  another instance of it regardless.
                            //
                            for (int i = 0; i < peers.Count && nextEle == null; i++)
                            {
                                SimpleField ftest = peers[i].GetField(attrName);
                                if (ftest != null && ftest.TextValue.Equals(v))
                                {
                                    nextEle = peers[i];
                                }
                            }
                        }

                        if (nextEle == null)
                        {
                            if (!(peers.Count > 0 && !repeatable))
                            {
                                nextEle =
                                    _createChild(relativeTo, subEleTag, valueBuilder, version, textFormatter,
                                                  pathFormatter);
                            }
                            else
                            {
                                //
                                //  subEleDef is not repeatable, so we need to back up
                                //  and add this attribute/value to a fresh instance of
                                //  relativeTo if possible. First use _xpath(path) to try
                                //  to select that instance in case it already exists (otherwise
                                //  we'd create a new instance each iteration, which is
                                //  not the desired result.)
                                //

                                string _tmp;
                                if (path.Length > 0)
                                {
                                    _tmp = path + "/" + curSegment;
                                }
                                else
                                {
                                    _tmp = curSegment;
                                }
                                if (XPATH_DEBUG)
                                {
                                    Console.Out.Write("Searching for path relative to " +
                                                       relativeTo.Root.ElementDef.Name + ": " + _tmp);
                                }

                                int _del = _tmp.IndexOf('/');
                                nextEle =
                                    (SifElement)
                                    _xpath((SifElement)relativeTo.Root,
                                            _tmp.Substring(0, (_del == -1 ? _tmp.Length : _del) - (0)),
                                            _del == -1 ? null : _tmp.Substring(_del + 1));

                                if (XPATH_DEBUG)
                                {
                                    if (nextEle == null)
                                    {
                                        Console.Out.WriteLine("; not found, a new instance will be created");
                                    }
                                    else
                                    {
                                        Console.Out.WriteLine("; found");
                                    }
                                }

                                if (nextEle == null)
                                {
                                    if (relativeTo.ElementDef.IsRepeatable(relativeTo.SifVersion))
                                    {
                                        //  Clone relativeTo
                                        SifElement grandParent = (SifElement)relativeTo.Parent;
                                        nextEle = SifElement.Create(grandParent, relativeTo.ElementDef);
                                        pathFormatter.AddChild(grandParent, nextEle, version);

                                        //  Clone subEleDef; this now becomes nextEle
                                        SifElement newEle = SifElement.Create(nextEle, subEleDef);
                                        pathFormatter.AddChild(nextEle, newEle, version);
                                        _copyAttributes(nextEle, prevAttributes);
                                        nextEle = newEle;
                                    }
                                    else
                                    {
                                        throw new AdkSchemaException(
                                            "It is not possible to create the element or attribute identified by this path: " +
                                            _tmp + (nextSegment == null ? "" : "/" + nextSegment) +
                                            ". The element or attribute is either undefined in this version of SIF, " +
                                            "or an attempt is being made to create another instance of an element that is not Repeatable.");
                                    }
                                }
                            }
                        }
                    }

                    if (nextEle != null)
                    {
                        _createField(nextEle, attrName, v);
                    }

                    if (a == attrList.Length && nextEle == null)
                    {
                        return null;
                    }
                }
            }
            else
            {
                //  Search for the named attribute/element
                if (attr != -1)
                {
                    SimpleField ff = relativeTo.GetField(curSegment.Substring(1));
                    if (ff == null)
                    {
                        ff = _createField(relativeTo, curSegment.Substring(1), null);
                    }

                    return ff;
                }
                else
                {
                    string _tag = curSegment;
                    int eq = curSegment.IndexOf('=');
                    if (eq != -1)
                    {
                        _tag = curSegment.Substring(0, (eq) - (0));
                    }

                    nextEle = relativeTo.GetChild(_tag);
                    if (nextEle == null)
                    {
                        //  The curSegment element does not exist as a child of the relativeTo
                        //  object, so create it.
                        nextEle =
                            _createChild(relativeTo, curSegment, valueBuilder, version, textFormatter, pathFormatter);
                        if (nextEle == null)
                        {
                            if (nextSegment == null)
                            {
                                return relativeTo.GetField(_tag);
                            }
                            return null;
                        }
                    }
                }
            }

            //  Continue the search if nextSegment has a value
            if (nextEle != null && (nextSegment != null && nextSegment.Length > 0))
            {
                int i = nextSegment.IndexOf('/');

                if (path.Length > 0)
                {
                    path.Append("/");
                }
                path.Append(curSegment);

                return _xpathBuild(
                    nextEle,
                    path, i == -1 ? nextSegment : nextSegment.Substring(0, (i)),
                    i == -1 ? null : nextSegment.Substring(i + 1),
                    _prevAttributes,
                    valueBuilder,
                    version,
                    textFormatter,
                    pathFormatter);
            }

            if (nextSegment == null && nextEle != null && (nextEle.TextValue == null || nextEle.TextValue.Length == 0))
            {
                int eq2 = curSegment.LastIndexOf('=');
                if (eq2 != -1)
                {
                    if (bracket == -1 || (curSegment.LastIndexOf(']') < eq2))
                    {
                        //
                        //  An equals sign in the final segment indicates there is
                        //  a value constant or expression following the XPath
                        //  (e.g. "OtherId[@Type='06']=@pad($(PERMNUM),0,5)" ). Use
                        //  the user-supplied ValueBuilder to evaluate it.
                        //
                        string str = curSegment.Substring(eq2 + 1);
                        nextEle.TextValue = valueBuilder == null ? str : valueBuilder.Evaluate(str);
                    }
                }
            }

            return nextEle;
        }
Exemplo n.º 37
0
 /// <summary>
 /// Creates a child element, if supported by this node
 /// </summary>
 /// <param name="parentPointer"></param>
 /// <param name="formatter"></param>
 /// <param name="version"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public INodePointer CreateChild( INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                  SifXPathContext context )
 {
     // TODO Auto-generated method stub
     return null;
 }
Exemplo n.º 38
0
        private void assertThrowsFormatException(SifFormatter formatter)
        {
            bool threwProperException = false;

            // Boolean
            try
            {
                formatter.ToBool("asdf");
            }
            catch (FormatException)
            {
                threwProperException = true;
            }
            Assertion.Assert("NumberFormatException was not thrown for toBoolean()", threwProperException);

            // DECIMAL
            threwProperException = false;
            try
            {
                formatter.ToDecimal("asdf");
            }
            catch (FormatException)
            {
                threwProperException = true;
            }
            Assertion.Assert("IllegalArgumentException was not thrown for toDecimal()", threwProperException);

            // DATE
            threwProperException = false;
            try
            {
                formatter.ToDate("asdf");
            }
            catch (FormatException)
            {
                threwProperException = true;
            }
            Assertion.Assert("IllegalArgumentException was not thrown for ToDate()", threwProperException);


            //
            // DateTime and Duration are not supported by the SIF1xFormatter
            //
            if (!(formatter is Sif1xFormatter))
            {
                // DATETIME
                threwProperException = false;
                try
                {
                    formatter.ToDateTime("asdf");
                }
                catch (FormatException)
                {
                    threwProperException = true;
                }
                Assertion.Assert("IllegalArgumentException was not thrown for ToDateTime()", threwProperException);

                // DURATION
                threwProperException = false;
                try
                {
                    formatter.ToTimeSpan("asdf");
                }
                catch (FormatException)
                {
                    threwProperException = true;
                }

                Assertion.Assert("IllegalArgumentException was not thrown for toDuration()", threwProperException);
            }
            // INT
            threwProperException = false;
            try
            {
                formatter.ToInt("asdf");
            }
            catch (FormatException)
            {
                threwProperException = true;
            }
            Assertion.Assert("IllegalArgumentException was not thrown for toint()", threwProperException);

            // TIME
            threwProperException = false;
            try
            {
                formatter.ToTime("asdf");
            }
            catch (FormatException)
            {
                threwProperException = true;
            }
            Assertion.Assert("IllegalArgumentException was not thrown for toTime()", threwProperException);
        }
Exemplo n.º 39
0
        /// <summary>  Handles SIF_Responses
        /// </summary>
        public virtual void OnQueryResults(IDataObjectInputStream in_Renamed,
                                           SIF_Error error,
                                           IZone zone,
                                           IMessageInfo inf)
        {
            SifMessageInfo info = (SifMessageInfo)inf;

            Console.WriteLine
                ("\nReceived a query response from agent \"" + info.SourceId + "\" in zone " +
                zone.ZoneId);
            IRequestInfo reqInfo = info.SIFRequestInfo;

            if (reqInfo != null)
            {
                Console.WriteLine
                    ("\nResponse was received in {0}. Object State is '{1}'",
                    DateTime.Now.Subtract(reqInfo.RequestTime), reqInfo.UserData);
            }

            //
            //  Use the Mappings class to translate the StudentPersonal objects received
            //  from the zone into a HashMap of field/value pairs, then dump the table
            //  to System.out
            //

            //  Always check for an error response
            if (error != null)
            {
                Console.WriteLine
                    ("The request for StudentPersonal failed with an error from the provider:");
                Console.WriteLine
                    ("  [Category=" + error.SIF_Category + "; Code=" + error.SIF_Code + "]: " +
                    error.SIF_Desc + ". " + error.SIF_ExtendedDesc);
                return;
            }

            //  Get the root Mappings object from the configuration file
            Edustructures.SifWorks.Tools.Mapping.Mappings m = fCfg.Mappings.GetMappings("Default");

            //  Ask the root Mappings instance to select a Mappings from its
            //  hierarchy. For example, you might have customized the agent.cfg
            //  file with mappings specific to zones, versions of SIF, or
            //  requesting agents. The Mappings.select() method will select
            //  the most appropriate instance from the hierarchy given the
            //  three parameters passed to it.
            //

            SifFormatter    textFormatter = Adk.Dtd.GetFormatter(info.SifVersion);
            MappingsContext context       =
                m.SelectInbound(StudentDTD.STUDENTPERSONAL, info);

            while (in_Renamed.Available)
            {
                StudentPersonal sp = (StudentPersonal)in_Renamed.ReadDataObject();

                //  Ask the Mappings object to populate a HashMap with field/value pairs
                //  by using the mapping rules in the configuration file to decompose
                //  the StudentPersonal object into field values.
                //
                Hashtable        data = new Hashtable();
                StringMapAdaptor sma  = new StringMapAdaptor(data, textFormatter);
                context.Map(sp, sma);

                //  Now dump the field/value pairs to System.out
                DumpDictionaryToConsole(data);
            }
        }
Exemplo n.º 40
0
 /// <summary>
 /// Creates a new instance of a StringMapAdaptor
 /// </summary>
 /// <param name="dataMap">The IDictionary instance to use for getting and setting values</param>
 /// <param name="formatter">The SifFormatter to use for getting and setting text values</param>
 public StringMapAdaptor(IDictionary dataMap, SifFormatter formatter) : base(dataMap)
 {
     fDataFormatter = formatter;
 }