Process call

@param \Thruway\Session $session
@param Call $call
@throws \Exception
@return bool | Call
425778
public function processCall(Session $session, Call $call)
    {
        // find a registration to call
        if (count($this->registrations) === 0) {
            $session->sendMessage(ErrorMessage::createErrorMessageFromMessage($call->getCallMessage(), 'wamp.error.no_such_procedure'));
            return false;
        }

        // just send it to the first one if we don't allow multiple registrations
        if (!$this->getAllowMultipleRegistrations()) {
            $this->registrations[0]->processCall($call);
        } else {
            $this->callQueue->enqueue($call);
            $this->processQueue();
        }

        return true;
    }
1311307
public function processCancel(Session $session, CancelMessage $msg)
    {
        if ($this->getCallerSession() !== $session) {
            Logger::warning($this, 'session attempted to cancel call they did not own.');
            return false;
        }

        if ($this->getCalleeSession() === null) {
            // this call has not been sent to a callee yet (it is in a queue)
            // we can just kill it and say it was canceled
            $errorMsg                             = ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.canceled');
            $details                              = $errorMsg->getDetails() ?: (object)[];
            $details->_thruway_removed_from_queue = true;
            $session->sendMessage($errorMsg);
            return true;
        }

        $details = (object)[];
        if ($this->getCalleeSession()->getHelloMessage() instanceof HelloMessage) {
            $details = $this->getCalleeSession()->getHelloMessage()->getDetails();
        }
        $calleeSupportsCancel = false;
        if (isset($details->roles->callee->features->call_canceling)
            && is_scalar($details->roles->callee->features->call_canceling)) {
            $calleeSupportsCancel = (bool)$details->roles->callee->features->call_canceling;
        }

        if (!$calleeSupportsCancel) {
            $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg);
            $errorMsg->setErrorURI('wamp.error.not_supported');
            $session->sendMessage($errorMsg);
            return false;
        }

        $this->setCancelMessage($msg);

        $this->canceling = true;

        $calleeSession = $this->getCalleeSession();

        $interruptMessage = new InterruptMessage($this->getInvocationRequestId(), (object)[]);
        $calleeSession->sendMessage($interruptMessage);
        $this->setInterruptMessage($interruptMessage);

        if (isset($msg->getOptions()->mode) && is_scalar($msg->getOptions()->mode) && $msg->getOptions()->mode === 'killnowait') {
            $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.canceled');
            $session->sendMessage($errorMsg);

            return true;
        }

        return false;
    }
251456
protected function call(Request $request) {
		$response = $request->execute();
		if (!$response->isSuccess()) {
			self::debug("Error in PayPal call", $response);			
			throw new PayPal_Exception_InvalidResponse("Error " . $response->status() . " in PayPal call (". $response->body() .")");
		}
		$res = json_decode($response->body());
		
		if (isset($res->error)) {
			self::error("Error in PayPal call: " . print_r($res, true));			
			throw new PayPal_Exception_InvalidResponse('PayPal: ' . $res->error_description . ' [' . $res->error . 
					'] while calling ' . $request->uri());
		}
		return $res;
	}
689541
protected function parseClosure(Query $query, $call, $show = true)
    {
        $newQuery = $query->newQuery()->setConnection($this->connection);
        $call($newQuery);

        return $newQuery->buildSql($show);
    }
1209405
public function call($call, array $params = array())
    {
        $startTime = microtime(true);

        if (!array_key_exists('culture', $params)) {
            $params['culture'] = $this->culture;
        }

        $url = $this->generateUrl($call, $params);
        $this->logger->debug('call start', array(
            'url'      => $url,
        ));

        $key = $this->cache->generateCacheKey($url);
        $content = $this->cache->get($key);
        if ($content !== false) {
            $this->logger->debug('call end', array(
                'url'      => $url,
                'cache'    => true,
                'time'     => microtime(true) - $startTime,
                'response' => $content,
            ));

            return $content;
        }

        $request = $this->createRequest($url);

        if (!ini_get('open_basedir') && filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN) === false) {
            $request->setOption(CURLOPT_FOLLOWLOCATION, true);
        }

        $response = $request->get();

        if ($request->getError()) {
            $this->throwError('The Api call returned an error: "' . $request->getError() . '"');
        }

        if ($request->getStatusCode() == 401) {
            $this->throwError('Bad Username / Password ' . $request->getStatusCode(), '\Justimmo\Exception\AuthenticationException');
        }

        if ($request->getStatusCode() == 404) {
            $this->throwError('Api call not found: ' . $request->getStatusCode(), '\Justimmo\Exception\NotFoundException');
        }

        if ($request->getStatusCode() >= 400 && $request->getStatusCode() < 500) {
            $exception = new InvalidRequestException('The Api call returned status code ' . $request->getStatusCode());
            $exception->setResponse($request->getContent());
            $this->logger->error($exception->getMessage());

            throw $exception;
        }

        if ($request->getStatusCode() != 200) {
            $this->throwError('The Api call returned status code ' . $request->getStatusCode(), '\Justimmo\Exception\StatusCodeException');
        }

        $this->cache->set($key, $response);

        $this->logger->debug('call end', array(
            'url'      => $url,
            'cache'    => false,
            'time'     => microtime(true) - $startTime,
            'response' => $response,
        ));

        return $response;
    }
1011082
public function removeCall($callToRemove)
    {
        /* @var $call \Thruway\Call */
        foreach ($this->calls as $i => $call) {
            if ($callToRemove === $call) {
                array_splice($this->calls, $i, 1);
                $this->session->decPendingCallCount();
                $callEnd = microtime(true);

                // average call time
                $callsInAverage = $this->invocationCount - count($this->calls) - 1;

                // add this call time into the total
                $this->completedCallTimeTotal += $callEnd - $call->getCallStart();
                $callsInAverage++;
                $this->invocationAverageTime = ((float)$this->completedCallTimeTotal) / $callsInAverage;

                if (count($this->calls) == 0) {
                    $this->lastIdledAt = new \DateTime();
                    if ($this->busyStart !== null) {
                        $this->busyTime  = $this->busyTime + ($callEnd - $this->busyStart);
                        $this->busyStart = null;
                    }
                }
            }
        }
    }
919333
public static function call(callable $callable, $args=[])
    {
        if (!is_array($args)) {
            $args = [$args];
        }

        switch (count($args)) {
            case 0:
                return call_user_func($callable);
            case 1:
                return call_user_func($callable, $args[0]);
            case 2:
                return call_user_func($callable, $args[0], $args[1]);
            case 3:
                return call_user_func($callable, $args[0], $args[1], $args[2]);
            case 4:
                return call_user_func($callable, $args[0], $args[1], $args[2], $args[3]);
        }

        return call_user_func_array($callable, $args);
    }
83848
private function updateCall(DICallWrapper $call)
    {
        $callsCount = count($this->serviceArray[$this::CALLS_SECTION]);

        for ($i = 0; $i < $callsCount; $i++) {
            $existingCall = new DICallWrapper($this->serviceArray[$this::CALLS_SECTION][$i]);
            if ($existingCall->getMethodName() === $call->getMethodName()) {
                $this->serviceArray[$this::CALLS_SECTION][$i] = $call->getCallAsArray();
                return;
            }
        }
        throw new MissingUpdateCallException();
    }
578982
public function _call($name, $arguments)
    {
        $object = $this->getObject();
		$callable = function() use ($name, $arguments, $object){
			if (!method_exists($object, $name)) {
				throw new \Exception('Unable to invoke method ' . $name . ' on object of class ' . get_class($object));
			}
			return call_user_func_array(array($object, $name), (array) $arguments);
		};
		return $this->breakScopeAndExecute($callable);
    }
575162
protected void invokeCall(RTMPConnection conn, IServiceCall call) {
        final IScope scope = conn.getScope();
        if (scope != null) {
            if (scope.hasHandler()) {
                final IScopeHandler handler = scope.getHandler();
                log.debug("Scope: {} handler: {}", scope, handler);
                if (!handler.serviceCall(conn, call)) {
                    // XXX: What to do here? Return an error?
                    log.warn("Scope: {} handler failed on service call", scope.getName(), new Exception("Service call failed"));
                    return;
                }
            }
            final IContext context = scope.getContext();
            log.debug("Context: {}", context);
            context.getServiceInvoker().invoke(call, scope);
        } else {
            log.warn("Scope was null for invoke: {} connection state: {}", call.getServiceMethodName(), conn.getStateCode());
        }
    }
1155813
public function leave(Session $session)
    {
        /* @var $procedure \Thruway\Procedure */
        foreach ($this->procedures as $procedure) {
            $procedure->leave($session);
        }

        foreach ($this->callInvocationIndex as $call) {
            if ($session->getSessionId() === $call->getCallerSession()->getSessionId()) {
                $cancelMsg = new CancelMessage($call->getCallMessage()->getRequestId(), (object)[]);
                $this->processCancel($session, $cancelMsg);
            }
        }

        // remove the list of registrations
        if ($this->registrationsBySession->contains($session)) {
            $this->registrationsBySession->detach($session);
        }
    }
442627
private function transformCall(RpcRequestInterface $call)
    {
        if ($call instanceof JsonRpcRequestInterface) {
            return $call;
        }

        return JsonRpcRequest::fromRpcRequest($call, $this->idGenerator->getRequestIdentifier($call));
    }
561816
private function _call()
    {

        // Time this
        $t = new Timer('apcaccess Extension');

        // Deal with calling it
        try {
            $result = $this->_CallExt->exec('apcaccess');
        } catch (Exception $e) {
            // messed up somehow
            Errors::add('apcaccess Extension', $e->getMessage());
            $this->_res = false;

            // Don't bother going any further
            return false;
        }

        // Store them here
        $this->_res = [];

        // Get name
        if (preg_match('/^UPSNAME\s+:\s+(.+)$/m', $result, $m)) {
            $this->_res['name'] = $m[1];
        }

        // Get model
        if (preg_match('/^MODEL\s+:\s+(.+)$/m', $result, $m)) {
            $this->_res['model'] = $m[1];
        }

        // Get battery voltage
        if (preg_match('/^BATTV\s+:\s+(\d+\.\d+)/m', $result, $m)) {
            $this->_res['volts'] = $m[1];
        }

        // Get charge percentage, and get it cool
        if (preg_match('/^BCHARGE\s+:\s+(\d+(?:\.\d+)?)/m', $result, $m)) {
            $charge = (int) $m[1];
            $this->_res['charge'] = '
					<div class="bar_chart">
						<div class="bar_inner" style="width: '.(int) $charge.'%;">
							<div class="bar_text">
								'.($charge ? $charge.'%' : '?').'
							</div>
						</div>
					</div>
			';
        }

        // Get time remaning
        if (preg_match('/^TIMELEFT\s+:\s+([\d\.]+)/m', $result, $m)) {
            $this->_res['time_left'] = Common::secondsConvert($m[1] * 60);
        }

        // Get status
        if (preg_match('/^STATUS\s+:\s+([A-Z]+)/m', $result, $m)) {
            $this->_res['status'] = $m[1] == 'ONBATT' ? 'On Battery' : ucfirst(strtolower($m[1]));
        }

        // Load percentage looking cool
        if (preg_match('/^LOADPCT\s+:\s+(\d+\.\d+)/m', $result, $m)) {
            $load = (int) $m[1];
            $this->_res['load'] = '
					<div class="bar_chart">
						<div class="bar_inner" style="width: '.(int) $load.'%;">
							<div class="bar_text">
								'.($load ? $load.'%' : '?').'
							</div>
						</div>
					</div>
			';
        }

        // Attempt getting wattage
        if (isset($load) && preg_match('/^NOMPOWER\s+:\s+(\d+)/m', $result, $m)) {
            $watts = (int) $m['1'];
            $this->_res['watts_used'] = $load * round($watts / 100);
        } else {
            $this->_res['watts_used'] = false;
        }

        // Apparent success
        return true;
    }
369399
@Override
  public Boolean call() throws Exception {

    ProcessRecord updatedRecord = null;
    Connection hbaseConnection = null;
    try {
      hbaseConnection = ConnectionFactory.createConnection(hbaseConf);
      // Connect only when needed.
      ProcessRecordService processRecordService =
          new ProcessRecordService(hbaseConf, hbaseConnection);

      updatedRecord =
          processRecordService.setProcessState(processRecord, newState);
    } finally {
      if (hbaseConnection != null) {
        hbaseConnection.close();
      }
    }

    if ((updatedRecord != null)
        && (updatedRecord.getProcessState() == newState)) {
      return true;
    }
    return false;
  }
1120438
public function execute(HTTPRequest $request, callable $callback, $flush = false)
    {
        try {
            return $this->callMiddleware($request, function ($request) use ($callback, $flush) {
                // Pre-request boot
                $this->getKernel()->boot($flush);
                return call_user_func($callback, $request);
            });
        } catch (HTTPResponse_Exception $ex) {
            return $ex->getResponse();
        } finally {
            $this->getKernel()->shutdown();
        }
    }
903972
private function callMethod($instance, $method)
    {
        if (!method_exists($instance, $method) || !is_callable([$instance, $method])) {
            return false;
        }

        return call_user_func([$instance, $method]);
    }
746383
public function start(): bool
    {
        if (!$this->started) {
            // check headers
            if (headers_sent($file, $line)) {
                throw new SessionException(sprintf("Cannot use '%s()', headers already sent in %s:%s",
                    __method__, $file, $line));
            }

            // start session
            $this->started = session_start();
            if (!$this->started) {
                session_write_close();
                throw new SessionException(sprintf("Session start failed in '%s()'", __method__));
            }

            // check id for last time
            if (session_id() !== $this->id) {
                session_write_close();
                throw new SessionException(sprintf("Session ID match failed in '%s()'", __method__));
            }

            // init sub-array
            if (!isset($_SESSION[$this->name])) {
                $_SESSION[$this->name] = [];
            }
        }

        return $this->started;
    }