应用启动事件

@param Event $event
@param Application $app
433420
public function boot(Event $event, Application $app)
    {
        /** @var IConfig $config */
        $config = $this->di->get('config');
        //获取概率xhprof
        $prob = (int)$config->get('xhprof.prob', 1);
        if ($prob <= 0 || $prob > 1) {
            $prob = 1;
        }
        $mtMax = intval(1 / $prob);
        //在一定概率下执行
        if (mt_rand(1, $mtMax) == 1) {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
            $this->xhprofOn = true;
        }
    }
60784
public function terminate(Event $event, IApp $app)
    {
        if ($this->xhprofOn) {
            /** @var IConfig $config */
            $config = $this->di->get('config');
            /** @var LoggerAdapterInterface $logger */
            $logger = $config->get('xhprof.logger');
            $data = xhprof_disable();
            $logger->log($data);
        }
    }
293177
protected function startEventsPlugin($app)
    {
        $this->onRegister('events', function ($app) {
            $events = $this->app->make(Dispatcher::class);

            foreach ($this->events() as $event => $listeners) {
                foreach ($listeners as $listener) {
                    $events->listen($event, $listener);
                }
            }
//        })
//        $this->onBoot('events', function ($app) {
//            $events = $this->app->make('events');

            foreach ($this->listens() as $event => $listeners) {
                foreach ($listeners as $listener) {
                    $events->listen($event, $listener);
                }
            }

            foreach ($this->subscribe as $subscriber) {
                $events->subscribe($subscriber);
            }
        });
    }
271639
protected function closeWebSocket(Container $app): void
    {
        /* @var Channel $channel */
        try {
            $channel = $this->currentChannel($this->fd);
        } catch (\Exception $exception) {
            echo "closeWebSocket: {$exception->getMessage()}, fd:{$this->fd}".PHP_EOL;
            $channel = null;
        }

        if (is_null($channel)) {
            return;
        }

        $websocket = (new Socket($app, $channel))->setFd($this->fd);

        $app->instance('websocket', $websocket);

        try {
            if ($channel->eventExists('disconnection')) {
                $channel->dispatch('disconnection');
            }
        } catch (\Exception $exception) {
            throw $exception;
        } finally {
            $websocket->leave();
        }
    }
609492
public function dispatchEvent($event) {
		$type = $event->getType();
		if (isset($this->eventsListeners[$type])) {
			for ($j = 0; $j < count($this->eventsListeners[$type]); $j++) {
				list($plugin, $action) = explode(':', $this->eventsListeners[$type][$j]);
				//加载plugin && 调用action
				//echo $type.'<br/>';
				$this->app->runPluginAction($plugin, $action, $event);
			}
		}
		
	}
462146
protected void doPublishEvent(final ApplicationEvent e) {
        if (applicationEventPublisher != null) {
            LOGGER.trace("Publishing [{}]", e);
            this.applicationEventPublisher.publishEvent(e);
        }
    }
564525
protected function handle(Event $event): void
    {
        $method = 'apply'.ClassName::short($event);

        if (!method_exists($this, $method)) {
            return;
        }

        $this->$method($event);
    }
891634
public void init(Application app) {

        HMSAgentLog.d("init");

        // 保存应用程序context
        context = app.getApplicationContext();

        // 取得应用程序包名
        curAppPackageName = app.getPackageName();

        // 注册activity onResume回调
        ActivityMgr.INST.unRegisterActivitResumeEvent(this);
        ActivityMgr.INST.registerActivitResumeEvent(this);

        // 注册activity onPause回调
        ActivityMgr.INST.unRegisterActivitPauseEvent(this);
        ActivityMgr.INST.registerActivitPauseEvent(this);

        // 注册activity onDestroyed 回调
        ActivityMgr.INST.unRegisterActivitDestroyedEvent(this);
        ActivityMgr.INST.registerActivitDestroyedEvent(this);
    }
1035331
public static function run(Application $app)
    {
        $config = Config::getOrEmpty('application');
        $debug  = (bool)Arr::get($config, 'debug', false);
        define('DEBUG', $debug);

        self::setUpErrorHandling($debug);
        self::configure($config);
        self::bootstrap($config);
        self::initAPI($config, $app);

        Session::start();

        foreach (Arr::get($config, 'response.defaultHeaders', []) as $header) {
            header($header);
        }
    }
160921
public function handle(EventInterface $event)
    {

        try {
            // load the application server instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();

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

            // print a message with the old UID/EUID
            $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());

            // extract the variables
            $uid = 0;
            extract(posix_getpwnam('root'));

            // switcht the effective UID to the passed user
            if (posix_seteuid($uid) === false) {
                $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid));
            }

            // print a message with the new UID/EUID
            $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());

            // @TODO Switch group also!!!!

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
614040
public void onApplicationEvent(ApplicationEvent event) {

        // All events we care about are subtypes of ClientSecurityEvent
        if( event instanceof ClientSecurityEvent ) {
            Authentication authentication = (Authentication) event.getSource();

            if( logger.isDebugEnabled() ) {
                logger.debug( "RECEIVED ClientSecurityEvent: " + event );
                logger.debug( "Authentication token: " + authentication );
            }

            // Note that we need to inspect the new authentication token and see if it is
            // NO_AUTHENTICATION. If so, then we need to use null instead. This little
            // dance is required because the source of an event can't actually be null.

            if( authentication == ClientSecurityEvent.NO_AUTHENTICATION ) {
                if( logger.isDebugEnabled() ) {
                    logger.debug( "Converted NO_AUTHENTICATION to null" );
                }
                authentication = null;
            }

            // And dispatch according to the event type.

            if( event instanceof AuthenticationEvent ) {
                broadcastAuthentication( authentication );
            } else if( event instanceof LoginEvent ) {
                broadcastLogin( authentication );
            } else if( event instanceof LogoutEvent ) {
                broadcastLogout( authentication );
            } else {
                if( logger.isDebugEnabled() ) {
                    logger.debug( "Unsupported event not processed" );
                }
            }
        }
    }
1116491
public static function prepareMigrationTable(App $app): void{
        $migration = new class($app) extends Migration{

            /**
             * Create the migration table if it does not exist yet
             */
            public function up(): void{
                $schema = $this->getSchema('default');
                if (!$schema->hasTable('migrations')) {
                    $schema->create('migrations', function (Blueprint $table){
                        $table->increments('id');
                        $table->string('name', 255);
                    });
                }
            }

            /**
             * Is not needed, but add it nevertheless
             */
            public function down(): void{
                $this->getSchema('default')->drop('migrations');
            }
        };
        $migration->up();
    }
1198908
public function trigger($name, $event = null)
	{
		$this->ensureEvents();
		
		$this->ensureEventListeners();
		
		$this->bindEventListenersEvents();
		
		if (!empty($this->_events[$name])) {
		    // 增加事件处理的动态参数
		    $args = func_get_args();
		    array_shift($args);
		    
			if (!$event instanceof Event) {
				$event = new Event();
				array_unshift($args, $event);
			}
			if ($event->sender === null) {
				$event->sender = $this;
			}
			
			$event->name = $name;
			
			foreach ($this->_events[$name] as $handler) {
			    if (isset($handler[1]) && $handler[1]) {
			        $olddata = $handler[1];
			        $event->data = array_merge($olddata, $event->data);
			    }
			    
			    if (is_string($handler[0]) && strpos($handler[0], ':') === false) {
			        $callable = [$this, $handler[0]];
			    } else {
			        $callable = Ioc::resolveCallable($handler[0]);
			    }
			    
			    // call_user_func($callable, $event);
			    call_user_func_array($callable, $args);
			    
			    // stop further handling if the event is handled
			    if ($event->isPropagationStopped()) {
			        return;
			    }
			}
		}
		
		// invoke class-level attached handlers
		Event::trigger($this, $name, $event);
	}
687354
public function handle(EventInterface $event)
    {

        try {
            // load the application server and system configuration instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
            $systemConfiguration = $applicationServer->getSystemConfiguration();

            // load the initial context configuration
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\InitialContextConfigurationInterface $initialContextNode */
            $initialContextNode = $systemConfiguration->getInitialContext();
            $reflectionClass = new \ReflectionClass($initialContextNode->getType());
            /** @var \AppserverIo\Psr\ApplicationServer\ContextInterface $initialContext */
            $initialContext = $reflectionClass->newInstanceArgs(array($systemConfiguration));

            // attach the registered loggers to the initial context
            $initialContext->setLoggers($applicationServer->getLoggers());
            $initialContext->setSystemLogger($applicationServer->getSystemLogger());

            // set the initial context and flush it initially
            $applicationServer->setInitialContext($initialContext);

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
804075
protected function handle(Event $event)
    {
        $method = $this->getApplyMethod($event);
        if (!method_exists($this, $method)) {
            return;
        }
        $this->$method($event);
    }
1129564
public static function onApplicationStop(Event $event)
    {
        $container = $event->getTarget()->getContainer();
        $eventDispatcher = $container->has('event.dispatcher') ? $container->get('event.dispatcher') : null;

        foreach (array_keys($container->findTaggedServiceIds('bundle')) as $bundleId) {
            if (!$container->hasInstanceOf($bundleId)) {
                continue;
            }

            $bundle = $container->get($bundleId);
            $bundle->stop();

            if (null !== $eventDispatcher) {
                $eventDispatcher->dispatch(
                    sprintf('bundle.%s.stopped', $bundleId),
                    new BundleStopEvent($container->get($bundleId))
                );
            }
        }
    }
1223952
public function register(Application $app)
    {
        $app['events.order_subscriber'] = $app->share(function (Application $app) {
            $notifierRegistry = new ValidationNotifierRegistry();

            $notifierRegistry->registerNotifier(Order::NOTIFY_MAIL, new MailNotifier($app));
            $notifierRegistry->registerNotifier(Order::NOTIFY_WEBHOOK, new WebhookNotifier(
                new LazyLocator($app, 'manipulator.webhook-event')
            ));

            return new OrderSubscriber($app, $notifierRegistry);
        });
    }