This is the main method every webserver must have called

@throws Exception Will be thrown if there's a severe problem with the underlying PHP
@throws RestException Will be thrown if there's a formal error with the client request
354798
public function handle()
    {
        // Access-Control-Allow-Origin header should always be set
        $this->header_manager->addHeader("Access-Control-Allow-Origin", join(', ', $this->cors_allowed_origin));

        $http_methods_allowed = HttpMethods::getMethodsWhereRequestBodyIsAllowed();
        $http_methods_allowed[] = HttpMethods::GET;
        if (in_array($this->getMethod(), $http_methods_allowed)) {
            try {
                $this->data = $this->getData();
            } catch (RestException $e) {
                $this->handleError($e->getCode(), $e->getMessage());
            }
        }

        list($obj, $method, $params, $this->params, $keys) = $this->findUrl();

        if ($obj) {
            if (is_string($obj)) {
                if (class_exists($obj)) {
                    $obj = new $obj();
                } else {
                    throw new Exception("Class $obj does not exist");
                }
            }

            $obj->server = $this;

            try {
                if (method_exists($obj, 'init')) {
                    $obj->init();
                }

                if (empty($keys['noAuth'])) {
                    if (method_exists($this, 'doServerWideAuthorization')) {
                        if (!$this->doServerWideAuthorization()) {
                            $this->unauthorized(false);
                        }
                    } elseif (method_exists($obj, 'authorize')) {
                        // Standard behaviour
                        if (!$obj->authorize()) {
                            $this->unauthorized(false);
                        }
                    }
                }

                $accept_language_header = isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
                    ? $_SERVER['HTTP_ACCEPT_LANGUAGE']
                    : '';
                $language = new Language(
                    $this->supported_languages,
                    $this->default_language,
                    $accept_language_header
                );
                $params = $this->injectLanguageIntoMethodParameters($language, $obj, $method, $params);

                $result = call_user_func_array(array($obj, $method), $params);

                $this->automaticContentLanguageHeaderDispatch($language);

            } catch (RestException $e) {
                $this->handleError($e->getCode(), $e->getMessage());
            }

            if (!empty($result)) {
                $this->sendData($result);
            }
        } elseif (!isset($obj) && $this->getMethod() == HttpMethods::OPTIONS) {
            $this->handleCorsPreflightRequest();
        } else {
            $this->handleError(HttpStatusCodes::NOT_FOUND);
        }
    }
722962
protected final function error($code, $message = null) {
        if (empty($message) && is_string($code)) {
            $msg = explode('@', $code);
            if (count($msg) >= 2) {
                $message = $msg[1];
                $code    = intval($msg[0]);
            } else {
                $message = $code;
                $code    = 500;
            }
        } else if (empty($message)) {
            $message = __('Internal Error');
        }
        throw new RestException($message, $code);
    }
37649
public function decode()
    {
        $this->body = json_decode($this->body);

        $errorCode = json_last_error();
        $errorMessage = json_last_error_msg();

        if ($errorCode !== 0 && isset($errorMessage)) {
            throw new \OtherCode\Rest\Exceptions\RestException($errorMessage, $errorCode);
        }
    }
1302364
public function prepare(): bool
    {
        $request = $this->getRequest();
        $response = $this->getResponse();
        $thrown = false;

        try {
            //dispatch an init
            $continue = $this->getPreprocessor()->process($request, $response);
        //we are going to ignore this because
        //there is a conflict between PHP5.6 and PHP7
        //and how it deals with Throwable
        // @codeCoverageIgnoreStart
        } catch (Throwable $e) {
            //if there is an exception
            //you may not want to out
            //right throw it out
            $thrown = true;
            $response->setStatus(500, HttpHandler::STATUS_500);
            $continue = $this->getErrorProcessor()->process($request, $response, $e);
            //if there's an error in the errorware then let it be thrown
        } catch (Exception $e) {
            if (!$thrown) {
                //same logic as above
                $response->setStatus(500, HttpHandler::STATUS_500);
                $continue = $this->getErrorProcessor()->process($request, $response, $e);
                //if there's an error in the errorware then let it be thrown
            }
        }
        // @codeCoverageIgnoreEnd

        return $continue;
    }
792252
@Override
    public void connect() throws Exception {
        String host = sysConfig.getProperty(RestCommunication.SYSPROP_HOST, "localhost");
        int port = sysConfig.getIntProperty(RestCommunication.SYSPROP_PORT, 443);
        RestAssured.useRelaxedHTTPSValidation();
        this.reqSpec = RestAssured.given();

        if (port % 1000 == 443) {
            this.reqSpec = this.reqSpec.baseUri("https://" + host + ":" + port);
        } else {
            this.reqSpec = this.reqSpec.baseUri("http://" + host + ":" + port);
        }

        String user = sysConfig.getProperty(RestCommunication.SYSPROP_USER);
        String pass = sysConfig.getProperty(RestCommunication.SYSPROP_PASS);
        if (null != user && null != pass) {
            this.reqSpec = this.reqSpec.auth().preemptive().basic(user, pass);
        }

        String clientCert = sysConfig.getProperty(RestCommunication.SYSPROP_CLIENT_CERT);
        String clientCertPass = sysConfig.getProperty(RestCommunication.SYSPROP_CLIENT_CERT_PASS);
        if (null != clientCert && null != clientCertPass) {
            this.reqSpec = this.reqSpec.auth().certificate(clientCert, clientCertPass);
        }
    }
1346575
public function process()
    {
        //formulate the request and response
        $request = $this->getRequest();
        $response = $this->getResponse();
        
        //register shutdown
        register_shutdown_function(function ($server) {
            $server->trigger('server-end');
        }, $this);
        
        //if it's not a child
        if (!($this->parentServer instanceof Index)) {
            //handle errors in case
            $this->handleErrors($request, $response);
        }
        
        //if we are Good, route
        if ($this->processGlobal($request, $response)) {
            //if no routing on this
            if (!$this->processRoutes($request, $response)) {
                $response->set('code', 404);
                
                //throw an exception
                Exception::i()
                    ->setMessage(self::NOT_FOUND)
                    ->setType(self::RESPONSE_ERROR_TYPE)
                    ->trigger();
            }
        }
        
        //do we have a body ?
        $body = $response->get('body');
        
        if ($body === null
        || !is_scalar($body)
        || !strlen((string) $body)) {
            $response->set('code', 404);
            
            //throw an exception
            Exception::i()
                ->setMessage(self::NOT_FOUND)
                ->setType(self::RESPONSE_ERROR_TYPE)
                ->trigger();
        }
        
        return array($request, $response);
    }
1184719
public function main()
    {
        // if composer autoloader is not yet loaded, load it here
        @include_once 'vendor/autoload.php';
        if (!class_exists('\\JShrink\\Minifier')) {
            throw new BuildException(
                'JsMinTask depends on JShrink being installed and on include_path.',
                $this->getLocation()
            );
        }

        if (empty($this->targetDir)) {
            throw new BuildException('Attribute "targetDir" is required');
        }

        foreach ($this->filesets as $fs) {
            try {
                $this->processFileSet($fs);
            } catch (BuildException $be) {
                // directory doesn't exist or is not readable
                if ($this->failonerror) {
                    throw $be;
                } else {
                    $this->log($be->getMessage(), Project::MSG_WARN);
                }
            }
        }
    }
1260909
def execute(method, path, parameters, headers = { accept: :json }, &block)
      payload = {}.merge(parameters)
      url = base_url + path

      request_arguments = {
        method:  method,
        url:     url,
        payload: payload,
        headers: headers
      }

      RestClient::Request.execute(request_arguments, &block)
    rescue RestClient::Unauthorized
      raise AuthError, "Authentication failed"
    rescue RestClient::InternalServerError
      raise ServerError, "Server error"
    rescue RestClient::Forbidden => e
      raise BadRequest, e.http_body
    end
1316419
public function handleRequests(): void
    {
        $tail_call = false;
        do {
            $this->arg = $this->simpleArg;
            $this->stack = [$this->arg];
            $this->idx = 0;
            $this->parser->parse();
            if (count($this->stack) > 1) {
                $arg = array_pop($this->stack);
                if ($arg instanceof ApplyArg) {
                    $this->apply($arg);
                } else {
                    $msg = 'Error: $arg should be of type ApplyArg, error in client';
                    $this->logger->critical($msg);
                    throw new Exception\RuntimeException($msg);
                }
                $tail_call = true;
            }
            $this->stack = null;
        } while ($tail_call);
    }
368582
private function makeHttpRequest()
    {
        try {
            return $this->client->post($this->apiUrl, [
                $this->httpBodyParam => $this->post->toArray(),
            ])->getBody();
        } catch (HttpClientException $e) {
            throw new \Exception($e->getRequest().' '.$e->getResponse());
        } catch (HttpServerException $e) {
            throw new \Exception($e->getRequest().' '.$e->getResponse());
        } catch (HttpBadResponseException $e) {
            throw new \Exception($e->getRequest().' '.$e->getResponse());
        }
    }
1110332
protected function initialize() {
	$request   = bootstrap::get_library('request');
	$response  = bootstrap::get_library('response');
	$exception = bootstrap::get_library('exception');
	
	$this->url    = $request::get_url();
	$this->method = $request::get_method();
	
	if (empty($this->method)) {
		throw new $exception('unknown http method', $response::STATUS_METHOD_NOT_ALLOWED);
	}
}
772063
function hasException()
    {
        // Check exception from raw response
        // Server Response Status is 200 but Logical Error May Happen And Returned in Response Body
        if (! $this->exception ) {
            $res = $this->expected();
            if ($res instanceof DataEntity) {
                // Response Body Can parsed To Data Structure
                if ( $exception = $res->get('error') ) {
                    // TODO handle token revoke exceptions; OAuth Exceptions
                    $this->exception = new exTokenMismatch(
                        $res->get('error_description')
                        .' '
                        .$res->get('hint')

                        , 401
                    );
                }
            }
        } else if ($this->exception instanceof exHttpResponse) {
            // Determine Known Errors ...
            $expected = $this->expected();
            if ($expected && $err = $expected->get('error') ) {

                if ( is_string($err) )
                {
                    switch ($err) {
                        case 'access_denied':
                        case 'invalid_grant':
                            $description = $expected->get('error_description');
                            $this->exception = new exOAuthAccessDenied($description);
                            break;
                        case 'invalid_request':
                            $description = $expected->get('error_description');
                            $this->exception = new exInvalidRequest($description);
                            break;
                    }

                } elseif (isset($err['state']))
                {
                    switch (@$err['state']) {
                        case 'exUserNotFound':
                            $this->exception = new exUserNotFound($err['message'], (int)$err['code']);
                            break;
                        case 'exOAuthAccessDenied':
                            $this->exception = new exTokenMismatch($err['message'], (int)$err['code']);
                            break;
                        case 'exIdentifierExists':
                            $this->exception = new exIdentifierExists($err['message'], (int)$err['code']);
                            break;
                        case 'exPasswordNotMatch':
                            $this->exception = new exPasswordNotMatch($err['message'], (int)$err['code']);
                            break;
                        case 'exUnexpectedValue':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                        case 'exMessageMalformed':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                    }
                }
            }
        }


        return $this->exception;
    }
816499
function parse_request(){
		parent::parse_request();
		if (isset($_GET["id"]))
			$this->request->set_filter($this->config->id["name"],$_GET["id"],"=");
		else if (!$_POST["ids"])
			throw new Exception("ID parameter is missed");
	}
1088359
public function main()
    {

        // Set a default fetchmode if none was specified
        // (We're doing that here to prevent errors loading the class is PDO is not available.)
        if ($this->fetchMode === null) {
            $this->fetchMode = PDO::FETCH_ASSOC;
        }

        // Initialize the formatters here.  This ensures that any parameters passed to the formatter
        // element get passed along to the actual formatter object
        foreach ($this->formatters as $fe) {
            $fe->prepare($this->getLocation());
        }

        $savedTransaction = [];
        for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
            $savedTransaction[] = clone $this->transactions[$i];
        }

        $savedSqlCommand = $this->sqlCommand;

        $this->sqlCommand = trim($this->sqlCommand);

        try {
            if ($this->srcFile === null && $this->sqlCommand === ""
                && empty($this->filesets) && empty($this->filelists)
                && count($this->transactions) === 0
            ) {
                throw new BuildException(
                    "Source file or fileset/filelist, "
                    . "transactions or sql statement "
                    . "must be set!",
                    $this->getLocation()
                );
            }

            if ($this->srcFile !== null && !$this->srcFile->exists()) {
                throw new BuildException("Source file does not exist!", $this->getLocation());
            }

            // deal with the filesets
            foreach ($this->filesets as $fs) {
                $ds = $fs->getDirectoryScanner($this->project);
                $srcDir = $fs->getDir($this->project);
                $srcFiles = $ds->getIncludedFiles();
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // process filelists
            foreach ($this->filelists as $fl) {
                $srcDir = $fl->getDir($this->project);
                $srcFiles = $fl->getFiles($this->project);
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // Make a transaction group for the outer command
            $t = $this->createTransaction();
            if ($this->srcFile) {
                $t->setSrc($this->srcFile);
            }
            $t->addText($this->sqlCommand);
            $this->conn = $this->getConnection();

            try {
                $this->statement = null;

                // Initialize the formatters.
                $this->initFormatters();

                try {
                    // Process all transactions
                    for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
                        if (!$this->isAutocommit()) {
                            $this->log("Beginning transaction", Project::MSG_VERBOSE);
                            $this->conn->beginTransaction();
                        }
                        $this->transactions[$i]->runTransaction();
                        if (!$this->isAutocommit()) {
                            $this->log("Committing transaction", Project::MSG_VERBOSE);
                            $this->conn->commit();
                        }
                    }
                } catch (Exception $e) {
                    $this->closeConnection();
                    throw $e;
                }
            } catch (IOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            } catch (PDOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            }

            // Close the formatters.
            $this->closeFormatters();

            $this->log(
                $this->goodSql . " of " . $this->totalSql .
                " SQL statements executed successfully"
            );
        } catch (Exception $e) {
            $this->transactions = $savedTransaction;
            $this->sqlCommand = $savedSqlCommand;
            $this->closeConnection();
            throw $e;
        }
        // finally {
        $this->transactions = $savedTransaction;
        $this->sqlCommand = $savedSqlCommand;
        $this->closeConnection();
    }
490304
public function execute()
    {
        $ch = curl_init();
        $this->setAuth($ch);
        try {
            switch (strtoupper($this->verb)) {
                case 'GET':
                    $this->executeGet($ch);
                    break;
                case 'POST':
                    $this->executePost($ch);
                    break;
                case 'PUT':
                    $this->executePut($ch);
                    break;
                case 'DELETE':
                    $this->executeDelete($ch);
                    break;
                default:
                    throw new \InvalidArgumentException(
                        'Current verb (' . $this->verb
                        . ') is an invalid REST verb.'
                    );
            }
        } catch (\InvalidArgumentException $e) {
            curl_close($ch);
            throw $e;
        } catch (\Exception $e) {
            curl_close($ch);
            throw $e;
        }

        /*
         * check and debug api request total time
         */
        $this->processDebugApi();

        return $this->responseBody;
    }
149969
protected function loadClient(): void
    {
        if (self::$client === null) {
            $options = $this->options;

            if (!isset($options['servlet_address'])) {
                throw new Exception\InvalidArgumentException(__METHOD__.' Missing required parameter servlet_address');
            }

            $connection = static::parseServletUrl($options['servlet_address']);

            $params = new ArrayObject([
                Client::PARAM_JAVA_HOSTS => $connection['servlet_host'],
                Client::PARAM_JAVA_SERVLET => $connection['servlet_uri'],
                Client::PARAM_JAVA_AUTH_USER => $connection['auth_user'],
                Client::PARAM_JAVA_AUTH_PASSWORD => $connection['auth_password'],
                Client::PARAM_JAVA_DISABLE_AUTOLOAD => $options['java_disable_autoload'],
                Client::PARAM_JAVA_PREFER_VALUES => $options['java_prefer_values'],
                Client::PARAM_JAVA_SEND_SIZE => $options['java_send_size'],
                Client::PARAM_JAVA_RECV_SIZE => $options['java_recv_size'],
                Client::PARAM_JAVA_LOG_LEVEL => $options['java_log_level'],
                Client::PARAM_XML_PARSER_FORCE_SIMPLE_PARSER => $options['force_simple_xml_parser'],
                Client::PARAM_USE_PERSISTENT_CONNECTION => $options['use_persistent_connection']
            ]);

            self::$client = new Client($params, $this->logger);

            // Added in order to work with custom exceptions
            self::getClient()->throwExceptionProxyFactory = new Proxy\DefaultThrowExceptionProxyFactory(self::$client, $this->logger);

            $this->bootstrap();
        }
    }
855925
public function encode()
    {
        $this->headers['Content-Type'] = 'application/json';
        $this->body = json_encode($this->body);

        $errorCode = json_last_error();
        $errorMessage = json_last_error_msg();

        if ($errorCode !== 0 && isset($errorMessage)) {
            throw new \OtherCode\Rest\Exceptions\RestException($errorMessage, $errorCode);
        }
    }