Run the application

@throws Exception on error
511147
public function run() {
        try {
            $this
                ->loadComposerFile()
                ->loadArgs()
                ->parseOptions()
                ->parseArguments()
                ->loadOptionalConfigFiles()
                ->loadAdditionalConfigFiles()
                ->addRuntimeSettings()
                ->configureLogger()
                ->satisfyUserChoice();
        } catch (Exception $exception) {
            $this->abort($exception);
        }
    }
62983
public function run()
    {
        $this->run_called = true;
        $this->hook('beforeRender');
        $this->is_rendering = true;

        // if no App layout set
        if (!isset($this->html)) {
            throw new Exception(['App layout should be set.']);
        }

        $this->html->template->set('title', $this->title);
        $this->html->renderAll();
        $this->html->template->appendHTML('HEAD', $this->html->getJS());
        $this->is_rendering = false;
        $this->hook('beforeOutput');

        if (isset($_GET['__atk_callback']) && $this->catch_runaway_callbacks) {
            $this->terminate('!! Callback requested, but never reached. You may be missing some arguments in '.$_SERVER['REQUEST_URI']);
        }

        echo $this->html->template->render();
    }
763432
@Override
    public void run() {
        try {
            this.delegate.run();
        } catch (UndeclaredThrowableException ex) {
            this.errorHandler.handleError(ex.getUndeclaredThrowable());
        } catch (Throwable ex) {
            this.errorHandler.handleError(ex);
        }
    }
775791
public function runApplication()
    {
        $routeCollection = $this->createRouteCollection();
        $dispatcher = $routeCollection->getDispatcher();

        $request = $this->createRequest();
        $response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
        $response->send();
    }
958662
public function run()
    {
        try
        {
            $this['triggers']->callTrigger('before-match-request', $this);

            $this['request']->attributes->add(
                $this['router']->matchRequest($this['request'])
            );

            $this['triggers']->callTrigger('before-controller-resolver', $this);

            $this['response'] = $this->controllerResolver();
        }
        catch (ResourceNotFoundException $e)
        {
            $this['response'] = (new Controller($this))->serve404();
        }
        catch (\Exception $e)
        {
            $this['response'] = new Response();
            $this['response']->headers->set('Content-Type', 'text/plain');
            $this['response']->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
            $this['response']->setContent($e->getMessage());
        }

        if ($this['x-frame-options']) {
            $this['response']->headers->set('x-frame-options', $this['x-frame-options']);
        }

        $this['response']->prepare($this['request']);

        $this['triggers']->callTrigger('before-send-response', $this);

        $this['response']->send();
    }
1047290
private void run(String[] arguments) throws Exception {

        if(isHelpRequested(arguments)) {
            usage();
        }

        validateArguments(arguments);

        checkTemporaryDirectory(arguments);


        addShutdownHook();

        File war = getWarLocation();

        File tempDirectory = createTempDirectory(war.getName(), getPort(arguments));

        cl = createClassLoader(war, tempDirectory);

        Thread.currentThread().setContextClassLoader(cl);

        startJettyConsole(cl, arguments, tempDirectory);
    }
1244052
protected function run()
    {
        $this->silentRunActionTrigger(Action::EVENT_START);
        try {
            $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS;
            $this->context->exitCode = 0;
        } catch (ErrorException $errorException) {
            $event = Action::EVENT_ERROR;
            $this->context->exception = $errorException;
            $this->context->exitCode = 2;
        } catch (Exception $exception) {
            $event = Action::EVENT_FAILURE;
            $this->context->exception = $exception;
            $this->context->exitCode = 1;
        }
        $this->context->finishTime = time();
        $this->silentRunActionTrigger($event);
        $this->silentRunActionTrigger(Action::EVENT_FINISH);
    }
250413
public function run()
    {
        try {

            // ~ Hook for console help
            if (! $this->argument->has('name')) {

                // ~ Display Help
                $this->help();

                // ~ If no help asked, throw exception !
                if (! $this->argument->has('help')) {
                    throw new \Exception(__METHOD__ . '|Script name must be defined !');
                }

                return;
            }

            // ~ Create new object '*'
            $className = $this->argument->get('name');
            $script = new $className();

            if (!($script instanceof ConsoleInterface)) {
                throw new \Exception('Current script must be implement ConsoleInterface interface !');
            }

            if (! $script->executable()) {
                throw new \Exception(__METHOD__ . '|Script is not executable !');
            }

            $style = new Style(' >>> RUN - ' . $className . ' - ' . date('Y-m-d H:i:s') . ' <<<');
            $style->color('fg', Style::COLOR_GREEN);

            if ($this->argument->has('help')) {

                Out::std($style->get());

                $script->help();
            } else {

                // ~ Execute this method before starting main script method
                $script->before();

                // ~ Display header script only after execution of before method (prevent error with start_session() for example).
                Out::std($style->get());

                // ~ Execute main script method.
                $script->run();

                // ~ Execute this method after execution of main script method.
                $script->after();
            }
        } catch (\Exception $exception) {

            if (! $this->isVerbose) {
                throw $exception;
            }

            $style = new Style(' ~~ EXCEPTION[' . $exception->getCode() . ']: ' . $exception->getMessage());
            $style->color('bg', Style::COLOR_RED);
            Out::std(PHP_EOL . $style->get());

            if ($this->argument->has('debug')) {
                echo $exception->getTraceAsString(), PHP_EOL;
            }
        }
    }
411037
public function run()
    {

        try {
            // register the default autoloader
            require SERVER_AUTOLOADER;

            // register shutdown handler
            register_shutdown_function(array(&$this, "shutdown"));

            // add the application instance to the environment
            Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $this);

            // create s simulated request/session ID whereas session equals request ID
            Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString());
            Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId);

            // log a message that we now start to connect the application
            $this->getInitialContext()->getSystemLogger()->debug(sprintf('%s wait to be connected', $this->getName()));

            // register the class loaders
            $this->registerClassLoaders();

            // register the annotation registries
            $this->registerAnnotationRegistries();

            // initialize the managers
            $this->initializeManagers();

            // provision the application
            if ($this->getContainer()->hasProvisioningEnabled()) {
                $this->provision();
            }

            // initialize the profile logger and the thread context
            $profileLogger = null;
            /** @var \AppserverIo\Logger\ThreadSafeLoggerInterface $profileLogger */
            if ($profileLogger = $this->getInitialContext()->getLogger(LoggerUtils::PROFILE)) {
                $profileLogger->appendThreadContext('application');
            }

            // invoke the application's managers postStartup() lifecycle callbacks
            $this->postStartupManagers();

            // the application has successfully been initialized
            $this->synchronized(function ($self) {
                $self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL);
            }, $this);

            // log a message that we has successfully been connected now
            \info(sprintf('%s has successfully been connected', $this->getName()));

            // initialize the flag to keep the application running
            $keepRunning = true;

            // wait till application will be shutdown
            while ($keepRunning) {
                // query whether we've a profile logger, log resource usage
                if ($profileLogger) {
                    $profileLogger->debug(sprintf('Application %s is running', $this->getName()));
                }

                // wait a second to lower system load
                $keepRunning = $this->synchronized(function ($self) {
                    $self->wait(100000 * Application::TIME_TO_LIVE);
                    return $self->applicationState->equals(ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL));
                }, $this);
            }

            // log a message that we has successfully been shutdown now
            \info(sprintf('%s start to shutdown managers', $this->getName()));

            // array for the manager shutdown threads
            $shutdownThreads = array();

            // we need to stop all managers, because they've probably running threads
            /** @var \AppserverIo\Psr\Application\ManagerInterface $manager */
            foreach ($this->getManagers() as $manager) {
                $shutdownThreads[] = new ManagerShutdownThread($manager);
            }

            // wait till all managers have been shutdown
            /** @var \AppserverIo\Appserver\Application\ManagerShutdownThread $shutdownThread */
            foreach ($shutdownThreads as $shutdownThread) {
                $shutdownThread->join();
            }

            // the application has been shutdown successfully
            $this->synchronized(function ($self) {
                $self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::SHUTDOWN);
            }, $this);

            // cleanup the naming directory with the application entries
            $this->unload();

            // log a message that we has successfully been shutdown now
            \info(sprintf('%s has successfully been shutdown', $this->getName()));

        } catch (\Exception $e) {
            LoggerUtils::log(LogLevel::ERROR, $e);
        }
    }
476747
public function run()
    {
        if(empty($this->name))
            throw new Exception(Yii::t('fproject/yii2-flex','FlexWidget.name cannot be empty.'));
        if(empty($this->baseUrl))
            throw new Exception(Yii::t('fproject/yii2-flex','FlexWidget.baseUrl cannot be empty.'));
        if($this->altHtmlContent===null)
            $this->altHtmlContent=Yii::t('fproject/yii2-flex','This content requires the {link}',[
                'link' => '<a href="http://www.adobe.com/go/getflash/">Adobe Flash Player</a>.',
            ]);

        $this->registerClientScript();

        return $this->render('flexWidget', [
            'name' => $this->name,
            'logoUrl' => $this->logoUrl,
            'flashVersion' => $this->flashVersion,
            'baseUrl' => $this->baseUrl,
            'flashVarsAsString' => $this->flashVarsAsString,
            'quality' => $this->quality,
            'bgColor' => $this->bgColor,
            'allowScriptAccess' => $this->allowScriptAccess,
            'allowFullScreen' => $this->b2s($this->allowFullScreen),
            'allowFullScreenInteractive' => $this->b2s($this->allowFullScreenInteractive),
            'width' => $this->width,
            'height' => $this->height,
            'align' => $this->align,
        ]);
    }
21671
public function run() {
        try {
            $request  = $this->getLoops()->getService("request");
            $response = $this->getLoops()->getService("response");
            $web_core = $this->getLoops()->getService("web_core");

            //dispatch request
            echo $web_core->dispatch($this->url, $request, $response);
        }
        catch(Throwable $exception) {
            http_response_code(500);

            try {
                $renderer = $this->getLoops()->getService("renderer");
                echo $renderer->render($exception);
            }
            catch(Throwable $render_exception) {
                Misc::displayException($exception);
            }
        }
    }
1043563
@Override
  public void run()
  {
    try {
      runImpl();
    } catch (final Throwable e) {
      // env/0203 vs env/0206
      if (e instanceof DisplayableException)
        log.warning(e.getMessage());
      else
        log.warning(e.toString());
      
      _exception = e;
    } finally {
      notifyComplete();
    }
  }
759805
public void run() {
		if (logger.isDebugEnabled()){
    		logger.debug("run");
    	}
		
		final SipContext sipContext = sipFactoryImpl.getSipApplicationDispatcher().findSipApplication(key.getApplicationName());
		if(sipContext != null) {
			SipManager sipManager = sipContext.getSipManager();
			final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
					key.getApplicationName(), 
					key.getApplicationSessionId(),
					null);								
			MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
			MobicentsSipSession sipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);	
					
			if(sipSession != null) {				
				boolean batchStarted = false;
				ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
				try {
					sipContext.enterSipContext();	
					sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
					batchStarted = sipContext.enterSipAppHa(true);
					
					work.doAsynchronousWork(sipSession);
				} catch(Throwable t) {
					logger.error("An unexpected exception happened in the SipSessionAsynchronousWork callback on sip session " + key, t);
				} finally {
					sipContext.exitSipAppHa(null, null, batchStarted);
					sipContext.exitSipApp(sipApplicationSession, sipSession);
					sipContext.exitSipContext(oldClassLoader);				
				}
			} else {
				if(logger.isDebugEnabled()) {
					logger.debug("SipSession " + key + " couldn't be found, it may have been already invalidated.");
				}
			}
		}
	}
506488
public void run() throws Exception {
        if (ranges == null) {
            throw new ModelsIllegalargumentException("No ranges have been defined for the parameter space.", this);
        }

        createSwarm();
        double[] previous = null;
        while( iterationStep <= maxIterations ) {
            updateSwarm();

            if (printStep()) {
                System.out.println(prefix + " - ITER: " + iterationStep + " global best: " + globalBest + " - for positions: "
                        + Arrays.toString(globalBestLocations));
            }

            if (function.hasConverged(globalBest, globalBestLocations, previous)) {
                break;
            }
            previous = globalBestLocations.clone();
        }
    }
1312689
@Override
    public void run() throws Exception {
        QueueContainer queueContainer = getContainer();
        if (queueContainer.hasEnoughCapacity(txSize + 1)) {
            response = queueContainer.txnOfferReserve(transactionId);
        }
    }
335060
public void compileAndRun() throws Exception {
		synchronized (this.monitor) {
			try {
				stop();
				Class<?>[] compiledSources = compile();
				monitorForChanges();
				// Run in new thread to ensure that the context classloader is setup
				this.runThread = new RunThread(compiledSources);
				this.runThread.start();
				this.runThread.join();
			}
			catch (Exception ex) {
				if (this.fileWatchThread == null) {
					throw ex;
				}
				else {
					ex.printStackTrace();
				}
			}
		}
	}
559454
@SuppressWarnings({"unchecked"})
    public void run() throws Exception {
        LOG.info("Starting JstormMaster");
        Credentials credentials =
                UserGroupInformation.getCurrentUser().getCredentials();
        DataOutputBuffer dob = new DataOutputBuffer();
        credentials.writeTokenStorageToStream(dob);
        // Now remove the AM->RM token so that containers cannot access it.
        Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
        LOG.info("Executing with tokens:");
        while (iter.hasNext()) {
            Token<?> token = iter.next();
            LOG.info(token);
            if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
                iter.remove();
            }
        }
        jstormMasterContext.allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());

        // Create appSubmitterUgi and add original tokens to it
        String appSubmitterUserName =
                System.getenv(ApplicationConstants.Environment.USER.name());
        appSubmitterUgi =
                UserGroupInformation.createRemoteUser(appSubmitterUserName);
        appSubmitterUgi.addCredentials(credentials);


        AMRMClientAsync.CallbackHandler allocListener = new RMCallbackHandler();
        amRMClient = AMRMClientAsync.createAMRMClientAsync(JOYConstants.AM_RM_CLIENT_INTERVAL, allocListener);
        jstormMasterContext.amRMClient = amRMClient;
        amRMClient.init(conf);
        amRMClient.start();

        containerListener = createNMCallbackHandler();
        nmClientAsync = new NMClientAsyncImpl(containerListener);
        nmClientAsync.init(conf);
        nmClientAsync.start();

        startTimelineClient(conf);
        if (timelineClient != null) {
            publishApplicationAttemptEvent(timelineClient, jstormMasterContext.appAttemptID.toString(),
                    DSEvent.DS_APP_ATTEMPT_START, jstormMasterContext.domainId, appSubmitterUgi);
        }


        // Register self with ResourceManager
        // This will start heartbeating to the RM
        jstormMasterContext.appMasterHostname = NetUtils.getHostname();
        //get available port
        buildPortScanner();
        jstormMasterContext.appMasterThriftPort = portScanner.getAvailablePort();

        //since appMasterRpcPort not used yet,  set appMasterRpcPort to appMasterThriftPort
        jstormMasterContext.appMasterRpcPort = jstormMasterContext.appMasterThriftPort;

        RegisterApplicationMasterResponse response = amRMClient
                .registerApplicationMaster(jstormMasterContext.appMasterHostname, jstormMasterContext.appMasterRpcPort,
                        jstormMasterContext.appMasterTrackingUrl);
        // Dump out information about cluster capability as seen by the
        // resource manager
        jstormMasterContext.maxMemory = response.getMaximumResourceCapability().getMemory();
        LOG.info("Max mem capability of resources in this cluster " + jstormMasterContext.maxMemory);

        jstormMasterContext.maxVcores = response.getMaximumResourceCapability().getVirtualCores();
        LOG.info("Max vcores capability of resources in this cluster " + jstormMasterContext.maxVcores);

        // A resource ask cannot exceed the max.
        if (jstormMasterContext.containerMemory > jstormMasterContext.maxMemory) {
            LOG.info("Container memory specified above max threshold of cluster."
                    + " Using max value." + ", specified=" + jstormMasterContext.containerMemory + ", max="
                    + jstormMasterContext.maxMemory);
            jstormMasterContext.containerMemory = jstormMasterContext.maxMemory;
        }

        if (jstormMasterContext.containerVirtualCores > jstormMasterContext.maxVcores) {
            LOG.info("Container virtual cores specified above max threshold of cluster."
                    + " Using max value." + ", specified=" + jstormMasterContext.containerVirtualCores + ", max="
                    + jstormMasterContext.maxVcores);
            jstormMasterContext.containerVirtualCores = jstormMasterContext.maxVcores;
        }

        List<Container> previousAMRunningContainers =
                response.getContainersFromPreviousAttempts();
        LOG.info(jstormMasterContext.appAttemptID + " received " + previousAMRunningContainers.size()
                + " previous attempts' running containers on AM registration.");
        jstormMasterContext.numAllocatedContainers.addAndGet(previousAMRunningContainers.size());

        //Setup RegistryOperations
        registryOperations = RegistryOperationsFactory.createInstance(JOYConstants.YARN_REGISTRY, conf);
        setupInitialRegistryPaths();
        registryOperations.start();

        //add previous AM containers to supervisor and nimbus container list
        for (Container container : previousAMRunningContainers) {

            String containerPath = RegistryUtils.componentPath(
                    JOYConstants.APP_TYPE, jstormMasterContext.instanceName,
                    container.getId().getApplicationAttemptId().getApplicationId().toString(), container.getId().toString());
            ServiceRecord sr = null;
            try {
                if (!registryOperations.exists(containerPath)) {

                    String contianerHost = container.getNodeId().getHost();
                    registryOperations.mknode(containerPath, true);
                    sr = new ServiceRecord();
                    sr.set(JOYConstants.HOST, contianerHost);
                    sr.set(YarnRegistryAttributes.YARN_ID, container.getId().toString());
                    sr.description = JOYConstants.CONTAINER;
                    sr.set(YarnRegistryAttributes.YARN_PERSISTENCE,
                            PersistencePolicies.CONTAINER);
                    registryOperations.bind(containerPath, sr, BindFlags.OVERWRITE);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (container.getPriority().getPriority() == 0)
                jstormMasterContext.supervisorContainers.add(container);
            else if (container.getPriority().getPriority() == 1) {
                jstormMasterContext.nimbusContainers.add(container);
            }
        }

        jstormMasterContext.requestBlockingQueue = new LinkedBlockingQueue<ContainerRequest>();

        jstormMasterContext.service_user_name = RegistryUtils.currentUser();

        jstormMasterContext.instanceName = conf.get(JOYConstants.INSTANCE_NAME_KEY);
        this.jstormMasterContext.user = conf.get(JOYConstants.JSTORM_YARN_USER);
        this.jstormMasterContext.password = conf.get(JOYConstants.JSTORM_YARN_PASSWORD);
        this.jstormMasterContext.oldPassword = conf.get(JOYConstants.JSTORM_YARN_OLD_PASSWORD);

        LOG.info("find available port for am rpc server which is : " + jstormMasterContext.appMasterThriftPort);

        String appPath = RegistryUtils.servicePath(
                JOYConstants.APP_TYPE, jstormMasterContext.instanceName, jstormMasterContext.appAttemptID.getApplicationId().toString());
        String instancePath = RegistryUtils.serviceclassPath(
                JOYConstants.APP_TYPE, jstormMasterContext.instanceName);

        LOG.info("Registering application " + jstormMasterContext.appAttemptID.getApplicationId().toString());

        ServiceRecord application = setupServiceRecord();
        jstormMasterContext.nimbusDataDirPrefix = conf.get(JOYConstants.INSTANCE_DATA_DIR_KEY);
        LOG.info("generate instancePath on zk , path is:" + instancePath);

        if (registryOperations.exists(instancePath)) {
            ServiceRecord previousRegister = registryOperations.resolve(instancePath);
            application.set(JOYConstants.NIMBUS_HOST, previousRegister.get(JOYConstants.NIMBUS_HOST, JOYConstants.EMPTY));
            application.set(JOYConstants.NIMBUS_CONTAINER, previousRegister.get(JOYConstants.NIMBUS_CONTAINER, JOYConstants.EMPTY));
            application.set(JOYConstants.NIMBUS_LOCAL_DIR, previousRegister.get(JOYConstants.NIMBUS_LOCAL_DIR, JOYConstants.EMPTY));

            jstormMasterContext.previousNimbusHost = previousRegister.get(JOYConstants.NIMBUS_HOST, "");

            Date now = new Date();
            Map<String, ServiceRecord> apps = RegistryUtils.listServiceRecords(registryOperations, instancePath);
            for (String subAppPath : apps.keySet()) {
                LOG.info("existApp:" + subAppPath);
                ServiceRecord subApp = apps.get(subAppPath);
                Long lastHeatBeatTime = 0l;
                try {
                    lastHeatBeatTime = Long.parseLong(subApp.get(JOYConstants.APP_HEARTBEAT_TIME));
                } catch (Exception e) {
                    LOG.error(e);
                }
                if (now.getTime() - lastHeatBeatTime > 5 * JOYConstants.HEARTBEAT_TIME_INTERVAL
                        || lastHeatBeatTime > now.getTime() || subAppPath.trim().equals(appPath.trim())) {
                    LOG.info("application " + subAppPath + " not response , delete it!");
                    registryOperations.delete(subAppPath, true);
                }
            }
        }

        if (!jstormMasterContext.done) {
            jstormMasterContext.config = conf;
            registryOperations.mknode(appPath, true);
            registryOperations.bind(instancePath, application, BindFlags.OVERWRITE);
            ServiceRecord previousRegister = registryOperations.resolve(instancePath);
            LOG.info("previousRegister:" + previousRegister.toString());
            LOG.info("register path: " + instancePath);
            AMServer as = new AMServer(jstormMasterContext.appMasterThriftPort);
            as.Start(this);
        }
    }