java_headers.append(os.path.join(java_headers[0], 'solaris'))
simulator_env.AppendUnique(CPPPATH = java_headers)
+ simulator_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
+
simulator_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
-simulator_env.PrependUnique(LIBS = ['octbstack', 'oc', 'RamlParser'])
+simulator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'RamlParser'])
simulator_env.AppendUnique(LIBS = ['pthread'])
- simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+ simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-Wall', '-fmessage-length=0', '-std=c++0x'])
######################################################################
# Source files and Targets
void GETRequestGenerator::SendAllRequests()
{
// Notify the progress status
- OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ OIC_LOG(DEBUG, TAG, "Sending OP_START event");
m_callback(m_id, OP_START);
+ QPGenerator queryParamGen(m_requestSchema->getQueryParams());
do
{
- if (!m_stopRequested)
- {
- // Get the next possible queryParameter
- std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+ // Get the next possible queryParameter
+ auto queryParam = queryParamGen.next();
+ try
+ {
// Send the request
- try
- {
- m_requestSender->sendRequest(queryParam, std::bind(&GETRequestGenerator::onResponseReceived, this,
- std::placeholders::_1, std::placeholders::_2), true);
- m_requestCnt++;
- }
- catch (SimulatorException &e)
- {
- m_stopRequested = true;
- return completed();
- }
+ m_requestSender.send(queryParam, std::bind(&GETRequestGenerator::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+ m_requestCnt++;
+ }
+ catch (SimulatorException &e)
+ {
+ m_stopRequested = true;
+ break;
}
}
- while (m_queryParamGen.hasNext());
+ while (!m_stopRequested && queryParamGen.hasNext());
- m_requestsSent = true;
completed();
}
void GETRequestGenerator::onResponseReceived(SimulatorResult result,
- SimulatorResourceModelSP repModel)
+ const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
{
- OIC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
- OC_LOG(DEBUG, TAG, "Response recieved");
++ OIC_LOG(DEBUG, TAG, "Response recieved");
m_responseCnt++;
completed();
}
void POSTRequestGenerator::SendAllRequests()
{
// Notify the progress status
- OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ OIC_LOG(DEBUG, TAG, "Sending OP_START event");
m_callback(m_id, OP_START);
- OC_LOG(ERROR, TAG, "Request representation model is null!");
+ std::shared_ptr<SimulatorResourceModelSchema> repSchema =
+ m_requestSchema->getRequestRepSchema();
+
+ if (!repSchema)
+ {
++ OIC_LOG(ERROR, TAG, "Request representation model is null!");
+ m_callback(m_id, OP_COMPLETE);
+ return;
+ }
+
// Create attribute generator for value manipulation
std::vector<AttributeGenerator> attributeGenList;
- for (auto &attributeElement : m_rep->getAttributes())
- attributeGenList.push_back(AttributeGenerator(attributeElement.second));
+ for (auto &propertyElement : repSchema->getChildProperties())
+ attributeGenList.push_back(AttributeGenerator(propertyElement.first, propertyElement.second));
if (!attributeGenList.size())
{
}
void POSTRequestGenerator::onResponseReceived(SimulatorResult result,
- SimulatorResourceModelSP repModel)
+ const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
{
- OIC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
- OC_LOG(DEBUG, TAG, "Response recieved");
++ OIC_LOG(DEBUG, TAG, "Response recieved");
m_responseCnt++;
completed();
}
void PUTRequestGenerator::SendAllRequests()
{
- OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ OIC_LOG(DEBUG, TAG, "Sending OP_START event");
m_callback(m_id, OP_START);
- OC_LOG(ERROR, TAG, "Request representation model is null!");
+ std::shared_ptr<SimulatorResourceModelSchema> repSchema =
+ m_requestSchema->getRequestRepSchema();
+
+ if (!repSchema)
+ {
++ OIC_LOG(ERROR, TAG, "Request representation model is null!");
+ m_callback(m_id, OP_ABORT);
+ return;
+ }
+
+ SimulatorResourceModel representation = repSchema->buildResourceModel();
+
// Create attribute combination generator for generating resource model
// with different attribute values
- std::vector<SimulatorResourceModel::Attribute> attributes;
- for (auto &attributeElement : m_rep->getAttributes())
+ std::vector<SimulatorResourceAttribute> attributes;
+ for (auto &attributeElement : representation.getAttributeValues())
{
- attributes.push_back(attributeElement.second);
+ SimulatorResourceAttribute attribute;
+ attribute.setName(attributeElement.first);
+ attribute.setValue(attributeElement.second);
+ attribute.setProperty(repSchema->get(attributeElement.first));
+ attributes.push_back(attribute);
}
if (!attributes.size())
{
- OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+ OIC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+ m_callback(m_id, OP_COMPLETE);
return;
}
}
void PUTRequestGenerator::onResponseReceived(SimulatorResult result,
- SimulatorResourceModelSP repModel)
+ const SimulatorResourceModel &repModel, const RequestInfo &reqInfo)
{
- OIC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
- OC_LOG(DEBUG, TAG, "Response recieved");
++ OIC_LOG(DEBUG, TAG, "Response recieved");
m_responseCnt++;
completed();
}
#define TAG "AUTO_REQ_GEN_MNGR"
- int AutoRequestGenMngr::startOnGET(RequestSenderSP requestSender,
- const std::map<std::string, std::vector<std::string>> &queryParams,
- AutoRequestGeneration::ProgressStateCallback callback)
+ RequestAutomationMngr::RequestAutomationMngr(
+ const std::shared_ptr<OC::OCResource> &ocResource)
+ : m_id(0), m_ocResource(ocResource) {}
+
+ int RequestAutomationMngr::startOnGET(
+ const std::shared_ptr<RequestModel> &requestSchema,
+ RequestGeneration::ProgressStateCallback callback)
{
- // Input validation
- if (!requestSender)
+ if (!requestSchema)
{
- throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
- OC_LOG(ERROR, TAG, "Request schema is null!");
++ OIC_LOG(ERROR, TAG, "Request schema is null!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
}
if (!callback)
{
- OC_LOG(ERROR, TAG, "Invalid callback!");
++ OIC_LOG(ERROR, TAG, "Invalid callback!");
throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
}
// Check is there auto request generation session already going on for GET requests
if (isInProgress(RequestType::RQ_TYPE_GET))
{
- throw OperationInProgressException("Another GET request generation session is already in progress!");
- OC_LOG(ERROR, TAG, "Auto requesting for GET is already in progress!");
++ OIC_LOG(ERROR, TAG, "Auto requesting for GET is already in progress!");
+ throw OperationInProgressException(
+ "Another GET request generation session is already in progress!");
}
// Create request generation session
return m_id++;
}
- int AutoRequestGenMngr::startOnPUT(RequestSenderSP requestSender,
- const std::map<std::string, std::vector<std::string>> &queryParams,
- SimulatorResourceModelSP resModel,
- AutoRequestGeneration::ProgressStateCallback callback)
+ int RequestAutomationMngr::startOnPUT(const std::shared_ptr<RequestModel> &requestSchema,
+ RequestGeneration::ProgressStateCallback callback)
{
- // Input validation
- if (!requestSender)
+ if (!requestSchema)
{
- throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
- OC_LOG(ERROR, TAG, "Request schema is null!");
++ OIC_LOG(ERROR, TAG, "Request schema is null!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
}
if (!callback)
{
- OC_LOG(ERROR, TAG, "Invalid callback!");
++ OIC_LOG(ERROR, TAG, "Invalid callback!");
throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
}
// Check is there auto request generation session already going on for GET requests
if (isInProgress(RequestType::RQ_TYPE_PUT))
{
- throw OperationInProgressException("Another GET request generation session is already in progress!");
- OC_LOG(ERROR, TAG, "Auto requesting for PUT is already in progress!");
++ OIC_LOG(ERROR, TAG, "Auto requesting for PUT is already in progress!");
+ throw OperationInProgressException(
+ "Another PUT request generation session is already in progress!");
}
// Create request generation session
return m_id++;
}
- int AutoRequestGenMngr::startOnPOST(RequestSenderSP requestSender,
- const std::map<std::string, std::vector<std::string>> &queryParams,
- SimulatorResourceModelSP resModel,
- AutoRequestGeneration::ProgressStateCallback callback)
+ int RequestAutomationMngr::startOnPOST(const std::shared_ptr<RequestModel> &requestSchema,
+ RequestGeneration::ProgressStateCallback callback)
{
- // Input validation
- if (!requestSender)
+ if (!requestSchema)
{
- throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
- OC_LOG(ERROR, TAG, "Request schema is null!");
++ OIC_LOG(ERROR, TAG, "Request schema is null!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Request model is null!");
}
if (!callback)
{
- OC_LOG(ERROR, TAG, "Invalid callback!");
++ OIC_LOG(ERROR, TAG, "Invalid callback!");
throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
}
// Check is there auto request generation session already going on for GET requests
if (isInProgress(RequestType::RQ_TYPE_POST))
{
- throw OperationInProgressException("Another GET request generation session is already in progress!");
- OC_LOG(ERROR, TAG, "Auto requesting for POST is already in progress!");
++ OIC_LOG(ERROR, TAG, "Auto requesting for POST is already in progress!");
+ throw OperationInProgressException(
+ "Another POST request generation session is already in progress!");
}
// Create request generation session
std::lock_guard<std::mutex> lock(m_observeLock);
if (m_observeState)
{
- OC_LOG(ERROR, TAG, "Resource is already being observed!");
++ OIC_LOG(ERROR, TAG, "Resource is already being observed!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Resource is already being observed!")
+
throw SimulatorException(SIMULATOR_ERROR, "Resource is already being observed!");
}
{
OCStackResult ocResult = m_ocResource->cancelObserve(OC::QualityOfService::HighQos);
if (OC_STACK_OK != ocResult)
- throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+ {
- OC_LOG(ERROR, TAG, "Cancelling observe failed!");
++ OIC_LOG(ERROR, TAG, "Cancelling observe failed!");
+ SIM_LOG(ILogger::INFO, "[URI: " << getURI() << "] Sending OBSERVE cancel request failed!")
+
+ throw SimulatorException(static_cast<SimulatorResult>(ocResult),
+ OC::OCException::reason(ocResult));
+ }
- SIM_LOG(ILogger::INFO, "OBSERVE CANCEL request sent");
+ SIM_LOG(ILogger::INFO, "[URI: " << getURI() << "] Sent OBSERVE cancel request.")
}
catch (OC::OCException &e)
{
{
VALIDATE_CALLBACK(callback)
- if (!m_getRequestSender)
+ SimulatorResult result = m_getRequestSender.send(std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid GET request sender!");
- throw NoSupportException("Can not send GET request on this resource!");
- }
- OC_LOG(ERROR, TAG, "Failed to send GET request!");
++ OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
- m_getRequestSender->sendRequest(interfaceType, queryParams,
- nullptr, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ throw SimulatorException(result, "Failed to send GET request!");
+ }
}
void SimulatorRemoteResourceImpl::get(const std::map<std::string, std::string> &queryParams,
{
VALIDATE_CALLBACK(callback)
- if (!m_getRequestSender)
+ SimulatorResult result = m_getRequestSender.send(queryParams, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid GET request sender !");
- throw NoSupportException("Can not send GET request on this resource!");
- }
- OC_LOG(ERROR, TAG, "Failed to send GET request!");
++ OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
- m_getRequestSender->sendRequest(std::string(), queryParams,
- nullptr, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ throw SimulatorException(result, "Failed to send GET request!");
+ }
}
- void SimulatorRemoteResourceImpl::put(const std::string &interfaceType,
+ void SimulatorRemoteResourceImpl::get(const std::string &interfaceType,
const std::map<std::string, std::string> &queryParams,
- SimulatorResourceModelSP resourceModel,
- ResponseCallback callback)
+ const GetResponseCallback &callback)
{
VALIDATE_CALLBACK(callback)
- if (!m_putRequestSender)
+ std::map<std::string, std::string> queryParamsCpy = queryParams;
+ if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
{
- OIC_LOG(ERROR, TAG, "Invalid PUT request sender !");
- throw NoSupportException("Can not send PUT request on this resource!");
+ queryParamsCpy["if"] = interfaceType;
}
- m_putRequestSender->sendRequest(interfaceType, queryParams,
- resourceModel, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ SimulatorResult result = m_getRequestSender.send(queryParamsCpy, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
+ {
- OC_LOG(ERROR, TAG, "Failed to send GET request!");
++ OIC_LOG(ERROR, TAG, "Failed to send GET request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send GET request!")
+
+ throw SimulatorException(result, "Failed to send GET request!");
+ }
}
- void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
- SimulatorResourceModelSP resourceModel,
- ResponseCallback callback)
+ void SimulatorRemoteResourceImpl::put(const SimulatorResourceModel &representation,
+ const PutResponseCallback &callback)
{
VALIDATE_CALLBACK(callback)
- if (!m_putRequestSender)
+ SimulatorResult result = m_putRequestSender.send(representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid PUT request sender !");
- throw NoSupportException("Can not send PUT request on this resource!");
- }
- OC_LOG(ERROR, TAG, "Failed to send PUT request!");
++ OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
- m_putRequestSender->sendRequest(std::string(), queryParams,
- resourceModel, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ throw SimulatorException(result, "Failed to send PUT request!");
+ }
}
- void SimulatorRemoteResourceImpl::post(const std::string &interfaceType,
- const std::map<std::string, std::string> &queryParams,
- SimulatorResourceModelSP resourceModel,
- ResponseCallback callback)
+ void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
+ const SimulatorResourceModel &representation,
+ const PutResponseCallback &callback)
{
VALIDATE_CALLBACK(callback)
- if (!m_postRequestSender)
+ SimulatorResult result = m_putRequestSender.send(queryParams, representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid POST request sender !");
- throw NoSupportException("Can not send POST request on this resource!");
- }
- OC_LOG(ERROR, TAG, "Failed to send PUT request!");
++ OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
- m_postRequestSender->sendRequest(interfaceType, queryParams,
- resourceModel, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ throw SimulatorException(result, "Failed to send PUT request!");
+ }
}
- void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
- SimulatorResourceModelSP resourceModel,
- ResponseCallback callback)
+ void SimulatorRemoteResourceImpl::put(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ const SimulatorResourceModel &representation,
+ const PutResponseCallback &callback)
{
VALIDATE_CALLBACK(callback)
- if (!m_postRequestSender)
+ std::map<std::string, std::string> queryParamsCpy = queryParams;
+ if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
{
- OIC_LOG(ERROR, TAG, "Invalid POST request sender !");
- throw NoSupportException("Can not send POST request on this resource!");
+ queryParamsCpy["if"] = interfaceType;
}
- m_postRequestSender->sendRequest(std::string(), queryParams,
- resourceModel, std::bind(
- &SimulatorRemoteResourceImpl::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2, callback));
+ SimulatorResult result = m_putRequestSender.send(queryParamsCpy, representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
+ {
- OC_LOG(ERROR, TAG, "Failed to send PUT request!");
++ OIC_LOG(ERROR, TAG, "Failed to send PUT request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send PUT request!")
+
+ throw SimulatorException(result, "Failed to send PUT request!");
+ }
}
- int SimulatorRemoteResourceImpl::startVerification(RequestType type,
- StateCallback callback)
+ void SimulatorRemoteResourceImpl::post(const SimulatorResourceModel &representation,
+ const PostResponseCallback &callback)
{
VALIDATE_CALLBACK(callback)
- if (!m_autoRequestGenMngr)
+ SimulatorResult result = m_postRequestSender.send(representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
- throw NoSupportException("Resource is not configured with RAML!");
- OC_LOG(ERROR, TAG, "Failed to send POST request!");
++ OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
+
+ throw SimulatorException(result, "Failed to send POST request!");
}
+ }
- if (m_requestModelList.end() == m_requestModelList.find(type))
- throw NoSupportException("Resource does not support this request type!");
+ void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
+ const SimulatorResourceModel &representation,
+ const PostResponseCallback &callback)
+ {
+ VALIDATE_CALLBACK(callback)
- // Local callback for handling progress sate callback
- AutoRequestGeneration::ProgressStateCallback localCallback = [this, callback](
- int sessionId, OperationState state)
- {
- callback(m_id, sessionId, state);
- };
+ SimulatorResult result = m_postRequestSender.send(queryParams, representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
- switch (type)
+ if (SIMULATOR_OK != result)
{
- case RequestType::RQ_TYPE_GET:
- if (m_getRequestSender)
- {
- return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
- localCallback);
- }
- break;
- OC_LOG(ERROR, TAG, "Failed to send POST request!");
++ OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
- case RequestType::RQ_TYPE_PUT:
- if (m_putRequestSender)
- {
- return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
- }
- break;
-
- case RequestType::RQ_TYPE_POST:
- if (m_postRequestSender)
- {
- return m_autoRequestGenMngr->startOnPOST(m_postRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
- localCallback);
- }
- break;
-
- case RequestType::RQ_TYPE_DELETE:
- default:
- throw NoSupportException("Resource does not support this request type!");
+ throw SimulatorException(result, "Failed to send POST request!");
}
-
- return -1; // Code should not reach here
}
- void SimulatorRemoteResourceImpl::stopVerification(int id)
+ void SimulatorRemoteResourceImpl::post(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ const SimulatorResourceModel &representation,
+ const PostResponseCallback &callback)
{
- if (id < 0)
+ VALIDATE_CALLBACK(callback)
+
+ std::map<std::string, std::string> queryParamsCpy = queryParams;
+ if (!interfaceType.empty() && queryParamsCpy.end() == queryParamsCpy.find("if"))
{
- OIC_LOG(ERROR, TAG, "Invalid session id!");
- throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid ID!");
+ queryParamsCpy["if"] = interfaceType;
}
- if (!m_autoRequestGenMngr)
+ SimulatorResult result = m_postRequestSender.send(queryParamsCpy, representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3, callback));
+
+ if (SIMULATOR_OK != result)
{
- OIC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
- throw NoSupportException("Resource is not configured with RAML!");
- }
- OC_LOG(ERROR, TAG, "Failed to send POST request!");
++ OIC_LOG(ERROR, TAG, "Failed to send POST request!");
+ SIM_LOG(ILogger::ERROR, "[URI: " << getURI() << "] Failed to send POST request!")
- m_autoRequestGenMngr->stop(id);
+ throw SimulatorException(result, "Failed to send POST request!");
+ }
}
- SimulatorResourceModelSP SimulatorRemoteResourceImpl::configure(const std::string &path)
+ std::map<RequestType, SimulatorRequestModel>
+ SimulatorRemoteResourceImpl::configure(const std::string &path)
{
VALIDATE_INPUT(path.empty(), "Path is empty!")
- std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(path);
- RAML::RamlPtr raml = ramlParser->getRamlPtr();
-
- configure(raml);
+ try
+ {
+ std::shared_ptr<RAML::RamlParser> ramlParser =
+ std::make_shared<RAML::RamlParser>(path);
+ RAML::RamlPtr raml = ramlParser->getRamlPtr();
- if (m_requestModelList.empty())
- throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "RAML file is invalid for the resource!");
+ m_requestModels = RequestModelBuilder().build(raml, m_ocResource->uri());
+ }
+ catch (RAML::RamlException &e)
+ {
+ throw SimulatorException(SIMULATOR_ERROR, "Failed to configure resource!");
+ }
- for (auto &model : m_requestModelList)
+ std::map<RequestType, SimulatorRequestModel> requestModels;
+ for (auto &requestModelEntry : m_requestModels)
{
- SimulatorResourceModelSP schema = (model.second)->getRepSchema();
- if (schema)
- {
- return std::make_shared<SimulatorResourceModel>(*(schema.get()));
- }
+ RequestType requestType = requestTypeToEnum(requestModelEntry.first);
+ SimulatorRequestModel requestModel(requestType);
+ requestModel.setQueryParams((requestModelEntry.second)->getQueryParams());
+ requestModel.setRequestBodySchema((requestModelEntry.second)->getRequestRepSchema());
+
+ requestModels[requestType] = requestModel;
}
- return std::make_shared<SimulatorResourceModel>();
+ return requestModels;
}
- void SimulatorRemoteResourceImpl::configure(std::shared_ptr<RAML::Raml> &raml)
+ int SimulatorRemoteResourceImpl::startAutoRequesting(RequestType type,
+ AutoRequestGenerationCallback callback)
{
- m_requestModelList = RequestModelBuilder(raml).build(m_ocResource->uri());
- if (m_getRequestSender &&
- m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_GET))
- {
- m_getRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_GET]);
- }
+ VALIDATE_CALLBACK(callback)
- if (m_putRequestSender &&
- m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_PUT))
+ // Check if resource supports request type
+ std::string requestType = requestTypeToString(type);
+ if (m_requestModels.end() == m_requestModels.find(requestType))
{
- m_putRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_PUT]);
- OC_LOG(ERROR, TAG, "Resource is not configured for this request type!");
++ OIC_LOG(ERROR, TAG, "Resource is not configured for this request type!");
+ throw NoSupportException("Resource is not configured for this request type!");
}
- if (m_postRequestSender &&
- m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_POST))
+ std::shared_ptr<RequestModel> requestModel = m_requestModels[requestType];
+ switch (type)
{
- m_postRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_POST]);
- }
+ case RequestType::RQ_TYPE_GET:
+ return m_requestAutomationMngr.startOnGET(requestModel,
+ std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+ std::placeholders::_1, std::placeholders::_2, callback));
- if (!m_autoRequestGenMngr)
- {
- m_autoRequestGenMngr = std::make_shared<AutoRequestGenMngr>();
+ case RequestType::RQ_TYPE_PUT:
+ return m_requestAutomationMngr.startOnPUT(requestModel,
+ std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+ std::placeholders::_1, std::placeholders::_2, callback));
+
+ case RequestType::RQ_TYPE_POST:
+ return m_requestAutomationMngr.startOnPOST(requestModel,
+ std::bind(&SimulatorRemoteResourceImpl::onAutoRequestingState, this,
+ std::placeholders::_1, std::placeholders::_2, callback));
+
+ case RequestType::RQ_TYPE_DELETE:
+ default:
+ throw NoSupportException("Not implemented!");
}
+
+ return -1; // Code should not reach here
+ }
+
+ void SimulatorRemoteResourceImpl::stopAutoRequesting(int id)
+ {
+ m_requestAutomationMngr.stop(id);
}
void SimulatorRemoteResourceImpl::onResponseReceived(SimulatorResult result,
#define TAG "REQ_MODEL_BUILDER"
- RequestModelBuilder::RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml)
- : m_raml (raml) {}
+ static std::string getRequestType(RAML::ActionType actionType)
+ {
+ switch (actionType)
+ {
+ case RAML::ActionType::GET:
+ return "GET";
+ case RAML::ActionType::PUT:
+ return "PUT";
+ case RAML::ActionType::POST:
+ return "POST";
+ case RAML::ActionType::DELETE:
+ return "DELETE";
+ }
- std::map<RequestType, RequestModelSP> RequestModelBuilder::build(const std::string &uri)
+ return ""; // This code should never reach
+ }
+
+ std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build(
+ const std::shared_ptr<RAML::Raml> &raml, const std::string &uri)
{
- std::map<RequestType, RequestModelSP> modelList;
- if (!m_raml)
+ std::unordered_map<std::string, RequestModelSP> requestModels;
+
+ if (!raml)
{
- return modelList;
- OC_LOG(ERROR, TAG, "Raml pointer is null!");
++ OIC_LOG(ERROR, TAG, "Raml pointer is null!");
+ return requestModels;
}
- for (auto &resource : m_raml->getResources())
+ for (auto &resource : raml->getResources())
{
// Pick the resource based on the resource uri.
if (std::string::npos == uri.find((resource.second)->getResourceUri()))
{
RequestModelSP requestModel = createRequestModel(action.second);
if (requestModel)
- modelList[requestModel->type()] = requestModel;
+ {
+ requestModels[requestModel->getType()] = requestModel;
+ }
}
+
+ break;
}
- return modelList;
+ return requestModels;
}
- RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+ std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build(
+ const std::shared_ptr<RAML::RamlResource> &resource)
{
- OIC_LOG(DEBUG, TAG, "Creating request model");
+ std::unordered_map<std::string, RequestModelSP> requestModels;
- OC_LOG(ERROR, TAG, "Resource pointer is null!");
+ if (!resource)
+ {
++ OIC_LOG(ERROR, TAG, "Resource pointer is null!");
+ return requestModels;
+ }
+
+ // Construct Request and Response Model from RAML::Action
+ for (auto &action : resource->getActions())
+ {
+ RequestModelSP requestModel = createRequestModel(action.second);
+ if (requestModel)
+ {
+ requestModels[requestModel->getType()] = requestModel;
+ }
+ }
+
+ return requestModels;
+ }
+
+ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+ {
// Validate the action type. Only GET, PUT, POST and DELETE are supported.
RAML::ActionType actionType = action->getType();
if (actionType != RAML::ActionType::GET
&& actionType != RAML::ActionType::POST
&& actionType != RAML::ActionType::DELETE)
{
- OIC_LOG(ERROR, TAG, "Failed to create request model as it is of unknown type!");
- OC_LOG(ERROR, TAG, "Request model is of unknown type!");
++ OIC_LOG(ERROR, TAG, "Request model is of unknown type!");
return nullptr;
}
return responseModel;
}
- SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::RequestResponseBodyPtr
- &rep)
+ std::shared_ptr<SimulatorResourceModelSchema> RequestModelBuilder::createRepSchema(
+ const RAML::RequestResponseBodyPtr &responseBody)
{
- if (!rep)
- {
- return nullptr;
- }
-
- RAML::SchemaPtr schema = rep->getSchema();
- if (!schema)
+ if (!responseBody)
{
- OC_LOG(ERROR, TAG, "Response body is null!");
++ OIC_LOG(ERROR, TAG, "Response body is null!");
return nullptr;
}
--- /dev/null
- OC_LOG(ERROR, TAG, "RAML schema pointer is null!");
+ /******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+ #include "resource_model_schema_builder.h"
+ #include "simulator_resource_model_schema.h"
+ #include "Raml.h"
+ #include "Properties.h"
+ #include "logger.h"
+
+ #define TAG "RES_MODEL_BUILDER"
+
+ ResourceModelSchemaBuilder::ResourceModelSchemaBuilder(
+ const std::shared_ptr<RAML::RequestResponseBody> &ramlSchema)
+ : m_ramlSchema (ramlSchema) {}
+
+ std::shared_ptr<SimulatorResourceModelSchema> ResourceModelSchemaBuilder::build()
+ {
+ if (!m_ramlSchema)
+ {
- OC_LOG(ERROR, TAG, "Unknown type!");
++ OIC_LOG(ERROR, TAG, "RAML schema pointer is null!");
+ return nullptr;
+ }
+
+ std::shared_ptr<SimulatorResourceModelSchema> modelSchema =
+ SimulatorResourceModelSchema::build();
+
+ auto jsonSchema = m_ramlSchema->getSchema()->getProperties();
+ for (auto &propertyElement : jsonSchema->getProperties())
+ {
+ auto property = propertyElement.second;
+ auto attributeProperty = buildAttribute(property);
+
+ if (!attributeProperty)
+ return nullptr;
+
+ modelSchema->add(property->getName(), attributeProperty);
+ }
+
+ return modelSchema;
+ }
+
+ std::shared_ptr<AttributeProperty> ResourceModelSchemaBuilder::buildAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ switch (property->getType().type())
+ {
+ case RAML::VariantType::INTEGER:
+ return buildIntegerAttribute(property);
+
+ case RAML::VariantType::DOUBLE:
+ return buildDoubleAttribute(property);
+
+ case RAML::VariantType::BOOLEAN:
+ return buildBooleanAttribute(property);
+
+ case RAML::VariantType::STRING:
+ return buildStringAttribute(property);
+
+ case RAML::VariantType::PROPERTY:
+ return buildArrayAttribute(property);
+
+ case RAML::VariantType::ARRAY:
+ return buildModelArrayAttribute(property);
+
+ case RAML::VariantType::OBJECT:
+ return buildModelAttribute(property);
+
+ default:
- OC_LOG(ERROR, TAG, "Unknown array element type!");
++ OIC_LOG(ERROR, TAG, "Unknown type!");
+ return nullptr;
+ }
+
+ return nullptr;
+ }
+
+ std::shared_ptr<IntegerProperty> ResourceModelSchemaBuilder::buildIntegerAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<IntegerProperty> integerProperty = IntegerProperty::build();
+
+ // Set Default value
+ if (property->isDefaultValue())
+ {
+ integerProperty->setDefaultValue(property->getValue<int>());
+ }
+
+ // Set the Range/Enum property
+ for (auto &valueProperty : property->getValueProperties())
+ {
+ if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+ {
+ integerProperty->setRange(valueProperty->min(), valueProperty->max());
+ break;
+ }
+ else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+ {
+ std::vector<int> values;
+ for (auto &value : valueProperty->valueSet())
+ values.push_back(boost::get<int>(value));
+ integerProperty->setValues(values);
+ break;
+ }
+ }
+
+ return integerProperty;
+ }
+
+ std::shared_ptr<DoubleProperty> ResourceModelSchemaBuilder::buildDoubleAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<DoubleProperty> doubleProperty = DoubleProperty::build();
+
+ // Set Default value
+ if (property->isDefaultValue())
+ {
+ doubleProperty->setDefaultValue(property->getValue<double>());
+ }
+
+ // Set the Range/Enum property
+ for (auto &valueProperty : property->getValueProperties())
+ {
+ if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+ {
+ doubleProperty->setRange(valueProperty->min(), valueProperty->max());
+ break;
+ }
+ else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+ {
+ std::vector<double> values;
+ for (auto &value : valueProperty->valueSet())
+ values.push_back(boost::get<double>(value));
+ doubleProperty->setValues(values);
+ break;
+ }
+ }
+
+ return doubleProperty;
+ }
+
+ std::shared_ptr<BooleanProperty> ResourceModelSchemaBuilder::buildBooleanAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<BooleanProperty> boolProperty = BooleanProperty::build();
+
+ // Set Default value
+ if (property->isDefaultValue())
+ {
+ boolProperty->setDefaultValue(property->getValue<bool>());
+ }
+
+ return boolProperty;
+ }
+
+ std::shared_ptr<StringProperty> ResourceModelSchemaBuilder::buildStringAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<StringProperty> stringProperty = StringProperty::build();
+
+ // Set Default value
+ if (property->isDefaultValue())
+ {
+ stringProperty->setDefaultValue(property->getValue<std::string>());
+ }
+
+ // Set the Range/Enum property
+ for (auto &valueProperty : property->getValueProperties())
+ {
+ if (RAML::ValueProperty::Type::RANGE == valueProperty->type())
+ {
+ stringProperty->setRange(valueProperty->min(), valueProperty->max());
+ break;
+ }
+ else if (RAML::ValueProperty::Type::VALUE_SET == valueProperty->type())
+ {
+ std::vector<std::string> values;
+ for (auto &value : valueProperty->valueSet())
+ values.push_back(boost::get<std::string>(value));
+ stringProperty->setValues(values);
+ break;
+ }
+ }
+
+ return stringProperty;
+ }
+
+ std::shared_ptr<ArrayProperty> ResourceModelSchemaBuilder::buildArrayAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<ArrayProperty> arrayProperty = ArrayProperty::build();
+
+ auto arrayAttribute = boost::get<RAML::Properties>(property->getValue());
+ switch (arrayAttribute.getType().type())
+ {
+ case RAML::VariantType::INTEGER:
+ {
+ std::shared_ptr<RAML::Properties> elementAttribute =
+ std::make_shared<RAML::Properties>(arrayAttribute);
+
+ std::shared_ptr<IntegerProperty> elementProperty =
+ buildIntegerAttribute(elementAttribute);
+
+ setArrayProperties(property, arrayProperty);
+ arrayProperty->setElementProperty(elementProperty);
+ }
+ break;
+
+ case RAML::VariantType::DOUBLE :
+ {
+ std::shared_ptr<RAML::Properties> elementAttribute =
+ std::make_shared<RAML::Properties>(arrayAttribute);
+
+ std::shared_ptr<DoubleProperty> elementProperty =
+ buildDoubleAttribute(elementAttribute);
+
+ setArrayProperties(property, arrayProperty);
+ arrayProperty->setElementProperty(elementProperty);
+ }
+ break;
+
+ case RAML::VariantType::BOOLEAN :
+ {
+ std::shared_ptr<RAML::Properties> elementAttribute =
+ std::make_shared<RAML::Properties>(arrayAttribute);
+
+ std::shared_ptr<BooleanProperty> elementProperty =
+ buildBooleanAttribute(elementAttribute);
+
+ setArrayProperties(property, arrayProperty);
+ arrayProperty->setElementProperty(elementProperty);
+ }
+ break;
+
+ case RAML::VariantType::STRING :
+ {
+ std::shared_ptr<RAML::Properties> elementAttribute =
+ std::make_shared<RAML::Properties>(arrayAttribute);
+
+ std::shared_ptr<StringProperty> elementProperty =
+ buildStringAttribute(elementAttribute);
+
+ setArrayProperties(property, arrayProperty);
+ arrayProperty->setElementProperty(elementProperty);
+ }
+ break;
+
+ default:
++ OIC_LOG(ERROR, TAG, "Unknown array element type!");
+ return nullptr;
+ }
+
+ return arrayProperty;
+ }
+
+ std::shared_ptr<ArrayProperty> ResourceModelSchemaBuilder::buildModelArrayAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::vector<RAML::Properties> attributes =
+ boost::get<std::vector<RAML::Properties> >(property->getValue());
+
+ std::shared_ptr<ModelProperty> modelProperty = ModelProperty::build();
+
+ for (auto attributeProp : attributes)
+ {
+ auto elementProperty = std::make_shared<RAML::Properties>(attributeProp);
+ modelProperty->add(elementProperty->getName(), buildAttribute(elementProperty));
+ }
+
+ std::shared_ptr<ArrayProperty> arrayProperty = ArrayProperty::build();
+ setArrayProperties(property, arrayProperty);
+ arrayProperty->setElementProperty(modelProperty);
+
+ return arrayProperty;
+ }
+
+ std::shared_ptr<ModelProperty> ResourceModelSchemaBuilder::buildModelAttribute(
+ const std::shared_ptr<RAML::Properties> &property)
+ {
+ std::shared_ptr<ModelProperty> modelProperty = ModelProperty::build();
+
+ std::vector<RAML::Properties> attributes =
+ boost::get<std::vector<RAML::Properties> >(property->getValue());
+
+ for (auto attributeProp : attributes)
+ {
+ auto elementProperty = std::make_shared<RAML::Properties>(attributeProp);
+ modelProperty->add(elementProperty->getName(), buildAttribute(elementProperty));
+ }
+
+ return modelProperty;
+ }
+
+ void ResourceModelSchemaBuilder::setArrayProperties(
+ const std::shared_ptr<RAML::Properties> &property,
+ const std::shared_ptr<ArrayProperty> &arrayProperty)
+ {
+ for (auto &valueProperty : property->getValueProperties())
+ {
+ if (RAML::ValueProperty::Type::ARRAY == valueProperty->type())
+ {
+ int minItems = 0;
+ int maxItems = 0;
+ bool unique = false;
+ bool additionalItems = false;
+
+ valueProperty->valueArray(minItems, maxItems, unique, additionalItems);
+ arrayProperty->setRange(minItems, maxItems);
+ arrayProperty->setUnique(unique);
+ arrayProperty->setVariable(additionalItems);
+ break;
+ }
+ }
+ }
void AttributeUpdateAutomation::start()
{
- m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
+ SimulatorResourceAttribute attribute;
+ if (false == m_resource->getAttribute(m_attrName, attribute))
+ {
- OC_LOG(ERROR, TAG, "Attribute is not present in resource!");
++ OIC_LOG(ERROR, ATAG, "Attribute is not present in resource!");
+ throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
+ }
+
+ m_thread.reset(new std::thread(&AttributeUpdateAutomation::updateAttribute, this, attribute));
}
void AttributeUpdateAutomation::stop()
if (!m_stopRequested)
{
- OC_LOG_V(DEBUG, ATAG, "Attribute:%s automation is completed!", m_attrName.c_str());
+ OIC_LOG_V(DEBUG, ATAG, "Attribute:%s automation is completed!", m_attrName.c_str());
- SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
+ SIM_LOG(ILogger::INFO, "Attribute automation completed [Name: \"" << m_attrName
+ << "\", id: " << m_id <<"].");
+ }
+ else
+ {
+ SIM_LOG(ILogger::INFO, "Attribute automation stopped [Name: \"" << m_attrName
+ << "\", id: " << m_id <<"].");
}
// Notify application through callback
if (!m_stopRequested)
{
- SIM_LOG(ILogger::INFO, "Resource update automation complete [id: " << m_id << "]");
- OC_LOG_V(DEBUG, ATAG, "Resource update automation complete [id: %d]!", m_id);
++ OIC_LOG_V(DEBUG, RTAG, "Resource update automation complete [id: %d]!", m_id);
+ SIM_LOG(ILogger::INFO, "Resource automation completed [URI: \"" << m_resource->getURI()
+ << "\", id: " << m_id << "].");
+ }
+ else
+ {
+ SIM_LOG(ILogger::INFO, "Resource automation stopped [URI: \"" << m_resource->getURI()
+ << "\", id: " << m_id <<"].");
}
// Notify application
std::shared_ptr<OC::OCResourceRequest> request)
{
if (!request)
- OC_LOG(ERROR, TAG, "Request received from stack is null!");
+ {
++ OIC_LOG(ERROR, TAG, "Request received from stack is null!");
return OC_EH_ERROR;
+ }
+ // Handle GET, PUT, POST and DELETE requests
if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
{
{
return std::shared_ptr<SimulatorCollectionResource>(collectionResource);\r
}\r
\r
- SimulatorResourceModel::Attribute SimulatorResourceFactory::buildAttribute(\r
- std::shared_ptr<RAML::Properties> propertyElement)\r
+ std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(\r
+ const std::shared_ptr<RAML::RamlResource> &ramlResource)\r
{\r
- std::string propName = propertyElement->getName();\r
+ // Build resource request and respone model schema\r
+ RequestModelBuilder requestModelBuilder;\r
+ std::unordered_map<std::string, RequestModelSP> requestModels =\r
+ requestModelBuilder.build(ramlResource);\r
\r
- // Build representation attribute\r
- SimulatorResourceModel::Attribute attribute(propName);\r
- switch (propertyElement->getVariantType())\r
+ // Build SimulatorResourceModel from "GET" response schema\r
+ if (requestModels.end() == requestModels.find("GET"))\r
{\r
- case RAML::VariantType::INT:\r
- {\r
- attribute.setValue(propertyElement->getValue<int>());\r
- \r
- // Convert suppoted values\r
- std::vector<int> allowedValues = propertyElement->getAllowedValuesInt();\r
- if (allowedValues.size() > 0)\r
- {\r
- SimulatorResourceModel::AttributeProperty attrProp(allowedValues);\r
- attribute.setProperty(attrProp);\r
- }\r
- }\r
- break;\r
- \r
- case RAML::VariantType::DOUBLE:\r
- {\r
- attribute.setValue(propertyElement->getValue<double>());\r
- \r
- // Convert suppoted values\r
- std::vector<double> allowedValues = propertyElement->getAllowedValuesDouble();\r
- if (allowedValues.size() > 0)\r
- {\r
- SimulatorResourceModel::AttributeProperty attrProp(allowedValues);\r
- attribute.setProperty(attrProp);\r
- }\r
- }\r
- break;\r
- \r
- case RAML::VariantType::BOOL:\r
- {\r
- attribute.setValue(propertyElement->getValue<bool>());\r
- \r
- std::vector<bool> allowedValues = {true, false};\r
- SimulatorResourceModel::AttributeProperty attrProp(allowedValues);\r
- attribute.setProperty(attrProp);\r
- }\r
- break;\r
- \r
- case RAML::VariantType::STRING:\r
- {\r
- attribute.setValue(propertyElement->getValue<std::string>());\r
- \r
- // Convert suppoted values\r
- std::vector<std::string> allowedValues = propertyElement->getAllowedValuesString();\r
- if (allowedValues.size() > 0)\r
- {\r
- SimulatorResourceModel::AttributeProperty attrProp(allowedValues);\r
- attribute.setProperty(attrProp);\r
- }\r
- }\r
- break;\r
- OC_LOG(ERROR, TAG, "Resource's RAML does not have GET request model!");\r
++ OIC_LOG(ERROR, TAG, "Resource's RAML does not have GET request model!");\r
+ return nullptr;\r
}\r
\r
- // Set the range property if its present\r
- double min, max;\r
- int multipleof;\r
- propertyElement->getRange(min, max, multipleof);\r
- if (min != INT_MIN && max != INT_MAX)\r
+ RequestModelSP getRequestModel = requestModels["GET"];\r
+ ResponseModelSP getResponseModel = getRequestModel->getResponseModel(200);\r
+ if (!getResponseModel)\r
{\r
- SimulatorResourceModel::AttributeProperty attrProp(min, max);\r
- attribute.setProperty(attrProp);\r
- OC_LOG(ERROR, TAG, "Resource's RAML does not have response for GET request!");\r
++ OIC_LOG(ERROR, TAG, "Resource's RAML does not have response for GET request!");\r
+ return nullptr;\r
}\r
- return attribute;\r
- }\r
\r
- SimulatorResourceModel SimulatorResourceFactory::buildResourceModel(\r
- std::shared_ptr<RAML::Items> item)\r
- {\r
- SimulatorResourceModel itemModel;\r
- for ( auto &propElement : item->getProperties())\r
+ std::shared_ptr<SimulatorResourceModelSchema> responseSchema =\r
+ getResponseModel->getSchema();\r
+ if (!responseSchema)\r
{\r
- if (!propElement.second)\r
- continue;\r
- OC_LOG(ERROR, TAG, "Failed to get schema from response model!");\r
++ OIC_LOG(ERROR, TAG, "Failed to get schema from response model!");\r
+ return nullptr;\r
+ }\r
\r
- std::string propName = propElement.second->getName();\r
- if ("p" == propName || "n" == propName || "id" == propName)\r
- {\r
- continue;\r
- }\r
+ SimulatorResourceModel resourceModel = responseSchema->buildResourceModel();\r
\r
- if ("array" == propElement.second->getType())\r
- {\r
- std::vector<SimulatorResourceModel> arrayResModel;\r
- for ( auto &propertyItem : propElement.second->getItems())\r
- {\r
- arrayResModel.push_back(buildResourceModel(propertyItem));\r
- }\r
- itemModel.add(propName, arrayResModel);\r
- }\r
- else\r
- {\r
- itemModel.add(buildAttribute(propElement.second));\r
- }\r
- }\r
- return itemModel;\r
- }\r
+ // Remove the common properties from resource Model\r
+ std::string resourceURI = ramlResource->getResourceUri();\r
+ std::string resourceName = ramlResource->getDisplayName();\r
+ std::string resourceType;\r
\r
- RAML::RequestResponseBodyPtr SimulatorResourceFactory::getRAMLResponseBody(\r
- std::shared_ptr<RAML::RamlResource> ramlResource, RAML::ActionType type, std::string responseCode)\r
- {\r
- // Get the resource representation schema from response body\r
- RAML::ActionPtr action = ramlResource->getAction(type);\r
- if (!action)\r
+ // Extracting resource type.\r
+ if (resourceModel.contains("rt"))\r
{\r
- OIC_LOG(ERROR, TAG, "Resource does not possess the request!");\r
- return nullptr;\r
+ resourceType = resourceModel.get<std::string>("rt");\r
+ resourceModel.remove("rt");\r
}\r
- \r
- RAML::ResponsePtr response = action->getResponse(responseCode);\r
- if (!response)\r
+ else if (resourceModel.contains("resourceType"))\r
{\r
- OIC_LOG(ERROR, TAG, "Resource does not provide valid GET response!");\r
- return nullptr;\r
+ resourceType = resourceModel.get<std::string>("resourceType");\r
+ resourceModel.remove("resourceType");\r
}\r
\r
- RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");\r
- if (!responseBody)\r
+ // Construct resource type from uri\r
+ if(resourceType.empty())\r
{\r
- OIC_LOG(ERROR, TAG, "GET response is not of type \"application/json\" ");\r
- return nullptr;\r
- }\r
+ std::ostringstream rtString;\r
+ rtString << "oic.r.";\r
\r
- return responseBody;\r
- }\r
- \r
- SimulatorResourceModel SimulatorResourceFactory::buildModelFromResponseBody(\r
- RAML::RequestResponseBodyPtr responseBody, std::string &resourceType,\r
- std::vector<std::string> &interfaceType)\r
- {\r
- SimulatorResourceModel resModel;\r
- \r
- if (!responseBody)\r
- return resModel;\r
- \r
- // Iterate throgh all resource property and extract information needed for simulating resource.\r
- RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();\r
+ size_t pos = resourceURI.rfind("/");\r
+ if (pos == std::string::npos)\r
+ pos = -1;\r
\r
+ std::string rtName = resourceURI.substr(pos+1);\r
+ std::transform(rtName.begin(), rtName.end(), rtName.begin(), ::tolower);\r
+ rtString << rtName;\r
+ resourceType = rtString.str();\r
+ }\r
\r
- for ( auto &propertyElement : resourceProperties->getProperties())\r
+ // Extracting interface type.\r
+ std::vector<std::string> interfaceTypes;\r
+ if (resourceModel.contains("if"))\r
{\r
- if (!propertyElement.second)\r
- continue;\r
- \r
- std::string propName = propertyElement.second->getName();\r
- \r
- // Resource type\r
- if ("rt" == propName || "resourceType" == propName)\r
+ SimulatorResourceModel::TypeInfo typeInfo = resourceModel.getType("if");\r
+ if(AttributeValueType::STRING == typeInfo.type())\r
{\r
- resourceType = propertyElement.second->getValueString();\r
- continue;\r
+ interfaceTypes.push_back(resourceModel.get<std::string>("if"));\r
}\r
- \r
- // Interface type\r
- if ("if" == propName)\r
+ else if(AttributeValueType::VECTOR == typeInfo.type()\r
+ && AttributeValueType::STRING == typeInfo.baseType()\r
+ && typeInfo.depth() == 1)\r
{\r
- if ("string" == propertyElement.second->getType())\r
- {\r
- interfaceType.push_back(propertyElement.second->getValueString());\r
- }\r
- else if ("array" == propertyElement.second->getType())\r
- {\r
- for (auto &item : propertyElement.second->getItems())\r
- {\r
- if ("string" == item->getType())\r
- {\r
- interfaceType = item->getAllowedValuesString();\r
- break;\r
- }\r
- }\r
- }\r
- continue;\r
+ interfaceTypes = resourceModel.get<std::vector<std::string>>("if");\r
+ if (interfaceTypes.size() > 1)\r
+ interfaceTypes.erase(interfaceTypes.begin()+1, interfaceTypes.end());\r
}\r
\r
- // Other Standard properties which should not be part of resource model\r
- if ("p" == propName || "n" == propName || "id" == propName)\r
- {\r
- continue;\r
- }\r
- \r
- // Add the attribute to resource model\r
- if ("array" == propertyElement.second->getType())\r
- {\r
- std::vector<SimulatorResourceModel> arrayResModel;\r
- for ( auto &propertyItem : propertyElement.second->getItems())\r
- {\r
- arrayResModel.push_back(buildResourceModel(propertyItem));\r
- }\r
- resModel.add(propName, arrayResModel);\r
- }\r
- else\r
- {\r
- resModel.add(buildAttribute(propertyElement.second));\r
- }\r
+ resourceModel.remove("if");\r
}\r
\r
- if ("array" == resourceProperties->getType())\r
+ for (auto &requestModel : requestModels)\r
{\r
- std::vector<SimulatorResourceModel> arrayResModel;\r
- for ( auto &propertyItem : resourceProperties->getItems())\r
+ if (requestModel.second)\r
{\r
- arrayResModel.push_back(buildResourceModel(propertyItem));\r
+ addInterfaceFromQueryParameter((requestModel.second)->getQueryParams("if"),\r
+ interfaceTypes);\r
}\r
- resModel.add("links", arrayResModel);\r
}\r
\r
- return resModel;\r
- }\r
- \r
- std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(\r
- std::shared_ptr<RAML::RamlResource> ramlResource)\r
- {\r
- std::string name;\r
- std::string uri;\r
- std::string resourceType, rt;\r
- std::vector<std::string> interfaceType, ifType;\r
- \r
- name = ramlResource->getDisplayName();\r
- uri = ramlResource->getResourceUri();\r
- std::map<RAML::ActionType, RAML::ActionPtr> actionType = ramlResource->getActions();\r
- \r
- RAML::RequestResponseBodyPtr successResponseBody = getRAMLResponseBody(\r
- ramlResource, RAML::ActionType::GET, "200");\r
- RAML::RequestResponseBodyPtr putErrorResponseBody = getRAMLResponseBody(\r
- ramlResource, RAML::ActionType::PUT, "403");\r
- RAML::RequestResponseBodyPtr postErrorResponseBody = getRAMLResponseBody(\r
- ramlResource, RAML::ActionType::POST, "403");\r
- \r
- SimulatorResourceModel successResponseModel = buildModelFromResponseBody(\r
- successResponseBody, resourceType, interfaceType);\r
- SimulatorResourceModel putErrorResponseModel = buildModelFromResponseBody(\r
- putErrorResponseBody, rt, ifType);\r
- SimulatorResourceModel postErrorResponseModel = buildModelFromResponseBody(\r
- postErrorResponseBody, rt, ifType);\r
+ // Remove properties which are not part of resource representation\r
+ resourceModel.remove("p");\r
+ resourceModel.remove("n");\r
+ resourceModel.remove("id");\r
\r
// Create simple/collection resource\r
std::shared_ptr<SimulatorResource> simResource;\r
OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests(
std::shared_ptr<OC::OCResourceRequest> request)
{
- OCEntityHandlerResult errCode = OC_EH_ERROR;
if (!request)
- OC_LOG(ERROR, TAG, "Request received from stack is null!");
+ {
++ OIC_LOG(ERROR, TAG, "Request received from stack is null!");
return OC_EH_ERROR;
+ }
+
+ OCEntityHandlerResult result = OC_EH_OK;
+ // Handle GET, PUT, POST and DELETE requests
if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
{
{