Dispatches an event

@throws \RuntimeException when the container is not present
@throws \RuntimeException when the site directory is not readable
761521
protected function dispatchEvent($event)
    {
        if (!$this->container) {
            throw new \RuntimeException("The container has not been set up.");
        }
        $dir = $this->container->getParameter('base_dir');
        if (!is_dir($dir) || !is_readable($dir)) {
            throw new \RuntimeException("'${dir}' is not a valid readable directory.");
        }
        $dispatcher = $this->container->get('event_dispatcher');
        $dispatcher->dispatch($event);
    }
95951
public function handleEvent(ActionEvent $event)
    {
        if (!$this->scopeDeterminator->currentScopeIsBackend()) {
            return;
        }

        $environment = $event->getEnvironment();

        if (null === ($serializedId = $this->getModelId($environment))) {
            return;
        }

        $operation = $this->getOperation($event->getAction(), $environment);
        if (!($operation instanceof ToggleCommandInterface)) {
            return;
        }

        if (false === $this->checkPermission($event)) {
            $event->stopPropagation();

            return;
        }

        $this->process($environment, $operation, $serializedId);
    }
566293
private function dispatchEvent($eventType, $filePath)
    {
        if (null !== $this->eventDispatcher) {
            $relativePath = $this->fs->makePathRelative(dirname($filePath), $this->root) . basename($filePath);
            $this->eventDispatcher->dispatch(
                $eventType,
                new ResourceEvent($relativePath, $this->httpRoot, $this->root)
            );

            if (null !== $this->imagineConfig) {
                if (false !== strpos($relativePath, '/../') || 0 === strpos($relativePath, '../')) {
                    // outside web root, stop.
                    return;
                }

                // Create events for the imagine cache as well.

                /** @var CacheManager $cacheManager */
                /** @var FilterConfiguration $filterConfig */
                list ($cacheManager, $filterConfig) = $this->imagineConfig;
                $webPath = $this->httpRoot . '/' . $relativePath;
                $cacheManager->remove($webPath);

                foreach ($filterConfig->all() as $name => $filter) {
                    $url = $cacheManager->resolve($webPath, $name);

                    // this weird construct is here because the imagine cache manager generates absolute urls
                    // even though they're local for some unapparent reason.
                    $relativeUrl = parse_url($url, PHP_URL_PATH);
                    $url = $this->fs->makePathRelative(dirname($relativeUrl), $this->httpRoot) . basename($relativeUrl);

                    if (false === strpos($url, '../')) {
                        $this->eventDispatcher->dispatch(
                            $eventType,
                            new ResourceEvent($url, $this->httpRoot, $this->root)
                        );
                    }
                }
            }
        }
    }
529052
public function run()
    {
        $environment    = $this->itemContainer->getEnvironment();
        $inputProvider  = $environment->getInputProvider();
        $sessionStorage = $environment->getSessionStorage();

        // Ajax request.
        // @codingStandardsIgnoreStart - We need POST access here.
        if ($_POST && Environment::get('isAjaxRequest')) // @codingStandardsIgnoreEnd
        {
            $ajax = new Ajax($inputProvider->getValue('action'));
            $ajax->executePreActions();
        }

        $inputTable = $inputProvider->getParameter('table');
        $inputField = $inputProvider->getParameter('field');
        $inputId    = $inputProvider->getParameter('id');

        // Define the current ID.
        \define('CURRENT_ID', ($inputTable ? $sessionStorage->get('CURRENT_ID') : $inputId));

        $dispatcher = $GLOBALS['container']['event-dispatcher'];

        $translator = new TranslatorChain();
        $translator->add(new LangArrayTranslator($dispatcher));

        $this->itemContainer = (new DcGeneralFactory())
            ->setContainerName($inputTable)
            ->setTranslator($translator)
            ->setEventDispatcher($dispatcher)
            ->createDcGeneral();

        $information = (array) $GLOBALS['TL_DCA'][$inputTable]['fields'][$inputField];

        if (!isset($information['eval'])) {
            $information['eval'] = [];
        }

        // Merge with the information from the data container.
        $property = $environment
            ->getDataDefinition()
            ->getPropertiesDefinition()
            ->getProperty($inputField);
        $extra    = $property->getExtra();

        $information['eval'] = \array_merge($extra, $information['eval']);

        $property->setExtra(\array_merge($property->getExtra(), $information['eval']));

        $dataProvider = $environment->getDataProvider();
        $model        = $dataProvider->getEmptyModel();
        if ($inputProvider->getParameter('id')) {
            $modelId = ModelId::fromSerialized($inputProvider->getParameter('id'));
            $model   = $dataProvider->fetch($dataProvider->getEmptyConfig()->setId($modelId->getId()));
        }

        /** @var \ContaoCommunityAlliance\DcGeneral\Contao\View\Contao2BackendView\TreePicker $treeSelector */
        $treeSelector        = (new WidgetBuilder($environment))->buildWidget($property, $model);
        $treeSelector->value = \array_filter(\explode(',', $inputProvider->getParameter('value')));

        // AJAX request.
        if (isset($ajax)) {
            $treeSelector->generateAjax();
            $ajax->executePostActions(new DcCompat($environment));
        }


        $template = new ContaoBackendViewTemplate('be_main');
        $template
            ->set('isPopup', true)
            ->set('main', $treeSelector->generatePopup())
            ->set('theme', Backend::getTheme())
            ->set('base', Environment::get('base'))
            ->set('language', $GLOBALS['TL_LANGUAGE'])
            ->set('title', StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['treepicker']))
            ->set('charset', $GLOBALS['TL_CONFIG']['characterSet'])
            ->set('addSearch', $treeSelector->searchField)
            ->set('search', $GLOBALS['TL_LANG']['MSC']['search'])
            ->set('action', \ampersand(Environment::get('request')))
            ->set('value', $sessionStorage->get($treeSelector->getSearchSessionKey()))
            ->set('manager', $GLOBALS['TL_LANG']['MSC']['treepickerManager'])
            ->set('breadcrumb', $GLOBALS['TL_DCA'][$treeSelector->foreignTable]['list']['sorting']['breadcrumb'])
            ->set('managerHref', '');

        // Add the manager link.
        if ($treeSelector->managerHref) {
            $template
                ->set('managerHref', 'contao?' . \ampersand($treeSelector->managerHref) . '&amp;popup=1');
        }

        // Prevent debug output at all cost.
        $GLOBALS['TL_CONFIG']['debugMode'] = false;
        $template->output();
    }
1074750
public function eventCall()
    {
        try {
            //Daemon::log('cb - '.Debug::zdump($this->cb));
            $func = $this->cb;
            $func($this);
        } catch (\Exception $e) {
            Daemon::uncaughtExceptionHandler($e);
        }
    }
1164318
final public function dispatch(Event $event): void
    {
        if (!$event instanceof ReceivedEvent && $this->discriminator->shouldEnqueue($event)) {
            $this->queue->send($event);
        }

        if ($event instanceof ReceivedEvent) {
            $event = $event->getOriginalEvent();
        }

        $this->wrappedEventBus->dispatch($event);
    }
650236
public function setActionByDispatchName($dispatchName)
    {
        if (array_key_exists($dispatchName, $this->availableEvents)) {
            $this->action = $this->availableEvents[$dispatchName];
        } else {
            throw new \RuntimeException('Document Model event dispatch type not found: ' . $dispatchName);
        }
    }
134393
public function onDispatch(SystemEvent $event)
    {
        $server  = $this->getServer();
        $request = $server->getRequest();

        $controllerName = $request->getAttribute('controller');
        if (! $controllerName) {
            throw new RuntimeException(
                'Unable to dispatch the system event, the server request not '
                . 'contains the "controller" attribute.'
            );
        }
        $actionName = $request->getAttribute('action', 'index');

        $events = $this->getEvents();

        $controllers = $this->getControllers();
        $controller  = $controllers->get($controllerName);
        $event->setContext($controller);

        $dispatchEvent = new DispatchEvent(
            $controller, $controllerName, $actionName, $event->getParams()
        );

        $events->trigger($dispatchEvent);
        $result = $dispatchEvent->getResult();
        $target = SystemEvent::DISPATCH;
        if ($result instanceof ResponseInterface) {
            $target = SystemEvent::FINISH;
        }
        $event->setResult($target, $result);
    }
229523
protected void dispatch() {
    // Event Based ----------------------------------------------------------
    if (isEventBased()) {
      // Current State: IDLE
      // Event: Request in storage
      // Action: Send stored request
      // New State: PENDING_B
      if (buffer != null) {
        setState(ClientRxSessionState.PENDING_BUFFERED);
        try {
          dispatchEvent(new AppRequestEventImpl(messageFromBuffer(ByteBuffer.wrap(buffer))));
        }
        catch (Exception e) {
          try {
            handleSendFailure(e, Event.Type.SEND_EVENT_REQUEST, messageFromBuffer(ByteBuffer.wrap(buffer)));
          }
          catch (Exception e1) {
            logger.error("Failure handling buffer send failure", e1);
          }
        }
      }
    } // Session Based --------------------------------------------------------
    else {
      if (sessionData.getClientRxSessionState() == ClientRxSessionState.OPEN && eventQueue.size() > 0) {
        try {
          this.handleEvent(eventQueue.remove(0));
        }
        catch (Exception e) {
          logger.error("Failure handling queued event", e);
        }
      }
    }
  }
1215764
protected void dispatch(Object event, EventHandler wrapper) {
    try {
      wrapper.handleEvent(event);
    } catch (InvocationTargetException e) {
      throwRuntimeException(
          "Could not dispatch event: " + event.getClass() + " to handler " + wrapper, e);
    }
  }
53328
private void handleEvent(CmsEvent event) {

        switch (event.getType()) {
            case I_CmsEventListener.EVENT_PUBLISH_PROJECT:
                //System.out.print(getEventName(event.getType()));
                String publishIdStr = (String)event.getData().get(I_CmsEventListener.KEY_PUBLISHID);
                if (publishIdStr != null) {
                    CmsUUID publishId = new CmsUUID(publishIdStr);
                    try {
                        List<CmsPublishedResource> publishedResources = m_cms.readPublishedResources(publishId);
                        if (!publishedResources.isEmpty()) {
                            String[] typesToMatch = new String[] {TYPE_PROPERTIES_BUNDLE, TYPE_XML_BUNDLE};
                            boolean reload = false;
                            for (CmsPublishedResource res : publishedResources) {
                                for (String typeName : typesToMatch) {
                                    if (OpenCms.getResourceManager().matchResourceType(typeName, res.getType())) {
                                        reload = true;
                                        break;
                                    }
                                }
                            }
                            if (reload) {
                                scheduleReload();
                            }
                        }
                    } catch (CmsException e) {
                        LOG.error(e.getLocalizedMessage(), e);
                    }
                }
                break;
            case I_CmsEventListener.EVENT_CLEAR_CACHES:
                scheduleReload();
                break;
            default:
        }
    }
68380
public function on_garbage_collection()
	{
		if (substr($GLOBALS['request']->server('SCRIPT_NAME'), -7) === 'app.php')
		{
			return;
		}

		// An Exception is throw because the TraceableEventDispatcher
		// stop all the events when KernelEvents::RESPONSE is trigger.
		// But because we are emulating the event through the
		// garbage_collection event, we got an exception at the end
		// of the dispatching of the event.
		// (stop() is called on an already stopped() event)
		set_exception_handler(array($this, 'exception_handler'));

		try {
			$response = new Response('<html><body></body></html>');
			$this->dispatcher->dispatch(KernelEvents::RESPONSE,
				new FilterResponseEvent(
					$this->http_kernel,
					$this->request_stack->getCurrentRequest(),
					HttpKernelInterface::MASTER_REQUEST,
					$response
				));

			if ($this->redirect_url !== null)
			{
				$url = $this->redirect_url;

				// Redirect via an HTML form for PITA webservers
				if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
				{
					header('Refresh: 0; URL=' . $url);

					echo '<!DOCTYPE html>';
					echo '<html dir="Direction" lang="en">';
					echo '<head>';
					echo '<meta charset="utf-8">';
					echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
					echo '<title>Redirect</title>';
					echo '</head>';
					echo '<body>';
					echo '<div style="text-align: center;"><a href="' . str_replace('&', '&amp;', $url) . '">Redirect</a></div>';
					echo '</body>';
					echo '</html>';

					$this->dispatcher->dispatch(KernelEvents::TERMINATE,
					new PostResponseEvent($this->http_kernel,
							$this->request_stack->getCurrentRequest(),
							$response
						)
					);
					exit;
				}

				// Behave as per HTTP/1.1 spec for others
				header('Location: ' . $url);
				$this->dispatcher->dispatch(KernelEvents::TERMINATE,
					new PostResponseEvent($this->http_kernel,
						$this->request_stack->getCurrentRequest(),
						$response
					)
				);
				exit;
			}
			else if ($response->getContent() !== '<html><body></body></html>')
			{
				if ('<html><body></body></html>' !== $response->getContent())
				{
					echo $response->getContent();
				}
			}

			$this->dispatcher->dispatch(KernelEvents::TERMINATE,
				new PostResponseEvent($this->http_kernel,
					$this->request_stack->getCurrentRequest(),
					$response
				)
			);
		}
		catch (\Exception $e)
		{dump($e);
		}
	}
451480
public function handle(EventInterface $event)
    {

        try {
            // load the application server and the naming directory instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */
            $namingDirectory = $applicationServer->getNamingDirectory();

            // write a log message that the event has been invoked
            $applicationServer->getSystemLogger()->info($event->getName());

            // deploy the applications for all containers
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
            foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) {
                // load the container instance to deploy the applications for
                /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */
                $container = $namingDirectory->search(
                    sprintf(
                        'php:services/%s/%s',
                        $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK),
                        $containerNode->getName()
                    )
                );

                // iterate over all applications and shut them down
                /** @var \AppserverIo\Psr\Application\ApplicationInterface $application */
                foreach ($container->getApplications() as $application) {
                    $application->stop();
                }
            }

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
919834
public function cmdGetEvent()
    {
        $result = $this->getListEvent();
        $this->outputFormat($result);
        $this->outputFormatTableEvent($result);
        $this->output();
    }
851103
public function dispatch($name, Event $event = null)
    {
        if (! $this->hasListener($name)) return;

        if (! $event) $event = new Event();
        $event->setDispatcher($this);
        $event->setName($name);

        foreach ($this->getListners($name) as $listener) {
            call_user_func($listener, $event);
            if ($event->isStop()) break;
        }
    }
1285796
public void handleEvent(Event event) {
        String topic = event.getTopic();
        if (topic.equals(TOPIC_QUEUED_WORK_NAME)) {
            Runnable r = event.getProperty(KEY_RUNNABLE, Runnable.class);
            if (null != r) {
                r.run();
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Unable to find runnable in event; " + topic);
                }
            }
        }
    }
983109
private function prepare()
    {
        try {
            $projectRoot = dirname(__DIR__, 4);
            if (!$this->router) {
                $this->useRoute($projectRoot . DIRECTORY_SEPARATOR . "route.json");
            }
            if (!$this->logDirectory) {
                $this->useLogger($projectRoot . DIRECTORY_SEPARATOR . "log");
            }
            $this->getErrorHandler()->register();
            unset($this->logDirectory);
        } catch (InvalidArgumentException $e) {
            throw new RuntimeException(
                "Can't prepare application: " . $e->getMessage());
        }
    }