Ejemplo n.º 1
0
 /// <summary>  Constructs an exception to wrap one or more SIF_Errors received from an
 /// inbound SIF_Ack message. This form of constructor is only called by
 /// the Adk.
 /// </summary>
 public SifException( SIF_Ack ack,
                      IZone zone )
     : base(null, zone)
 {
     fAck = ack;
     fError = ack != null ? ack.SIF_Error : null;
 }
Ejemplo n.º 2
0
 /// <summary>  Constructs an exception to wrap one or more SIF_Errors received from an
 /// inbound SIF_Ack message. This form of constructor is only called by
 /// the Adk.
 /// </summary>
 public SifException( string msg,
                      SIF_Ack ack,
                      IZone zone )
     : base(msg, zone)
 {
     fAck = ack;
     fError = ack != null ? ack.SIF_Error : null;
 }
Ejemplo n.º 3
0
        /// <summary>  Determines if this SIF_Ack contains the specified error code</summary>
        /// <param name="category">The error category
        /// </param>
        /// <param name="code">The error code
        /// </param>
        /// <returns> true if the SIF_Ack contains this error
        /// </returns>
        public virtual bool HasError(int category, int code)
        {
            string    ca    = category.ToString();
            string    co    = code.ToString();
            SIF_Error error = this.SIF_Error;

            if (error != null && error.SIF_Category == category && error.SIF_Code == code)
            {
                return(true);
            }

            return(false);
        }
        public void OnQueryResults( IDataObjectInputStream data,
                                    SIF_Error error,
                                    IZone zone,
                                    IMessageInfo info )
        {
            // Demonstrates basic handling of a SIF_Query response

            // 1) 	To read data from a SIF_Response, first check to see if an error was returned
            if ( error != null )
            {
                // The provider returned an error message for this SIF_Request
                Console.WriteLine( "An error was received from the provider of LearnerPersonal." );
                Console.WriteLine( error.SIF_Desc + "\r\n" + error.SIF_ExtendedDesc );
                return;
            }

            // 2) 	Now, read each object from the DataObjectInputStream until available() returns false
            while ( data.Available )
            {
                StudentPersonal sp = (StudentPersonal) data.ReadDataObject();
                fObjectCount++;
                Name stuName = sp.PersonInfo.Name;
                Console.WriteLine
                    ( fObjectCount + ") Refid:{" + sp.RefId +
                      "} Name: " + stuName.GivenName + " " + stuName.FamilyName );
            }

            // Demonstration purposes only: print out the total number of objects recieved
            Console.WriteLine( fObjectCount + " total objects received." );

            // 3)	To determine if you have completed receiving all responses, check the
            // 		MorePackets property of the SIFMessageInfo object
            if ( ((SifMessageInfo) info).MorePackets )
            {
                Console.WriteLine( "Waiting for more packets..." );
            }
            else
            {
                Console.WriteLine( "All requested packets have been received" );
            }
        }
Ejemplo n.º 5
0
        private void  LogCommon(string direction, log4net.ILog log)
        {
            System.Text.StringBuilder b = new System.Text.StringBuilder(direction);
            b.Append(ElementDef.Tag(SifVersion));
            b.Append(" (Status = ");

            SIF_Status stat = this.SIF_Status;

            if (stat != null)
            {
                b.Append(stat.SIF_Code);
            }
            else
            {
                b.Append("none");
            }

            SIF_Error err = this.SIF_Error;

            if (err != null)
            {
                b.Append("; 1 Error");
            }

            b.Append(")");
            log.Debug(b.ToString());

            if (err != null && (Adk.Debug & AdkDebugFlags.Messaging) != 0)
            {
                log.Debug(err.ToString());
            }

            if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0)
            {
                string id = MsgId;
                log.Debug("  MsgId: " + (id == null?"<none>":id));
                id = SIF_OriginalMsgId;
                log.Debug("  OrgId: " + (id == null?"<none>":id));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///  Attempts to parse attributes out of the source message enough to make a valid
        ///  SIF_Ack with a SIF_Error. This is useful in conditions where the source message cannot
        /// be parsed by the ADK
        /// </summary>
        /// <param name="sourceMessage"> The original message as a string</param>
        /// <param name="error">The error to place in the SIF_Ack/SIF_Error</param>
        /// <param name="zone">The zone associated with this message</param>
        /// <returns></returns>
        /// <exception cref="AdkMessagingException"></exception>
        public static SIF_Ack ackError(String sourceMessage, SifException error, ZoneImpl zone)
        {
            SifMessageInfo parsed = null;
            try
            {
                StringReader reader = new StringReader(sourceMessage);
                parsed = SifMessageInfo.Parse(reader, false, zone);
                reader.Close();
            }
            catch (Exception e)
            {
                zone.Log.Error(e, e);
            }

            SIF_Ack errorAck = new SIF_Ack(zone.HighestEffectiveZISVersion );

            if (parsed != null)
            {
                // Set SIFVersion, OriginalSourceId, and OriginalMsgId;
                if (parsed.SifVersion != null)
                {
                    errorAck.SifVersion = parsed.SifVersion;
                }
                errorAck.SIF_OriginalMsgId = parsed.GetAttribute("SIF_MsgId");
                errorAck.SIF_OriginalSourceId = parsed.GetAttribute("SIF_SourceId");
            }
            SetRequiredAckValues(errorAck);

            SIF_Error newErr = new SIF_Error();
            newErr.SIF_Category = (int)error.ErrorCategory;
            newErr.SIF_Code = error.ErrorCode;
            newErr.SIF_Desc = error.ErrorDesc;
            newErr.SIF_ExtendedDesc = error.ErrorExtDesc;
            errorAck.SIF_Error = newErr;

            return errorAck;
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Constructs a SifException for delivery to the ZIS
 /// </summary>
 /// <param name="category">A <c>SifErrorCategoryCode.</c> error category</param>
 /// <param name="code">A <c>SifErrorCodes</c> error code</param>
 /// <param name="desc">The error description</param>
 /// <param name="extDesc">An option extended error description</param>
 /// <param name="zone">The zone on which the error occurred</param>
 /// <param name="innerException">The internal error that was thrown by the agent</param>
 /// <remarks>
 ///  The Adk will include
 /// the error information provided by the exception when it sends a SIF_Ack
 /// in response to the message being processed. This form of constructor is
 /// typically called by the Adk, but may also be called by agent code if an
 /// exception occurs in a <c>IPublisher</c>, <c>ISubscriber</c>, or <c>IQueryResults</c>
 /// message handler implementation.
 /// </remarks>
 public SifException( SifErrorCategoryCode category,
                      int code,
                      string desc,
                      string extDesc,
                      IZone zone,
                      Exception innerException )
     : base(desc, zone, innerException)
 {
     fAck = null;
     fError = new SIF_Error( (int) category, code, desc == null ? "" : desc );
     if ( extDesc != null ) {
         fError.SIF_ExtendedDesc = extDesc;
     }
 }
Ejemplo n.º 8
0
        /// <summary>  Create an error SIF_Ack for this message.</summary>
        /// <param name="category">The value of the SIF_Error/SIF_Category element
        /// </param>
        /// <param name="code">The value of the SIF_Error/SIF_Code element
        /// </param>
        /// <param name="desc">The value of the SIF_Error/SIF_Desc element
        /// </param>
        /// <param name="extDesc">The value of the SIF_Error/SIF_ExtendedDesc element
        /// </param>
        /// <returns> A new SIF_Ack instance with a SIF_Error element and SIF_Ack
        /// header values derived from this message's header values
        /// </returns>
        public virtual SIF_Ack AckError(SifErrorCategoryCode category,
                                         int code,
                                         string desc,
                                         string extDesc)
        {
            SIF_Ack ack = new SIF_Ack();
            ack.SIF_OriginalMsgId = this.MsgId;
            ack.SIF_OriginalSourceId = this.SourceId;
            SIF_Error error = new SIF_Error
                (
                (int)category,
                code,
                desc ?? "");

            if (extDesc != null)
            {
                error.SIF_ExtendedDesc = extDesc;
            }
            ack.SIF_Error = error;

            //  Ack using the same version of SIF as this message
            ack.SifVersion = SifVersion;

            return ack;
        }
 /// <summary>  Called when the Publisher.onQuery method has thrown a SifException,
 /// indicating an error should be returned in the SIF_Response body
 /// </summary>
 public abstract void SetError( SIF_Error error );
Ejemplo n.º 10
0
        public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info)
        {
            SifMessageInfo smi = (SifMessageInfo)info;
            DateTime start = DateTime.Now;
            if (smi.Timestamp.HasValue) {
            start = smi.Timestamp.Value;
            }

            Console.WriteLine();
            Console.WriteLine( "********************************************* " );
            Console.WriteLine( "Received SIF_Response packet from zone" + zone.ZoneId );
            Console.WriteLine( "Details... " );
            Console.WriteLine( "Request MsgId: " + smi.SIFRequestMsgId );
            Console.WriteLine( "Packet Number: " + smi.PacketNumber );
            Console.WriteLine();

            if( error != null ){

            Console.WriteLine( "The publisher returned an error: " );
            Console.WriteLine( "Category: " + error.SIF_Category + " Code: " + error.SIF_Code  );
            Console.WriteLine( "Description " + error.SIF_Desc );
            if( error.SIF_ExtendedDesc != null )
            {
                Console.WriteLine( "Details: " + error.SIF_ExtendedDesc );
            }
            return;
            }

            try
            {
            int objectCount = 0;
            while( data.Available ){
                SifDataObject next = data.ReadDataObject();
                objectCount++;
                Console.WriteLine();
                Console.WriteLine( "Text Values for " + next.ElementDef.Name + " " + objectCount + " {" + next.Key + "}" );

                SifXPathContext context = SifXPathContext.NewSIFContext(next);

                //	Print out all attributes
                Console.WriteLine("Attributes:");
                XPathNodeIterator textNodes = context.Select("//@*");
                while( textNodes.MoveNext() ) {
                    XPathNavigator navigator = textNodes.Current;
                    Element value = (Element)navigator.UnderlyingObject;
                    IElementDef valueDef = value.ElementDef;
                    Console.WriteLine( valueDef.Parent.Tag( SifVersion.LATEST ) + "/@" + valueDef.Tag( SifVersion.LATEST ) + "=" + value.TextValue + ", " );
                }
                Console.WriteLine();
                // Print out all  elements that have a text value
                Console.WriteLine("Element:");
                textNodes = context.Select("//*");
                while( textNodes.MoveNext() ) {
                    XPathNavigator navigator = textNodes.Current;
                    Element value = (Element)navigator.UnderlyingObject;
                    String textValue = value.TextValue;
                    if( textValue != null ){
                        IElementDef valueDef = value.ElementDef;
                        Console.WriteLine( valueDef.Tag( SifVersion.LATEST ) + "=" + textValue + ", " );
                    }
                }

            }
            Console.WriteLine();
            Console.WriteLine( "Total Objects in Packet: " + objectCount );

            } catch( Exception ex ){
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            }

            if (!smi.MorePackets) {
            // This is the final packet. Print stats
            Console.WriteLine( "Final Packet has been received." );
            IRequestInfo ri = smi.SIFRequestInfo;
            if( ri != null ){
                Console.WriteLine( "Source Query: " );
                Console.WriteLine( ri.UserData );
                TimeSpan difference = start.Subtract(ri.RequestTime);
                Console.WriteLine( "Query execution time: " + difference.Milliseconds + " ms" );
            }

            } else {
            Console.WriteLine( "This is not the final packet for this SIF_Response" );
            }

            Console.WriteLine( "********************************************* " );
            Console.WriteLine( );
            PrintPrompt();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Create an error SIF_Ack for this message.
        /// </summary>
        /// <param name="sifEx">The SIFException that is the cause of the error</param>
        /// <returns></returns>
        public SIF_Ack AckError(SifException sifEx)
        {
            SIF_Ack ack = new SIF_Ack();
            ack.message = this;

            ack.SIF_OriginalMsgId = this.MsgId;
            ack.SIF_OriginalSourceId = this.SourceId;

            SIF_Error error = new SIF_Error(
                sifEx.ErrorCategory,
                sifEx.ErrorCode,
                sifEx.ErrorDesc,
                sifEx.ErrorExtDesc);

            ack.SIF_Error = error;

            //  Ack using the same version of SIF as this message
            ack.SifVersion = this.SifVersion;

            return ack;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Write a SIF_Error to the output stream
        /// </summary>
        /// <param name="error">A SIF_Error instance</param>
        public void Write( SIF_Error error )
        {
            _checkOpen();

            fOut.SetError( error );
        }
        /// <summary>  Called when the Publisher.OnQuery method has thrown a SifException,
        /// indicating an error should be returned in the SIF_Response body
        /// </summary>
        public override void SetError( SIF_Error error )
        {
            fError = error;

            //
            //  Write a SIF_Response packet that contains only this SIF_Error
            //
            try
            {
                NewPacket();
                SifWriter writer = new SifWriter( fCurrentOutputStream );
                writer.SuppressNamespace( true );
                writer.Write( error, fRenderAsVersion );
                writer.Close();
            }
            catch ( IOException ioe )
            {
                throw new AdkException
                    (
                    "Failed to write Publisher SIF_Error data (packet " + fCurPacket + ") to " +
                    fFile.FullName + ": " +
                    ioe, fZone );
            }
        }
Ejemplo n.º 14
0
 private void _checkErrorExists()
 {
     if ( fError == null ) {
         fError = new SIF_Error();
     }
 }
Ejemplo n.º 15
0
 public void OnQueryResults(IDataObjectInputStream data,
                             SIF_Error error,
                             IZone zone,
                             IMessageInfo info)
 {
     SifMessageInfo smi = (SifMessageInfo)info;
     if (error != null)
     {
         Adk.Log.Warn("Received Error Response: " + error.SIF_Desc);
     }
     else
     {
         string debug =
             string.Format
                 ("Received Response for {0} from zone: {1}. Packet {2} of {3}",
                   data.ObjectType, zone.ZoneId, smi.PacketNumber,
                   smi.MorePackets ? smi.PacketNumber + "+" : smi.PacketNumber + " (FINAL)");
         zone.Log.Info(debug);
         zone.ServerLog.Log
             (LogLevel.INFO, debug, null, "1003", LogEntryCodes.CATEGORY_SUCCESS,
               LogEntryCodes.CODE_SUCCESS, smi, null);
         bool logToconsole = fAgent.getChameleonProperty(zone, "logConsole", false);
         if (fAgent.getChameleonProperty(zone, "logResponses", true))
         {
             Log
                 (fDir + Path.DirectorySeparatorChar + zone.ZoneId +
                   Path.DirectorySeparatorChar + "Responses\\" + data.ObjectType.Name + "\\" +
                   data.ObjectType.Name + DateTime.Now.ToFileTime().ToString() + ".xml", data,
                   smi, logToconsole);
         }
     }
 }
Ejemplo n.º 16
0
        /// <summary>  Dispatch a SIF_Request.
        /// 
        /// <b>When ALQ Disabled:</b> The SIF_Request is immediately dispatched to
        /// the Publisher of the associated topic. Only after the Publisher has
        /// returned a result does this method return, causing the SIF_Request to
        /// be acknowledged. The result data returned by the Publisher is handed to
        /// the zone's ResponseDelivery thread, which sends SIF_Response messages to
        /// the ZIS until all of the result data has been sent, potentially with
        /// multiple SIF_Response packets. Note without the ALQ, there is the
        /// potential for the agent to terminate before all data has been sent,
        /// causing some results to be lost. In this case the SIF_Request will have
        /// never been ack'd and will be processed again the next time the agent
        /// is started.
        /// 
        /// 
        /// <b>When ALQ Enabled:</b> The SIF_Request is placed in the ALQ where it
        /// will be consumed by the zone's ResponseDelivery thread at a later time.
        /// This method returns immediately, causing the SIF_Request to be
        /// acknowledged. The ResponseDelivery handles dispatching the request to
        /// the Publisher of the associated topic, and also handles returning
        /// SIF_Response packets to the ZIS. With the ALQ, the processing of the
        /// SIF_Request and the returning of all SIF_Response data is guaranteed
        /// because the original SIF_Request will not be removed from the ALQ until
        /// both of these activities have completed successfully (even over multiple
        /// agent sessions).
        /// 
        /// 
        /// Note that any error that occurs during a SIF_Request should result in a
        /// successful SIF_Ack (because the SIF_Request was received successfully),
        /// and a single SIF_Response with a SIF_Error payload. The SIF Compliance
        /// harness checks for this.
        /// 
        /// 
        /// </summary>
        /// <param name="req">The SIF_Request to process
        /// </param>
        private void dispatchRequest(SIF_Request req)
        {
            SifVersion renderAsVer = null;
            SIF_Query q = null;
            SIF_QueryObject qo = null;
            IElementDef typ = null;
            int maxBufSize = 0;
            bool rethrow = false;

            try
            {
                //	block thread until Zone.query() has completed in case it is in the
                //	midst of a SIF_Request and the destination of that request is this 
                //	agent (i.e. a request of self). This is done to ensure that we don't 
                //	receive the SIF_Request from the zone before the ADK and agent have 
                //	finished issuing it in Zone.query()
                fZone.WaitForRequestsToComplete();

                //
                //  Check SIF_Version. If the version is not supported by the Adk,
                //  fail the SIF_Request with an error SIF_Ack. If the version is
                //  supported, continue on; the agent may not support this version,
                //  but that will be determined later and will result in a SIF_Response
                //  with a SIF_Error payload.
                //
                SIF_Version[] versions = req.GetSIF_Versions();
                if (versions == null || versions.Length == 0)
                {
                    rethrow = true;
                    throw new SifException
                        (
                        SifErrorCategoryCode.Xml,
                        SifErrorCodes.XML_MISSING_MANDATORY_ELEMENT_6,
                        "SIF_Request/SIF_Version is a mandatory element",
                        fZone);
                }

                //  SIF_Version specifies the version of SIF that will be used to render
                //  the SIF_Responses
                // TODO: Add support for multiple SIF_Request versions
                renderAsVer = SifVersion.Parse(versions[0].Value);
                if (!Adk.IsSIFVersionSupported(renderAsVer))
                {
                    rethrow = true;
                    throw new SifException
                        (
                        SifErrorCategoryCode.RequestResponse,
                        SifErrorCodes.REQRSP_UNSUPPORTED_SIFVERSION_7,
                        "SIF_Version " + renderAsVer + " is not supported by this agent",
                        fZone);
                }

                //  Check max buffer size
                int? maximumBufferSize = req.SIF_MaxBufferSize;
                if (!maximumBufferSize.HasValue )
                {
                    rethrow = true;
                    throw new SifException
                        (
                        SifErrorCategoryCode.Xml,
                        SifErrorCodes.XML_MISSING_MANDATORY_ELEMENT_6,
                        "SIF_Request/SIF_MaxBufferSize is a mandatory element",
                        fZone);
                }
                maxBufSize = maximumBufferSize.Value;


                if (maxBufSize < 4096 || maxBufSize > Int32.MaxValue)
                {
                    throw new SifException
                        (
                        SifErrorCategoryCode.RequestResponse,
                        SifErrorCodes.REQRSP_UNSUPPORTED_MAXBUFFERSIZE_8,
                        "Invalid SIF_MaxBufferSize value (" + maxBufSize + ")",
                        "Acceptable range is 4096 to " + Int32.MaxValue,
                        fZone);
                }

                // Check to see if the Context is supported
                try
                {
                    IList<SifContext> contexts = req.SifContexts;
                }
                catch (AdkNotSupportedException contextNotSupported)
                {
                    throw new SifException(
                            SifErrorCategoryCode.Generic,
                            SifErrorCodes.GENERIC_CONTEXT_NOT_SUPPORTED_4,
                            contextNotSupported.Message, fZone);
                }


                //  Lookup the SIF_QueryObject
                q = req.SIF_Query;
                if (q == null)
                {
                    // If it's a SIF_ExtendedQuery or SIF_Example, throw the appropriate error
                    if (req.SIF_ExtendedQuery != null)
                    {
                        throw new SifException(
                            SifErrorCategoryCode.RequestResponse,
                            SifErrorCodes.REQRSP_NO_SUPPORT_FOR_SIF_EXT_QUERY,
                            "SIF_ExtendedQuery is not supported", fZone);
                    }
                    else
                    {
                        throw new SifException
                            (
                            SifErrorCategoryCode.Xml,
                            SifErrorCodes.XML_MISSING_MANDATORY_ELEMENT_6,
                            "SIF_Request/SIF_Query is a mandatory element",
                            fZone);
                    }
                }

                qo = q.SIF_QueryObject;
                if (qo == null)
                {
                    rethrow = true;
                    throw new SifException
                        (
                        SifErrorCategoryCode.Xml,
                        SifErrorCodes.XML_MISSING_MANDATORY_ELEMENT_6,
                        "SIF_Query/SIF_QueryObject is a mandatory element",
                        fZone);
                }

                //  Lookup the ElementDef for the requested object type
                typ = Adk.Dtd.LookupElementDef(qo.ObjectName);
                if (typ == null)
                {
                    throw new SifException
                        (
                        SifErrorCategoryCode.RequestResponse,
                        SifErrorCodes.REQRSP_INVALID_OBJ_3,
                        "Agent does not support this object type: " + qo.ObjectName,
                        fZone);
                }
            }
            catch (SifException se)
            {
                if (!rethrow)
                {
                    sendErrorResponse(req, se, renderAsVer, maxBufSize);
                }

                //	rethrow all errors at this point
                throw se;


                //                //  Capture the SifException so it can be written to the output stream
                //                //  and thus returned as the payload of the SIF_Response message later
                //                //  in this function.
                //                error = se;
                //                fZone.Log.Error("Error in dispatchRequest that will be put into the SIF_Response", se);
            }


            // For now, SIFContext is not repeatable in SIF Requests

            SifContext requestContext = req.SifContexts[0];
            Object target = null;

            //
            //  Lookup the Publisher for this object type using Topics, 
            // but only if the context is the Default context
            //


            if (typ != null && SifContext.DEFAULT.Equals(requestContext))
            {
                ITopic topic = null;
                topic = fZone.Agent.TopicFactory.LookupInstance(typ, requestContext);
                if (topic != null)
                {
                    target = topic.GetPublisher();
                }
            }


            if (target == null)
            {
                target = fZone.GetPublisher(requestContext, typ);
                

                if (target == null)
                {
                    //
                    //  No Publisher message handler found. Try calling the Undeliverable-
                    //  MessageHandler for the zone or agent. If none is registered,
                    //  return an error SIF_Ack indicating the object type is not
                    //  supported.
                    //
                    Boolean handled = false;
                    IUndeliverableMessageHandler errHandler = fZone.ErrorHandler;
                    if (errHandler != null)
                    {
                        SifMessageInfo msginfo = new SifMessageInfo(req, fZone);

                        handled = errHandler.OnDispatchError(req, fZone, msginfo);

                        //	Notify MessagingListeners...
                        foreach (IMessagingListener ml in GetMessagingListeners(fZone))
                        {
                            ml.OnMessageProcessed(SifMessageType.SIF_Request, msginfo);
                        }


                    }
                    if (!handled)
                    {
                        fZone.Log.Warn("Received a SIF_Request for " + qo.ObjectName + " (MsgId=" + req.MsgId + "), but no Publisher object is registered to handle it");

                        SifException sifEx = new SifException(
                           SifErrorCategoryCode.RequestResponse,
                           SifErrorCodes.REQRSP_INVALID_OBJ_3,
                           "Agent does not support this object type",
                           qo.ObjectName, fZone);
                        sendErrorResponse(req, sifEx, renderAsVer, maxBufSize);
                        throw sifEx;
                    }
                    else
                    {
#if PROFILED 
                                          ( BuildOptions.PROFILED )
							                        ProfilerUtils.profileStop();
#endif

                        return;
                    }
                }
            }


            //bool success;
            DataObjectOutputStreamImpl outStream = null;
            SifMessageInfo msgInfo = new SifMessageInfo(req, fZone);
            Query query = null;

            try
            {
                //  Convert SIF_Request/SIF_Query into a Query object
                if (q != null)
                {
                    query = new Query(q);
                }

                msgInfo.SIFRequestObjectType = typ;
            }
            catch (Exception thr)
            {
                fZone.Log.Debug(thr.ToString());
                SifException sifEx =
                    new SifException
                        (SifErrorCategoryCode.Xml, SifErrorCodes.XML_MALFORMED_2,
                          "Could not parse SIF_Query element", thr.Message, fZone, thr);
                sendErrorResponse(req, sifEx, renderAsVer, maxBufSize);
                throw sifEx;
            }

            try
            {

                outStream = DataObjectOutputStreamImpl.NewInstance();

                outStream.Initialize
                    (
                    fZone,
                    query, 
                    req.SourceId,
                    req.MsgId,
                    renderAsVer,
                    maxBufSize );

                //  Call the agent-supplied Publisher, or if we have an error, write
                //  that error to the output stream instead

               
                ((IPublisher)target).OnRequest(outStream, query, fZone, msgInfo);
                

                //	Notify MessagingListeners...
                NotifyMessagingListeners_OnMessageProcessed
                    (SifMessageType.SIF_Request, msgInfo);

            }
            catch (SifException se)
            {
                //  For a SIF_Request, a SifException (other than a Transport Error)
                //  does not mean to return an error ack but instead to return a
                //  valid SIF_Response with a SIF_Error payload (see the SIF
                //  Specification). Transport Errors must be returned to the ZIS so
                //  that the message will be retried later.
                //
                if (se.Retry || se.ErrorCategory == SifErrorCategoryCode.Transport)
                {
                    //success = false;
                    //retry was requested, so we have to tell the output stream to not send an empty response
                    outStream.DeferResponse();
                    throw;
                }

                outStream.SetError(se.Error);
            }
            catch (AdkException adke)
            {
                //	If retry requested, throw a Transport Error back to the ZIS
                //	instead of returning a SIF_Error in the SIF_Response payload
                if (adke.Retry)
                {
                    //success = false;
                    //retry was requested, so we have to tell the output stream to not send an empty response
                    outStream.DeferResponse();
                    throw;
                }

                //	Return SIF_Error payload in SIF_Response
                SIF_Error err = new SIF_Error();
                err.SIF_Category = (int)SifErrorCategoryCode.Generic;
                err.SIF_Code = SifErrorCodes.GENERIC_GENERIC_ERROR_1;
                err.SIF_Desc = adke.Message;

                outStream.SetError(err);
            }
            catch (Exception thr)
            {
                SIF_Error err = new SIF_Error();
                err.SIF_Category = (int)SifErrorCategoryCode.Generic;
                err.SIF_Code = SifErrorCodes.GENERIC_GENERIC_ERROR_1;
                err.SIF_Desc = "Agent could not process the SIF_Request at this time";

                err.SIF_ExtendedDesc = "Exception in " +
                                        "Publisher.onRequest" +
                                       " message handler: " + thr.ToString();

                outStream.SetError(err);
            }
            finally
            {
                try
                {
                    outStream.Close();
                }
                catch
                {
                    // Do Nothing
                }

                try
                {
                    outStream.Commit();
                }
                catch
                {
                    /* Do Nothing */
                }
#if PROFILED
				ProfilerUtils.profileStop();
#endif
                outStream.Dispose();
            }
        }
Ejemplo n.º 17
0
    /// <summary>  Handles SIF_Responses
    /// </summary>
    public virtual void OnQueryResults( IDataObjectInputStream inStream,
                                        SIF_Error error,
                                        IZone zone,
                                        IMessageInfo inf )
    {
        SifMessageInfo info = (SifMessageInfo) inf;

        Console.WriteLine
            ( "\nReceived a query response from agent \"" + info.SourceId + "\" in zone " +
              zone.ZoneId );
        IRequestInfo reqInfo = info.SIFRequestInfo;
        if ( reqInfo != null )
        {
            Console.WriteLine
                ( "\nResponse was received in {0}. Object State is '{1}'",
                  DateTime.Now.Subtract( reqInfo.RequestTime ), reqInfo.UserData );
        }

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

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

        //  Get the root Mappings object from the configuration file
        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.
        MappingsContext mappings = m.SelectInbound( StudentDTD.STUDENTPERSONAL, info );
        Hashtable data = new Hashtable();
        StringMapAdaptor sma = new StringMapAdaptor( data, Adk.Dtd.GetFormatter( SifVersion.LATEST ) );

        int count = 0;
        while ( inStream.Available )
        {
            Console.WriteLine( "Object Number {0}", count++ );
            StudentPersonal sp = (StudentPersonal) inStream.ReadDataObject();
            //  Ask the Mappings object to populate the dictionary with field/value pairs
            //  by using the mapping rules in the configuration file to decompose
            //  the LearnerPersonal object into field values.
            mappings.Map( sp, sma );
            //  Now dump the field/value pairs to System.out
            DumpDictionaryToConsole( data );
            Console.WriteLine();
            data.Clear();
        }
    }
Ejemplo n.º 18
0
 public void OnQueryResults(IDataObjectInputStream data,
                             SIF_Error error,
                             IZone zone,
                             IMessageInfo info)
 {
     SifMessageInfo smi = (SifMessageInfo)info;
     if (!(fRequestState.Equals(smi.SIFRequestInfo.UserData)))
     {
         // This is a SIF_ZoneStatus response from a previous invocation of the agent
         return;
     }
     if (data.Available)
     {
         SIF_ZoneStatus zoneStatus = data.ReadDataObject() as SIF_ZoneStatus;
         AsyncUtils.QueueTaskToThreadPool(new zsDelegate(_processSIF_ZoneStatus), zoneStatus, zone);
     }
 }
Ejemplo n.º 19
0
        /**
	 * Sends a SIF_Ack in response to a pulled message
	 * @param sifGetMessageAck The original SIF_Ack from the SIF_GetMessage. This is sometimes null, when
	 * 						parsing fails
	 * @param pulledMEssage The message delivered inside of the above ack. NOTE that even if parsing fails,
	 *          the SIFParser tries to return what it can, and will return this message payload (in getParsed()),
	 *          instead of the above container message.
	 * @param ackStatus The status to ack (NOTE: This is ignored if the err property is set)
	 * @param err The error to set in the SIF_Ack
	 */
	private void sendPushAck(SIF_Ack sifGetMessageAck,
			SifMessagePayload pulledMEssage, int ackStatus, SifException err) {
		try
		{
			SIF_Ack ack2 = null;
			if( fAckAckOnPull && sifGetMessageAck != null){
				ack2 = sifGetMessageAck.ackStatus( ackStatus );
			} else {
				ack2 = pulledMEssage.ackStatus(ackStatus);
			}


			//  If an error occurred processing the message, return
			//  the details in the SIF_Ack
			if( err != null )
			{
				fZone.Log.Debug( "Handling exception by creating a SIF_Error", err );

				SIF_Error newErr = new SIF_Error();
				newErr.SIF_Category =  (int)err.ErrorCategory;
				newErr.SIF_Code = err.ErrorCode;
				newErr.SIF_Desc = err.ErrorDesc;
				newErr.SIF_ExtendedDesc = err.ErrorExtDesc;
				ack2.SIF_Error = newErr;

				//  Get rid of the <SIF_Status>
				SIF_Status status = ack2.SIF_Status;
				if( status != null ) {
					ack2.RemoveChild( status );
				}
			}

			//  Send the ack
			send(ack2);
		}
		catch( Exception ackEx )
		{
			fZone.Log.Debug( "Failed to send acknowledgement to pulled message: " + ackEx, ackEx );
		}
	}
Ejemplo n.º 20
0
        private void sendErrorResponse(SIF_Request req, SifException se, SifVersion renderAsVer, int maxBufSize)
        {

            DataObjectOutputStreamImpl outStream = DataObjectOutputStreamImpl.NewInstance();
            outStream.Initialize(fZone, (IElementDef[])null, req.SourceId, req.MsgId, renderAsVer, maxBufSize);

            SIF_Error err = new SIF_Error(
                (int)se.ErrorCategory,
                se.ErrorCode,
                se.ErrorDesc);
            err.SIF_ExtendedDesc = se.ErrorExtDesc;

            outStream.SetError(err);
            try
            {
                outStream.Close();
            }
            catch (Exception ignored)
            {
                fZone.Log.Warn("Ignoring exception in out.close()", ignored);
            }

            try
            {
                outStream.Commit();
            }
            catch (Exception ignored)
            {
                fZone.Log.Warn("Ignoring exception in out.commit()", ignored);
            }
        }