public void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
        {
            if (reg == null || finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

            m_log.DebugFormat(
                "[ENTITY TRANSFER MODULE]: Request Teleport to {0} ({1}) {2}/{3}",
                reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);

            uint newRegionX = (uint)(reg.RegionHandle >> 40);
            uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
            uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
            uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);

            ulong destinationHandle = finalDestination.RegionHandle;

            // Let's do DNS resolution only once in this process, please!
            // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
            // it's actually doing a lot of work.
            IPEndPoint endPoint = finalDestination.ExternalEndPoint;
            if (endPoint.Address != null)
            {
                // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
                // both regions
                if (sp.ParentID != (uint)0)
                    sp.StandUp();

                if (!sp.ValidateAttachments())
                    m_log.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}.  Continuing.",
                        sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName);

//                if (!sp.ValidateAttachments())
//                {
//                    sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
//                    return;
//                }

                string reason;
                string version;
                if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
                {
                    sp.ControllingClient.SendTeleportFailed("Teleport failed: " + reason);
                    return;
                }
                m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version);

                sp.ControllingClient.SendTeleportStart(teleportFlags);

                // the avatar.Close below will clear the child region list. We need this below for (possibly)
                // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
                //List<ulong> childRegions = avatar.KnownRegionHandles;
                // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
                // failure at this point (unlike a border crossing failure).  So perhaps this can never fail
                // once we reach here...
                //avatar.Scene.RemoveCapsHandler(avatar.UUID);

                string capsPath = String.Empty;

                AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
                AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
                agentCircuit.startpos = position;
                agentCircuit.child = true;
                agentCircuit.Appearance = sp.Appearance;
                if (currentAgentCircuit != null)
                {
                    agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
                    agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
                    agentCircuit.Viewer = currentAgentCircuit.Viewer;
                    agentCircuit.Channel = currentAgentCircuit.Channel;
                    agentCircuit.Mac = currentAgentCircuit.Mac;
                    agentCircuit.Id0 = currentAgentCircuit.Id0;
                }

                if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    // brand new agent, let's create a new caps seed
                    agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
                }

                // Let's create an agent there if one doesn't exist yet. 
                bool logout = false;
                if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
                {
                    sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
                                                                              reason));
                    return;
                }

                // OK, it got this agent. Let's close some child agents
                sp.CloseChildAgents(newRegionX, newRegionY);
                IClientIPEndpoint ipepClient;  
                if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
                    #region IP Translation for NAT
                    // Uses ipepClient above
                    if (sp.ClientView.TryGet(out ipepClient))
                    {
                        endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
                    }
                    #endregion
                    capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);

                    if (eq != null)
                    {
                        eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);

                        // ES makes the client send a UseCircuitCode message to the destination, 
                        // which triggers a bunch of things there.
                        // So let's wait
                        Thread.Sleep(200);

                        eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);

                    }
                    else
                    {
                        sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
                    }
                }
                else
                {
                    agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
                    capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                }


                SetInTransit(sp.UUID);

                // Let's send a full update of the agent. This is a synchronous call.
                AgentData agent = new AgentData();
                sp.CopyTo(agent);
                agent.Position = position;
                SetCallbackURL(agent, sp.Scene.RegionInfo);

                //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent...");

                if (!UpdateAgent(reg, finalDestination, agent))
                {
                    // Region doesn't take it
                    m_log.WarnFormat(
                        "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}.  Returning avatar to source region.", 
                        sp.Name, finalDestination.RegionName);
                    
                    Fail(sp, finalDestination);
                    return;
                }

                sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest");

                m_log.DebugFormat(
                    "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);

                if (eq != null)
                {
                    eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
                                           0, teleportFlags, capsPath, sp.UUID);
                }
                else
                {
                    sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
                                                                teleportFlags, capsPath);
                }

                // Let's set this to true tentatively. This does not trigger OnChildAgent
                sp.IsChildAgent = true;

                // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
                // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
                // that the client contacted the destination before we close things here.
                if (!WaitForCallback(sp.UUID))
                {
                    m_log.WarnFormat(
                        "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} failed due to no callback from destination region.  Returning avatar to source region.", 
                        sp.Name, finalDestination.RegionName);
                    
                    Fail(sp, finalDestination);                   
                    return;
                }

                // For backwards compatibility
                if (version == "Unknown" || version == string.Empty)
                {
                    // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
                    m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
                    CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
                }

                // May need to logout or other cleanup
                AgentHasMovedAway(sp, logout);

                // Well, this is it. The agent is over there.
                KillEntity(sp.Scene, sp.LocalId);

                // Now let's make it officially a child agent
                sp.MakeChildAgent();
                

//                sp.Scene.CleanDroppedAttachments();

                // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone

                if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
                {
                    Thread.Sleep(5000);
                    sp.Close();
                    sp.Scene.IncomingCloseAgent(sp.UUID);
                }
                else
                {
                    // now we have a child agent in this region. 
                    sp.IsInTransit = false; // not sure :(
                    sp.Reset();
                }

                // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
                if (sp.Scene.NeedSceneCacheClear(sp.UUID))
                {
                    m_log.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
                        sp.UUID);
                }
            }
            else
            {
                sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
            }
        }
Example #2
0
 public void Add(IEventQueue queue)
 {
     if (queue.IsSynched)
         this.tree.Add(queue);
     else
         this.list.Add(queue);
 }
Example #3
0
 public void Remove(IEventQueue queue)
 {
     if (queue.IsSynched)
         this.tree.Remove(queue);
     else
         this.list.Remove(queue);
 }
Example #4
0
		internal DataSeriesObject(DataSeries series, DateTime dateTime1, DateTime dateTime2, IEventQueue queue)
		{
			this.series = series;
			this.queue = queue;
			if (dateTime1 == DateTime.MinValue || dateTime1 < series.DateTime1)
			{
				this.index1 = 0L;
			}
			else
			{
				this.index1 = series.GetIndex(dateTime1, SearchOption.Next);
			}
			if (dateTime2 == DateTime.MaxValue || dateTime2 > series.DateTime2)
			{
				this.index2 = series.count - 1L;
			}
			else
			{
				this.index2 = series.GetIndex(dateTime2, SearchOption.Prev);
			}
			this.current = this.index1;
			this.obj = series[this.current];
			this.progressDelta = (int)Math.Ceiling((double)this.Count / 100.0);
			this.progressCount = this.progressDelta;
			this.progressPercent = 0;
		}
Example #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Replication"/> class.
        /// </summary>
        /// <param name="replicationLength">Length of the replication.</param>
        /// <param name="dataGatherer">The data gatherer.</param>
        /// <param name="queueFactory">The queue factory.</param>
        /// <param name="startup">The startup time.</param>
        public Replication(
			uint replicationLength, IDataGatherer dataGatherer, IEventQueueFactory queueFactory, uint startup )
        {
            _replicationLength = replicationLength;
            _startup = startup;
            CurrentState = ReplicationState.NotStarted;
            ReplicationData = dataGatherer;
            _queue = queueFactory.Create( dataGatherer );
        }
 /// <summary>
 /// Creates a new Parser Context
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="document">XML Document</param>
 /// <param name="traceParsing">Whether to Trace Parsing</param>
 public RdfXmlParserContext(IGraph g, XmlDocument document, bool traceParsing)
     : base(g) 
 {
     this._queue = new EventQueue(new DomBasedEventGenerator(document));
     if (this._queue.EventGenerator is IPreProcessingEventGenerator)
     {
         ((IPreProcessingEventGenerator)this._queue.EventGenerator).GetAllEvents(this);
     }
 }
Example #7
0
 private ExportComponent(bool supportInProcessStores, IEventQueue eventQueue)
 {
     this.SpanExporter     = Export.SpanExporter.Create(ExporterBufferSize, ExporterScheduleDelay);
     this.RunningSpanStore =
         supportInProcessStores
             ? new InProcessRunningSpanStore()
             : Export.RunningSpanStoreBase.NoopRunningSpanStore;
     this.SampledSpanStore =
         supportInProcessStores
             ? new InProcessSampledSpanStore(eventQueue)
             : Export.SampledSpanStoreBase.NoopSampledSpanStore;
 }
 public XEventDataReader(
     string connectionString,
     string sessionName,
     IEventQueue events,
     ExtendedEventsWorkloadListener.ServerType serverType
     )
 {
     ConnectionString = connectionString;
     SessionName      = sessionName;
     Events           = events;
     ServerType       = serverType;
 }
Example #9
0
        //init
        public DatabaseEventProvider(IEventQueue <TKey> eventQueue, IMonitor <TKey> eventSink
                                     , SenderSettings senderSettings, ISignalEventQueries <TKey> eventQueries, ILogger logger)
        {
            _eventQueue   = eventQueue;
            _monitor      = eventSink;
            _eventQueries = eventQueries;
            _logger       = logger;

            QueryPeriod       = senderSettings.DatabaseSignalProviderQueryPeriod;
            ItemsQueryCount   = senderSettings.DatabaseSignalProviderItemsQueryCount;
            MaxFailedAttempts = senderSettings.DatabaseSignalProviderItemsMaxFailedAttempts;
        }
Example #10
0
 private ExportComponent(bool supportInProcessStores, IEventQueue eventQueue)
 {
     SpanExporter          = Export.SpanExporter.Create(EXPORTER_BUFFER_SIZE, EXPORTER_SCHEDULE_DELAY);
     this.RunningSpanStore =
         supportInProcessStores
             ? new InProcessRunningSpanStore()
             : Export.RunningSpanStoreBase.NoopRunningSpanStore;
     this.SampledSpanStore =
         supportInProcessStores
             ? new InProcessSampledSpanStore(eventQueue)
             : Export.SampledSpanStoreBase.NoopSampledSpanStore;
 }
        private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
        {
            if (m_debugEnabled)
            {
                m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);

                DebugGridInstantMessage(im);
            }

            // Start group IM session
            if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
            {
                UUID groupID = new UUID(im.toAgentID);

                GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID);
                if (groupInfo != null)
                {
                    if (m_debugEnabled)
                    {
                        m_log.DebugFormat("[GROUPS-MESSAGING]: Start Group Session for {0}", groupInfo.GroupName);
                    }

                    AddAgentToGroupSession(im.fromAgentID, im.imSessionID);

                    ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, groupID);

                    IEventQueue queue = remoteClient.Scene.RequestModuleInterface <IEventQueue>();
                    queue.ChatterBoxSessionAgentListUpdates(
                        new UUID(groupID)
                        , new UUID(im.fromAgentID)
                        , new UUID(im.fromAgentID)
                        , false //canVoiceChat
                        , false //isModerator
                        , false //text mute
                        , im.dialog
                        );
                }
            }

            // Send a message from locally connected client to a group
            if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
            {
                UUID groupID = new UUID(im.toAgentID);

                if (m_debugEnabled)
                {
                    m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", groupID, im.imSessionID.ToString());
                }

                SendMessageToGroup(remoteClient, im, groupID);
            }
        }
Example #12
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="settings">The settings to use, or pass null to use the default settings.</param>
 /// <param name="templateManager">The <see cref="BaseTemplateManager"/> used to access templates.</param>
 /// <param name="blogSettingsResolver">The resolver used to resolve settings for specific blogs.</param>
 /// <param name="eventQueue">The event queue to submit new comments to.</param>
 public CommentManager(
     IWeBlogSettings settings = null,
     IWeBlogCommentSettings commentSettings     = null,
     BaseTemplateManager templateManager        = null,
     IBlogSettingsResolver blogSettingsResolver = null,
     BaseEventQueueProvider eventQueue          = null)
 {
     Settings             = settings ?? WeBlogSettings.Instance;
     CommentSettings      = commentSettings ?? ServiceLocator.ServiceProvider.GetRequiredService <IWeBlogCommentSettings>();
     TemplateManager      = templateManager ?? ServiceLocator.ServiceProvider.GetRequiredService <BaseTemplateManager>();
     BlogSettingsResolver = blogSettingsResolver ?? ServiceLocator.ServiceProvider.GetRequiredService <IBlogSettingsResolver>();
     EventQueue           = eventQueue ?? ServiceLocator.ServiceProvider.GetRequiredService <BaseEventQueueProvider>();
 }
        private void AddAgentToSession(UUID AgentID, UUID GroupID, GridInstantMessage msg)
        {
            // Agent not in session and hasn't dropped from session
            // Add them to the session for now, and Invite them
            AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);

            IClientAPI activeClient = GetActiveClient(AgentID);

            if (activeClient != null)
            {
                GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
                if (groupInfo != null)
                {
                    if (m_debugEnabled)
                    {
                        m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message");
                    }

                    UUID fromAgent = new UUID(msg.fromAgentID);
                    // Force? open the group session dialog???
                    // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
                    IEventQueue eq = activeClient.Scene.RequestModuleInterface <IEventQueue>();
                    if (eq != null)
                    {
                        eq.ChatterboxInvitation(
                            GroupID
                            , groupInfo.GroupName
                            , fromAgent
                            , msg.message
                            , AgentID
                            , msg.fromAgentName
                            , msg.dialog
                            , msg.timestamp
                            , msg.offline == 1
                            , (int)msg.ParentEstateID
                            , msg.Position
                            , 1
                            , new UUID(msg.imSessionID)
                            , msg.fromGroup
                            , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
                            );

                        var update  = new GroupChatListAgentUpdateData(AgentID);
                        var updates = new List <GroupChatListAgentUpdateData> {
                            update
                        };
                        eq.ChatterBoxSessionAgentListUpdates(GroupID, new UUID(msg.toAgentID), updates);
                    }
                }
            }
        }
Example #14
0
        public BattleEventProcessor(IGUIService guiService, IBattleGraphicController graphicService, IEventQueue queue, IEventCreator events)
        {
            this.guiService = guiService;
            this.graphicService = graphicService;
            this.queue = queue;

            events.CriticalDamage += CriticalDamageHandler;
            events.HPChanged += HPChangedHandler;
            events.MoveEffective += MoveEffectiveHandler;
            events.MoveUsed += MoveUsedHandler;
            events.NewTurn += NewTurnHandler;
            events.PokemonChanged += PokemonChangedHandler;
            events.StatusChanged += StatusChangedHandler;
        }
Example #15
0
 public EventPushBackgroundService(IEventQueue eventQueue,
                                   IHubContext <EventHub, IEventClient> hubContext,
                                   IdentityGenerator identityGenerator,
                                   IOptions <ApplicationSettings> options,
                                   IEventStoreQueue storeQueue,
                                   IMemoryCache memoryCache)
 {
     _eventQueue        = eventQueue;
     _hubContext        = hubContext;
     _identityGenerator = identityGenerator;
     _options           = options;
     _storeQueue        = storeQueue;
     _memoryCache       = memoryCache;
 }
Example #16
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing) return;

            if (this.eventQueue != null)
            {
                this.eventQueue.Dispose();
                this.eventQueue = null;
            }

            ExtensionPackage.Instance = null;
        }
        public static void CofigureWebRtcLib(CoreDispatcher uiDispatcher)
        {
            IEventQueue queue         = EventQueueMaker.Bind(uiDispatcher);
            var         configuration = new WebRtcLibConfiguration();

            configuration.Queue = queue;
            configuration.AudioCaptureFrameProcessingQueue = EventQueue.GetOrCreateThreadQueueByName("AudioCaptureProcessingQueue");
            configuration.AudioRenderFrameProcessingQueue  = EventQueue.GetOrCreateThreadQueueByName("AudioRenderProcessingQueue");
            configuration.VideoFrameProcessingQueue        = EventQueue.GetOrCreateThreadQueueByName("VideoFrameProcessingQueue");

            WebRtcLib.Setup(configuration);

            Initialized?.Invoke(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="subscriptionsManager"></param>
        /// <param name="eventStore"></param>
        /// <param name="serviceProvider"></param>
        public SimulationEventBus(
            ILogger <SimulationEventBus> logger,
            ISubscriptionsManager subscriptionsManager,
            IEventQueue eventStore,
            IServiceProvider serviceProvider)
        {
            this.logger = logger;
            this.subscriptionsManager = subscriptionsManager ?? new InMemorySubscriptionsManager();
            this.eventStore           = eventStore;
            this.serviceProvider      = serviceProvider;
            this.subscriptionsManager.OnEventRemoved += SubscriptionsManager_OnEventRemoved;

            DoConsume();
        }
Example #19
0
        public IList <Object> GetObjects(IList <IObjRef> orisToGet, ICacheIntern targetCache, CacheDirective cacheDirective)
        {
            CheckNotDisposed();
            if (orisToGet == null || orisToGet.Count == 0)
            {
                return(new List <Object>(0));
            }
            IEventQueue eventQueue = EventQueue;

            if (eventQueue != null)
            {
                eventQueue.Pause(this);
            }
            try
            {
                bool oldCacheModificationValue = CacheModification.Active;
                bool acquireSuccess            = AcquireHardRefTLIfNotAlready(orisToGet.Count);
                CacheModification.Active = true;
                try
                {
                    if (cacheDirective.HasFlag(CacheDirective.LoadContainerResult) || cacheDirective.HasFlag(CacheDirective.CacheValueResult))
                    {
                        return(Parent.GetObjects(orisToGet, this, cacheDirective));
                    }
                    bool doAnotherRetry;
                    while (true)
                    {
                        doAnotherRetry = false;
                        IList <Object> result = GetObjectsRetry(orisToGet, cacheDirective, out doAnotherRetry);
                        if (!doAnotherRetry)
                        {
                            return(result);
                        }
                    }
                }
                finally
                {
                    CacheModification.Active = oldCacheModificationValue;
                    ClearHardRefs(acquireSuccess);
                }
            }
            finally
            {
                if (eventQueue != null)
                {
                    eventQueue.Resume(this);
                }
            }
        }
Example #20
0
        public FakeLoggerProvider(IOptionsMonitor <FakeLoggerOptions> options, IEventQueue eventQueue)
        {
            var loggerOptions = options.CurrentValue;

            _interval  = loggerOptions.FlushPeriod;
            _batchSize = loggerOptions.BatchSize;
            _queueSize = loggerOptions.BackgroundQueueSize;

            _eventQueue = eventQueue ?? throw new ArgumentNullException(nameof(eventQueue));

            _processId = Process.GetCurrentProcess().Id;

            _optionsChangeToken = options.OnChange(UpdateOptions);
            UpdateOptions(options.CurrentValue);
        }
Example #21
0
 void EventManager_OnGetScriptRunning(OpenSim.Framework.IClientAPI controllingClient,
                                      OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID)
 {
     _exeScheduler.PostScriptInfoRequest(new ScriptInfoRequest(itemID, ScriptInfoRequest.Type.ScriptRunningRequest,
                                                               delegate(ScriptInfoRequest req)
     {
         IEventQueue eq = World.RequestModuleInterface <IEventQueue>();
         if (eq != null)
         {
             eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, req.IsRunning, false),
                        controllingClient.AgentId);
         }
     }
                                                               ));
 }
Example #22
0
        //init
        public EventProcessor(SenderState <TKey> hubState, IMonitor <TKey> eventSink
                              , ILogger logger, SenderSettings senderSettings
                              , IEventQueue <TKey> eventQueue, IDispatchQueue <TKey> dispatchQueue
                              , IEventHandlerRegistry <TKey> handlerRegistry, IEventSettingsQueries <TKey> eventSettingsQueries)
            : base(logger)
        {
            _hubState             = hubState;
            _monitor              = eventSink;
            _eventQueue           = eventQueue;
            _dispatchQueue        = dispatchQueue;
            _handlerRegistry      = handlerRegistry;
            _eventSettingsQueries = eventSettingsQueries;

            MaxParallelItems = senderSettings.MaxParallelEventsProcessed;
        }
Example #23
0
        public override void Initialize(IGameEngine engine)
        {
            base.Initialize(engine);

            // Create event queues.
            var events = Engine.Systems.First <IEventQueueSystem>();

            deletedEvents = events.CreateShared <int, EntityEventHandler>(EventQueueUsageHint.Lazy);

            unpairedFromChildEvents  = events.CreateShared <int, EntityPairEventHandler>(EventQueueUsageHint.Lazy);
            unpairedFromParentEvents = events.CreateShared <int, EntityPairEventHandler>(EventQueueUsageHint.Lazy);

            madeParentOfEvents = events.CreateShared <int, EntityPairEventHandler>(EventQueueUsageHint.Lazy);
            madeChildOfEvents  = events.CreateShared <int, EntityPairEventHandler>(EventQueueUsageHint.Lazy);
        }
Example #24
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing)
            {
                return;
            }

            if (this.eventQueue != null)
            {
                this.eventQueue.Dispose();
                this.eventQueue = null;
            }
        }
Example #25
0
        public void Add(IEventQueue queue)
        {
            if (queue.IsEmpty())
            {
                throw new Exception($"EventTree::Add Can not add queue, the queue is empty : {queue.Name}");
            }

            var item = new EventTreeItem(queue);

            if (this.eventTreeItem_0 == null)
            {
                this.eventTreeItem_0 = item;
                return;
            }
            this.method_0(item);
        }
Example #26
0
        /// <summary>
        /// Removes a collection of items from an event queue
        /// </summary>
        /// <param name="queue">The event queue</param>
        /// <param name="itemsToRemove">The items to remove the event queue</param>
        /// <returns>The new event queue, less the items to remove</returns>
        public static IEventQueue Remove(this IEventQueue queue, IEnumerable <EventQueueItem> itemsToRemove)
        {
            var newQueue   = new EventQueue();
            var queueItems = queue.ToList();

            foreach (var item in queueItems)
            {
                var matchFound = itemsToRemove.Any(_ => _.GetHashCode() == item.GetHashCode());

                if (false == matchFound)
                {
                    newQueue.Add(item.AggregateKey, item.AggregateType, item.Event);
                }
            }

            return(newQueue);
        }
Example #27
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing)
            {
                return;
            }

            if (this.eventQueue != null)
            {
                this.eventQueue.Dispose();
                this.eventQueue = null;
            }

            ExtensionPackage.Instance = null;
        }
Example #28
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing)
            {
                return;
            }

            if (_eventQueue != null)
            {
                _eventQueue.Dispose();
                _eventQueue = null;
            }

            Instance = null;
        }
        //init
        public Sender(SenderState <TKey> hubState, IEventQueue <TKey> eventQueue,
                      IDispatchQueue <TKey> dispatchQueue, IEnumerable <IRegularJob> regularJobs,
                      IEnumerable <ISignalProviderControl> signalEndpoints)
        {
            _hubState        = hubState;
            _regularJobs     = regularJobs.ToList();
            _eventQueue      = eventQueue;
            _dispatchQueue   = dispatchQueue;
            _signalEndpoints = signalEndpoints.ToList();

            _regularJobTimers = _regularJobs.Select(x => new NonReentrantTimer(x.Tick
                                                                               , NotificationsConstants.REGULAR_JOB_TICK_INTERVAL, intervalFromCallbackStarted: false))
                                .ToList();
            _stopMonitorTimer = new NonReentrantTimer(StopTimers
                                                      , NotificationsConstants.REGULAR_JOB_TICK_INTERVAL, intervalFromCallbackStarted: false);
            _stopEventHandle = new ManualResetEventSlim(false);
        }
Example #30
0
 private void Queue_EventReceived(IEventQueue sender, JToken arg)
 {
     lock (lockObj)
     {
         if (subscriptions.TryGetValue(sender.Name, out List <EvHandler> handlers))
         {
             foreach (var h in handlers)
             {
                 h(arg);//TODO: handle errors?
             }
         }
         else
         {
             throw new Exception("no handler exist for queue " + sender.Name + " but an event was received. this shouldnt happen. check yo code");
         }
     }
 }
Example #31
0
 /// <summary>
 /// Initializes all <see cref="IEventQueue" />s.
 /// </summary>
 private static void InitializeEventQueues()
 {
     try
     {
         Config config = Config.ReadConfig();
         foreach (Pipeline pipeline in config.Pipelines)
         {
             IEventQueue eventQueue = EventQueue.GetQueue(pipeline.Name);
             InitializeWorkerThreads(eventQueue, pipeline.WorkerThreads
                                     .GetValueOrDefault(config.ProcessModel.WorkerThreads));
         }
         Log.Info("Event queues and worker threads have been initialized.");
     }
     catch (Exception ex)
     {
         Log.Error(ex);
     }
 }
Example #32
0
        void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, GroupMembershipData[] data)
        {
            m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);

            OSDArray AgentData    = new OSDArray(1);
            OSDMap   AgentDataMap = new OSDMap(1);

            AgentDataMap.Add("AgentID", OSD.FromUUID(remoteClient.AgentId));
            AgentData.Add(AgentDataMap);


            OSDArray GroupData    = new OSDArray(data.Length);
            OSDArray NewGroupData = new OSDArray(data.Length);

            foreach (GroupMembershipData membership in data)
            {
                OSDMap GroupDataMap    = new OSDMap(6);
                OSDMap NewGroupDataMap = new OSDMap(1);

                GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID));
                GroupDataMap.Add("GroupPowers", OSD.FromBinary(membership.GroupPowers));
                GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices));
                GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture));
                GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution));
                GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName));
                NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile));

                GroupData.Add(GroupDataMap);
                NewGroupData.Add(NewGroupDataMap);
            }

            OSDMap llDataStruct = new OSDMap(3);

            llDataStruct.Add("AgentData", AgentData);
            llDataStruct.Add("GroupData", GroupData);
            llDataStruct.Add("NewGroupData", NewGroupData);

            IEventQueue queue = remoteClient.Scene.RequestModuleInterface <IEventQueue>();

            if (queue != null)
            {
                queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), remoteClient.AgentId);
            }
        }
Example #33
0
        public IList <IObjRelationResult> GetObjRelations(IList <IObjRelation> objRels, ICacheIntern targetCache, CacheDirective cacheDirective)
        {
            CheckNotDisposed();
            IEventQueue eventQueue = EventQueue;

            if (eventQueue != null)
            {
                eventQueue.Pause(this);
            }
            try
            {
                bool oldCacheModificationValue = CacheModification.Active;
                bool acquireSuccess            = AcquireHardRefTLIfNotAlready(objRels.Count);
                CacheModification.Active = true;
                try
                {
                    if (SecurityActive && ((targetCache == null && Privileged) || (targetCache != null && targetCache.Privileged) &&                 //
                                           SecurityActivation != null && SecurityActivation.FilterActivated))
                    {
                        return(SecurityActivation.ExecuteWithoutFiltering(delegate()
                        {
                            return Parent.GetObjRelations(objRels, targetCache, cacheDirective);
                        }));
                    }
                    else
                    {
                        return(Parent.GetObjRelations(objRels, targetCache, cacheDirective));
                    }
                }
                finally
                {
                    CacheModification.Active = oldCacheModificationValue;
                    ClearHardRefs(acquireSuccess);
                }
            }
            finally
            {
                if (eventQueue != null)
                {
                    eventQueue.Resume(this);
                }
            }
        }
Example #34
0
        /// <summary>
        /// Tries to teleport agent to landmark.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="regionHandle"></param>
        /// <param name="position"></param>
        public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
        {
            m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}",
                              (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position);
            if (lm.Gatekeeper == string.Empty)
            {
                base.RequestTeleportLandmark(remoteClient, lm);
                return;
            }

            GridRegion info = m_aScene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);

            // Local region?
            if (info != null)
            {
                ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
                                                                      Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
                return;
            }
            else
            {
                // Foreign region
                Scene scene = (Scene)(remoteClient.Scene);
                GatekeeperServiceConnector gConn = new GatekeeperServiceConnector();
                GridRegion gatekeeper            = new GridRegion();
                gatekeeper.ServerURI = lm.Gatekeeper;
                GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID));
                if (finalDestination != null)
                {
                    ScenePresence         sp          = scene.GetScenePresence(remoteClient.AgentId);
                    IEntityTransferModule transferMod = scene.RequestModuleInterface <IEntityTransferModule>();
                    IEventQueue           eq          = sp.Scene.RequestModuleInterface <IEventQueue>();
                    if (transferMod != null && sp != null && eq != null)
                    {
                        transferMod.DoTeleport(sp, gatekeeper, finalDestination, lm.Position,
                                               Vector3.UnitX, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark), eq);
                    }
                }
            }

            // can't find the region: Tell viewer and abort
            remoteClient.SendTeleportFailed("The teleport destination could not be found.");
        }
Example #35
0
        internal StatsManager(IEventQueue queue, IClock clock, CurrentStatsState state)
        {
            if (queue == null)
            {
                throw new ArgumentNullException(nameof(queue));
            }
            if (clock == null)
            {
                throw new ArgumentNullException(nameof(clock));
            }
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            this.queue = queue;
            this.clock = clock;
            this.state = state;
        }
Example #36
0
        public WorkloadListener()
        {
            switch (QueueType)
            {
            case EventQueueType.MMF:
                Events = new MMFEventQueue();
                break;

            case EventQueueType.LiteDB:
                throw new NotImplementedException();

            case EventQueueType.Sqlite:
                throw new NotImplementedException();

            case EventQueueType.BinarySerialized:
                Events            = new BinarySerializedBufferedEventQueue();
                Events.BufferSize = 10000;
                break;
            }
        }
Example #37
0
        /// <summary>
        /// Enqueues a <see cref="ShutdownRequestEvent"/>.
        /// </summary>
        /// <param name="eventQueue">The <see cref="IEventQueue"/> to use.</param>
        /// <param name="onRequestHandled">An optional delegate invoked sometime after the event finished being handled. It may not get called, if the event queue is suspended or being shut down. Check the return value to know whether you can reasonably expect it.</param>
        /// <param name="file">The source file of the caller.</param>
        /// <param name="member">The method or property name of the caller to this method.</param>
        /// <param name="line">The line number in <paramref name="file"/>.</param>
        /// <returns><c>true</c> if the event was enqueued successfully and you can expect a callback once it's done being handled; otherwise, <c>false</c>.</returns>
        public static bool RequestShutdown(
            this IEventQueue eventQueue,
            Action <ShutdownRequestEvent> onRequestHandled = null,
            [CallerFilePath] string file     = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line      = 0)
        {
            Action <EventBase> action = null;

            if (onRequestHandled.NotNullReference())
            {
                action = e => onRequestHandled((ShutdownRequestEvent)e);
            }

            return(eventQueue.Enqueue(
                       new ShutdownRequestEvent(),
                       action,
                       file,
                       member,
                       line));
        }
Example #38
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            GetDte();
            GetStatusbar();
            GetCodeModelProvider();
            RegisterLanguageService();
            RegisterIcons();
            ClearTempDirectory();


            this.solutionMonitor      = new SolutionMonitor();
            this.templateController   = new TemplateController(dte);
            this.eventQueue           = new EventQueue(statusBar);
            this.generationController = new GenerationController(dte, metadataProvider, templateController, eventQueue);
            RenderTemplate.Initialize(this);

            WireupEvents();
            ErrorList.Initialize(this);
        }
Example #39
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            GetDte();
            GetStatusbar();
            GetCodeModelProvider();
            RegisterLanguageService();
            RegisterIcons();
            ClearTempDirectory();
            
            
            this.solutionMonitor = new SolutionMonitor();
            this.templateController = new TemplateController(dte);
            this.eventQueue = new EventQueue(statusBar);
            this.generationController = new GenerationController(dte, metadataProvider, templateController, eventQueue);
            RenderTemplate.Initialize(this);

            WireupEvents();
            ErrorList.Initialize(this);
        }
Example #40
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'parseTypeResourcePropertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Resource Parse Type Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionParseTypeResourcePropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Parse Type Resource Property Element");
            }

            //Get the first Event, should be an ElementEvent
            //Type checking is done by the Parent Production
            IRdfXmlEvent first = eventlist.Dequeue();
            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);

            //Apply Namespaces
            this.ApplyNamespaces(context, element);

            //Validate Attributes
            String ID = String.Empty;
            if (element.Attributes.Count > 2)
            {
                //Can't be more than 2 Attributes, only allowed an optional rdf:ID and a required rdf:parseType
                throw ParserHelper.Error("An Property Element with Parse Type 'Resource' was encountered with too many Attributes.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Resource'", "Parse Type Resource Property Element", element);
            }
            else
            {
                //Check the attributes that do exist
                foreach (AttributeEvent a in element.Attributes)
                {
                    if (RdfXmlSpecsHelper.IsIDAttribute(a))
                    {
                        ID = "#" + a.Value;
                    }
                    else if (a.QName.Equals("rdf:parseType"))
                    {
                        //OK
                    }
                    else
                    {
                        //Invalid Attribute
                        throw ParserHelper.Error("Unexpected Attribute '" + a.QName + "' was encountered on a Property Element with Parse Type 'Resource'.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Resource'", "Parse Type Resource Property Element", element);
                    }
                }
            }

            //Add a Triple about this
            INode subj, pred, obj;

            //Get the Subject from the Parent
            ElementEvent parentEvent = (ElementEvent)parent;
            subj = parentEvent.SubjectNode;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID.Substring(1), subj);
            }

            //Create the Predicate from the Element
            pred = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);

            //Generate a Blank Node ID for the Object
            obj = context.Handler.CreateBlankNode();

            //Assert
            if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();

            //Reify if applicable
            if (!ID.Equals(String.Empty))
            {
                //Resolve the Uri
                UriReferenceEvent uriref = new UriReferenceEvent(ID, String.Empty);
                IUriNode uri = this.Resolve(context, uriref,element.BaseUri);

                this.Reify(context, uri, subj, pred, obj);
            }

            //Get the next event in the Queue which should be either an Element Event or a End Element Event
            //Validate this
            IRdfXmlEvent next = eventlist.Dequeue();
            if (next is EndElementEvent)
            {
                //Content is Empty so nothing else to do
            }
            else if (next is ElementEvent)
            {
                //Non-Empty Content so need to build a sequence of new events
                IEventQueue<IRdfXmlEvent> subEvents = new EventQueue<IRdfXmlEvent>();

                //Create an rdf:Description event as the container
                ElementEvent descrip = new ElementEvent("rdf:Description", element.BaseUri, String.Empty);
                descrip.Subject = new BlankNodeIDEvent(String.Empty);
                descrip.SubjectNode = obj;
                subEvents.Enqueue(descrip);

                //Add the current element we were looking at
                subEvents.Enqueue(next);

                //Add rest of events in list (exceot the last)
                while (eventlist.Count > 1)
                {
                    subEvents.Enqueue(eventlist.Dequeue());
                }

                //Terminate with an EndElement Event
                subEvents.Enqueue(new EndElementEvent());

                //Process with Node Element Production
                this.GrammarProductionNodeElement(context, subEvents);

                //Get the last thing in the List
                next = eventlist.Dequeue();
            }
            else
            {
                throw ParserHelper.Error("Unexpected Event '" + next.GetType().ToString() + "', expected an ElementEvent or EndElementEvent after a Parse Type Resource Property Element!", "Parse Type Resource Property Element", next);
            }

            //Check for the last thing being an EndElement Event
            if (!(next is EndElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + next.GetType().ToString() + "', expected an EndElementEvent to terminate a Parse Type Resource Property Element!", "Parse Type Resource Property Element", next);
            }
        }
 /// <summary>
 /// Creates a new Parser Context which uses Streaming parsing
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="stream">Stream</param>
 public RdfXmlParserContext(IGraph g, Stream stream)
     : base(g)
 {
     this._queue = new StreamingEventQueue(new StreamingEventGenerator(stream, g.BaseUri.ToSafeString()));
 }
 public void RegionLoaded(Scene scene)
 {
     m_eventQueue = scene.RequestModuleInterface<IEventQueue>();
     m_profileConnector = Aurora.DataManager.DataManager.RequestPlugin<IProfileConnector>();
 }
        protected void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
        {
            if (reg == null || finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

            m_log.DebugFormat(
                "[ENTITY TRANSFER MODULE]: Request Teleport to {0}:{1}:{2}/{3}",
                reg.ExternalHostName, reg.HttpPort, finalDestination.RegionName, position);

            uint newRegionX = (uint)(reg.RegionHandle >> 40);
            uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
            uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
            uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);

            ulong destinationHandle = finalDestination.RegionHandle;

            if (eq == null)
                sp.ControllingClient.SendTeleportLocationStart();

            // Let's do DNS resolution only once in this process, please!
            // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
            // it's actually doing a lot of work.
            IPEndPoint endPoint = finalDestination.ExternalEndPoint;
            if (endPoint.Address != null)
            {
                // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
                // both regions
                if (sp.ParentID != (uint)0)
                    sp.StandUp();

                if (!sp.ValidateAttachments())
                {
                    sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
                    return;
                }

                // the avatar.Close below will clear the child region list. We need this below for (possibly)
                // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
                //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
                // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
                // failure at this point (unlike a border crossing failure).  So perhaps this can never fail
                // once we reach here...
                //avatar.Scene.RemoveCapsHandler(avatar.UUID);

                string capsPath = String.Empty;

                AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
                AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
                agentCircuit.startpos = position;
                agentCircuit.child = true;
                agentCircuit.Appearance = sp.Appearance;
                if (currentAgentCircuit != null)
                {
                    agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
                    agentCircuit.Viewer = currentAgentCircuit.Viewer;
                }

                if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    // brand new agent, let's create a new caps seed
                    agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
                }

                string reason = String.Empty;

                // Let's create an agent there if one doesn't exist yet. 
                if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason))
                {
                    sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
                                                                              reason));
                    return;
                }

                // OK, it got this agent. Let's close some child agents
                sp.CloseChildAgents(newRegionX, newRegionY);

                if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    #region IP Translation for NAT
                    IClientIPEndpoint ipepClient;
                    if (sp.ClientView.TryGet(out ipepClient))
                    {
                        capsPath
                            = "http://"
                              + NetworkUtil.GetHostFor(ipepClient.EndPoint, finalDestination.ExternalHostName)
                              + ":"
                              + finalDestination.HttpPort
                              + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                    }
                    else
                    {
                        capsPath
                            = "http://"
                              + finalDestination.ExternalHostName
                              + ":"
                              + finalDestination.HttpPort
                              + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                    }
                    #endregion

                    if (eq != null)
                    {
                        #region IP Translation for NAT
                        // Uses ipepClient above
                        if (sp.ClientView.TryGet(out ipepClient))
                        {
                            endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
                        }
                        #endregion

                        eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);

                        // ES makes the client send a UseCircuitCode message to the destination, 
                        // which triggers a bunch of things there.
                        // So let's wait
                        Thread.Sleep(200);

                        eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);

                    }
                    else
                    {
                        sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
                    }
                }
                else
                {
                    agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
                    capsPath = "http://" + finalDestination.ExternalHostName + ":" + finalDestination.HttpPort
                                + "/CAPS/" + agentCircuit.CapsPath + "0000/";
                }

                // Expect avatar crossing is a heavy-duty function at the destination.
                // That is where MakeRoot is called, which fetches appearance and inventory.
                // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
                //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
                //                                                      position, false);

                //{
                //    avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
                //    // We should close that agent we just created over at destination...
                //    List<ulong> lst = new List<ulong>();
                //    lst.Add(reg.RegionHandle);
                //    SendCloseChildAgentAsync(avatar.UUID, lst);
                //    return;
                //}

                SetInTransit(sp.UUID);

                // Let's send a full update of the agent. This is a synchronous call.
                AgentData agent = new AgentData();
                sp.CopyTo(agent);
                agent.Position = position;
                SetCallbackURL(agent, sp.Scene.RegionInfo);

                UpdateAgent(reg, finalDestination, agent);

                m_log.DebugFormat(
                    "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);


                if (eq != null)
                {
                    eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
                                           0, teleportFlags, capsPath, sp.UUID);
                }
                else
                {
                    sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
                                                                teleportFlags, capsPath);
                }

                // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
                // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
                // that the client contacted the destination before we send the attachments and close things here.
                if (!WaitForCallback(sp.UUID))
                {
                    // Client never contacted destination. Let's restore everything back
                    sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");

                    ResetFromTransit(sp.UUID);

                    // Yikes! We should just have a ref to scene here.
                    //sp.Scene.InformClientOfNeighbours(sp);
                    EnableChildAgents(sp);

                    // Finally, kill the agent we just created at the destination.
                    m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);

                    return;
                }


                // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
                CrossAttachmentsIntoNewRegion(finalDestination, sp, true);

                KillEntity(sp.Scene, sp.LocalId);

                sp.MakeChildAgent();
                // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone

                if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
                {
                    Thread.Sleep(5000);
                    sp.Close();
                    sp.Scene.IncomingCloseAgent(sp.UUID);
                }
                else
                    // now we have a child agent in this region. 
                    sp.Reset();


                // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
                if (sp.Scene.NeedSceneCacheClear(sp.UUID))
                {
                    m_log.DebugFormat(
                        "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
                        sp.UUID);
                }
            }
            else
            {
                sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
            }
        }
 /// <summary>
 /// Creates a new Parser Context which uses Streaming parsing
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="input">Input</param>
 public RdfXmlParserContext(IGraph g, TextReader input)
     : base(g)
 {
     this._queue = new StreamingEventQueue(new StreamingEventGenerator(input, g.BaseUri.ToSafeString()));
 }
Example #45
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing) return;

            if (this.eventQueue != null)
            {
                this.eventQueue.Dispose();
                this.eventQueue = null;
            }
        }
 /// <summary>
 /// Creates a new Parser Context which uses Streaming parsing
 /// </summary>
 /// <param name="handler">RDF Handler</param>
 /// <param name="input">Input</param>
 public RdfXmlParserContext(IRdfHandler handler, TextReader input)
     : base(handler)
 {
     this._queue = new StreamingEventQueue(new StreamingEventGenerator(input, String.Empty));
 }
Example #47
0
		public void Add(IEventQueue queue)
		{
			this.queues.Add(queue);
		}
Example #48
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'parseTypeCollectionPropertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Collection Parse Type Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionParseTypeCollectionPropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Parse Type Collection Property Element");
            }

            //Get the first Event, should be an ElementEvent
            //Type checking is done by the Parent Production
            IRdfXmlEvent first = eventlist.Dequeue();
            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);

            //Apply Namespaces
            this.ApplyNamespaces(context, element);

            //Validate Attributes
            String ID = String.Empty;
            if (element.Attributes.Count > 2)
            {
                //Can't be more than 2 Attributes, only allowed an optional rdf:ID and a required rdf:parseType
                throw ParserHelper.Error("An Property Element with Parse Type 'Collection' was encountered with too many Attributes.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Collection'", "Parse Type Collection Property Element", element);
            }
            else
            {
                //Check the attributes that do exist
                foreach (AttributeEvent a in element.Attributes)
                {
                    if (RdfXmlSpecsHelper.IsIDAttribute(a))
                    {
                        ID = "#" + a.Value;
                    }
                    else if (a.QName.Equals("rdf:parseType"))
                    {
                        //OK
                    }
                    else
                    {
                        //Invalid Attribute
                        throw ParserHelper.Error("Unexpected Attribute '" + a.QName + "' was encountered on a Property Element with Parse Type 'Collection'.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Collection'", "Parse Type Collection Property Element", element);
                    }
                }
            }

            //Build sequence of Blank Nodes
            IRdfXmlEvent next;
            IRdfXmlEvent nodeElement;

            Queue<ElementEvent> seqNodes = new Queue<ElementEvent>();
            while (eventlist.Count > 1)
            {
                #region Node Element Processing
                //Need to process the Node Element first

                //Create a new Sublist
                IEventQueue<IRdfXmlEvent> subevents = new EventQueue<IRdfXmlEvent>();
                int nesting = 0;
                nodeElement = eventlist.Peek();

                //Add Node Element to sequence
                seqNodes.Enqueue((ElementEvent)nodeElement);

                //Gather the Sublist taking account of nesting
                do
                {
                    next = eventlist.Dequeue();
                    subevents.Enqueue(next);

                    if (next is ElementEvent)
                    {
                        nesting++;
                    }
                    else if (next is EndElementEvent)
                    {
                        nesting--;
                    }
                } while (nesting > 0);

                //Call the next Grammar Production
                this.GrammarProductionNodeElement(context, subevents);

                #endregion
            }

            //Build a triple expressing the start of the list (which may be an empty list)
            INode subj, pred, obj;
            INode firstPred, restPred;
            INode b1, b2;

            //Subject comes from Parent
            ElementEvent parentElement = (ElementEvent)parent;
            subj = parentElement.SubjectNode;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID.Substring(1), subj);
            }

            //Predicate from the Element
            pred = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);

            if (seqNodes.Count > 0)
            {
                //Non-empty list
                ElementEvent node;

                //Get first Element from the Queue
                node = seqNodes.Dequeue();

                //Object is first thing in the Sequence which we create a Blank Node for
                b1 = context.Handler.CreateBlankNode();

                //Assert
                if (!context.Handler.HandleTriple(new Triple(subj, pred, b1))) ParserHelper.Stop();

                //Reify if applicable
                if (!ID.Equals(String.Empty))
                {
                    //Resolve the Uri
                    UriReferenceEvent uriref = new UriReferenceEvent(ID, String.Empty);
                    IUriNode uri = this.Resolve(context, uriref, element.BaseUri);

                    this.Reify(context, uri, subj, pred, b1);
                }

                //Set the first element in the list
                subj = b1;
                firstPred = context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListFirst));
                if (!context.Handler.HandleTriple(new Triple(subj, firstPred, node.SubjectNode))) ParserHelper.Stop();

                //Middle elements of the list
                restPred = context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListRest));
                while (seqNodes.Count >= 1)
                {
                    node = seqNodes.Dequeue();

                    //Set Node 2 to be the rest of the previous items list
                    b2 = context.Handler.CreateBlankNode();
                    if (!context.Handler.HandleTriple(new Triple(b1, restPred, b2))) ParserHelper.Stop();

                    //Set Node 2 to be the start of it's own list
                    if (!context.Handler.HandleTriple(new Triple(b2, firstPred, node.SubjectNode))) ParserHelper.Stop();

                    b1 = b2;
                }

                //Set last element of the list to have its rest as nil
                if (!context.Handler.HandleTriple(new Triple(b1, restPred, context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListNil))))) ParserHelper.Stop();
            }
            else
            {
                //Empty list

                //Object is therefore rdf:nil
                obj = context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfListNil));

                //Assert
                if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();

                //Reify if applicable
                if (!ID.Equals(String.Empty))
                {
                    //Resolve the Uri
                    UriReferenceEvent uriref = new UriReferenceEvent(ID, String.Empty);
                    IUriNode uri = this.Resolve(context, uriref, element.BaseUri);

                    this.Reify(context, uri, subj, pred, obj);
                }
            }

            //Check last event is an EndElementEvent
            next = eventlist.Dequeue();
            if (!(next is EndElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + next.GetType().ToString() + "', expected an EndElementEvent to terminate a Parse Type Collection Property Element!", "Parse Type Collection Property Element", next);
            }
        }
Example #49
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'nodeElementList'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events to apply the Production to</param>
        private void GrammarProductionNodeElementList(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTrace("Node Element List");
            }

            IRdfXmlEvent next;

            //Want to break up into a number of sublists
            while (eventlist.Count > 0)
            {
                //Create a new Sublist
                IEventQueue<IRdfXmlEvent> subevents = new EventQueue<IRdfXmlEvent>();
                int nesting = 0;

                //Gather the Sublist taking account of nesting
                do
                {
                    next = eventlist.Dequeue();
                    subevents.Enqueue(next);

                    if (next is ElementEvent)
                    {
                        nesting++;
                    }
                    else if (next is EndElementEvent)
                    {
                        nesting--;
                    }
                } while (nesting > 0);

                //Call the next Grammar Production
                this.GrammarProductionNodeElement(context, subevents);
            }
        }
Example #50
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'nodeElement'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Node Element and its Children to apply the Production to</param>
        private void GrammarProductionNodeElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Node Element");
            }

            //Get First Event in the Queue
            IRdfXmlEvent first = eventlist.Dequeue();

            //Check it's an ElementEvent
            if (!(first is ElementEvent))
            {
                //Unexpected Event
                throw ParserHelper.Error("Expected an ElementEvent but encountered a '" + first.GetType().ToString() + "'", "Node Element", first);
            }

            //Check it has a valid Uri
            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);
            this.ApplyNamespaces(context, element);
            if (!RdfXmlSpecsHelper.IsNodeElementUri(element.QName))
            {
                throw ParserHelper.Error("A Node Element was encountered with an invalid URI '" + element.QName + "' \nCore Syntax Terms, Old Syntax Terms and rdf:li cannot be used as Node Element URIs", "Node Element", element);
            }

            //Check the set of Attributes is Valid
            int limitedAttributesFound = 0;
            String ID = String.Empty;
            foreach (AttributeEvent attr in element.Attributes)
            {
                if (RdfXmlSpecsHelper.IsIDAttribute(attr))
                {
                    ID = attr.Value;
                    limitedAttributesFound++;

                    //Set the Subject
                    element.Subject = new UriReferenceEvent("#" + attr.Value, attr.SourceXml);
                }
                else if (RdfXmlSpecsHelper.IsNodeIDAttribute(attr))
                {
                    limitedAttributesFound++;

                    //Validate the Node ID
                    if (!XmlSpecsHelper.IsName(attr.Value))
                    {
                        throw ParserHelper.Error("The value '" + attr.Value + "' for rdf:nodeID is not valid, RDF Node IDs can only be valid Names as defined by the W3C XML Specification", "Node Element", attr);
                    }

                    //Set the Subject
                    element.Subject = new BlankNodeIDEvent(attr.Value, attr.SourceXml);
                }
                else if (RdfXmlSpecsHelper.IsAboutAttribute(attr))
                {
                    limitedAttributesFound++;

                    //Set the Subject
                    element.Subject = new UriReferenceEvent(attr.Value, attr.SourceXml);
                }
                else if (RdfXmlSpecsHelper.IsPropertyAttribute(attr))
                {
                    //Don't need to do anything here yet
                }
                else
                {
                    //Unknown and Unexpected Attribute Type
                    throw ParserHelper.Error("Unexpected Attribute '" + attr.QName + "' was encountered!", "Node Element", element);
                }

                //Can't have more than 1 of ID, Node ID or About Attributes
                if (limitedAttributesFound > 1)
                {
                    throw ParserHelper.Error("A Node Element can only have 1 of the following attributes: rdf:id, rdf:nodeID, rdf:about", "Node Element", element);
                }
            }

            //Generate a Blank Node ID if our Subject is empty
            if (element.Subject == null)
            {
                element.Subject = new BlankNodeIDEvent(element.SourceXml);
            }

            //Add statements as necessary
            INode subj, pred, obj;
            if (element.SubjectNode == null)
            {
                //Don't always want to drop in here since the SubjectNode may already be set elsewhere
                if (element.Subject is UriReferenceEvent)
                {
                    UriReferenceEvent uri = (UriReferenceEvent)element.Subject;
                    subj = this.Resolve(context, uri, element.BaseUri);
                }
                else if (element.Subject is BlankNodeIDEvent)
                {
                    BlankNodeIDEvent blank = (BlankNodeIDEvent)element.Subject;

                    //Select whether we need to generate an ID or if there's one given for the Blank Node
                    //Note that we let the Graph class handle generation of IDs
                    if (blank.Identifier.Equals(String.Empty))
                    {
                        subj = context.Handler.CreateBlankNode();
                    }
                    else
                    {
                        subj = context.Handler.CreateBlankNode(blank.Identifier);
                    }
                }
                else
                {
                    throw ParserHelper.Error("Unexpected Subject generated for a Triple", "Node Element", element.Subject);
                }
            } else {
                subj = element.SubjectNode;
            }

            //Set the Subject Node property of the Event for later reuse
            element.SubjectNode = subj;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID, subj);
            }

            if (!element.QName.Equals("rdf:Description") && !element.QName.Equals(":Description"))
            {
                //Assert a Triple regarding Type
                pred = context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));
                obj = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);
                if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();
            }

            //Go back over Attributes looking for property attributes
            foreach (AttributeEvent attr in element.Attributes)
            {
                if (RdfXmlSpecsHelper.IsPropertyAttribute(attr))
                {
                    if (attr.QName.Equals("rdf:type"))
                    {
                        //Generate a Type Triple
                        pred = context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));

                        //Resolve URIRef into a Uri Node
                        UriReferenceEvent uriref = new UriReferenceEvent(attr.Value, attr.SourceXml);
                        obj = this.Resolve(context, uriref, element.BaseUri);

                        if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();
                    }
                    else
                    {
                        //Generate a Property Triple
                        pred = context.Handler.CreateUriNode(UriFactory.Create(Tools.ResolveQName(attr.QName, context.Namespaces, context.BaseUri)));

                        //Add Language to Literal if necessary
                        if (element.Language.Equals(String.Empty))
                        {
                            obj = context.Handler.CreateLiteralNode(attr.Value);
                        }
                        else
                        {
                            obj = context.Handler.CreateLiteralNode(attr.Value, element.Language);
                        }

                        if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();
                    }
                }
            }

            //Handle Child Elements
            IEventQueue<IRdfXmlEvent> children = new EventQueue<IRdfXmlEvent>();
            while (eventlist.Count > 1)
            {
                children.Enqueue(eventlist.Dequeue());
            }
            if (children.Count > 0) this.GrammarProductionPropertyElementList(context, children, element);

            //Check Last Event in queue is an EndElement event
            IRdfXmlEvent last = eventlist.Dequeue();
            if (!(last is EndElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + last.GetType().ToString() + "', expected an EndElement Event", "NodeElement", last);
            }
        }
Example #51
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'parseTypeLiteralPropertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Literal Parse Type Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionParseTypeLiteralPropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Parse Type Literal Property Element");
            }

            //Get the first Event, should be an ElementEvent
            //Type checking is done by the Parent Production
            IRdfXmlEvent first = eventlist.Dequeue();
            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);

            //Apply Namespaces
            this.ApplyNamespaces(context, element);

            //Validate Attributes
            String ID = String.Empty;
            if (element.Attributes.Count > 2)
            {
                //Can't be more than 2 Attributes, only allowed an optional rdf:ID and a required rdf:parseType
                throw ParserHelper.Error("An Property Element with Parse Type 'Literal' was encountered with too many Attributes.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Literal'", "Parse Type Literal Property Element", element);
            }
            else
            {
                //Check the attributes that do exist
                foreach (AttributeEvent a in element.Attributes)
                {
                    if (RdfXmlSpecsHelper.IsIDAttribute(a))
                    {
                        ID = "#" + a.Value;
                    }
                    else if (a.QName.Equals("rdf:parseType"))
                    {
                        //OK
                    }
                    else
                    {
                        //Invalid Attribute
                        throw ParserHelper.Error("Unexpected Attribute '" + a.QName + "' was encountered on a Property Element with Parse Type 'Literal'.  Only rdf:ID and rdf:parseType are allowed on Property Elements with Parse Type 'Literal'", "Parse Type Literal Property Element", element);
                    }
                }
            }

            //Get the next event in the Queue which should be a TypedLiteralEvent
            //Validate this
            IRdfXmlEvent lit = eventlist.Dequeue();
            if (!(lit is TypedLiteralEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + lit.GetType().ToString() + "', expected a TypedLiteralEvent after a Property Element with Parse Type 'Literal'", "Parse Type Literal Property Element", lit);
            }

            //Get the Subject from the Parent
            INode subj, pred, obj;
            ElementEvent parentEl = (ElementEvent) parent;
            subj = parentEl.SubjectNode;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID.Substring(1), subj);
            }

            //Create the Predicate from the Element
            pred = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);

            //Create the Object from the Typed Literal
            TypedLiteralEvent tlit = (TypedLiteralEvent)lit;
            //At the moment we're just going to ensure that we normalize it to Unicode Normal Form C
            String xmllit = tlit.Value;
            #if !NO_NORM
            xmllit = xmllit.Normalize();
            #endif
            obj = context.Handler.CreateLiteralNode(xmllit, UriFactory.Create(tlit.DataType));

            //Assert the Triple
            if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();

            //Reify if applicable
            if (!ID.Equals(String.Empty))
            {
                //Resolve the Uri
                UriReferenceEvent uriref = new UriReferenceEvent(ID, String.Empty);
                IUriNode uri = this.Resolve(context, uriref,element.BaseUri);

                this.Reify(context, uri, subj, pred, obj);
            }

            //Check for the last thing being an EndElement Event
            IRdfXmlEvent next = eventlist.Dequeue();
            if (!(next is EndElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + next.GetType().ToString() + "', expected an EndElementEvent to terminate a Parse Type Literal Property Element!", "Parse Type Literal Property Element", next);
            }
        }
Example #52
0
        public virtual void RegionLoaded(Scene scene)
        {
            if (!m_Enabled)
                return;

            m_eqModule = Scene.RequestModuleInterface<IEventQueue>();
            m_regionCombinerModule = Scene.RequestModuleInterface<IRegionCombinerModule>();
        }
Example #53
0
 public void RegionLoaded(Scene s)
 {
     m_scene.EventManager.OnRegisterCaps += RegisterCaps;
     m_eventQueue = m_scene.RequestModuleInterface<IEventQueue>();
 }
Example #54
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'propertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionPropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Property Element");
            }

            //Get first thing from the Queue
            IRdfXmlEvent first = eventlist.Dequeue();
            ElementEvent element;

            //Must be an ElementEvent
            if (!(first is ElementEvent))
            {
                //Unexpected Event
                throw ParserHelper.Error("Expected an ElementEvent but encountered a '" + first.GetType().ToString() + "'", "PropertyElement", first);
            }

            //Validate the Uri
            element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);
            this.ApplyNamespaces(context, element);
            if (!RdfXmlSpecsHelper.IsPropertyElementURI(element.QName))
            {
                //Invalid Uri
                throw ParserHelper.Error("A Property Element was encountered with an invalid URI '" + element.QName + "'\nCore Syntax Terms, Old Syntax Terms and rdf:Description cannot be used as Property Element URIs", "PropertyElement", element);
            }

            //List Expansion
            if (element.QName.Equals("rdf:li"))
            {
                UriReferenceEvent u = this.ListExpand(parent);
                element.SetUri(u);
            }

            //Need to select what to do based on the Type of Property Element
            IRdfXmlEvent next = eventlist.Peek();

            //This call inserts the first element back at the head of the queue
            //Most of the sub-productions here need this
            //Would ideally use Stacks instead of Queues but Queues make more sense for most of the Parsing
            this.QueueJump(eventlist, first);

            if (element.ParseType == RdfXmlParseType.None)
            {
                //A Resource/Literal Property Element

                if (next is ElementEvent)
                {
                    //Resource
                    this.GrammarProductionResourcePropertyElement(context, eventlist, parent);
                }
                else if (next is TextEvent)
                {
                    //Literal
                    this.GrammarProductionLiteralPropertyElement(context, eventlist, parent);
                }
                else if (next is EndElementEvent)
                {
                    //An Empty Property Element
                    this.GrammarProductionEmptyPropertyElement(context, element, parent);
                }
                else
                {
                    //Error
                    throw ParserHelper.Error("An Element which should be Parsed with the Default Parsing Rules was encountered without a valid subsequent Event - Parser cannot proceed!", "Property Element", element);
                }
            }
            else if (element.ParseType == RdfXmlParseType.Literal)
            {
                //A rdf:parseType="Literal" Property Element

                this.GrammarProductionParseTypeLiteralPropertyElement(context, eventlist, parent);
            }
            else if (element.ParseType == RdfXmlParseType.Collection)
            {
                //A rdf:parseType="Collection" Property Element

                this.GrammarProductionParseTypeCollectionPropertyElement(context, eventlist, parent);
            }
            else if (element.ParseType == RdfXmlParseType.Resource)
            {
                //A rdf:parseType="Resource" Property Element

                this.GrammarProductionParseTypeResourcePropertyElement(context, eventlist, parent);
            }
            else if (next is EndElementEvent)
            {
                //An Empty Property Element
                this.GrammarProductionEmptyPropertyElement(context, element, parent);
            }
            else
            {
                //Error
                throw ParserHelper.Error("An Element without a known Parse Type was encountered Or the Parser was unable to determine what to do based on the subsequent event - Parser cannot proceed!", "Node Element", element);
            }
        }
Example #55
0
 public EventHandler(IEventQueue eventQueue, IEventStore eventStore)
 {
     // TODO: Validate if input is null
     EventQueue = eventQueue;
     EventStore = eventStore;
 }
Example #56
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'resourcePropertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Resource Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionResourcePropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Resource Property Element");
            }

            //Cast to an ElementEvent
            //We don't validate type here since we know this will be an ElementEvent because the calling function
            //will have done this validation previously
            IRdfXmlEvent first = eventlist.Dequeue();
            IRdfXmlEvent next = eventlist.Peek();
            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);

            //Apply Namespaces
            this.ApplyNamespaces(context, element);

            //Only allowed one attribute max which must be an ID attribute
            String ID = String.Empty;
            if (element.Attributes.Count > 1)
            {
                throw ParserHelper.Error("A Resource Property Element contains too many Attributes, only rdf:ID is permitted", element);
            }
            else if (element.Attributes.Count == 1)
            {
                if (!RdfXmlSpecsHelper.IsIDAttribute(element.Attributes.First()))
                {
                    throw ParserHelper.Error("A Resource Property Element was encountered with a single attribute which was not rdf:ID, only rdf:ID is permitted", element);
                }
                else
                {
                    ID = element.Attributes.First().Value;
                }
            }

            //Next must be an ElementEvent
            if (!(next is ElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + next.GetType().ToString() + "', expected an ElementEvent as the first Event in a Resource Property Elements Event list", next);
            }

            //Get list of Sub Events
            IEventQueue<IRdfXmlEvent> subevents = new EventQueue<IRdfXmlEvent>();
            while (eventlist.Count > 1)
            {
                subevents.Enqueue(eventlist.Dequeue());
            }
            this.GrammarProductionNodeElement(context, subevents);

            //Check Last is an EndElementEvent
            IRdfXmlEvent last = eventlist.Dequeue();
            if (!(last is EndElementEvent))
            {
                throw ParserHelper.Error("Unexpected Event '" + last.GetType().ToString() + "', expected an EndElement Event", last);
            }

            //Now we can generate the relevant RDF
            INode subj, pred, obj;

            //Validate the Type of the Parent
            if (!(parent is ElementEvent))
            {
                throw ParserHelper.Error("Unexpected Parent Event '" + parent.GetType().ToString() + "', expected an ElementEvent", parent);
            }
            ElementEvent parentEl = (ElementEvent)parent;

            //Get the Subject Node from the Parent
            subj = parentEl.SubjectNode;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID, subj);
            }

            //Create a Predicate from this Element
            pred = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);

            //Get the Object Node from the Child Node
            ElementEvent child = (ElementEvent)next;
            obj = child.SubjectNode;

            //Assert the Triple
            if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();

            //Add Reification where appropriate
            if (element.Attributes.Count == 1)
            {
                //Must be an rdf:ID attribute as we've validated this earlier

                //Get the Attribute Event and generate a Uri from it
                AttributeEvent attr = element.Attributes.First();
                UriReferenceEvent uriref = new UriReferenceEvent("#" + attr.Value, attr.SourceXml);
                IUriNode uri = this.Resolve(context, uriref, element.BaseUri);

                this.Reify(context, uri, subj, pred, obj);
            }
        }
Example #57
0
        public virtual void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
        {
            sp.ControllingClient.SendTeleportProgress(teleportFlags, "sending_dest");
            if (reg == null || finalDestination == null)
            {
                sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
                return;
            }

            m_log.DebugFormat(
                "[ENTITY TRANSFER MODULE]: Request Teleport to {0}:{1}:{2}/{3}",
                reg.ExternalHostName, reg.HttpPort, finalDestination.RegionName, position);

            uint newRegionX = (uint)(reg.RegionHandle >> 40);
            uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
            uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
            uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);

            ulong destinationHandle = finalDestination.RegionHandle;

            // Let's do DNS resolution only once in this process, please!
            // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
            // it's actually doing a lot of work.
            IPEndPoint endPoint = finalDestination.ExternalEndPoint;
            if (endPoint.Address != null)
            {
                sp.ControllingClient.SendTeleportProgress(teleportFlags, "arriving");
                    
                if (m_cancelingAgents.Contains(sp.UUID))
                {
                    Cancel(sp);
                    return;
                }
                // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
                // both regions
                if (sp.ParentID != UUID.Zero)
                    sp.StandUp();

                if (!sp.ValidateAttachments())
                {
                    sp.ControllingClient.SendTeleportProgress(teleportFlags, "missing_attach_tport");
                    sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
                    return;
                }

                string capsPath = String.Empty;

                AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
                AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
                agentCircuit.startpos = position;
                agentCircuit.child = true;
                agentCircuit.Appearance = sp.Appearance;
                if (currentAgentCircuit != null)
                {
                    agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
                    agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
                    agentCircuit.Viewer = currentAgentCircuit.Viewer;
                    agentCircuit.Channel = currentAgentCircuit.Channel;
                    agentCircuit.Mac = currentAgentCircuit.Mac;
                    agentCircuit.Id0 = currentAgentCircuit.Id0;
                }

                if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    // brand new agent, let's create a new caps seed
                    agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
                }

                string reason = String.Empty;
                // Let's create an agent there if one doesn't exist yet. 
                bool logout = false;
                if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
                {
                    sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
                                                                              reason));
                    return;
                }

                // OK, it got this agent. Let's close some child agents
                sp.CloseChildAgents(newRegionX, newRegionY);

                if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY))
                {
                    //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");

                    #region IP Translation for NAT
                    IClientIPEndpoint ipepClient;
                    if (sp.ClientView.TryGet(out ipepClient))
                    {
                        capsPath
                            = "http://"
                              + NetworkUtil.GetHostFor(ipepClient.EndPoint, finalDestination.ExternalHostName)
                              + ":"
                              + finalDestination.HttpPort
                              + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                    }
                    else
                    {
                        capsPath
                            = "http://"
                              + finalDestination.ExternalHostName
                              + ":"
                              + finalDestination.HttpPort
                              + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
                    }
                    #endregion

                    if (eq != null)
                    {
                        #region IP Translation for NAT
                        // Uses ipepClient above
                        if (sp.ClientView.TryGet(out ipepClient))
                        {
                            endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
                        }
                        #endregion

                        eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);

                        // ES makes the client send a UseCircuitCode message to the destination, 
                        // which triggers a bunch of things there.
                        // So let's wait
                        Thread.Sleep(200);

                        eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);

                    }
                    else
                    {
                        sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
                    }
                }
                else
                {
                    agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
                    capsPath = "http://" + finalDestination.ExternalHostName + ":" + finalDestination.HttpPort
                                + "/CAPS/" + agentCircuit.CapsPath + "0000/";
                }

                if (m_cancelingAgents.Contains(sp.UUID))
                {
                    Cancel(sp);
                    return;
                }

                SetInTransit(sp.UUID);

                // Let's send a full update of the agent. This is a synchronous call.
                AgentData agent = new AgentData();
                sp.CopyTo(agent);
                agent.Position = position;
                SetCallbackURL(agent, sp.Scene.RegionInfo);

                //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent...");

                if (!UpdateAgent(reg, finalDestination, agent))
                {
                    // Region doesn't take it
                    Fail(sp, finalDestination);
                    return;
                }

                m_log.DebugFormat(
                    "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);

                if (eq != null)
                {
                    eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
                                           0, teleportFlags, capsPath, sp.UUID, teleportFlags);
                }
                else
                {
                    sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
                                                                teleportFlags, capsPath);
                }

                // Let's set this to true tentatively. This does not trigger OnChildAgent
                sp.IsChildAgent = true;

                // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
                // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
                // that the client contacted the destination before we send the attachments and close things here.
                
                //OpenSim sucks at callbacks, disable it for now
                
                if (!WaitForCallback(sp.UUID))
                {
                    /*//Make sure the client hasn't TPed back in this time.
                    ScenePresence SP = m_aScene.GetScenePresence(sp.UUID);
                    if (SP != null && SP.IsChildAgent)
                    {
                        //Disabling until this actually helps and doesn't kill clients
                        //Fail(sp, finalDestination);
                        return;
                    }
                    else if (SP == null)
                    {
                        //Err.. this happens somehow.
                        return;
                    }*/
                }

                /*//Make sure the client hasn't TPed back in this time.
                ScenePresence newSP = m_aScene.GetScenePresence(sp.UUID);
                if (newSP != null && !newSP.IsChildAgent)
                {
                    //They are root again, don't cross them!
                    return;
                }
                else if (newSP == null)
                {
                    //Err.. this happens somehow.
                    return;
                }*/


                // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
                CrossAttachmentsIntoNewRegion(finalDestination, sp, true);

                // Well, this is it. The agent is over there.

                KillEntity(sp.Scene, sp.LocalId);

                // May need to logout or other cleanup
                AgentHasMovedAway(sp.ControllingClient.SessionId, logout);

                // Now let's make it officially a child agent
                sp.MakeChildAgent();

                // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone

                if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
                {
                    Thread.Sleep(5000);
                    sp.Close();
                    sp.Scene.IncomingCloseAgent(sp.UUID);
                }
                else
                    // now we have a child agent in this region. 
                    sp.Reset();

                //If they canceled too late, remove them so the next tp does not fail.
                if (m_cancelingAgents.Contains(sp.UUID))
                    m_cancelingAgents.Remove(sp.UUID);
            }
            else
            {
                sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
            }
        }
Example #58
0
        /// <summary>
        /// Helper function which inserts an Element back on the front of a Queue
        /// </summary>
        /// <param name="eventlist">Queue to insert onto the Front of</param>
        /// <param name="evt">Event to put on the front of the Queue</param>
        private void QueueJump(IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent evt)
        {
            Stack<IRdfXmlEvent> temp = new Stack<IRdfXmlEvent>();
            temp.Push(evt);

            while (eventlist.Count > 0)
            {
                temp.Push(eventlist.Dequeue());
            }

            foreach (IRdfXmlEvent e in temp.Reverse())
            {
                eventlist.Enqueue(e);
            }
        }
 /// <summary>
 /// Creates a new Parser Context which uses Streaming parsing
 /// </summary>
 /// <param name="handler">RDF Handler</param>
 /// <param name="stream">Stream</param>
 public RdfXmlParserContext(IRdfHandler handler, Stream stream)
     : base(handler)
 {
     this._queue = new StreamingEventQueue(new StreamingEventGenerator(stream, String.Empty));
 }
Example #60
0
        /// <summary>
        /// Implementation of the RDF/XML Grammar Production 'literalPropertyElt'
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="eventlist">Queue of Events that make up the Literal Property Element and its Children</param>
        /// <param name="parent">Parent Event (ie. Node) of the Property Element</param>
        private void GrammarProductionLiteralPropertyElement(RdfXmlParserContext context, IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent parent)
        {
            //Tracing
            if (this._traceparsing)
            {
                this.ProductionTracePartial("Literal Property Element");
            }

            //Get the 3 Events (should only be three)
            IRdfXmlEvent first, middle, last;
            first = eventlist.Dequeue();
            middle = eventlist.Dequeue();
            last = eventlist.Dequeue();

            //If Queue is non-empty then Error
            if (eventlist.Count > 0)
            {
                throw ParserHelper.Error("Too many events encountered while trying to parse a Literal Property Element", first);
            }

            ElementEvent element = (ElementEvent)first;
            if (this._traceparsing) this.ProductionTracePartial(element);

            //Apply Namespaces
            this.ApplyNamespaces(context, element);

            //Validate that the middle event is a TextEvent
            if (!(middle is TextEvent))
            {
                throw ParserHelper.Error("Unexpected event '" + middle.GetType().ToString() + "', expected a TextEvent in a Literal Property Element", middle);
            }
            TextEvent text = (TextEvent)middle;

            //Validate the Attributes
            String ID = String.Empty;
            String datatype = String.Empty;
            if (element.Attributes.Count > 2)
            {
                throw ParserHelper.Error("A Literal Property Element contains too many attributes, only rdf:ID and rdf:datatype are permitted", element);
            }
            else
            {
                //Only rdf:ID and rdf:datatype allowed
                foreach (AttributeEvent a in element.Attributes)
                {
                    if (RdfXmlSpecsHelper.IsIDAttribute(a)) {
                        ID = "#" + a.Value;
                    }
                    else if (RdfXmlSpecsHelper.IsDataTypeAttribute(a))
                    {
                        datatype = a.Value;
                    }
                    else
                    {
                        throw ParserHelper.Error("A Literal Property Element contains an unexpected attribute, only rdf:ID and rdf:datatype are permitted", element);
                    }
                }
            }

            //Create the Nodes for the Graph
            INode subj, pred, obj;

            //Get the Subject from the Parent
            ElementEvent parentEl = (ElementEvent)parent;
            subj = parentEl.SubjectNode;

            //Validate the ID (if any)
            if (!ID.Equals(String.Empty))
            {
                this.ValidateID(context, ID.Substring(1), subj);
            }

            //Create a Predicate from this Element
            pred = this.Resolve(context, element);//context.Handler.CreateUriNode(element.QName);

            //Create an Object from the Text Event
            if (datatype.Equals(String.Empty))
            {
                //No Type with possible Language
                if (element.Language.Equals(String.Empty))
                {
                    obj = context.Handler.CreateLiteralNode(text.Value);
                }
                else
                {
                    obj = context.Handler.CreateLiteralNode(text.Value, element.Language);
                }
            }
            else
            {
                //Typed

                //Resolve the Datatype Uri
                UriReferenceEvent dtref = new UriReferenceEvent(datatype, String.Empty);
                IUriNode dturi = this.Resolve(context, dtref, element.BaseUri);

                obj = context.Handler.CreateLiteralNode(text.Value, dturi.Uri);
            }

            //Assert the Triple
            if (!context.Handler.HandleTriple(new Triple(subj, pred, obj))) ParserHelper.Stop();

            //Reify if applicable
            if (!ID.Equals(String.Empty))
            {
                //Resolve the Uri
                UriReferenceEvent uriref = new UriReferenceEvent(ID, String.Empty);
                IUriNode uri = this.Resolve(context, uriref,element.BaseUri);

                this.Reify(context, uri, subj, pred, obj);
            }
        }