Beispiel #1
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);
            }
        }
Beispiel #2
0
        public void TestxsiNill_SDOObjectXML()
        {
            LearnerPersonal lp = new LearnerPersonal();

            // Add a null UPN
            SifString str = new SifString(null);

            lp.SetField(LearnerDTD.LEARNERPERSONAL_UPN, str);

            // Add a null AlertMsg
            AlertMsg msg = new AlertMsg(AlertMsgType.DISCIPLINE, null);

            lp.AlertMsgList = new AlertMsgList(msg);
            msg.SetField(CommonDTD.ALERTMSG, new SifString(null));



            //  Write the object to a file
            Console.WriteLine("Writing to file...");
            using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
            {
                SifWriter writer = new SifWriter(fos);
                lp.SetChanged(true);
                writer.Write(lp);
                writer.Flush();
                fos.Close();
            }

            //  Parse the object from the file
            Console.WriteLine("Parsing from file...");
            SifParser p = SifParser.NewInstance();

            using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
            {
                lp = (LearnerPersonal)p.Parse(fis, null);
            }


            SimpleField upn = lp.GetField(LearnerDTD.LEARNERPERSONAL_UPN);

            Assert.IsNotNull(upn);

            SifString rawValue = (SifString)upn.SifValue;

            Assert.IsNotNull(rawValue);
            Assert.IsNull(rawValue.Value);
            Assert.IsNull(upn.Value);

            AlertMsgList alertMsgs = lp.AlertMsgList;

            Assert.IsNotNull(alertMsgs);
            Assert.IsTrue(alertMsgs.Count == 1);
            msg = (AlertMsg)alertMsgs.GetChildList()[0];

            Assert.IsNull(msg.Value);
            SifSimpleType msgValue = msg.SifValue;

            Assert.IsNotNull(msgValue);
            Assert.IsNull(msgValue.RawValue);
        }
        public void WriteSpeedTest()
        {
            Adk.Debug = AdkDebugFlags.None;

            StudentPersonal sp   = ObjectCreator.CreateStudentPersonal();
            Address         addr = sp.AddressLists[0][0];

            // Add in a few cases where escaping needs to be done
            addr.Street.Line1 = "ATTN: \"Miss Thompson\"";
            addr.Street.Line2 = "321 Dunn & Bradstreeet Lane";
            addr.Street.Line3 = "Weyer's Way, MO 32254";

            // Dump the object once to the console
            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sp);
            writer.Flush();

            MemoryStream stream = new MemoryStream();

            writer = new SifWriter(stream);

            for (int a = 0; a < 50000; a++)
            {
                writer.Write(sp);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);
            }

            Console.WriteLine("Test Complete. Please See timings for details");
        }
Beispiel #4
0
        public void CustomSIFElementEncoding()
        {
            SIF_Query q = new SIF_Query();

            q.SIF_QueryObject = new SIF_QueryObject(StudentDTD.STUDENTPERSONAL.Name);
            SIF_Conditions conditions = new SIF_Conditions(ConditionType.NONE);

            conditions.AddSIF_Condition("Name[@Type=\"05\"]/LastName", Operators.EQ, "Cookie");
            q.SetSIF_ConditionGroup(ConditionType.NONE, conditions);

            string xml;

            using (StringWriter w = new StringWriter())
            {
                SifWriter writer = new SifWriter(w);
                writer.Write(q);
                writer.Flush();
                writer.Close();
                xml = w.ToString();
            }

            Console.WriteLine(xml);
            // Mainly, just check to make sure that the single quotes didn't get encoded
            int index = xml.IndexOf("&quot;");

            Assert.AreEqual(-1, index, "Single quotes should not be encoded");
        }
Beispiel #5
0
        public void testSubjectAreaSIF15r1()
        {
            Adk.SifVersion = SifVersion.SIF15r1;
            SchoolCourseInfo sci = new SchoolCourseInfo();
            SubjectAreaList  lst = new SubjectAreaList();

            sci.SubjectAreaList = lst;

            SubjectArea sa = new SubjectArea("13");

            sa.TextValue = "Graphic Arts"; // for SIF 1.x ???
            OtherCodeList ocl = new OtherCodeList();

            ocl.Add(new OtherCode(Codeset.TEXT, "Graphic Arts"));
            sa.OtherCodeList = ocl;
            lst.Add(sa);

            StringWriter sw   = new StringWriter();
            SifWriter    sifw = new SifWriter(sw);

            sifw.Write(sci);
            sifw.Flush();
            sifw.Close();

            String xml = sw.ToString();

            Console.WriteLine(xml);

            int found = xml.IndexOf(">Graphic Arts</SubjectArea>");

            Assertion.Assert(found > -1);
        }
Beispiel #6
0
        public static T WriteParseAndReturn<T>(T o, SifVersion version, SchemaValidator validator, bool echoOut)
            where T : SifElement
        {
            T returnVal;

            if ( o is SifMessagePayload )
            {
                o.SifVersion = version;
            }


            SifWriter echo = null;
            if ( echoOut )
            {
                //   Write the object to System.out
                Console.WriteLine( "Writing object : " + o.ElementDef.Name + " using SIFVersion: " + version.ToString() );

                echo = new SifWriter( Console.Out );
                echo.Write( o, version );
            }

            //  Write the object to a file
            Console.WriteLine( "Writing to file... test.xml" );

            using ( Stream fos = File.Open( "test.xml", FileMode.Create, FileAccess.Write ) )
            {
                SifWriter writer = new SifWriter( fos );
                writer.Write( o, version  );
                writer.Flush();
                writer.Close();
                fos.Close();
            }


            if ( validator != null )
            {
                Validate( "test.xml", validator );
            }

            //  Parse the object from the file
            Console.WriteLine( "Parsing from file..." );
            SifParser p = SifParser.NewInstance();
            using ( Stream fis = File.OpenRead( "test.xml" ) )
            {
                returnVal = (T) p.Parse( fis, null );
                fis.Close();
            }


            //  Write the parsed object to System.out
            returnVal.SetChanged( true );
            Console.WriteLine( "Read object : " + returnVal.ElementDef.Name );
            if ( echoOut )
            {
                echo.Write( returnVal, version );
                echo.Flush();
            }
             
            return returnVal;
        }
Beispiel #7
0
        public void testStudentMappingAdk15Mappings()
        {
            StudentPersonal sp       = new StudentPersonal();
            Mappings        mappings = fCfg.Mappings.GetMappings("Default");
            IDictionary     map      = buildIDictionaryForStudentPersonalTest();

            StringMapAdaptor adaptor = new StringMapAdaptor(map);

            mappings.MapOutbound(adaptor, sp);

            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sp);
            writer.Flush();

            // Assert that the StudentPersonal object was mapped correctly
            assertStudentPersonal(sp);

            // Now, map the student personal back to a hashmap and assert it
            IDictionary restoredData = new Hashtable();

            adaptor.Dictionary = restoredData;
            mappings.MapInbound(sp, adaptor);
            assertMapsAreEqual(map, restoredData, "ALT_PHONE_TYPE");
        }
Beispiel #8
0
        public void TestXsiNill_AllChildrenNil()
        {
            SchoolInfo            si   = new SchoolInfo();
            AddressableObjectName paon = new AddressableObjectName( );

            paon.Description = "The little white school house";
            paon.StartNumber = "321";
            Address      addr = new Address(AddressType.CURRENT, paon);
            GridLocation gl   = new GridLocation();

            gl.SetField(CommonDTD.GRIDLOCATION_PROPERTYEASTING, new SifDecimal(null));
            gl.SetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING, new SifDecimal(null));
            addr.GridLocation = gl;

            si.AddressList = new AddressList(addr);


            //  Write the object to a file
            Console.WriteLine("Writing to file...");
            using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write))
            {
                SifWriter writer = new SifWriter(fos);
                si.SetChanged(true);
                writer.Write(si);
                writer.Flush();
                fos.Close();
            }

            //  Parse the object from the file
            Console.WriteLine("Parsing from file...");
            SifParser p = SifParser.NewInstance();

            using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml"))
            {
                si = (SchoolInfo)p.Parse(fis, null);
            }


            AddressList al = si.AddressList;

            Assert.IsNotNull(al);

            addr = al.ItemAt(0);
            Assert.IsNotNull(addr);

            gl = addr.GridLocation;
            Assert.IsNotNull(gl);

            Assert.IsNull(gl.PropertyEasting);
            Assert.IsNull(gl.PropertyNorthing);

            SimpleField sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYEASTING);

            Assert.IsNotNull(sf);
            Assert.IsNull(sf.Value);

            sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING);
            Assert.IsNotNull(sf);
            Assert.IsNull(sf.Value);
        }
Beispiel #9
0
        private void Log(string fileName,
                         IDataObjectInputStream input,
                         SifMessageInfo info,
                         bool logToConsole)
        {
            try
            {
                // Ensure that the directory is there
                FileInfo file = new FileInfo(fileName);
                file.Directory.Create();
                int numObjects = 0;

                using (Stream outStream = File.OpenWrite(fileName))
                {
                    using (TextWriter twriter = new StreamWriter(outStream, Encoding.UTF8))
                    {
                        twriter.WriteLine("<SIF_ObjectData>");
                        twriter.Flush();
                        SifWriter writer        = new SifWriter(twriter);
                        SifWriter consoleWriter = null;
                        if (logToConsole)
                        {
                            consoleWriter = new SifWriter(Console.Out);
                        }

                        SifDataObject o;
                        while ((o = input.ReadDataObject()) != null)
                        {
                            numObjects++;
                            Track(o);
                            writer.Write(o);
                            if (logToConsole)
                            {
                                consoleWriter.Write(o);
                                Console.WriteLine();
                            }
                        }
                        writer.Flush();
                        if (logToConsole)
                        {
                            consoleWriter.Flush();
                        }
                        twriter.WriteLine("</SIF_ObjectData>");
                    }

                    outStream.Close();

                    Console.WriteLine
                        ("Received {0} objects for {1}, Packet# {2}", numObjects,
                        input.ObjectType.Name, info.PacketNumber);
                }
            }
            catch (Exception ex)
            {
                Adk.Log.Error(ex.Message, ex);
            }
        }
Beispiel #10
0
        /**
         * @param sp
         * @param mappings
         * @param map
         * @throws AdkMappingException
         */

        private void MapOutbound(StudentPersonal sp, Mappings mappings, IDictionary map)
        {
            StringMapAdaptor adaptor = new StringMapAdaptor(map);

            mappings.MapOutbound(adaptor, sp);

            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sp);
            writer.Flush();
            writer.Close();
        }
Beispiel #11
0
 public static void WriteObject(SifVersion writeVersion, string fileName, SifMessagePayload smp)
 {
     using (FileStream outputStream = new FileStream(fileName, FileMode.Create))
     {
         SifWriter writer = new SifWriter(outputStream);
         smp.SetChanged(true);
         smp.SifVersion = writeVersion;
         writer.Write(smp);
         writer.Flush();
         writer.Close();
         outputStream.Close();
     }
 }
        /**
         * Runs a schema validation test on a single object using the ADK
         * @param sdo
         * @throws Exception
         */
        protected void testSchemaElement(SifElement se)
        {
            bool validated = fSchemaValidator.Validate(se, fVersion);

            // 4) If validation failed, write the object out for tracing purposes
            if (!validated)
            {
                SifWriter outWriter = new SifWriter(fOutput);
                outWriter.Write(se, fVersion);
                outWriter.Flush();
                fSchemaValidator.PrintProblems(fOutput);
                Assertion.Assert("Errors validating...", false);
            }
        }
Beispiel #13
0
        public void testStudentContactMapping010()
        {
            StudentContact sc       = new StudentContact();
            Mappings       mappings = fCfg.Mappings.GetMappings("Default");
            IFieldAdaptor  adaptor  = createStudentContactFields();

            mappings.MapOutbound(adaptor, sc);
            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sc);
            writer.Flush();

            Assertion.AssertEquals("Testing Pickup Rights", "Yes", sc.ContactFlags.PickupRights);
        }
Beispiel #14
0
        public void testFieldMapping010()
        {
            StudentPersonal sp       = new StudentPersonal();
            Mappings        mappings = fCfg.Mappings.GetMappings("Default");
            IDictionary     map      = buildIDictionaryForStudentPersonalTest();

            // Add a "default" to the middle name rule and assert that it gets
            // created
            ObjectMapping om             = mappings.GetObjectMapping("StudentPersonal", false);
            FieldMapping  middleNameRule = om.GetRule(3);

            middleNameRule.DefaultValue = "Jerry";
            map.Remove("MIDDLE_NAME");

            StringMapAdaptor adaptor = new StringMapAdaptor(map);

            mappings.MapOutbound(adaptor, sp);
            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sp);
            writer.Flush();

            // For the purposes of this test, all we care about is the Ethnicity
            // mapping.
            // It should have the default outbound value we specified, which is "7"
            Assertion.AssertEquals("Middle Name should be Jerry", "Jerry", sp
                                   .Name.MiddleName);

            // Now, remap the student back into application fields
            IDictionary restoredData = new Hashtable();

            adaptor.Dictionary = restoredData;
            mappings.MapInbound(sp, adaptor);

            Assertion.AssertEquals("Middle Name should be Jerry", "Jerry",
                                   restoredData["MIDDLE_NAME"]);

            sp.Name.LastName = null;
            // Now, remap the student back into application fields
            restoredData       = new Hashtable();
            adaptor.Dictionary = restoredData;
            mappings.MapInbound(sp, adaptor);

            Object lastName = restoredData["LAST_NAME"];

            Console.WriteLine(sp.ToXml());
            Assertion.AssertNull("Last Name should be null", lastName);
        }
        public static SifDataObject WriteParseAndReturn(SifDataObject o,
                                                        SifVersion version)
        {
            SifDataObject returnVal = null;

            try
            {
                //  Write the object to System.out
                Console.WriteLine("Writing object : " + o.ObjectTag
                                  + " using SifVersion: " + version.ToString());
                SifWriter echo = new SifWriter(Console.Out);
                echo.Write(o, version);
                o.SetChanged(false);
                echo.Write(o);

                //  Write the object to a file
                Console.WriteLine("Writing to file...");
                using (Stream fos = File.Open("test.xml", FileMode.Create, FileAccess.Write))
                {
                    SifWriter writer = new SifWriter(fos);
                    o.SetChanged(true);
                    writer.Write(o, version);
                    writer.Flush();
                    fos.Close();
                }

                //  Parse the object from the file
                Console.WriteLine("Parsing from file...");
                SifParser p = SifParser.NewInstance();
                using (Stream fis = File.OpenRead("test.xml"))
                {
                    returnVal = (SifDataObject)p.Parse(fis, null);
                }


                //  Write the parsed object to System.out
                returnVal.SetChanged(true);
                Console.WriteLine("Read object : " + returnVal.ObjectTag);
                echo.Write(returnVal, version);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Assert.Fail("Exception: " + e.Message);
            }

            return(returnVal);
        }
        public static SifDataObject WriteParseAndReturn( SifDataObject o,
			SifVersion version )
        {
            SifDataObject returnVal = null;

            try
            {
                //  Write the object to System.out
                Console.WriteLine( "Writing object : " + o.ObjectTag
                           + " using SifVersion: " + version.ToString() );
                SifWriter echo = new SifWriter( Console.Out );
                echo.Write( o, version );
                o.SetChanged( false );
                echo.Write( o );

                //  Write the object to a file
                Console.WriteLine( "Writing to file..." );
                using(Stream fos = File.Open( "test.xml", FileMode.Create, FileAccess.Write ) )
                {
                    SifWriter writer = new SifWriter( fos );
                    o.SetChanged( true );
                    writer.Write( o, version  );
                    writer.Flush();
                    fos.Close();
                }

                //  Parse the object from the file
                Console.WriteLine( "Parsing from file..." );
                SifParser p = SifParser.NewInstance();
                using( Stream fis = File.OpenRead( "test.xml"))
                {
                    returnVal = (SifDataObject) p.Parse( fis, null );
                }

                //  Write the parsed object to System.out
                returnVal.SetChanged( true );
                Console.WriteLine( "Read object : " + returnVal.ObjectTag );
                echo.Write( returnVal, version  );
            }
            catch (Exception e)
            {
                Console.WriteLine( e );
                Assert.Fail( "Exception: " + e.Message );
            }

            return returnVal;
        }
Beispiel #17
0
        /// <summary>
        /// Writes the object to the outgoing data stream
        /// </summary>
        /// <param name="data"></param>
        /// <param name="buffer"></param>
        /// <param name="version"></param>
        /// <param name="fieldRestrictions"></param>
        protected virtual void WriteObject(SifDataObject data,
                                           Stream buffer,
                                           SifVersion version,
                                           IElementDef[] fieldRestrictions)
        {
            SifWriter writer = new SifWriter(buffer);

            writer.SuppressNamespace(true);
            if (fQuery != null)
            {
                fQuery.SetRenderingRestrictionsTo(data);
            }
            else if (fQueryRestrictions != null)
            {
                writer.Filter = fQueryRestrictions;
            }
            writer.Write(data, version);
            writer.Flush();
        }
        private static IMessageInputStream makeAck()
        {
            SIF_Ack retval = new SIF_Ack();
            retval.SIF_Status = new SIF_Status( 0 );
            MemoryStream ms = new MemoryStream();
            try
            {
                SifWriter sifWriter = new SifWriter( ms );
                sifWriter.Write( retval );
                sifWriter.Flush();
                //sifWriter.Close();


                MessageStreamImpl imp = new MessageStreamImpl( ms );
                return (IMessageInputStream) imp;
            }
            catch ( Exception )
            {
                return null;
            }
        }
        public void CreateElementOrAttribute()
        {
            String          firstName  = "Rosemary";
            String          middleName = null;
            String          lastName   = "Evans";
            StudentPersonal retval     = new StudentPersonal();

            retval.SetElementOrAttribute("Name[@Type='04']/FirstName", firstName);
            retval.SetElementOrAttribute("Name[@Type='04']/MiddleName", middleName);
            retval.SetElementOrAttribute("Name[@Type='04']/LastName", lastName);

            Name name = retval.Name;

            Assert.AreEqual(firstName, name.FirstName, "First Name");
            Assert.AreEqual(lastName, name.LastName, "Last Name");
            Assert.IsNull(name.MiddleName, "Middle Name");

            // echo to the console so we can see what's going on
            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(retval);
            writer.Flush();
        }
        //public string Send(string msg)
        //{
        //   lock (this)
        //   {
        //      fMessages.AddLast(msg);
        //   }
        //   return makeAck();
        //}

        public IMessageInputStream Send( IMessageOutputStream msg )
        {
            lock ( this )
            {
                try
                {
                    MemoryStream stream = new MemoryStream();
                    msg.CopyTo( stream );
                    stream.Seek( 0, SeekOrigin.Begin );
                    SifParser parser = SifParser.NewInstance();
                    SifMessagePayload smp = (SifMessagePayload) parser.Parse( stream, fZone );

                    fMessages.Add( smp );
                    parser = null;

                    SIF_Ack ack = smp.ackStatus( 0 );
                    SIF_Header hdr = ack.Header;
                    hdr.SIF_Timestamp = DateTime.Now;
                    hdr.SIF_MsgId = Adk.MakeGuid();
                    hdr.SIF_SourceId = fZone.Agent.Id;

                    StringWriter str = new StringWriter();
                    SifWriter writer = new SifWriter( str );
                    writer.Write( ack );
                    writer.Flush();
                    writer.Close();
                    writer = null;
                    return new MessageStreamImpl( str.ToString() );
                }
                catch( Exception ex )
                {
                    // Possible error parsing. Write the message to console out
                    Console.Out.WriteLine(msg.Decode());
                    throw new AdkMessagingException(ex.Message, fZone, ex);
                }
            }
        }
Beispiel #21
0
        public void StudentPlacementMapping()
        {
            StudentPlacement sp       = new StudentPlacement();
            Mappings         mappings = fCfg.Mappings.GetMappings("Default");
            IDictionary      map      = buildIDictionaryForStudentPlacementTest();
            StringMapAdaptor sma      = new StringMapAdaptor(map);

            mappings.MapOutbound(sma, sp);

            SifWriter writer = new SifWriter(Console.Out);

            writer.Write(sp);
            writer.Flush();

            // Assert that the StudentPersonal object was mapped correctly
            assertStudentParticipation(sp);

            // Now, map the student personal back to a hashmap and assert it
            IDictionary      restoredData = new HybridDictionary();
            StringMapAdaptor restorer     = new StringMapAdaptor(restoredData);

            mappings.MapInbound(sp, restorer);
            assertDictionariesAreEqual(map, restoredData);
        }
Beispiel #22
0
        /// <summary>  Calculate the size of a SIF_Response minus the SIF_ObjectData content.</summary>
        protected virtual long CalcEnvelopeSize(ZoneImpl zone)
        {
            long size = 400;

            try {
                SIF_Response rsp = new SIF_Response();
                rsp.SIF_MorePackets  = "Yes";
                rsp.SIF_RequestMsgId = fReqId;
                rsp.SIF_PacketNumber = 100000000;
                SIF_ObjectData data = new SIF_ObjectData();
                data.TextValue     = " ";
                rsp.SIF_ObjectData = data;

                SIF_Header hdr = rsp.Header;

                hdr.SIF_Timestamp     = DateTime.Now;
                hdr.SIF_MsgId         = "012345678901234567890123456789012";
                hdr.SIF_SourceId      = zone.Agent.Id;
                hdr.SIF_Security      = zone.Dispatcher.secureChannel();
                hdr.SIF_DestinationId = fDestId;

                using (MemoryStream buffer = new MemoryStream()) {
                    SifWriter writer = new SifWriter(buffer);
                    writer.Write(rsp);
                    writer.Flush();
                    size = buffer.Length + 10;
                    writer.Close();
                    buffer.Close();
                }
            }
            catch (Exception ex) {
                zone.Log.Warn("Error calculating packet size: " + ex, ex);
            }

            return(size);
        }
        /// <summary>  Poll the ZIS for messages pending in the agent's queue.
        /// 
        /// This method is typically called by a ProtocolHandler thread to perform a
        /// periodic pull when the agent is running in pull mode. It may also be
        /// called by the framework to force a pull if the framework requires an
        /// immediate response to a message it has sent to the ZIS, such as a
        /// request for SIF_ZoneStatus.
        /// 
        /// 
        /// If a message is retrieved from the ZIS, it is dispatched through the
        /// Adk's usual message routing mechanism just as pushed messages are. Thus,
        /// there is no difference between push and pull mode once a message has
        /// been obtained from the ZIS. Because message routing is asynchronous (i.e.
        /// the MessageDispatcher will forward the message to the appropriate
        /// framework or agent code), this method does not return a value. If an
        /// error is returned in the SIF_Ack, the agent's FaultListener will be
        /// notified if one is registered. If an exception occurs, it is thrown to
        /// the caller.
        /// 
        /// 
        /// Each time this method is invoked it repeatedly sends SIF_GetMessage to
        /// the ZIS until no more messages are available, effectively emptying out
        /// the agent's queue.
        /// 
        /// </summary>
        /// <returns> zero if no messages were waiting in the agent's queue; 1 if a
        /// message was pulled from the agent's queue; -1 if the zone is sleeping
        /// </returns>
        public virtual int Pull()
        {
            //  Wait for fPullCanStart to be set to true by the ZoneImpl class once
            //  the zone is connected
            if (fPullCanStart != null)
            {
                lock (fPullCanStart)
                {
                    try
                    {
                        Monitor.Wait(fPullCanStart);
                    }
                    catch
                    {
                        // Do Nothing
                    }
                }
            }

            while (true)
            {
                if ((Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0)
                {
                    fZone.Log.Debug("Polling for next message...");
                }

                //  Send a SIF_GetMessage, get a SIF_Ack
                SIF_SystemControl sys = new SIF_SystemControl();
                SIF_SystemControlData cmd = new SIF_SystemControlData();
                cmd.AddChild(new SIF_GetMessage());
                sys.SIF_SystemControlData = cmd;
                SIF_Ack ack = null;
                try
                {
                    ack = send(sys, true);
                }
                catch (PullMessageParseException pmpe)
                {
                    // Unable to parse the pulled message. Try sending the proper
                    // Error SIF_Ack to remove the message from the queue
                    if (pmpe.fSourceMessage != null)
                    {
                        fZone.Log.Debug("Handling exception by creating a SIF_Error", pmpe.fParseException);
                        // Try parsing out the SIF_OriginalMsgId so that we can remove the message
                        // from the queue.
                        // Ack either the SIF_Ack or the internal, embedded message, based on our setting
                        int startIndex = fAckAckOnPull ? 0 : 10;
                        int messageStart = pmpe.fSourceMessage.IndexOf("<SIF_Message", startIndex);
                        SifException sourceException = null;
                        if (pmpe.fParseException is SifException)
                        {
                            sourceException = (SifException)pmpe.fParseException;
                        }
                        else
                        {
                            sourceException = new SifException(
                                SifErrorCategoryCode.Xml,
                                SifErrorCodes.XML_GENERIC_ERROR_1,
                                "Unable to parse pulled SIF_Message",
                                pmpe.fParseException.Message,
                                fZone, pmpe.fParseException );
                        }
                        SIF_Ack errorAck = SIFPrimitives.ackError(pmpe.fSourceMessage.Substring(messageStart), sourceException, fZone);
                        errorAck.SifVersion = sys.SifVersion;
                        send( errorAck );
                        continue;
                    }
                }


                //
                //  Process the response. If status code 9 (no message), no
                //  action is taken. If status code 0 (success), the content of
                //  the SIF_Status / SIF_Data element is parsed and dispatched.
                //  If an error is reported in the ack, the agent's fault
                //  handler is called with a SifException describing the error
                //  if a fault handler has been registered.
                //
                if (ack.HasStatusCode(SifStatusCodes.NO_MESSAGES_9))
                {
                    if ((Adk.Debug & AdkDebugFlags.Messaging_Pull ) != 0)
                        fZone.Log.Debug( "No messages waiting in agent queue" );

                    return 0;
                }

                if(ack.HasError())
                {
                    SifException se = new SifException(ack, fZone);
                    fZone.Log.Debug("Unable to pull the next message from the queue: " + se.ToString());
                    AdkUtils._throw(se, fZone.Log);
                }

                if (ack.HasStatusCode(SifStatusCodes.SUCCESS_0))
                {
                    AdkException parseEx = null;
                    SifMessagePayload payload = getPullMessagePayload(ack);
                    if ((Adk.Debug & ( AdkDebugFlags.Messaging | AdkDebugFlags.Messaging_Pull ) ) != 0)
                    {
                        fZone.Log.Debug("Pulled a " + payload.ElementDef.Tag(payload.SifVersion) + " message (SIF " + payload.SifVersion + ")");
                    }

                    #region	Notify MessagingListeners...

                    bool cancelled = false;
                    ICollection<IMessagingListener> msgList = GetMessagingListeners(fZone);
                    if (msgList.Count > 0)
                    {
                        StringWriter tmp = new StringWriter();
                        SifWriter sifwriter = new SifWriter(tmp);
                        sifwriter.Write(payload);
                        sifwriter.Flush();
                        tmp.Flush();

                        StringBuilder xml = new StringBuilder();
                        xml.Append(tmp.ToString());

                        //	Determine message type before parsing
                        foreach (IMessagingListener listener in msgList)
                        {
                            try
                            {
                                SifMessageType pload =
                                    (SifMessageType)
                                    Adk.Dtd.GetElementType(payload.ElementDef.Name);
                                MessagingReturnCode code = listener.OnMessageReceived(pload, xml);
                                switch (code)
                                {
                                    case MessagingReturnCode.Discard:
                                        cancelled = true;
                                        break;

                                    case MessagingReturnCode.Reparse:
                                        {
                                            try
                                            {
                                                //	Reparse the XML into a new message
                                                payload =
                                                    (SifMessagePayload)
                                                    fParser.Parse(xml.ToString(), fZone);
                                            }
                                            catch (IOException ioe)
                                            {
                                                parseEx =
                                                    new AdkException
                                                        (
                                                        "Failed to reparse message that was modified by MessagingListener: " +
                                                        ioe, fZone);
                                            }
                                        }
                                        break;
                                }
                            }
                            catch (AdkException adke)
                            {
                                parseEx = adke;
                            }
                        }
                    }

                    #endregion

                    if (fQueue != null)
                    {
                        //  TODO: put message on agent local queue
                    }
                    else
                    {
                        if (parseEx != null)
                        {
                            throw parseEx;
                        }

                        int ackStatus = SifStatusCodes.IMMEDIATE_ACK_1;
                        SifException err = null;
                        bool acknowledge = true;

                        try
                        {
                            //  Dispatch the message
                            if (!cancelled)
                            {
                                ackStatus = dispatch(payload);
                            }
                        }
                        catch (LifecycleException)
                        {
                            throw;
                        }
                        catch (SifException se)
                        {
                            err = se;
                        }
                        catch (AdkException adke)
                        {
                            //  TODO: This needs to generate proper category/code based on payload

                            if (adke.HasSifExceptions())
                            {
                                //  Return the first exception
                                err = adke.SIFExceptions[0];
                            }
                            else
                            {
                                //  Build a SifException to describe this AdkException
                                err =
                                    new SifException
                                        (SifErrorCategoryCode.Generic,
                                          SifErrorCodes.GENERIC_GENERIC_ERROR_1, adke.Message, fZone);
                            }
                        }
                        catch (Exception thr)
                        {
                            //  Uncaught exception (probably an Adk internal error)
                            string txt =
                                "An unexpected error occurred while processing a pulled message: " +
                                thr;
                            fZone.Log.Debug(txt);

                            //  Build a SifException to describe this Throwable
                            err =
                                new SifException
                                    (SifErrorCategoryCode.System, SifErrorCodes.SYS_GENERIC_ERROR_1,
                                      thr.Message, thr.ToString(), fZone, thr);

                            fZone.Log.Debug(err);
                        }

                        if (acknowledge)
                        {
                            sendPushAck(ack, payload, ackStatus, err);
                        }
                        else
                            return 1;
                    }
                }
                else
                {
                    // We only get to here if there is no error and no success code
                    if (ack.HasStatusCode(SifStatusCodes.SLEEPING_8))
                    {
                        //  Zone is sleeping
                        return -1;
                    }
                    else
                    {
                        // Unknown condition
                        AdkUtils._throw(new SifException(ack, fZone), fZone.Log );
                    }
                }
            }
        }
        /// <summary>  Calculate the size of a SIF_Response minus the SIF_ObjectData content.</summary>
        protected virtual long CalcEnvelopeSize( ZoneImpl zone )
        {
            long size = 400;

            try {
                SIF_Response rsp = new SIF_Response();
                rsp.SIF_MorePackets = "Yes";
                rsp.SIF_RequestMsgId = fReqId;
                rsp.SIF_PacketNumber = 100000000;
                SIF_ObjectData data = new SIF_ObjectData();
                data.TextValue = " ";
                rsp.SIF_ObjectData = data;

                SIF_Header hdr = rsp.Header;

                hdr.SIF_Timestamp = DateTime.Now;
                hdr.SIF_MsgId = "012345678901234567890123456789012";
                hdr.SIF_SourceId = zone.Agent.Id;
                hdr.SIF_Security = zone.Dispatcher.secureChannel();
                hdr.SIF_DestinationId = fDestId;

                using ( MemoryStream buffer = new MemoryStream() ) {
                    SifWriter writer = new SifWriter( buffer );
                    writer.Write( rsp );
                    writer.Flush();
                    size = buffer.Length + 10;
                    writer.Close();
                    buffer.Close();
                }
            }
            catch( Exception ex ) {
                zone.Log.Warn( "Error calculating packet size: " + ex, ex );
            }

            return size;
        }
Beispiel #25
0
        /// <summary>  Respond to SIF RequestsGetTopicMap
        /// </summary>
        public virtual void OnRequest(IDataObjectOutputStream outStream,
                                      Query query,
                                      IZone zone,
                                      IMessageInfo inf)
        {
            SifMessageInfo info  = (SifMessageInfo)inf;
            SifWriter      debug = new SifWriter(Console.Out);

            Console.WriteLine
                ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId +
                "\" in zone " + zone.ZoneId);

            //  Read all students from the database to populate a HashMap of
            //  field/value pairs. The field names can be whatever we choose as long
            //  as they match the field names used in the <mappings> section of the
            //  agent.cfg configuration file. Each time a record is read, convert it
            //  to a StudentPersonal object using the Mappings class and stream it to
            //  the supplied output stream.
            //
            IDbCommand command = null;

            // Set a basic filter on the outgoing data stream
            // What will happen is that any object written to the output stream will
            // be evaluated based on the query conditions. If the object doesn't meet the
            // query conditions, it will be excluded
            outStream.Filter = query;

            //  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.
            //
            //IDictionary<string, string> dataMap = new System.Collections.Generic.Dictionary<string, string>();
            // IFieldAdaptor adaptor = new StringMapAdaptor(dataMap);
            //m.MapOutbound();
            MappingsContext mc = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info);

            try {
                int count = 0;

                //  Query the database for all students
                command = fConn.CreateCommand();
                fConn.Open();
                command.CommandText = "SELECT * FROM Students";
                using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection)) {
                    DataReaderAdaptor dra = new DataReaderAdaptor(rs);

                    while (rs.Read())
                    {
                        //  Finally, create a new StudentPersonal object and ask the
                        //  Mappings to populate it with SIF elements from the HashMap
                        //  of field/value pairs. As long as there is an <object>/<field>
                        //  definition for each entry in the HashMap, the ADK will take
                        //  care of producing the appropriate SIF element/attribute in
                        //  the StudentPersonal object.
                        //
                        StudentPersonal sp = new StudentPersonal();
                        sp.RefId = Adk.MakeGuid();
                        // TODO: When using custom macros for outboud mapping operations, set the ValueBuilder.
                        // You will need to call SetValueBuilder() giving the MappingsContext a derived version
                        // of DefaultValueBuilder that has the macro methods available in it.
                        mc.SetValueBuilder(new DataUtilMacro(dra));
                        mc.Map(sp, dra);

                        //  Now write out the StudentPersonal to the output stream and
                        //  we're done publishing this student.
                        //
                        Console.WriteLine("\nThe agent has read these values from the database:");

                        DumpFieldsToConsole(rs);
                        Console.WriteLine("To produce this StudentPersonal object:");
                        debug.Write(sp);
                        debug.Flush();

                        outStream.Write(sp);
                    }

                    rs.Close();
                }
                Console.WriteLine
                    ("- Returned " + count + " records from the Student database in response");
            } catch (Exception ex) {
                Console.WriteLine("- Returning a SIF_Error response: " + ex);
                throw new SifException
                          (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1,
                          "An error occurred while querying the database for students", ex.ToString(), zone);
            } finally {
                if (command != null)
                {
                    try {
                        fConn.Close();
                    } catch (Exception ignored) {
                        Log.Warn(ignored.Message, ignored);
                    }
                }
            }
        }
        private bool RunSingleTest(
            SifVersion parseVersion, 
            SifVersion writeVersion, 
            string fileName, 
            TextWriter output, 
            SchemaValidator sv)
        {
            sv.Clear();

            if (VERBOSE)
            {
                output.Write("Running test on " + fileName + "\r\n");
            }

            // 1) Read the object into memory
            SifElement se = null;
            try
            {
                se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
            }
            catch (AdkException adke)
            {
                // Parsing failed. However, since this unit test is a complete
                // test of all available objects, just emit the problem and allow
                // the test to continue (with a notification of false)
                output
                        .WriteLine("Error parsing file " + fileName + "\r\n  - "
                                + adke);
                output.WriteLine();
                return false;
            }
            catch (Exception re)
            {
                output.WriteLine("Error parsing file " + fileName + "\r\n  - " + re);
                output.WriteLine();
                return false;
            }

            //            if (VERBOSE)
            //            {
            //                SifWriter writer = new SifWriter(output);
            //                writer.Write(se,parseVersion);
            //                output.Flush();
            //            }

            // Before we can validate with the schema, we need to ensure that the
            // data object is wrapped in a SIF_Message elements, because the SIF
            // Schema makes that assumption
            SifMessagePayload smp = SchemaValidator.MakeSIFMessagePayload(se);

            String tmpFileName = fileName + "." + writeVersion.ToString() + ".adk";

            // 2) Write the message out to a file
            SchemaValidator.WriteObject(writeVersion, tmpFileName, smp);

            // 3) Validate the file
            bool validated = sv.Validate(tmpFileName);

            // 4) If validation failed, write the object out for tracing purposes
            if (!validated)
            {
                if (VERBOSE)
                {
                    SifWriter outWriter = new SifWriter(output);
                    outWriter.Write(se, writeVersion );
                    outWriter.Flush();
                }
                output.WriteLine("Validation failed on " + tmpFileName );
                sv.PrintProblems(output);
                return false;
            }

            // 5) Read the object again into memory
            try
            {
                se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
            }
            catch (AdkException adke)
            {
                // Parsing failed. However, since this unit test is a complete
                // test of all available objects, just emit the problem and allow
                // the test to continue (with a notification of false)
                output.WriteLine("Error parsing file " + fileName + ": "
                        + adke.Message );
                return false;
            }
            catch (Exception re)
            {
                output.Write("Error parsing file " + fileName + ": "
                        + re.Message + "\r\n");
                return false;
            }

            return validated;
        }
Beispiel #27
0
    /// <summary>  Respond to SIF Requests
    /// </summary>
    public virtual void OnRequest(IDataObjectOutputStream outStream,
                                  Query query,
                                  IZone zone,
                                  IMessageInfo inf)
    {
        SifMessageInfo info  = (SifMessageInfo)inf;
        SifWriter      debug = new SifWriter(Console.Out);

        Console.WriteLine
            ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId +
            "\" in zone " + zone.ZoneId);

        // Tell the ADK to automatically filter out any objects that don't meet the requirements
        // of the query conditions
        outStream.Filter = query;

        //  Read all learners from the database to populate a HashMap of
        //  field/value pairs. The field names can be whatever we choose as long
        //  as they match the field names used in the <mappings> section of the
        //  agent.cfg configuration file. Each time a record is read, convert it
        //  to a LearnerPersonal object using the Mappings class and stream it to
        //  the supplied output stream.
        //
        IDictionary data    = new Hashtable();
        IDbCommand  command = null;

        Console.WriteLine("The SIF Request was requested in the following SIF Versions");
        foreach (SifVersion version in info.SIFRequestVersions)
        {
            Console.WriteLine("    - " + version);
        }

        Console.WriteLine("This agent will respond in its latest supported version, which is: ");
        Console.WriteLine("    - " + info.LatestSIFRequestVersion);

        //  Get the root Mappings object from the configuration file
        Mappings m =
            fCfg.Mappings.GetMappings("Default").Select
                (info.SourceId, zone.ZoneId, info.LatestSIFRequestVersion);

        //  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.selectOutbound() method will select
        //  the most appropriate instance from the hierarchy given the
        //  three parameters passed to it.
        MappingsContext mappings = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info);

        try
        {
            int count = 0;

            //  Query the database for all students
            command = fConn.CreateCommand();
            fConn.Open();
            command.CommandText = "SELECT * FROM Students";
            using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                DataReaderAdaptor dra = new DataReaderAdaptor(rs);
                while (rs.Read())
                {
                    count++;
                    //  Finally, create a new LearnerPersonal object and ask the
                    //  Mappings to populate it with SIF elements from the HashMap
                    //  of field/value pairs. As long as there is an <object>/<field>
                    //  definition for each entry in the HashMap, the ADK will take
                    //  care of producing the appropriate SIF element/attribute in
                    //  the LearnerPersonal object.
                    //
                    StudentPersonal sp = new StudentPersonal();
                    sp.RefId = Adk.MakeGuid();
                    mappings.Map(sp, dra);

                    //  Now write out the LearnerPersonal to the output stream and
                    //  we're done publishing this student.
                    //
                    Console.WriteLine("\nThe agent has read these values from the database:");
                    DumpDictionaryToConsole(data);
                    Console.WriteLine("To produce this LearnerPersonal object:");
                    debug.Write(sp);
                    debug.Flush();

                    outStream.Write(sp);
                    data.Clear();
                }

                rs.Close();
            }

            Console.WriteLine
                ("- Returned " + count + " records from the Student database in response");
        }
        catch (Exception ex)
        {
            Console.WriteLine("- Returning a SIF_Error response: " + ex.ToString());
            throw new SifException
                      (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1,
                      "An error occurred while querying the database for students", ex.ToString(), zone);
        }
        finally
        {
            if (command != null)
            {
                try
                {
                    fConn.Close();
                }
                catch (Exception ignored)
                {
                }
            }
        }
    }
Beispiel #28
0
        /// <summary>  Respond to SIF RequestsGetTopicMap
        /// </summary>
        public virtual void OnRequest(IDataObjectOutputStream outStream,
                                       Query query,
                                       IZone zone,
                                       IMessageInfo inf)
        {
            SifMessageInfo info = (SifMessageInfo)inf;
            SifWriter debug = new SifWriter(Console.Out);

            Console.WriteLine
                ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId +
                  "\" in zone " + zone.ZoneId);

            //  Read all students from the database to populate a HashMap of
            //  field/value pairs. The field names can be whatever we choose as long
            //  as they match the field names used in the <mappings> section of the
            //  agent.cfg configuration file. Each time a record is read, convert it
            //  to a StudentPersonal object using the Mappings class and stream it to
            //  the supplied output stream.
            //
            IDbCommand command = null;

            // Set a basic filter on the outgoing data stream
            // What will happen is that any object written to the output stream will
            // be evaluated based on the query conditions. If the object doesn't meet the
            // query conditions, it will be excluded
            outStream.Filter = query;

            //  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.
            //
            //IDictionary<string, string> dataMap = new System.Collections.Generic.Dictionary<string, string>();
            // IFieldAdaptor adaptor = new StringMapAdaptor(dataMap);
            //m.MapOutbound();
            MappingsContext mc = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info);

            try {
                int count = 0;

                //  Query the database for all students
                command = fConn.CreateCommand();
                fConn.Open();
                command.CommandText = "SELECT * FROM Students";
                using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection)) {

                    DataReaderAdaptor dra = new DataReaderAdaptor(rs);

                    while (rs.Read()) {

                        //  Finally, create a new StudentPersonal object and ask the
                        //  Mappings to populate it with SIF elements from the HashMap
                        //  of field/value pairs. As long as there is an <object>/<field>
                        //  definition for each entry in the HashMap, the ADK will take
                        //  care of producing the appropriate SIF element/attribute in
                        //  the StudentPersonal object.
                        //
                        StudentPersonal sp = new StudentPersonal();
                        sp.RefId = Adk.MakeGuid();
                        // TODO: When using custom macros for outboud mapping operations, set the ValueBuilder.
                        // You will need to call SetValueBuilder() giving the MappingsContext a derived version
                        // of DefaultValueBuilder that has the macro methods available in it.
                        mc.SetValueBuilder(new DataUtilMacro(dra));
                        mc.Map(sp, dra);

                        //  Now write out the StudentPersonal to the output stream and
                        //  we're done publishing this student.
                        //
                        Console.WriteLine("\nThe agent has read these values from the database:");

                        DumpFieldsToConsole(rs);
                        Console.WriteLine("To produce this StudentPersonal object:");
                        debug.Write(sp);
                        debug.Flush();

                        outStream.Write(sp);
                    }

                    rs.Close();
                }
                Console.WriteLine
                    ("- Returned " + count + " records from the Student database in response");
            } catch (Exception ex) {
                Console.WriteLine("- Returning a SIF_Error response: " + ex);
                throw new SifException
                    (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1,
                      "An error occurred while querying the database for students", ex.ToString(), zone);
            } finally {
                if (command != null) {
                    try {
                        fConn.Close();
                    } catch (Exception ignored) {
                        Log.Warn(ignored.Message, ignored);
                    }
                }
            }
        }
        /// <summary>
        /// Sends the message to the SIF Zone and returns the SIFAck that was received
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isPullMessage"></param>
        /// <returns></returns>
        public virtual SIF_Ack send(SifMessagePayload msg,
                                     bool isPullMessage)
        {
            if (fZone.ProtocolHandler == null)
            {
                throw new AdkTransportException("Zone is not connected", fZone);
            }

            try
            {
                PolicyManager policyMan = PolicyManager.GetInstance(fZone);
                if (policyMan != null)
                {
                    policyMan.ApplyOutboundPolicy(msg, fZone);
                }
            }
            catch (AdkException adkex)
            {
                throw new AdkMessagingException("Unable to apply outbound message policy: " + adkex, fZone, adkex);
            }

            SIF_Ack ack = null;
            SifWriter w = null;
            byte stage = 1;
            bool queued = false;
            SifMessageType pload = 0;
            bool cancelled = false;
            ICollection<IMessagingListener> msgList = null;

            try
            {
                //  Assign values to message header
                SIF_Header hdr = msg.Header;
                hdr.SIF_Timestamp = DateTime.Now;
                hdr.SIF_MsgId = SifFormatter.GuidToSifRefID(Guid.NewGuid());
                hdr.SIF_SourceId = fSourceId;
                hdr.SIF_Security = secureChannel();

                //	Adk 1.5+: SIF_LogEntry requires that we *duplicate* the
                //	header within the object payload. This is really the only
                //	place we can do that and ensure that the SIF_Header and
                //	the SIF_LogEntry/SIF_LogEntryHeader are identical.

                if (msg is SIF_Event)
                {
                    // TODO: Should this be done at a higher level, such as zone.ReportEvent()?
                    SIF_Event ev = ((SIF_Event)msg);
                    SIF_ObjectData od =
                        (SIF_ObjectData)ev.GetChild(InfraDTD.SIF_EVENT_SIF_OBJECTDATA);
                    SIF_EventObject eo = od == null ? null : od.SIF_EventObject;
                    if (eo != null)
                    {
                        SIF_LogEntry logentry = (SIF_LogEntry)eo.GetChild(InfraDTD.SIF_LOGENTRY);
                        if (logentry != null)
                        {
                            SIF_LogEntryHeader sleh = new SIF_LogEntryHeader();
                            sleh.SIF_Header = (SIF_Header)hdr.Clone();
                            logentry.SIF_LogEntryHeader = sleh;
                        }
                    }
                }

                if (!isPullMessage || (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0)
                {
                    msg.LogSend(fZone.Log);
                }
            }
            catch (Exception thr)
            {
                throw new AdkMessagingException
                    ("MessageDispatcher could not assign outgoing message header: " + thr,
                      fZone, thr);
            }

            try
            {
                //  Convert message to a stream
                using (MessageStreamImpl memBuf = new MessageStreamImpl())
                {
                    w = new SifWriter(memBuf.GetInputStream());
                    w.Write(msg);
                    w.Flush();

                    stage = 2;

                    //  SIF_Event and SIF_Response are posted to the agent local queue
                    //  if enabled, otherwise sent immediately. All other message types
                    //  are sent immediately even when the queue is enabled.
                    //
                    if (fQueue != null &&
                         (msg is SIF_Event ||
                          msg is SIF_Response))
                    {
                        fQueue.PostMessage(msg);
                        queued = true;
                    }

                    //	Notify MessagingListeners...
                    pload = (SifMessageType)Adk.Dtd.GetElementType(msg.ElementDef.Name);
                    if (pload != SifMessageType.SIF_Ack)
                    {
                        msgList = GetMessagingListeners(fZone);
                        if (msgList.Count > 0)
                        {
                            StringBuilder stringBuffer = new StringBuilder(memBuf.Decode());
                            SifMessageInfo msgInfo = new SifMessageInfo(msg, fZone);
                            foreach (IMessagingListener listener in msgList)
                            {
                                try
                                {
                                    if (!listener.OnSendingMessage(pload, msgInfo, stringBuffer)
                                        )
                                    {
                                        cancelled = true;
                                    }
                                }
                                catch { } // Do Nothing
                            }
                        }
                    }

                    if (!cancelled)
                    {
                        //  Send the message
                        IMessageInputStream ackStream = fZone.fProtocolHandler.Send(memBuf);
                        {
                            try
                            {
                                //  Parse the results into a SIF_Ack
                                ack =
                                    (SIF_Ack)
                                    fParser.Parse
                                        ( ackStream.GetInputStream(), fZone,
                                          isPullMessage
                                              ? SifParserFlags.ExpectInnerEnvelope
                                              : SifParserFlags.None );
                            }
                            catch (Exception parseEx)
                            {
                                if (isPullMessage && (parseEx is AdkParsingException || parseEx is SifException || parseEx is System.Xml.XmlException))
                                {
                                    String ackStr = ackStream.ToString();
                                    if ((Adk.Debug & AdkDebugFlags.Message_Content ) != 0)
                                    {
                                        fZone.Log.Info( ackStr );
                                    }
                                    // The SIFParse was unable to parse this message. Try to create an appropriate
                                    // SIF_Ack, if SIFMessageInfo is able to parse enough of the message
                                    throw new PullMessageParseException(parseEx, ackStr, fZone);

                                }

                                throw new AdkMessagingException(parseEx.Message, fZone);
                            }
                        }

                        if (ack != null)
                        {
                            ack.message = msg;
                            if (!isPullMessage || (Adk.Debug & AdkDebugFlags.Messaging_Pull) != 0)
                            {
                                ack.LogRecv(fZone.Log);
                            }
                        }

                        //	Notify MessagingListeners...
                        if (msgList != null && msgList.Count > 0)
                        {
                            SifMessageInfo msgInfo = new SifMessageInfo(msg, fZone);

                            foreach (IMessagingListener listener in msgList)
                            {
                                try
                                {
                                    listener.OnMessageSent(pload, msgInfo, ack);
                                }
                                catch { } // Do Nothing
                            }
                        }
                    }
                    else
                    {
                        //	Prepare a success SIF_Ack to return
                        ack = msg.AckImmediate();
                    }
                }
            }
            catch (AdkMessagingException)
            {
                throw;
            }
            catch (AdkTransportException)
            {
                throw;
            }
            catch (Exception thr)
            {
                if (stage == 1)
                {
                    throw new AdkMessagingException
                        (
                        "MessageDispatcher could not convert outgoing infrastructure message to a string: " +
                        thr, fZone);
                }
                if (stage == 2)
                {
                    throw new AdkMessagingException
                        (
                        "MessageDispatcher could not convert SIF_Ack response to an object: " + thr,
                        fZone);
                }
            }
            finally
            {
                //  Removed queued message from queue
                if (queued)
                {
                    try
                    {
                        fQueue.RemoveMessage(msg.MsgId);
                    }
                    catch
                    {
                        // Do nothing
                    }
                }
            }

            return ack;
        }
 /// <summary>
 /// Writes the object to the outgoing data stream
 /// </summary>
 /// <param name="data"></param>
 /// <param name="buffer"></param>
 /// <param name="version"></param>
 /// <param name="fieldRestrictions"></param>
 protected virtual void WriteObject( SifDataObject data,
                                     Stream buffer,
                                     SifVersion version,
                                     IElementDef[] fieldRestrictions )
 {
     SifWriter writer = new SifWriter( buffer );
     writer.SuppressNamespace( true );
     if ( fQuery != null )
     {
         fQuery.SetRenderingRestrictionsTo( data );
     }
     else if ( fQueryRestrictions != null )
     {
         writer.Filter = fQueryRestrictions;
     }
     writer.Write( data, version );
     writer.Flush();
 }
Beispiel #31
0
        public static SifElement WriteParseAndReturn( 
            SifElement o,
            SifVersion version,
            SchemaValidator validator, 
            Boolean echoOut )
        {
            SifElement returnVal;

            if ( o is SifMessagePayload )
            {
                o.SifVersion = version;
            }

            SifWriter echo = null;

            if ( echoOut )
            {
                //   Write the object to System.out
                Console.WriteLine( "Writing object : " + o.ElementDef.Name
                                   + " using SIFVersion: " + version.ToString() );

                echo = new SifWriter( Console.Out );
                echo.Write( o, version );
                echo.Flush();
                Console.Out.Flush();
                
            }

            //  Write the object to a file
            Console.WriteLine( "Writing to file... test.xml" );
            using (Stream fos = new FileStream("test.xml", FileMode.Create))
            {
                SifWriter writer = new SifWriter( new StreamWriter( fos, Encoding.UTF8 ) );
                o.SetChanged( true );
                writer.Write( o, version );
                writer.Flush();
                writer.Close();
                fos.Close();
            }

            if ( validator != null )
            {
                Validate( "test.xml", validator );
            }

            //  Parse the object from the file
            Console.WriteLine( "Parsing from file..." );
            SifParser p = SifParser.NewInstance();

            FileStream fr = new FileStream( "test.xml", FileMode.Open );

            StreamReader inStream = new StreamReader( fr, Encoding.UTF8 );


            returnVal = p.Parse( inStream, null, 0, version );

            inStream.Close();
            fr.Close();
            //  Write the parsed object to System.out
            returnVal.SetChanged( true );
            Console.WriteLine( "Read object : " + returnVal.ElementDef.Name );
            if ( echoOut )
            {
                echo.Write( returnVal, version );
                echo.Flush();
            }


            return returnVal;
        }
Beispiel #32
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();
            }
        }
        private bool RunSingleTest(
            SifVersion parseVersion,
            SifVersion writeVersion,
            string fileName,
            TextWriter output,
            SchemaValidator sv)
        {
            sv.Clear();

            if (VERBOSE)
            {
                output.Write("Running test on " + fileName + "\r\n");
            }

            // 1) Read the object into memory
            SifElement se = null;

            try
            {
                se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
            }
            catch (AdkException adke)
            {
                // Parsing failed. However, since this unit test is a complete
                // test of all available objects, just emit the problem and allow
                // the test to continue (with a notification of false)
                output
                .WriteLine("Error parsing file " + fileName + "\r\n  - "
                           + adke);
                output.WriteLine();
                return(false);
            }
            catch (Exception re)
            {
                output.WriteLine("Error parsing file " + fileName + "\r\n  - " + re);
                output.WriteLine();
                return(false);
            }

//            if (VERBOSE)
//            {
//                SifWriter writer = new SifWriter(output);
//                writer.Write(se,parseVersion);
//                output.Flush();
//            }

            // Before we can validate with the schema, we need to ensure that the
            // data object is wrapped in a SIF_Message elements, because the SIF
            // Schema makes that assumption
            SifMessagePayload smp = SchemaValidator.MakeSIFMessagePayload(se);

            String tmpFileName = fileName + "." + writeVersion.ToString() + ".adk";

            // 2) Write the message out to a file
            SchemaValidator.WriteObject(writeVersion, tmpFileName, smp);

            // 3) Validate the file
            bool validated = sv.Validate(tmpFileName);

            // 4) If validation failed, write the object out for tracing purposes
            if (!validated)
            {
                if (VERBOSE)
                {
                    SifWriter outWriter = new SifWriter(output);
                    outWriter.Write(se, writeVersion);
                    outWriter.Flush();
                }
                output.WriteLine("Errors reading/writing " + fileName);
                sv.PrintProblems(output);
                return(false);
            }

            // 5) Read the object again into memory
            try
            {
                se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
            }
            catch (AdkException adke)
            {
                // Parsing failed. However, since this unit test is a complete
                // test of all available objects, just emit the problem and allow
                // the test to continue (with a notification of false)
                output.WriteLine("Error parsing file " + fileName + ": "
                                 + adke.Message);
                return(false);
            }
            catch (Exception re)
            {
                output.Write("Error parsing file " + fileName + ": "
                             + re.Message + "\r\n");
                return(false);
            }

            return(validated);
        }
Beispiel #34
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();
                    }
                }
            }
        }