public function dispatch($service, $action, $params = array()) { KalturaLog::debug("Dispatching service [" . $service . "], action [" . $action . "] with params " . print_r($params, true)); $start = microtime(true); // prevent impersonate to partner zero $p = isset($params["p"]) && $params["p"] ? $params["p"] : null; if (!$p) { $p = isset($params["partnerId"]) && $params["partnerId"] ? $params["partnerId"] : null; } $GLOBALS["partnerId"] = $p; // set for logger $userId = ""; $ksStr = isset($params["ks"]) ? $params["ks"] : null; if (!$service) { throw new KalturaAPIException(KalturaErrors::SERVICE_NOT_SPECIFIED); } try { // load the service reflector $reflector = new KalturaServiceReflector($service); } catch (Exception $ex) { throw new KalturaAPIException(KalturaErrors::SERVICE_DOES_NOT_EXISTS, $service); } // check if action exists if (!$action) { throw new KalturaAPIException(KalturaErrors::ACTION_NOT_SPECIFIED, $service); } if (!$reflector->isActionExists($action)) { throw new KalturaAPIException(KalturaErrors::ACTION_DOES_NOT_EXISTS, $action, $service); } $actionParams = $reflector->getActionParams($action); // services.ct - check if partner is allowed to access service ... // validate it's ok to access this service $deserializer = new KalturaRequestDeserializer($params); $arguments = $deserializer->buildActionArguments($actionParams); $serviceInstance = $reflector->getServiceInstance(); kCurrentContext::$host = isset($_SERVER["HOSTNAME"]) ? $_SERVER["HOSTNAME"] : null; kCurrentContext::$user_ip = requestUtils::getRemoteAddress(); kCurrentContext::$ps_vesion = "ps3"; kCurrentContext::$service = $reflector->getServiceName(); kCurrentContext::$action = $action; kCurrentContext::$client_lang = isset($params['clientTag']) ? $params['clientTag'] : null; kCurrentContext::initKsPartnerUser($ksStr, $p, $userId); kPermissionManager::init(kConf::get('enable_cache')); // initialize the service before invoking the action on it $serviceInstance->initService($reflector->getServiceId(), $reflector->getServiceName(), $action); $invokeStart = microtime(true); KalturaLog::debug("Invoke start"); $res = $reflector->invoke($action, $arguments); KalturaLog::debug("Invoke took - " . (microtime(true) - $invokeStart) . " seconds"); KalturaLog::debug("Disptach took - " . (microtime(true) - $start) . " seconds"); $this->clearMemory(); return $res; }
/** * Static instantiator - create the reflector with serviceId and optional action name * @param string $service * @param string $action * @return KalturaServiceReflector */ public static function constructFromServiceId($service) { $newInstance = new KalturaServiceReflector(); $newInstance->_serviceId = strtolower($service); $newInstance->_servicesMap = KalturaServicesMap::getMap(); if (!$newInstance->isServiceExists($newInstance->_serviceId)) { throw new Exception("Service [{$service}] does not exists in service list [" . print_r(array_keys($newInstance->_servicesMap), true) . "]"); } $serviceActionItem = $newInstance->_servicesMap[$newInstance->_serviceId]; /* @var $serviceActionItem KalturaServiceActionItem */ $newInstance->_serviceClass = $serviceActionItem->serviceClass; if (!class_exists($newInstance->_serviceClass)) { throw new Exception("Service class [{$newInstance->_serviceClass}] for service [{$service}] does not exists"); } $reflectionClass = new ReflectionClass($newInstance->_serviceClass); $newInstance->_serviceInfo = new KalturaDocCommentParser($reflectionClass->getDocComment()); return $newInstance; }
protected function writeAfterService(KalturaServiceReflector $serviceReflector) { $this->writeTest("\t/**"); $this->writeTest("\t * Called when all tests are done"); $this->writeTest("\t * @param int \$id"); $this->writeTest("\t * @return int"); $this->writeTest("\t * @depends {$this->lastDependencyTest} - TODO: replace {$this->lastDependencyTest} with last test function that uses that id"); $this->writeTest("\t */"); $this->writeTest("\tpublic function testFinished(\$id)"); $this->writeTest("\t{"); $this->writeTest("\t\treturn \$id;"); $this->writeTest("\t}"); $this->writeTest(""); $this->writeTest("}"); $this->writeBase("\t/**"); $this->writeBase("\t * Called when all tests are done"); $this->writeBase("\t * @param int \$id"); $this->writeBase("\t * @return int"); $this->writeBase("\t */"); $this->writeBase("\tabstract public function testFinished(\$id);"); $this->writeBase(""); $this->writeBase("}"); $serviceName = $serviceReflector->getServiceName(); $serviceClass = $serviceReflector->getServiceClass(); $testPath = realpath(dirname(__FILE__) . '/../') . "/tests/api/{$serviceName}"; if ($serviceReflector->isFromPlugin()) { $servicePath = KAutoloader::getClassFilePath($serviceClass); $testPath = realpath(dirname($servicePath) . '/../') . "/tests/services/{$serviceName}"; } $this->writeToFile("{$testPath}/{$serviceClass}BaseTest.php", $this->_txtBase); $this->writeToFile("{$testPath}/{$serviceClass}Test.php", $this->_txtTest, false); $this->writeToFile("{$testPath}/{$serviceClass}Test.php.ini", $this->_txtIni, false); }
/** * (non-PHPdoc) * @see ClientGeneratorFromPhp::writeServiceAction() */ protected function writeServiceAction($serviceId, $serviceName, $action, $actionParams, $outputTypeReflector) { KalturaLog::debug("Service id [{$serviceId}] name [{$serviceName}] action [{$action}]"); /* @var $outputTypeReflector KalturaParamInfo */ if ($outputTypeReflector && $outputTypeReflector->isFile()) { KalturaLog::debug("Service id [{$serviceId}] name [{$serviceName}] action [{$action}] is file"); return; } if (in_array($action, array("list", "clone", "goto"))) { $action = "{$action}Action"; } //KalturaLog::info("Generates action [$serviceName.$action]"); $isBase = false; $testReturnedType = null; $dependency = null; //Set the tests to be the regression tests if ($action == 'add' || $action == 'update' || $action == 'get' || $action == 'listAction' || $action == 'delete') { $isBase = true; } //Createds the dependency between the tests to the add tests if ($action == 'update') { $dependency = 'testAdd'; } if ($action == 'get') { $dependency = 'testUpdate'; } if ($action == 'delete') { $dependency = 'testGet'; } //Special care for add method as it needs to return the id to the other tests if ($action == 'add' || $action == 'update' || $action == 'get') { $outputType = $outputTypeReflector->getType(); $testReturnedType = "{$outputType}"; // for the dependency (CRUD) } if ($action) { $actionName = ucfirst($action); } $this->writeIni(""); $this->writeIni("[test{$actionName}]"); $this->write("\t/**", $isBase); $this->write("\t * Tests {$serviceName}->{$action} action", $isBase); $testParams = array(); $testValues = array(); $validateValues = array(); foreach ($actionParams as $actionParam) { $this->setTestParamsAndValues($actionParam, $testParams, $testValues, $validateValues, $isBase); } if ($outputTypeReflector) { $this->setOutputData($outputTypeReflector, $testParams, $testValues, $isBase, $validateValues); } $testParams = implode(', ', $testParams); $testValues = implode(', ', $testValues); $validateValues = implode(', ', $validateValues); $outputType = null; if ($outputTypeReflector) { $outputType = $outputTypeReflector->getType(); } if ($testReturnedType) { $this->lastDependencyTest = "test{$actionName}"; $this->write("\t * @return {$testReturnedType}", $isBase); //will always be for the base } if ($dependency) { $this->write("\t * @depends {$dependency} with data set #0", $isBase); } if (count($testValues)) { $this->write("\t * @dataProvider provideData", $isBase); } $this->writeActionTest($serviceName, $actionName, $action, $testParams, $testValues, $outputType, $isBase, $testReturnedType, $validateValues); if ($isBase && $outputType) { $this->writeBase("\t/**"); $this->writeBase("\t * Validates test{$actionName} results"); $this->writeBase("\t * Hook to be overriden by the extending class"); $this->writeBase("\t * "); $this->writeBase("\t * @param {$outputType} \$resultObject"); $this->writeBase("\t */"); $this->writeBase("\tprotected function validate{$actionName}({$outputType} \$resultObject){}"); $this->writeBase(""); $serviceReflector = KalturaServiceReflector::constructFromServiceId($serviceId); $serviceClass = $serviceReflector->getServiceClass(); $this->writeTest("\t/* (non-PHPdoc)"); $this->writeTest("\t * @see {$serviceClass}TestBase::validate{$actionName}()"); $this->writeTest("\t */"); $this->writeTest("\tprotected function validate{$actionName}({$outputType} \$resultObject)"); $this->writeTest("\t{"); //$this->writeTest(" parent::validate{$actionName}($validateValues);"); $this->writeTest("\t\t// TODO - add your own validations here"); $this->writeTest("\t}"); $this->writeTest(""); } }
private function writeMainClassServiceInitialization(KalturaServiceReflector $serviceReflector) { $serviceName = $serviceReflector->getServiceName(); $serviceClassName = "Kaltura" . $this->upperCaseFirstLetter($serviceName) . "Service"; $this->echoLine("\t\t\$this->{$serviceName} = new {$serviceClassName}(\$this);"); }
<?php require_once "../../bootstrap.php"; KalturaLog::setContext("TESTME"); $service = $_GET["service"]; $serviceReflector = new KalturaServiceReflector($service); $actionsArray = $serviceReflector->getActions(); $actionNames = array_keys($actionsArray); sort($actionNames); $actions = array(); foreach ($actionNames as $actionName) { $actionInfo = $serviceReflector->getActionInfo($actionName); if (!$actionInfo->deprecated) { $actions[] = $actionInfo->action; } } echo json_encode($actions);
private function getServiceActionElement(KalturaServiceReflector $serviceReflector, $actionId) { $outputTypeReflector = $serviceReflector->getActionOutputType($actionId); $actionInfo = $serviceReflector->getActionInfo($actionId); $actionParams = $serviceReflector->getActionParams($actionId); $outputType = null; if ($outputTypeReflector) { $outputType = $outputTypeReflector->getType(); } $actionElement = $this->_doc->createElement("action"); $actionElement->setAttribute("name", $actionInfo->action); foreach ($actionParams as $actionParam) { $actionParamElement = $this->_doc->createElement("param"); $actionParamElement->setAttribute("name", $actionParam->getName()); if ($actionParam->isArray()) { $actionParamElement->setAttribute("type", "array"); $actionParamElement->setAttribute("arrayType", $actionParam->getArrayType()); } elseif ($actionParam->isEnum()) { $actionParamElement->setAttribute("type", "int"); $actionParamElement->setAttribute("enumType", $actionParam->getType()); } else { if ($actionParam->isStringEnum()) { $actionParamElement->setAttribute("type", "string"); $actionParamElement->setAttribute("enumType", $actionParam->getType()); } else { $actionParamElement->setAttribute("type", $actionParam->getType()); } } $actionParamElement->setAttribute("optional", $actionParam->isOptional() ? "1" : "0"); if ($actionParam->isOptional()) { switch ($actionParam->getType()) { case "bool": if ($actionParam->getDefaultValue() === true) { $actionParamElement->setAttribute("default", "true"); } else { if ($actionParam->getDefaultValue() === false) { $actionParamElement->setAttribute("default", "false"); } } break; case "int": case "float": case "string": if ($actionParam->getDefaultValue() === null) { $actionParamElement->setAttribute("default", "null"); } else { $actionParamElement->setAttribute("default", $actionParam->getDefaultValue()); } break; default: if ($actionParam->isEnum()) { $actionParamElement->setAttribute("default", $actionParam->getDefaultValue()); } else { $actionParamElement->setAttribute("default", "null"); } } } $description = $actionParam->getDescription(); $description = $this->fixDescription($description); $actionParamElement->setAttribute("description", $description); $actionElement->appendChild($actionParamElement); } $resultElement = $this->_doc->createElement("result"); $arrayType = null; if ($outputTypeReflector) { if ($outputTypeReflector->isArray()) { $resultElement->setAttribute("type", "array"); $arrayType = $outputTypeReflector->getArrayType(); $resultElement->setAttribute("arrayType", $arrayType); } else { $resultElement->setAttribute("type", $outputType); } } $description = $actionInfo->description; $description = $this->fixDescription($description); $actionElement->setAttribute("description", $description); $actionElement->appendChild($resultElement); return $actionElement; }
static function cacheMap($servicePath, $cacheFilePath) { if (!is_dir($servicePath)) { throw new Exception('Invalid directory [' . $servicePath . ']'); } $servicePath = realpath($servicePath); $serviceMap = array(); $classMap = KAutoloader::getClassMap(); $checkedClasses = array(); //Retrieve all service classes from the classMap. $serviceClasses = array(); foreach ($classMap as $class => $classFilePath) { $classFilePath = realpath($classFilePath); if (strpos($classFilePath, $servicePath) === 0) { $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isSubclassOf('KalturaBaseService')) { $serviceDoccomment = new KalturaDocCommentParser($reflectionClass->getDocComment()); $serviceClasses[$serviceDoccomment->serviceName] = $class; } } } //Retrieve all plugin service classes. $pluginInstances = KalturaPluginManager::getPluginInstances('IKalturaServices'); foreach ($pluginInstances as $pluginName => $pluginInstance) { $pluginServices = $pluginInstance->getServicesMap(); foreach ($pluginServices as $serviceName => $serviceClass) { $serviceName = strtolower($serviceName); $serviceId = "{$pluginName}_{$serviceName}"; $serviceClasses[$serviceId] = $serviceClass; } } //Add core & plugin services to the services map $aliasActions = array(); foreach ($serviceClasses as $serviceId => $serviceClass) { $serviceReflectionClass = KalturaServiceReflector::constructFromClassName($serviceClass); $serviceMapEntry = new KalturaServiceActionItem(); $serviceMapEntry->serviceId = $serviceId; $serviceMapEntry->serviceClass = $serviceClass; $serviceMapEntry->serviceInfo = $serviceReflectionClass->getServiceInfo(); $actionMap = array(); $nativeActions = $serviceReflectionClass->getActions(); foreach ($nativeActions as $actionId => $actionName) { $actionMap[strtolower($actionId)] = array("serviceClass" => $serviceClass, "actionMethodName" => $actionName, "serviceId" => $serviceId, "actionName" => $actionId); } $serviceMapEntry->actionMap = $actionMap; $serviceMap[strtolower($serviceId)] = $serviceMapEntry; foreach ($serviceReflectionClass->getAliasActions() as $alias => $methodName) { $aliasActions[$alias] = "{$serviceId}.{$methodName}"; } } // add aliases foreach ($aliasActions as $aliasAction => $sourceAction) { list($aliasService, $aliasAction) = explode('.', $aliasAction); list($sourceService, $sourceAction) = explode('.', $sourceAction); $aliasService = strtolower($aliasService); $sourceService = strtolower($sourceService); $extServiceClass = $serviceClasses[$sourceService]; $serviceMap[$aliasService]->actionMap[strtolower($aliasAction)] = array("serviceClass" => $extServiceClass, "actionMethodName" => $sourceAction, "serviceId" => $sourceService, "actionName" => $aliasAction); } // filter out services that have no actions $serviceMap = array_filter($serviceMap, array('KalturaServicesMap', 'filterEmptyServices')); if (!is_dir(dirname($cacheFilePath))) { mkdir(dirname($cacheFilePath)); chmod(dirname($cacheFilePath), 0755); } kFile::safeFilePutContents($cacheFilePath, serialize($serviceMap), 0644); }
private function testSingleService($service, $testedClient, $permissions, $alwaysAllowedActions) { $serviceReflector = new KalturaServiceReflector($service); $actions = array_keys($serviceReflector->getActions()); $serviceName = $serviceReflector->getServiceName(); foreach ($actions as $action) { // Params $actionParams = $serviceReflector->getActionParams($action); $params = array(); foreach ($actionParams as $actionParam) { $actionName = $actionParam->getName(); $typeName = $actionParam->getType(); if ($typeName == "KalturaPermissionItem") { $params[] = new KalturaApiActionPermissionItem(); continue; } if ($actionParam->isComplexType()) { if ($actionParam->isArray()) { $params[] = array(); } else { $type = $actionParam->getTypeReflector(); if ($type != null) { if (!$type->isAbstract()) { $params[] = $type->getInstance(); } else { //TODO: handle abstract classes $params[] = new KalturaApiActionPermissionItem(); } } else { $params[] = null; } } } else { $params[] = 0; } } if ($action == "list") { $action .= "Action"; } try { call_user_func_array(array($testedClient->{$serviceName}, $action), $params); //TODO: Handle non exception cases $this->compareServiceAction($permissions, $alwaysAllowedActions, $serviceName, $action); } catch (Exception $ex) { //Check if the service / action is found in the user permissions $this->compareServiceAction($permissions, $alwaysAllowedActions, $serviceName, $action, $ex); } } }
/** * (non-PHPdoc) * @see ClientGeneratorFromPhp::writeServiceAction() */ protected function writeServiceAction($serviceId, $serviceName, $action, $actionParams, $outputTypeReflector) { if ($outputTypeReflector && $outputTypeReflector->isFile()) { return; } if (in_array($action, array("list", "clone", "goto"))) { $action = "{$action}Action"; } //KalturaLog::info("Generates action [$serviceName.$action]"); $isBase = false; $testReturnedType = null; $addId = false; //Set the tests to be the regression tests if ($action == 'add' || $action == 'update' || $action == 'get' || $action == 'listAction' || $action == 'delete' || $action == 'addFromEntry' && $serviceName == 'documents') { $isBase = true; } //Createds the dependency between the tests to the add tests if ($action == 'update' || $action == 'get' || $action == 'delete') { // || $action == 'listAction' TODO: add list if needed $addId = true; } //Special care for add method as it needs to return the id to the other tests if ($action == 'add' || $action == 'addFromEntry' && $serviceName == 'documents') { //TODO: support return type of int $outputType = $outputTypeReflector->getType(); $testReturnedType = "{$outputType}"; // for the dependency (CRUD) } //TODO:delete this $resgressionTests = array('add', 'get', 'delete', 'update', 'listAction'); if (!in_array($action, $resgressionTests)) { return; } if ($action) { $actionName = ucfirst($action); } $this->writeIni(""); $this->writeIni("[test{$actionName}]"); $this->writeXml("<TestProcedureData testProcedureName='test{$actionName}'>"); $this->writeXml("\t<TestCaseData testCaseInstanceName='test{$actionName} with data set #0'>"); $this->writeXmlSource("\t\t<TestProcedureData testProcedureName='test{$actionName}'>"); $this->writeXmlSource("\t\t\t<TestCaseData testCaseInstanceName='test{$actionName} with template data set'>"); $this->write("\t/**", $isBase); $this->write("\t * Tests {$serviceName}->{$action} action", $isBase); $testParams = array(); $testValues = array(); $validateValues = array(); foreach ($actionParams as $actionParam) { $this->setTestParamsAndValues($actionParam, $testParams, $testValues, $validateValues, $addId, $isBase); } if ($outputTypeReflector) { $this->setOutputData($outputTypeReflector, $testParams, $testValues, $isBase, $validateValues); } $this->writeXml("\t</TestCaseData>"); $this->writeXml("</TestProcedureData>"); $this->writeXmlSource("\t\t\t</TestCaseData>"); $this->writeXmlSource("\t\t</TestProcedureData>"); $testParams = implode(', ', $testParams); $testValues = implode(', ', $testValues); $validateValues = implode(', ', $validateValues); $outputType = null; if ($outputTypeReflector) { $outputType = $outputTypeReflector->getType(); } if ($testReturnedType) { $this->lastDependencyTest = "test{$actionName}"; $this->write("\t * @return {$testReturnedType}", $isBase); //will always be for the base } if ($addId) { $this->write("\t * @depends testAdd with data set #{$this->dependencyIndex}", $isBase); $this->dependencyIndex++; } if (count($testValues)) { $this->write("\t * @dataProvider provideData", $isBase); } $this->writeActionTest($serviceName, $actionName, $action, $testParams, $testValues, $outputType, $isBase, $testReturnedType, $validateValues); if ($isBase && $outputType) { $this->writeBase("\t/**"); $this->writeBase("\t * Validates test{$actionName} results"); $this->writeBase("\t * Hook to be overriden by the extending class"); $this->writeBase("\t * "); $this->writeBase("\t * @param {$outputType} \$resultObject"); $this->writeBase("\t */"); $this->writeBase("\tprotected function validate{$actionName}({$outputType} \$resultObject){}"); $this->writeBase(""); $serviceReflector = KalturaServiceReflector::constructFromServiceId($serviceId); $serviceClass = $serviceReflector->getServiceClass(); $this->writeTest("\t/* (non-PHPdoc)"); $this->writeTest("\t * @see {$serviceClass}TestBase::validate{$actionName}()"); $this->writeTest("\t */"); $this->writeTest("\tprotected function validate{$actionName}({$outputType} \$resultObject)"); $this->writeTest("\t{"); //$this->writeTest(" parent::validate{$actionName}($validateValues);"); $this->writeTest("\t\t// TODO - add your own validations here"); $this->writeTest("\t}"); $this->writeTest(""); } }
public function setIncludeOrExcludeList($include, $exclude) { // load full list of actions and services $fullList = array(); $serviceMap = KalturaServicesMap::getMap(); $services = array_keys($serviceMap); foreach ($services as $service) { $serviceReflector = new KalturaServiceReflector($service); $actions = $serviceReflector->getActions(); foreach ($actions as &$action) { // we need only the keys $action = true; } $fullList[$service] = $actions; } $includeList = array(); if ($include !== null) { $tempList = explode(",", str_replace(" ", "", $include)); foreach ($tempList as $item) { $service = null; $action = null; $item = strtolower($item); if (strpos($item, ".") !== false) { list($service, $action) = explode(".", $item); } if (!key_exists($service, $includeList)) { $includeList[$service] = array(); } if ($action == "*") { if (!array_key_exists($service, $fullList)) { throw new Exception("Service [{$service}] not found"); } $includeList[$service] = $fullList[$service]; } else { $includeList[$service][$action] = true; } } } else { if ($exclude !== null) { $includeList = $fullList; $tempList = explode(",", str_replace(" ", "", $exclude)); foreach ($tempList as $item) { $service = null; $action = null; $item = strtolower($item); if (strpos($item, ".") !== false) { list($service, $action) = explode(".", $item); } if ($action == "*") { // KalturaLog::debug("Excluding service [$service]"); unset($includeList[$service]); } else { // KalturaLog::debug("Excluding action [$service.$action]"); unset($includeList[$service][$action]); } } } else { $includeList = $fullList; } } $this->setIncludeList($includeList); }
<?php try { $serviceReflector = new KalturaServiceReflector($service); } catch (Exception $ex) { die('Service "' . $service . '" not found'); } $actions = $serviceReflector->getActions(); try { $actionParams = $serviceReflector->getActionParams($action); } catch (Exception $ex) { die('Action "' . $action . '" does not exist for service "' . $service . '"'); } $actionInfo = $serviceReflector->getActionInfo($action); ?> <h2>Kaltura API</h2> <table class="action"> <tr> <th colspan="3" class="service_action_title"><?php echo $service; ?> :<?php echo $action; ?> </th> </tr> <tr> <td colspan="3" class="title">Description:</td> </tr> <tr> <td class="description" colspan="3"><?php
<?php require_once "../../bootstrap.php"; KalturaLog::setContext("TESTME"); $service = $_GET["service"]; $action = $_GET["action"]; $bench_start = microtime(true); KalturaLog::INFO(">------- api_v3 testme [{$service}][{$action}]-------"); function toArrayRecursive(KalturaPropertyInfo $propInfo) { return $propInfo->toArray(); } $actionInfo = null; try { $serviceReflector = new KalturaServiceReflector($service); $actionParams = $serviceReflector->getActionParams($action); $actionInfo = $serviceReflector->getActionInfo($action); $actionInfo = array("actionParams" => array(), "description" => $actionInfo->description); foreach ($actionParams as $actionParam) { $actionInfo["actionParams"][] = toArrayRecursive($actionParam); } } catch (Exception $ex) { KalturaLog::ERR("<------- api_v3 testme [{$service}][{$action}\n" . $ex->__toString() . " " . " -------"); } //echo "<pre>"; //echo print_r($actionInfo); echo json_encode($actionInfo); $bench_end = microtime(true); KalturaLog::INFO("<------- api_v3 testme [{$service}][{$action}][" . ($bench_end - $bench_start) . "] -------");