Пример #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);
            }
        }
Пример #2
0
        /**
         *  Sends a SIF_Event
         *  @param zone The zone to send the sifEvent to
         */
        public SIF_Ack SifEvent(IZone zone, Event sifEvent, String destinationId, String sifMsgId)
        {
            if (sifEvent.Data == null || sifEvent.Data.Available == false)
            {
                throw new AdkException("The sifEvent has no SIFDataObjects", zone);
            }

            SIF_ObjectData od = new SIF_ObjectData();

            //  Fill out the SIF_ObjectData
            IDataObjectInputStream inStr = sifEvent.Data;
            SifDataObject          data  = inStr.ReadDataObject();

            SifVersion msgVersion = data.EffectiveSIFVersion;

            SIF_EventObject eo = new SIF_EventObject();

            od.SIF_EventObject = eo;
            eo.Action          = sifEvent.ActionString;
            eo.ObjectName      = data.ElementDef.Tag(msgVersion);

            // Create the SIF_Event object
            SIF_Event msg = new SIF_Event(msgVersion);

            msg.SIF_ObjectData = od;

            SIF_Header msgHdr = msg.Header;

            //	Assign SIF_DestinationId if applicable
            if (destinationId != null)
            {
                msgHdr.SIF_DestinationId = destinationId;
            }

            while (data != null)
            {
                eo.Attach(data);
                data = inStr.ReadDataObject();
            }

            if (sifMsgId != null)
            {
                msgHdr.SIF_MsgId = sifMsgId;
            }

            SifContext[] contexts = sifEvent.Contexts;
            if (contexts == null)
            {
                contexts = new SifContext[] { SifContext.DEFAULT };
            }

            SIF_Contexts msgContexts = new SIF_Contexts();

            foreach (SifContext context in contexts)
            {
                msgContexts.AddSIF_Context(context.Name);
            }
            msgHdr.SIF_Contexts = msgContexts;
            return(((ZoneImpl)zone).Dispatcher.send(msg));
        }
        public void testSifResponseSenderMultiplePackets()
        {
            MessageDispatcher testDispatcher = new MessageDispatcher(Zone);

            Zone.Properties.OneObjectPerResponse = true;
            Zone.SetDispatcher(testDispatcher);
            Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler;

            testProto.clear();

            // Send a single SIF_Response with a small Authentication object

            String     SifRequestMsgId = Adk.MakeGuid();
            String     sourceId        = "TEST_SOURCEID";
            SifVersion testVersion     = SifVersion.LATEST;
            int        maxBufferSize   = int.MaxValue;

            IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };

            SifResponseSender srs = new SifResponseSender();

            srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Close();


            for (int x = 0; x < 5; x++)
            {
                // Retrieve the SIF_Response message off the protocol handler and asssert the results
                SIF_Response response = (SIF_Response)testProto.readMsg();

                Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
                Assert.AreEqual(x + 1, response.SIF_PacketNumber.Value);
                if (x == 4)
                {
                    Assert.AreEqual("No", response.SIF_MorePackets);
                }
                else
                {
                    Assert.AreEqual("Yes", response.SIF_MorePackets);
                }

                SIF_Header header = response.SIF_Header;
                Assert.AreEqual(sourceId, header.SIF_DestinationId);

                SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
                Assert.IsNotNull(responseObject);
            }
        }
        public void testSetPacketNumberAndMorePackets()
        {
            MessageDispatcher testDispatcher = new MessageDispatcher(this.Zone);

            this.Zone.SetDispatcher(testDispatcher);
            this.Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)this.Zone.ProtocolHandler;

            testProto.clear();

            // Send a single SIF_Response with a small Authentication object

            String     SifRequestMsgId  = Adk.MakeGuid();
            String     sourceId         = "TEST_SOURCEID";
            SifVersion testVersion      = SifVersion.LATEST;
            int        maxBufferSize    = int.MaxValue;
            int        packetNumber     = 999;
            YesNo      morePacketsValue = YesNo.YES;

            IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };

            SifResponseSender srs = new SifResponseSender();

            srs.Open(this.Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);

            srs.SIF_PacketNumber = packetNumber;
            srs.SIF_MorePackets  = morePacketsValue;

            // Assert the values of the properties set before writing
            Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
            Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);

            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Close();

            // Assert the values of the properties set after writing
            Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
            Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);

            // Retrieve the SIF_Response message off the protocol handler and asssert the results
            SIF_Response response = (SIF_Response)testProto.readMsg();

            Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
            Assert.AreEqual(packetNumber, response.SIF_PacketNumber.Value);
            Assert.AreEqual(morePacketsValue.ToString(), response.SIF_MorePackets);

            SIF_Header header = response.SIF_Header;

            Assert.AreEqual(sourceId, header.SIF_DestinationId);

            SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];

            Assert.IsNotNull(responseObject);
        }
Пример #5
0
        /// <summary>  Called by the Adk to construct a SifMessageInfo</summary>
        /// <param name="msg">The SIF_Message
        /// </param>
        /// <param name="zone">The associated zone
        /// </param>
        public SifMessageInfo(SifMessagePayload msg,
                              IZone zone)
        {
            fZone    = zone;
            fPayload = Adk.Dtd.GetElementType(msg.ElementDef.Name);
            if (zone.Properties.KeepMessageContent)
            {
                try {
                    StringWriter sw     = new StringWriter();
                    SifWriter    writer = new SifWriter(sw);
                    writer.Write(msg);
                    writer.Flush();
                    writer.Close();
                    sw.Close();

                    fMessage = sw.ToString();
                }
                catch {
                    // Do nothing
                }
            }

            //  Set SIF_Header values
            fHeader = msg.Header;
            IList <SifContext> contexts = msg.SifContexts;

            fContexts = new SifContext[contexts.Count];
            contexts.CopyTo(fContexts, 0);

            //  Set information about the message payload
            fPayloadVersion = msg.SifVersion;
            switch (fPayload)
            {
            case SifMessageType.SIF_Request:
            {
                SIF_Request req = (SIF_Request)msg;
                fObjects["SIF_MaxBufferSize"]   = req.SIF_MaxBufferSize;
                fObjects["SIF_RequestVersions"] = req.parseRequestVersions(fZone.Log);
            }
            break;

            case SifMessageType.SIF_Response:
            {
                SIF_Response rsp = (SIF_Response)msg;
                this.SIFRequestMsgId         = rsp.SIF_RequestMsgId;
                fObjects["SIF_PacketNumber"] = rsp.SIF_PacketNumber;
                SetAttribute("SIF_MorePackets", rsp.SIF_MorePackets);
            }
            break;
            }
        }
Пример #6
0
        public static SifMessagePayload MakeSIFMessagePayload(SifElement payload)
        {
            if (payload is SIF_Response)
            {
                return((SIF_Response)payload);
            }

            SIF_Response rsp = new SIF_Response();

            rsp.SetSIF_MorePackets(YesNo.NO);
            rsp.SIF_RequestMsgId = Adk.MakeGuid();
            rsp.SIF_PacketNumber = 1;

            SIF_Header hdr = rsp.Header;

            hdr.SIF_Timestamp = DateTime.Now;
            hdr.SIF_MsgId     = Adk.MakeGuid();
            hdr.SIF_SourceId  = "ADK Unit Tests";
            hdr.SetSIF_Security(new SIF_SecureChannel(AuthenticationLevel.ZERO,
                                                      EncryptionLevel.ZERO));
            hdr.SIF_DestinationId = "Schema Validator";
            if (payload is SifDataObject)
            {
                SIF_ObjectData data = new SIF_ObjectData();
                data.AddChild(payload);
                rsp.SIF_ObjectData = data;
            }
            else if (payload is SIF_ObjectData)
            {
                rsp.SIF_ObjectData = (SIF_ObjectData)payload;
            }
            else
            {
                throw new ArgumentException("Unable to use payload: "
                                            + payload.ElementDef.Name);
            }

            return(rsp);
        }
        //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);
                }
            }
        }
Пример #8
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);
        }
        public void testSifResponseSender010()
        {
            string queryStr =
                @"<SIF_Query>
                                         <SIF_QueryObject ObjectName='SectionInfo'>
                                            <SIF_Element>@RefId</SIF_Element>
                                            <SIF_Element>@SchoolCourseInfoRefId</SIF_Element>
                                            <SIF_Element>@SchoolYear</SIF_Element>
                                            <SIF_Element>LocalId</SIF_Element>
                                            <SIF_Element>ScheduleInfoList/ScheduleInfo/@TermInfoRefId</SIF_Element>
                                            <SIF_Element>Description</SIF_Element>
                                            <SIF_Element>LanguageOfInstruction</SIF_Element>
                                            <SIF_Element>LanguageOfInstruction/Code</SIF_Element>
                                         </SIF_QueryObject>
                                      </SIF_Query>";

            string sectionInfoStr =
                @"<SectionInfo RefId='D9C9889878144863B190C7D3428D7953' SchoolCourseInfoRefId='587F89D23EDD4761A59C04BA0D39E8D9' SchoolYear='2008'>
                                                  <LocalId>1</LocalId>
                                                  <Description>section 19</Description>
                                                  <ScheduleInfoList>
                                                    <ScheduleInfo TermInfoRefId='0D8165B1ADB34780BD1DFF9E38A7B935'>
                                                      <TeacherList>
                                                        <StaffPersonalRefId>F9D3916707634682B84C530BCF96B5CA</StaffPersonalRefId>
                                                      </TeacherList>
                                                      <SectionRoomList>
                                                        <RoomInfoRefId>EED167D761CD493EA94A875F56ABB0CB</RoomInfoRefId>
                                                      </SectionRoomList>
                                                      <MeetingTimeList>
                                                        <MeetingTime>
                                                          <TimetableDay>R</TimetableDay>
                                                          <TimetablePeriod>6</TimetablePeriod>
                                                        </MeetingTime>
                                                        <MeetingTime>
                                                          <TimetableDay>F</TimetableDay>
                                                          <TimetablePeriod>6</TimetablePeriod>
                                                        </MeetingTime>
                                                        <MeetingTime>
                                                          <TimetableDay>W</TimetableDay>
                                                          <TimetablePeriod>6</TimetablePeriod>
                                                        </MeetingTime>
                                                        <MeetingTime>
                                                          <TimetableDay>M</TimetableDay>
                                                          <TimetablePeriod>6</TimetablePeriod>
                                                        </MeetingTime>
                                                        <MeetingTime>
                                                          <TimetableDay>T</TimetableDay>
                                                          <TimetablePeriod>6</TimetablePeriod>
                                                        </MeetingTime>
                                                      </MeetingTimeList>
                                                    </ScheduleInfo>
                                                  </ScheduleInfoList>
                                                  <MediumOfInstruction><Code>0605</Code></MediumOfInstruction>
                                                  <LanguageOfInstruction><Code>eng</Code></LanguageOfInstruction>
                                                  <SummerSchool>No</SummerSchool>
                                                </SectionInfo>";


            SifParser   parser   = SifParser.NewInstance();
            SIF_Query   sifquery = (SIF_Query)parser.Parse(queryStr);
            SectionInfo section  = (SectionInfo)parser.Parse(sectionInfoStr);
            Query       query    = new Query(sifquery);

            String     SifRequestMsgId = Adk.MakeGuid();
            String     sourceId        = "TEST_SOURCEID";
            SifVersion testVersion     = SifVersion.LATEST;
            int        maxBufferSize   = int.MaxValue;

            MessageDispatcher testDispatcher = new MessageDispatcher(Zone);

            Zone.SetDispatcher(testDispatcher);
            Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler;

            testProto.clear();

            SifResponseSender srs = new SifResponseSender();

            srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, query);
            srs.Write(section);
            srs.Close();

            // Retrieve the SIF_Response message off the protocol handler and asssert the results
            SIF_Response response = (SIF_Response)testProto.readMsg();

            Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
            Assert.AreEqual(1, response.SIF_PacketNumber.Value);
            Assert.AreEqual("No", response.SIF_MorePackets);

            SIF_Header header = response.SIF_Header;

            Assert.AreEqual(sourceId, header.SIF_DestinationId);

            SifDataObject responseObject = (SifDataObject)response.SIF_ObjectData.GetChildList()[0];

            Assert.IsNotNull(responseObject);

            Console.Out.WriteLine(responseObject.ToXml());

            SifXPathContext context = SifXPathContext.NewSIFContext(responseObject);

            foreach (ElementRef reference in query.FieldRestrictionRefs)
            {
                Element found = context.GetElementOrAttribute(reference.XPath);
                Assert.IsNotNull(found, reference.XPath);
            }


            Element sectionInfoList =
                responseObject.GetElementOrAttribute("ScheduleInfoList/ScheduleInfo/SectionInfoList");

            Assert.IsNull(sectionInfoList);
        }
        public void testSifResponseSenderError()
        {
            MessageDispatcher testDispatcher = new MessageDispatcher(Zone);

            Zone.SetDispatcher(testDispatcher);
            Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler;

            testProto.clear();

            // Send a single SIF_Response with a small Authentication object

            String     SifRequestMsgId = Adk.MakeGuid();
            String     sourceId        = "TEST_SOURCEID";
            SifVersion testVersion     = SifVersion.LATEST;
            int        maxBufferSize   = int.MaxValue;
            SIF_Error  error           =
                new SIF_Error(SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1, "ERROR", "EXT_ERROR");

            IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };

            SifResponseSender srs = new SifResponseSender();

            srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(error);
            srs.Close();

            // Retrieve the SIF_Response message off the protocol handler and asssert the results
            SIF_Response response = (SIF_Response)testProto.readMsg();

            Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
            Assert.AreEqual(1, response.SIF_PacketNumber.Value);
            Assert.AreEqual("Yes", response.SIF_MorePackets);

            SIF_Header header = response.SIF_Header;

            Assert.AreEqual(sourceId, header.SIF_DestinationId);

            SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];

            Assert.IsNotNull(responseObject);

            // now test the error packet
            response = (SIF_Response)testProto.readMsg();

            Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
            Assert.AreEqual(2, response.SIF_PacketNumber.Value);
            Assert.AreEqual("No", response.SIF_MorePackets);

            header = response.SIF_Header;
            Assert.AreEqual(sourceId, header.SIF_DestinationId);

            Assert.IsNull(response.SIF_ObjectData);
            SIF_Error respError = response.SIF_Error;

            Assert.IsNotNull(respError);
            Assert.AreEqual(12, respError.SIF_Category.Value);
            Assert.AreEqual(1, respError.SIF_Code.Value);
            Assert.AreEqual("ERROR", respError.SIF_Desc);
            Assert.AreEqual("EXT_ERROR", respError.SIF_ExtendedDesc);
        }
Пример #11
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();
            }
        }
Пример #12
0
        /**
         *  SIF_Request
         */
        public SIF_Ack SifRequest(IZone zone, Query query, String destinationId, String sifMsgId)
        {
            //  Send SIF_Request...
            SIF_Request msg = new SIF_Request();
            // Find the maxmimum requested version and set the version of the message to lower
            // if the version is currently higher than the highest requested version.
            // In other words, if the Adk is initialized to 2.0, but the highest requested version
            // is 1.5r1, set the message version to 1.5r1
            SifVersion highestRequestVersion = SifVersion.SIF11;

            if (query.ObjectType == InfraDTD.SIF_ZONESTATUS)
            {
                // This query will be satisfied by the ZIS. Use the ZIS compatibility
                // version, which returns the highest version supported by the ZIS
                // (Default to Adk.SIFVersion() if not specified in the config)
                highestRequestVersion = ((ZoneImpl)zone).HighestEffectiveZISVersion;
                msg.AddSIF_Version(new SIF_Version(highestRequestVersion));
            }
            else
            {
                SifVersion[] requestVersions = query.SifVersions;
                if (requestVersions.Length > 0)
                {
                    // If the Query has one or more SIFVersions set, use them,
                    // and also add [major].*
                    foreach (SifVersion version in requestVersions)
                    {
                        msg.AddSIF_Version(new SIF_Version(version));
                        if (version.CompareTo(highestRequestVersion) > 0)
                        {
                            highestRequestVersion = version;
                        }
                    }
                }
                else
                {
                    highestRequestVersion = Adk.SifVersion;
                    if (highestRequestVersion.Major == 1)
                    {
                        msg.AddSIF_Version(new SIF_Version(highestRequestVersion));
                    }
                    else
                    {
                        // 2.0 and greater, request all data using
                        // [major].*, with 2.0r1 as the message version
                        // This allows for maximum compatibility will all 2.x providers
                        msg.AddSIF_Version(new SIF_Version(highestRequestVersion.Major + ".*"));
                        msg.SifVersion = SifVersion.GetEarliest(highestRequestVersion.Major);
                    }
                }
            }

            AgentProperties zoneProperties = zone.Properties;

            if (zoneProperties.OverrideSifMessageVersionForSifRequests != null)
            {
                //There is a property in Agent.cfg that can be used to override the message version from the
                //default of 2.0r1 This is needed to pass the test harness for 2.3
                msg.SifVersion = SifVersion.Parse(zoneProperties.OverrideSifMessageVersionForSifRequests);
            }

            else if (msg.SifVersion.CompareTo(highestRequestVersion) > 0)
            {
                // The current version of the SIF_Message is higher than the highest
                // requested version. Back the version number of message down to match
                msg.SifVersion = highestRequestVersion;
            }

            msg.SIF_MaxBufferSize = zone.Properties.MaxBufferSize;

            SIF_Query sifQ = CreateSIF_Query(query, highestRequestVersion, zone);

            msg.SIF_Query = sifQ;

            SIF_Header msgHeader = msg.Header;

            if (destinationId != null)
            {
                msgHeader.SIF_DestinationId = destinationId;
            }
            if (sifMsgId != null)
            {
                msgHeader.SIF_MsgId = sifMsgId;
            }

            // Set the SIF_Context
            msgHeader.SIF_Contexts = new SIF_Contexts(
                new SIF_Context(query.SifContext.Name));

            return(((ZoneImpl)zone).Dispatcher.send(msg));
        }
Пример #13
0
        /// <summary>   Post a SIF_LogEntry to the server.
        ///
        /// Use this form of the <c>log</c> method to post an error, warning,
        /// or informative message to the server that references a
        /// SIF Message and optionally a set of SIF Data Objects previously received
        /// by the agent. The log entry is assigned a category and code defined by
        /// the SIF Specification, and may have an extended error description and
        /// optional application-defined error code.
        ///
        /// </summary>
        /// <param name="level">The LogLevel to assign to this log entry
        /// </param>
        /// <param name="desc">A textual description of the error
        /// </param>
        /// <param name="extDesc">Extended error description, or <c>null</c> if no
        /// value is to be assigned to the SIF_LogEntry/SIF_ExtDesc element
        /// </param>
        /// <param name="appCode">Error code specific to the application posting the log
        /// entry, or <c>null</c> if no value is to be assigned to the
        /// SIF_LogEntry/SIF_ApplicationCode element
        /// </param>
        /// <param name="category">The SIF_Category value to assign to this log entry, as
        /// defined by the SIF Specification
        /// </param>
        /// <param name="category">The SIF_Code value to assign to this log entry, as
        /// defined by the SIF Specification
        /// </param>
        /// <param name="info">The <i>SifMessageInfo</i> instance from the Adk message
        /// handler implementation identifying a SIF Message received by the agent
        /// </param>
        /// <param name="objects">One or more SifDataObject instances received in the message
        /// identified by the <i>info</i> parameter
        /// </param>
        public virtual void Log(LogLevel level,
                                string desc,
                                string extDesc,
                                string appCode,
                                int category,
                                int code,
                                SifMessageInfo info,
                                params SifDataObject [] objects)
        {
            if (fZone == null)
            {
                throw new SystemException
                          ("ServerLog.log can only be called on a zone's ServerLog instance");
            }

            string       msg = null;
            SIF_LogEntry le  = null;

            if (Adk.SifVersion.CompareTo(SifVersion.SIF15r1) >= 0)
            {
                //	Create a SIF_LogEntry
                le = new SIF_LogEntry();
                le.SetSource(LogSource.AGENT);
                le.SetLogLevel(LogLevel.Wrap(level == null ? "Unknown" : level.ToString()));
                if (desc != null)
                {
                    le.SIF_Desc = desc;
                }
                if (extDesc != null)
                {
                    le.SIF_ExtendedDesc = extDesc;
                }
                if (appCode != null)
                {
                    le.SIF_ApplicationCode = appCode;
                }
                if (category != -1)
                {
                    le.SIF_Category = category.ToString();
                }
                if (code != -1)
                {
                    le.SIF_Code = code;
                }

                //	Reference a SIF_Message?
                if (info != null)
                {
                    try {
                        SIF_Header         headerCopy = (SIF_Header)info.SIFHeader.Clone();
                        SIF_LogEntryHeader sleh       = new SIF_LogEntryHeader();
                        sleh.SIF_Header = headerCopy;

                        //	Assign to SIF_OriginalHeader
                        le.SIF_OriginalHeader = sleh;
                    }
                    catch (Exception ex) {
                        fZone.Log.Warn
                            ("Unable to clone SIF_Header for SIF_LogEntry event:" + ex.Message, ex);
                    }
                }

                if (objects != null)
                {
                    SIF_LogObjects slos = new SIF_LogObjects();
                    le.SIF_LogObjects = slos;

                    for (int i = 0; i < objects.Length; i++)
                    {
                        if (objects[i] == null)
                        {
                            continue;
                        }

                        //	Package into a SIF_LogObject and add to the repeatable list
                        //	of SIF_LogEntry/SIF_LogObjects
                        SIF_LogObject lo = new SIF_LogObject();
                        lo.ObjectName = objects[i].ObjectType.Tag(info.SifVersion);
                        lo.AddChild((SifElement)objects[i].Clone());
                        slos.Add(lo);
                    }
                }
            }
            else
            {
                //  When running in SIF 1.1 or earlier, there is no
                //	SIF_LogEntry support. Build a string that can be
                //	written to the local zone log, including as much
                //	information from the would-be SIF_LogEntry as
                //	possible.

                StringBuilder b = new StringBuilder();

                b.Append("Server Log [Level=");
                b.Append(level == null ? "Unknown" : level.ToString());

                if (category != -1 && code != -1)
                {
                    b.Append(", Category=");
                    b.Append(category);
                    b.Append(", Code=");
                    b.Append(code);
                }
                if (appCode != null)
                {
                    b.Append(", AppCode=");
                    b.Append(appCode);
                }

                b.Append("] ");

                if (desc != null)
                {
                    b.Append(desc);
                }
                if (extDesc != null)
                {
                    b.Append(". " + extDesc);
                }

                msg = b.ToString();
            }

            //	Post the the server
            IServerLogModule [] chain = _getLogChain(fZone);
            for (int i = 0; i < chain.Length; i++)
            {
                if (le != null)
                {
                    chain[i].Log(fZone, le);
                }
                else
                {
                    chain[i].Log(fZone, msg);
                }
            }
        }
Пример #14
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();
                    }
                }
            }
        }