Process HelloMessage

@param \Thruway\Session $session
@param \Thruway\Message\WelcomeMessage $msg
@throws InvalidRealmNameException
761300
private function processSendWelcome(Session $session, WelcomeMessage $msg)
    {
        $helloDetails = $session->getHelloMessage()->getDetails();

        if (is_object($helloDetails) && isset($helloDetails->roles) && is_object($helloDetails->roles)) {
            $session->setRoleFeatures($helloDetails->roles);
        }

        $session->setState(Session::STATE_UP); // this should probably be after authentication

        $details = $msg->getDetails();

        if (is_object($details) && isset($details->roles) && is_object($details->roles)) {
            $roles = array_filter((array) $details->roles, function($key) {
                return in_array($key, ['broker', 'dealer']);
            }, ARRAY_FILTER_USE_KEY);

            $details->roles = (object) $roles;
            $msg->setDetails($details);
        }
    }
897051
private function processAuthenticate(Session $session, AuthenticateMessage $msg)
    {
        $session->abort(new \stdClass(), 'thruway.error.internal');
        Logger::error($this, 'Authenticate sent to realm without auth manager.');
    }
863472
function sendMessage(CometSession $session)
    {
        $request = $this->wait_requests[$session->id];
        $response = new Swoole\Response;
        $response->setHeader('Access-Control-Allow-Origin', $this->origin);
        $response->body = json_encode(array('success' => 1, 'data' => $session->popMessage()));
        unset($this->wait_requests[$session->id]);
        return $this->response($request, $response);
    }
1076952
protected function createException(
        string $msg,
        string $query,
        array $params
    ) : void {
        throw new Exception(
            $msg
            . "<br><br>SQL ("
            . substr_count($query, "?")
            . " params):<br><pre>$query</pre><br>PARAMS ("
            . count($params)
            . "):<br><pre>"
            . implode($params, "\n")
            . "</pre>"
        );
    }
623336
public function processMessage(BaseAMQPMessage $msg)
    {
        $newMsg = new AMQPMessage($msg->body, $msg->get_properties());
        $newMsg->delivery_info = $msg->delivery_info;
        $newMsg->body_size = $msg->body_size;
        $newMsg->is_truncated = $msg->is_truncated;
        $newMsg->setQueueName($this->queueName);

        $processFlag = call_user_func($this->callback, $newMsg);
        $this->handleProcessMessage($newMsg, $processFlag);
    }
1093626
public function processUnregister(Session $session, UnregisterMessage $msg)
    {
        for ($i = 0; $i < count($this->registrations); $i++) {
            /** @var Registration $registration */
            $registration = $this->registrations[$i];
            if ($registration->getId() == $msg->getRegistrationId()) {

                // make sure the session is the correct session
                if ($registration->getSession() !== $session) {
                    $session->sendMessage(ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.no_such_registration'));
                    //$this->manager->warning('Tried to unregister a procedure that belongs to a different session.');
                    return false;
                }

                array_splice($this->registrations, $i, 1);

                // TODO: need to handle any calls that are hanging around

                $session->sendMessage(UnregisteredMessage::createFromUnregisterMessage($msg));
                return true;
            }
        }

        $session->sendMessage(ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.no_such_registration'));

        return false;
    }
918942
protected static function output_msg($msg) {
        global $CFG, $PAGE;

        // If we are using the web interface we want pretty messages.
        if (!CLI_SCRIPT) {

            $renderer = $PAGE->get_renderer('tool_behat');
            echo $renderer->render_error($msg);

            // Stopping execution.
            exit(1);

        } else {

            // We continue execution after this.
            $clibehaterrorstr = "Ensure you set \$CFG->behat_* vars in config.php " .
                "and you ran admin/tool/behat/cli/init.php.\n" .
                "More info in " . self::DOCS_URL;

            echo 'Error: ' . $msg . "\n\n" . $clibehaterrorstr;
        }
    }
1246733
protected  function writeMessage($level, $msg, $vars = null) {
		// Because of date('u')-PHP-bug (always 00000)
		$mtimeParts = explode(' ', microtime());

		$repl = array(
			Logger::PATTERN_CLASS => $this->classContext,
            Logger::PATTERN_CLASSNAME => StringUtils::afterLast($this->classContext, '\\'),
			Logger::PATTERN_LEVEL => str_pad($level, 5, ' ', STR_PAD_RIGHT),
			Logger::PATTERN_MESSAGE => $msg,
			Logger::PATTERN_TIMESTAMP => date($this->dtFormat, $mtimeParts[1]) . ',' . substr($mtimeParts[0], 2) /* date('Y-m-d H:i:s,u') */
		);

		error_log(str_ireplace(array_keys($repl), $repl, $this->pattern) . "\r\n", 3, $this->logfilePath);
	}
731485
protected function processSubscribe(Session $session, SubscribeMessage $msg)
    {
        // get a subscription group "hash"
        /** @var MatcherInterface $matcher */
        $matcher = $this->getMatcherForMatchType($msg->getMatchType());
        if ($matcher === false) {
            Logger::alert($this,
                "no matching match type for \"" . $msg->getMatchType() . "\" for URI \"" . $msg->getUri() . "\"");

            return;
        }

        if (!$matcher->uriIsValid($msg->getUri(), $msg->getOptions())) {
            $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg);
            $session->sendMessage($errorMsg->setErrorURI('wamp.error.invalid_uri'));

            return;
        }

        $matchHash = $matcher->getMatchHash($msg->getUri(), $msg->getOptions());

        if (!isset($this->subscriptionGroups[$matchHash])) {
            $this->subscriptionGroups[$matchHash] = new SubscriptionGroup($matcher, $msg->getUri(), $msg->getOptions());
        }

        /** @var SubscriptionGroup $subscriptionGroup */
        $subscriptionGroup = $this->subscriptionGroups[$matchHash];
        $subscription      = $subscriptionGroup->processSubscribe($session, $msg);

        $registry = $this->getStateHandlerRegistry();
        if ($registry !== null) {
            $registry->processSubscriptionAdded($subscription);
        }
    }
318978
public function handleHelloMessage(Realm $realm, Session $session, HelloMessage $msg)
    {
        $requestedMethods = $msg->getAuthMethods();
        $sentMessage      = false;

        // Go through the authmethods and try to send a response message
        foreach ($this->authMethods as $authMethod => $authMethodInfo) {
            if (in_array($authMethod, $requestedMethods)
                && (in_array($realm->getRealmName(), $authMethodInfo['auth_realms'])
                    || in_array("*", $authMethodInfo['auth_realms']))
            ) {
                $this->onHelloAuthHandler($authMethod, $authMethodInfo, $realm, $session, $msg);
                $sentMessage = true;
            }
        }

        //If we already replied with a message, we don't have to do anything else
        if ($sentMessage) {
            return;
        }

        // If no authentication providers are registered for this realm send an abort message
        if ($this->realmHasAuthProvider($realm->getRealmName())) {
            $session->abort(new \stdClass(), 'wamp.error.not_authorized');

            return;
        }

        //If we've gotten this far, it means that the user needs to be Logged in as anonymous
        $session->setAuthenticationDetails(AuthenticationDetails::createAnonymous());

        $details = new \stdClass();

        $session->sendMessage(new WelcomeMessage($session->getSessionId(), $details));
        $session->setAuthenticated(true);

    }
1258993
private function message_object_prepare(&$msg, &$size = 0)
    {
        // Remove body too big
        if (isset($msg->body)) {
            $length = strlen($msg->body);

            if ($msg->body_modified || $size + $length > $this->threshold * 1024) {
                unset($msg->body);
            }
            else {
                $size += $length;
            }
        }

        // Fix mimetype which might be broken by some code when message is displayed
        // Another solution would be to use object's copy in rcube_message class
        // to prevent related issues, however I'm not sure which is better
        if ($msg->mimetype) {
            list($msg->ctype_primary, $msg->ctype_secondary) = explode('/', $msg->mimetype);
        }

        unset($msg->replaces);

        if (is_object($msg->structure)) {
            $this->message_object_prepare($msg->structure, $size);
        }

        if (is_array($msg->parts)) {
            foreach ($msg->parts as $part) {
                $this->message_object_prepare($part, $size);
            }
        }
    }
772223
function view_session_message(req, msg) {
		var result = copy(msg);
		result.$ref = ref(req, opts.path + '/messages', msg.$id );
		return result;
	}
263225
public function onClientMessage(MessageInterface $msg, $routing)
    {
        $client = $this->client(array_shift($routing));

        if ($msg instanceof ExecuteRequest) {
            $this->clientRequest($client, $msg);

            return;
        }

        if ($msg instanceof FetchRequest) {
            $this->clientFetch($client, $msg);

            return;
        }

        $this->getLogger()->info('Invalid message type: '.get_class($msg).'.');
    }
1111980
public static function parse(string $msg): Message
    {
        $decoded = json_decode($msg);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Error(json_last_error_msg(), ErrorCode::PARSE_ERROR);
        }
        if (Notification::isNotification($decoded)) {
            $obj = new Notification($decoded->method, $decoded->params ?? null);
        } else if (Request::isRequest($decoded)) {
            $obj = new Request($decoded->id, $decoded->method, $decoded->params ?? null);
        } else if (SuccessResponse::isSuccessResponse($decoded)) {
            $obj = new SuccessResponse($decoded->id, $decoded->result);
        } else if (ErrorResponse::isErrorResponse($decoded)) {
            $obj = new ErrorResponse($decoded->id, new Error($decoded->error->message, $decoded->error->code, $decoded->error->data ?? null));
        } else {
            throw new Error('Invalid message', ErrorCode::INVALID_REQUEST);
        }
        return $obj;
    }
686607
public function redirect($url, $msg='', $msgType='')
	{
		if ($url)
		{
			$url = str_replace('&amp;', '&', $url);

			//preserve plugin messages after redirect
			if (count($this->pluginMessageQueue))
			{
				\App::get('session')->set('plugin.message.queue', $this->pluginMessageQueue);
			}

			\App::redirect($url, $msg, $msgType);
		}
	}
978254
private function processYield(Session $session, YieldMessage $msg)
    {

        /* @var $call Call */
        $call = isset($this->callInvocationIndex[$msg->getRequestId()]) ? $this->callInvocationIndex[$msg->getRequestId()] : null;

        if (!$call) {
            $session->sendMessage(ErrorMessage::createErrorMessageFromMessage($msg));
            Logger::error($this, "Was expecting a call");

            return;
        }

        $keepIndex = $call->processYield($session, $msg);

        if (!$keepIndex) {
            $this->removeCall($call);
        }

        /* @var $procedure \Thruway\Procedure */
        $procedure = isset($this->procedures[$call->getCallMessage()->getUri()]) ? $this->procedures[$call->getCallMessage()->getUri()] : null;
        if ($procedure && $procedure->getAllowMultipleRegistrations()) {
            $procedure->processQueue();
        }

        //Process queues on other registrations if we can take more requests
        if ($session->getPendingCallCount() == 0 && $this->registrationsBySession->contains($session)) {
            $this->processQueue($session);
        }

    }
1210441
private synchronized void showMessage(final String msg)
	{
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				getMessages().setText(msg);
			}
		});
	}