Handles incoming worker requests.

@param string $message Json-encoded data received from worker.
@throws ServerException
515018
public function onWorkerReplyMessage(string $message)
    {
        try {
            $data = json_decode($message, true);
            if (empty($data) || !isset($data['request'])) {
                throw new ServerException('Invalid worker request received.');
            }
            $result = null;
            switch ($data['request']) {
                case 'register_job':
                    $result = $this->registerJob($data['job_name'], $data['worker_id']);
                    break;
                case 'unregister_job':
                    $result = $this->unregisterJob($data['job_name'], $data['worker_id']);
                    break;
                case 'change_state':
                    $result = $this->changeWorkerState($data['worker_id'], $data['state']);
                    break;
                case 'job_completed':
                    $this->onJobCompleted($data['worker_id'], $data['job_id'], $data['result']);
                    break;
            }
            $response = ($result === true) ? 'ok' : 'error';
            $this->workerReplySocket->send($response);
        } catch (ServerException $e) {
            $errorMsgPattern = 'Worker message error: %s (%s:%d)';
            $this->logger->error(sprintf($errorMsgPattern, $e->getMessage(), $e->getFile(), $e->getLine()));
        }
    }
389984
protected function accessDenied(?string $message=NULL) {
		
		$this->enqueueError(($message ? $message : $this->translator->get('ACCESS_DENIED')));
		$this->redirect(strtolower($this->name));
		
	}
815165
public function handle(StatusMessage $message)
    {
        $this->message = $message;
        $this->output = $message->getOutput();
        $output = $this->output;

        $repository = $message->getRepository();
        $storage = $message->getStorage();

        $availableMigrations = $repository->fetchAll();
        $migratedVersions = $storage->fetchAll();

        $migratedVersions->sortWith($message->getComparator());
        $headVersion = $migratedVersions->last();

        $currentMessage = $headVersion ?
            "Current version: <comment>{$headVersion->getId()}</comment>" :
            'Nothing has been migrated yet.';
        $output->writeln($currentMessage);

        $diff = array_diff($availableMigrations->toArray(), $migratedVersions->toArray());

        $pendingCount = count($diff);

        if ($pendingCount > 0) {
            $executable = defined('MIGRATIONS_EXECUTABLE') ? MIGRATIONS_EXECUTABLE . ' ' : '';
            $output->writeln([
                "Your database is out-of-date by $pendingCount versions, and can be migrated.",
                sprintf(
                    '  (use "<comment>%smigrate</comment>" to execute all migrations)',
                    $executable
                ),
                ''
            ]);
            if ($headVersion) {
                list($beforeHead, $afterHead) = $this->splitDiff($diff, $message->getComparator(), $headVersion);
            } else {
                $beforeHead = [];
                $afterHead = $diff;
            }
            $this->printDiff(
                $beforeHead,
                [
                    'Old migrations still pending:',
                    sprintf("  (use \"<comment>{$executable}migrate HEAD</comment>\" to migrate them)", $executable),
                ],
                self::STYLE_COMMENT
            );
            $this->printDiff($afterHead, ['New migrations:'], self::STYLE_INFO);
        } else {
            $output->writeln('Your database is up-to-date.');
        }
    }
1246816
protected function dispatch($message, MessageCallback $callback) : void
    {
        $handled = false;
        foreach ($this->callableWrappersFor($message) as $callable) {
            $handled = true;
            if ($message instanceof PropagationStoppable && $message->isPropagationStopped()) {
                break;
            }
            try {
                $result = $callable->invoke($message);
                self::getLogger()->debug(
                    "The following message has been dispatched to handler '{}' through message bus '{}': {}",
                    [$callable, $this, $message]
                );
                if ($result !== null) {
                    $callback->onSuccess($result);
                }
            } catch (Exception $exp) {
                self::getLogger()->warn(
                    "An error occurred in the following message handler through message bus '{}': {}, message is {}!",
                    [$this, $callable, $message],
                    $exp
                );
                $context = new SubscriberExceptionContext($this, $message, $callable);
                try {
                    $this->exceptionHandler->handleException($exp, $context);
                } catch (Exception $e) {
                    self::getLogger()->error(
                        "An error occurred in the exception handler with context '{}'",
                        [$context],
                        $e
                    );
                }
                try {
                    $callback->onFailure($exp);
                } catch (Exception $e) {
                    self::getLogger()->error("An error occurred in message callback on bus '{}'", [$this], $e);
                }
            }
        }
        if (!$handled && !($message instanceof DeadMessage)) {
            self::getLogger()->debug(
                "The following message as a DeadMessage is being posted to '{}' message bus: {}",
                [$this, $message]
            );
            $this->dispatch(new DeadMessage($message), $callback);
        }
    }
613568
public function sendMessage($message)
    {
        if ($payload = $this->getJsonPayload($message)) {
            $response = $this->getHttpClient()
                ->post($this->getWebhook(), [
                    'headers' => ['Content-Type' => 'application/json'],
                    'body' => $payload,
                ]);

            return 200 === $response->getStatusCode();
        }

        return false;
    }
170686
public function respondUnauthorized($message = null): JsonResponse
    {
        return $this->setStatusCode(IlluminateResponse::HTTP_UNAUTHORIZED)
            ->respondWithError(ApiResponse::CODE_NOT_AUTHORIZED, $message);
    }
815175
private function parseRawMessage($message) {
		$positionStartBody = strpos($message, "\r\n\r\n");

		$startPositionOffset = 4;
		if ($positionStartBody === false) {
			$positionStartBody = strpos($message, "\n\n");
			$startPositionOffset = 2;
			if ($positionStartBody === false) {
				throw new \Exception("Invalid HTTP message provided. It does not contain a header part.");
			}
		}

		$headerString = str_replace("\r\n", "\n", trim(substr($message, 0, $positionStartBody), "\r\n"));
		$content = substr($message, $positionStartBody + $startPositionOffset);

		$this->headers = $this->parseHttpHeaders($headerString);
		$statusLine = current(explode("\n", $headerString));
		$this->parseStatusLine($statusLine);
		$this->body = $content;
	}
164545
public function notify($message)
    {
        try {
            $command = $this->createCommand($message);
            $this->socket->send($command);

            $result = false;
            $limit = microtime(true) + $this->timeout;

            while (microtime(true) < $limit && false === $result = $this->socket->recv(\ZMQ::MODE_NOBLOCK)) {
                usleep(1000);
            }

            if (false === $result) {
                $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout));
                throw new RuntimeException('Unable to retrieve information.');
            }

            $data = @json_decode($result, true);
            if (JSON_ERROR_NONE !== json_last_error()) {
                throw new RuntimeException('Invalid task manager response : invalid JSON.');
            }
            if (!isset($data['reply']) || !isset($data['request']) || $command !== $data['request']) {
                throw new RuntimeException('Invalid task manager response : missing fields.');
            }

            return $data['reply'];
        } catch (\ZMQSocketException $e) {
            $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout), ['exception' => $e]);
            throw new RuntimeException('Unable to retrieve information.', $e->getCode(), $e);
        }
    }
935864
@Override
	public void handleMessageToClient(WebSocketSession session, Message<?> message) {
		if (!(message instanceof WampMessage)) {
			logger.error("Expected WampMessage. Ignoring " + message + ".");
			return;
		}

		boolean closeWebSocketSession = false;
		try {
			String json = ((WampMessage) message).toJson(this.jsonFactory);
			session.sendMessage(new TextMessage(json));
		}
		catch (SessionLimitExceededException ex) {
			// Bad session, just get out
			throw ex;
		}
		catch (Throwable ex) {
			// Could be part of normal workflow (e.g. browser tab closed)
			logger.debug("Failed to send WebSocket message to client in session "
					+ session.getId() + ".", ex);
			closeWebSocketSession = true;
		}
		finally {
			if (closeWebSocketSession) {
				try {
					session.close(CloseStatus.PROTOCOL_ERROR);
				}
				catch (IOException ex) {
					// Ignore
				}
			}
		}
	}
1277685
protected function handlePost($data)
    {
        PWELogger::debug($_SERVER['REQUEST_METHOD'] . ": %s", $data);
        throw new HTTP5xxException('Not supported method for this call: ' . $_SERVER['REQUEST_METHOD'], HTTP5xxException::UNIMPLEMENTED);
    }
625546
protected function onMasterMessage(string $message): Generator
    {
        yield Dispatcher::async($this->broadcast(Frame::encode($message), false));
    }
272627
@Override
    public void handleMessage(final Message message) throws Fault {
        OutputStream os = message.getContent(OutputStream.class);

        if (null == os) {
            String encoding = (String) message.get(Message.ENCODING);
            if (encoding == null) {
                encoding = "UTF-8";
            }

            final Writer writer = message.getContent(Writer.class);
            if (null != writer) {
                os = new WriterOutputStream(writer, encoding);
                message.setContent(Writer.class,null);
            }
        }

        if (null != os) {
            final CacheAndWriteTapOutputStream newOut = new CacheAndWriteTapOutputStream(os);

            message.setContent(OutputStream.class, newOut);

            if (WireTapHelper
                    .isMessageContentToBeLogged(message, logMessageContent, logMessageContentOverride)) {
                message.setContent(CachedOutputStream.class, newOut);
            }else {
                try {
                    final CachedOutputStream cos = new CachedOutputStream();
                    cos.write(WireTapHelper.CONTENT_LOGGING_IS_DISABLED.getBytes(Charset.forName("UTF-8")));
                    message.setContent(CachedOutputStream.class, cos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (wireTap != null) {
                newOut.registerCallback(new CallBack(message));
            }
        }
    }
279675
public function sendMessage( $message )
	{
		if( !$this->receiver )
			throw new RuntimeException( 'No Receiver set.' );
		$this->sendMessageTo( $message, $this->receiver->get() );
	}
1363344
protected function _send($message)
    {
        $options = [
            'headers' => ['Authorization' => 'Bearer ' . $this->getConfig('api_key')]
        ];
        $response = $this->http->post('/api/mail.send.json', $message, $options);
        if ($response->getStatusCode() !== 200) {
            throw new SendgridEmailException(sprintf(
                'SendGrid error %s %s: %s',
                $response->getStatusCode(),
                $response->getReasonPhrase(),
                implode('; ', $response->json['errors'])
            ));
        }

        return $response->json;
    }
354200
protected function flush($message)
    {
        $this->socket->create(AF_INET, SOCK_DGRAM, SOL_UDP);
        $this->socket->setNonBlocking();
        $this->socket->sendMessage($message, $this->server, $this->port);
        $this->socket->close();
    }
222972
protected function appendMessage(string $message): void
    {
        $this->messages[] = $message;

        if (sizeof($this->messages) > $this->config['max_messages']) {
            array_shift($this->messages);
        }
    }
1127700
public function onPipeMessage(Server $server, int $srcWorkerId, string $message)
    {
        /* @var PipeMessageInterface $pipeMessage */
        $pipeMessage = App::getBean(PipeMessage::class);
        list($type, $data) = $pipeMessage->unpack($message);

        App::trigger(AppEvent::PIPE_MESSAGE, null, $type, $data, $srcWorkerId);
    }