Change set has below mentioned changes.
1. Folder restructure in simulator "src" folder.
2. Adding exception support.
3. Implementation of new APIs like getDeviceInfo, getPlatformInfo.. etc
Change-Id: I565ec2ed2469b919c7050cce05601ec4f8f7ee38
Signed-off-by: Harish Kumara Marappa <h.marappa@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/2494
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Madan Lanka <lanka.madan@samsung.com>
# Simulator build script
##
-import os
+import os, sys
Import('env')
lib_env = env.Clone()
######################################################################
# Build flags
######################################################################
-simulator_env.AppendUnique(CPPPATH = ['inc', 'src'])
+simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client-controller', 'src/service-provider', 'src/common'])
simulator_env.AppendUnique(CPPPATH = [
'../../resource/include/',
'../../resource/csdk/stack/include',
######################################################################
# Source files and Targets
######################################################################
-simulator_src = [env.Glob('src/*.cpp'), env.Glob('java/jni/*.cpp')]
+simulator_src = [env.Glob('src/*.cpp')
+ ,env.Glob('src/*/*.cpp')
+ ,env.Glob('java/jni/*.cpp')
+ ]
simulatorsdk = simulator_env.SharedLibrary('SimulatorManager', simulator_src)
simulator_env.InstallTarget(simulatorsdk, 'libSimulator')
######################################################################
sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
sim_env.AppendUnique(CPPPATH = ['../../inc'])
-sim_env.AppendUnique(CPPPATH = ['../../src'])
sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
sim_env.AppendUnique(LIBS = ['SimulatorManager'])
******************************************************************/
#include "simulator_manager.h"
+#include <map>
+#include <mutex>
+
+std::string getOperationStateString(OperationState state)
+{
+ switch (state)
+ {
+ case OP_START: return "OP_START";
+ case OP_COMPLETE: return "OP_COMPLETE";
+ case OP_ABORT: return "OP_ABORT";
+ }
+
+ return "OP_UNKNOWN";
+}
class AppLogger : public ILogger
{
int choice = -1;
std::cout << "Enter your choice: ";
std::cin >> choice;
- if (choice < 0 || choice > 8)
+ if (choice < 0 || choice > 12)
{
std::cout << "Invaild choice !" << std::endl; continue;
}
case 5: sendGet(); break;
case 6: sendPut(); break;
case 7: sendPost(); break;
- case 8: printMenu(); break;
+ case 8: sendAllGETRequests(); break;
+ case 9: sendAllPUTRequests(); break;
+ case 10: sendAllPOSTRequests(); break;
+ case 11: configure(); break;
+ case 12: printMenu(); break;
case 0: cont = false;
}
}
std::cout << "5. Send GET message" << std::endl;
std::cout << "6. Send PUT message" << std::endl;
std::cout << "7. Send POST message" << std::endl;
- std::cout << "8: Help" << std::endl;
+ std::cout << "8. Send All GET requests" << std::endl;
+ std::cout << "9. Send All PUT requests" << std::endl;
+ std::cout << "10. Send All POST requests" << std::endl;
+ std::cout << "11. Configure (using RAML file)" << std::endl;
+ std::cout << "12: Help" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "###################################################" << std::endl;
}
- int selectResource(std::vector<SimulatorRemoteResourcePtr> resourceList)
+ SimulatorRemoteResourceSP selectResource()
{
- if (0 == resourceList.size())
+ std::lock_guard<std::recursive_mutex> lock(m_mutex);
+ if (0 == m_resList.size())
{
std::cout << "No resouces!" << std::endl;
- return -1;
+ return nullptr;
}
int index = 1;
- for (auto & resource : resourceList)
+ std::vector<std::string> ids;
+ for (auto & resourceEntry : m_resList)
{
- std::cout << index++ << ": " << resource->getURI() << "[" << resource->getHost() << "]" << std::endl;
+ std::cout << index++ << ": " << (resourceEntry.second)->getURI() << "[" <<
+ (resourceEntry.second)->getHost() << "]" << std::endl;
+ ids.push_back((resourceEntry.second)->getID());
}
int choice = -1;
if (choice < 1 || choice > index - 1)
{
std::cout << "Invalid choice !" << std::endl;
- choice = -1;
+ return nullptr;
}
- return choice;
+ return m_resList[ids[choice-1]];
}
void findResource()
{
std::cout << "Resource found ######" << std::endl;
displayResource(resource);
+
+ // Add to local list
+ std::lock_guard<std::recursive_mutex> lock(m_mutex);
+ if (m_resList.end() == m_resList.find(resource->getID()))
+ m_resList[resource->getID()] = resource;
+ else
+ std::cout << "Resource with UID: "<< resource->getID() << "already exist in the list!"<< std::endl;
};
- SimulatorResult result = SimulatorManager::getInstance()->findResource
- (resourceType, callback);
- if (SIMULATOR_SUCCESS != result)
- std::cout << "SimulatorManager::findResource returned error : " << result << std::endl;
+ try
+ {
+ SimulatorManager::getInstance()->findResources(resourceType, callback);
+ std::cout << "SimulatorManager::findResource is successfull" << std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
void displayResource()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
-
- displayResource(resourceList[index - 1]);
+ displayResource(selectResource());
}
- void displayResource(SimulatorRemoteResourcePtr resource)
+ void displayResource(SimulatorRemoteResourceSP resource)
{
+ if (!resource) return;
+
std::cout << "#############################" << std::endl;
std::cout << "URI: " << resource->getURI().c_str() << std::endl;
std::cout << "Host: " << resource->getHost().c_str() << std::endl;
+ std::cout << "ID: " << resource->getID().c_str() << std::endl;
std::cout << "Resource Types: ";
for (auto &type : resource->getResourceTypes())
std::cout << type << " ";
void observeResource()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
-
- SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
// callback implementaion
- SimulatorRemoteResource::RepresentationChangeCallback callback =
- [](int errorCode, const SimulatorResourceModel &rep, int seq)
+ SimulatorRemoteResource::ObserveNotificationCallback callback =
+ [](std::string uid, SimulatorResult errorCode, SimulatorResourceModelSP rep, int seq)
{
- std::cout << "\nObserve notificatoin received ###[errorcode: " << errorCode << " seq: " << seq << "]" << std::endl;
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+ std::cout << "\nObserve notificatoin received ###[errorcode: " << errorCode <<
+ " seq: " << seq << "UID: " << uid << "]" << std::endl;
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
for (auto & attribute : attributes)
{
std::cout << (attribute.second).getName() << " : {" << std::endl;
std::cout << std::endl;
};
- std::map <std::string, std::string> queryParams;
- SimulatorResult result = resource->observe(SimulatorRemoteResource::OBSERVE, queryParams, callback);
- if ( SIMULATOR_SUCCESS == result)
+ try
+ {
+ resource->observe(ObserveType::OBSERVE, callback);
std::cout << "Observe is successfull!" << std::endl;
- else
- std::cout << "Observe is failed!error: " << result << std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
void cancelObserving()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
- SimulatorRemoteResourcePtr resource = resourceList[index - 1];
- SimulatorResult result = resource->cancelObserve();
- if ( SIMULATOR_SUCCESS == result)
+ try
+ {
+ resource->cancelObserve();
std::cout << "Cancelling observe is successfull!" << std::endl;
- else
- std::cout << "Cancelling observe is failed!error: " << result << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
void sendGet()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
-
- SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](int errorCode, const SimulatorResourceModel & rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
std::cout << "\nGET Response received ### [errorcode: " << errorCode << "]" << std::endl;
+ std::cout << "UID is: " << uId << std::endl;
std::cout << "Representation is: " << std::endl;
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
for (auto & attribute : attributes)
{
std::cout << (attribute.second).getName() << " : {" << std::endl;
std::cout << std::endl;
};
- std::map <std::string, std::string> queryParams;
- SimulatorResult result = resource->get(queryParams, callback);
- if ( SIMULATOR_SUCCESS == result)
+ try
+ {
+ resource->get(std::map <std::string, std::string>(), callback);
std::cout << "GET is successfull!" << std::endl;
- else
- std::cout << "GET is failed!error: " << result << std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
void sendPut()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
-
- SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](int errorCode, const SimulatorResourceModel & rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
std::cout << "\nPUT Response received ![errorcode: " << errorCode << "]" << std::endl;
+ std::cout << "UID is: " << uId << std::endl;
std::cout << "Representation is: " << std::endl;
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
for (auto & attribute : attributes)
{
std::cout << (attribute.second).getName() << " : {" << std::endl;
std::cout << std::endl;
};
- std::map <std::string, std::string> queryParams;
- SimulatorResourceModel rep;
- rep.addAttribute("power", "off");
- rep.addAttribute("intensity", 5);
+ try
+ {
+ SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
+ std::string value = "off";
+ rep->addAttribute("power", value);
+ rep->addAttribute("intensity", 5);
- SimulatorResult result = resource->put(rep, queryParams, callback);
- if ( SIMULATOR_SUCCESS == result)
+ resource->put(std::map <std::string, std::string>(), rep, callback);
std::cout << "PUT is successfull!" << std::endl;
- else
- std::cout << "PUT is failed!error: " << result << std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
void sendPost()
{
- std::vector<SimulatorRemoteResourcePtr> resourceList =
- SimulatorManager::getInstance()->getFoundResources();
-
- int index = selectResource(resourceList);
- if (-1 == index)
- return;
-
- SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](int errorCode, const SimulatorResourceModel & rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
std::cout << "\nPOST Response received ![errorcode: " << errorCode << "]" << std::endl;
+ std::cout << "UID is: " << uId << std::endl;
std::cout << "Representation is: " << std::endl;
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
for (auto & attribute : attributes)
{
std::cout << (attribute.second).getName() << " : {" << std::endl;
std::cout << std::endl;
};
- std::map <std::string, std::string> queryParams;
- SimulatorResourceModel rep;
- rep.addAttribute("power", "on");
- rep.addAttribute("intensity", 7);
+ try
+ {
+ SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
+ std::string value = "on";
+ rep->addAttribute("power", value);
+ rep->addAttribute("intensity", 7);
- SimulatorResult result = resource->post(rep, queryParams, callback);
- if ( SIMULATOR_SUCCESS == result)
+ resource->post(std::map <std::string, std::string>(), rep, callback);
std::cout << "POST is successfull!" << std::endl;
- else
- std::cout << "POST is failed!error: " << result << std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
}
+
+ void sendAllGETRequests()
+ {
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
+
+ SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ {
+ std::cout << "\nResource verification status received ![id: " << sessionId << " State: "
+ << getOperationStateString(state) << " UID: "<< uid << "]" << std::endl;
+ };
+
+ try
+ {
+ int id = resource->startVerification(RequestType::RQ_TYPE_GET, callback);
+ std::cout << "startVerification for GET is successfull!id: " << id <<std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+
+ void sendAllPUTRequests()
+ {
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
+
+ SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ {
+ std::cout << "\nResource verification status received ![id: " << sessionId << " State: "
+ << getOperationStateString(state) << " UID: "<< uid << "]" << std::endl;
+ };
+
+ try
+ {
+ int id = resource->startVerification(RequestType::RQ_TYPE_PUT, callback);
+ std::cout << "startVerification for PUT is successfull!id: " << id <<std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+
+ void sendAllPOSTRequests()
+ {
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
+
+ SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ {
+ std::cout << "\nResource verification status received ![id: " << sessionId << " State: "
+ << getOperationStateString(state) << " UID: "<< uid << "]" << std::endl;
+ };
+
+ try
+ {
+ int id = resource->startVerification(RequestType::RQ_TYPE_POST, callback);
+ std::cout << "startVerification for POST is successfull!id: " << id <<std::endl;
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(NoSupportException &e)
+ {
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+
+ void configure()
+ {
+ SimulatorRemoteResourceSP resource = selectResource();
+ if (!resource) return;
+
+ try
+ {
+ resource->configure("../../../../../../../../service/simulator/ramlparser/example/oic.r.light.raml");
+ std::cout << "configuration is successfull!" << std::endl;
+ }
+ catch (InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch (SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+
+ private:
+ std::recursive_mutex m_mutex;
+ std::map<std::string, SimulatorRemoteResourceSP> m_resList;
};
void printMainMenu()
{
std::cout << "############### MAIN MENU###############" << std::endl;
std::cout << "1. Client Controller Test" << std::endl;
- std::cout << "2. Set Logger" << std::endl;
- std::cout << "3. Help" << std::endl;
+ std::cout << "2. Get device information" << std::endl;
+ std::cout << "3. Get platform information" << std::endl;
+ std::cout << "4. Set Logger" << std::endl;
+ std::cout << "5. Help" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "######################################" << std::endl;
}
{
if (false == SimulatorManager::getInstance()->setDefaultConsoleLogger())
std::cout << "Failed to set the default console logger" << std::endl;
- } break;
+ }
+ break;
+
case 2:
{
std::string filePath;
std::cin >> filePath;
if (false == SimulatorManager::getInstance()->setDefaultFileLogger(filePath))
std::cout << "Failed to set default file logger" << std::endl;
- } break;
- case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
+ }
+ break;
+
+ case 3:
+ SimulatorManager::getInstance()->setLogger(gAppLogger);
}
}
int choice = -1;
std::cout << "Enter your choice: ";
std::cin >> choice;
- if (choice < 0 || choice > 3)
+ if (choice < 0 || choice > 5)
{
std::cout << "Invaild choice !" << std::endl; continue;
}
case 1: clientController.startTest();
std::cout << "Welcome back to main menu !" << std::endl;
break;
- case 2: setLogger(); break;
- case 3: printMainMenu(); break;
+
+ case 2:
+ {
+ try
+ {
+ SimulatorManager::getInstance()->getDeviceInfo(std::bind([](DeviceInfo &deviceInfo)
+ {
+ std::cout << "###Device Information received...." << std::endl;
+ std::ostringstream out;
+ out << "Device name: " << deviceInfo.getName() << std::endl;
+ out << "Device ID: " << deviceInfo.getID() << std::endl;
+ out << "Device Spec version: " << deviceInfo.getSpecVersion() << std::endl;
+ out << "Device dat model version: " << deviceInfo.getDataModelVersion() << std::endl;
+
+ std::cout << out.str() << std::endl;
+ }, std::placeholders::_1));
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+ break;
+
+ case 3:
+ {
+ try
+ {
+ SimulatorManager::getInstance()->getPlatformInfo(std::bind([](PlatformInfo &platformInfo)
+ {
+ std::cout << "###Platform Information received...." << std::endl;
+ std::ostringstream out;
+ out << "Platform ID: " << platformInfo.getPlatformID() << std::endl;
+ out << "Platform version: " << platformInfo.getPlatformVersion() << std::endl;
+ out << "Manufacturer name: " << platformInfo.getManufacturerName() << std::endl;
+ out << "Manufacturer url: " << platformInfo.getManufacturerUrl() << std::endl;
+ out << "Modle number: " << platformInfo.getModelNumber() << std::endl;
+ out << "Date of manufacture: " << platformInfo.getDateOfManfacture() << std::endl;
+ out << "Operatio system version: " << platformInfo.getOSVersion() << std::endl;
+ out << "Hardware version: " << platformInfo.getHardwareVersion() << std::endl;
+ out << "Firmware version: " << platformInfo.getFirmwareVersion() << std::endl;
+ out << "Support url: " << platformInfo.getSupportUrl() << std::endl;
+ out << "System time: " << platformInfo.getSystemTime() << std::endl;
+
+ std::cout << out.str() << std::endl;
+ }, std::placeholders::_1));
+ }
+ catch(InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ catch(SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ }
+ }
+ break;
+
+ case 4: setLogger(); break;
+
+ case 5: printMainMenu(); break;
+
case 0: cont = false;
}
}
######################################################################
sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
sim_env.AppendUnique(CPPPATH = ['../../inc'])
-sim_env.AppendUnique(CPPPATH = ['../../src'])
sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
sim_env.AppendUnique(LIBS = ['SimulatorManager'])
switch (choice)
{
case 1 : simulateResource(configPath); break;
- case 2: displayResource(); break;
- case 3: deleteResource(); break;
- case 4: updateAttributePower(); break;
- case 5: updateAttributeIntensity(); break;
- case 6: automateResourceUpdate(); break;
- case 7: automateAttributeUpdate(); break;
- case 8: stopAutomation(); break;
- case 9: printMenu(); break;
+ case 2 : displayResource(); break;
+ case 3 : deleteResource(); break;
+ case 4 : updateAttributePower(); break;
+ case 5 : updateAttributeIntensity(); break;
+ case 6 : automateResourceUpdate(); break;
+ case 7 : automateAttributeUpdate(); break;
+ case 8 : stopAutomation(); break;
+ case 9 : getObservers(); break;
+ case 10: printMenu(); break;
case 0: cont = false;
}
}
std::cout << "6. Automate resource update" << std::endl;
std::cout << "7. Automate attributes update" << std::endl;
std::cout << "8. Stop Automation" << std::endl;
- std::cout << "9: Help" << std::endl;
+ std::cout << "9. Get Observers of a resource" << std::endl;
+ std::cout << "10: Help" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "#######################################" << std::endl;
}
{
SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
&SimLightResource::onResourceModelChanged, this, std::placeholders::_1, std::placeholders::_2);
- SimulatorResourceServerPtr resource = SimulatorManager::getInstance()->createResource(configPath,
+ SimulatorResourceServerSP resource = SimulatorManager::getInstance()->createResource(configPath,
callback);
if (NULL == resource.get())
std::cout << "Failed to create resource" << std::endl;
if (-1 == index)
return;
- if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]))
- {
- std::cout << "Resource deleted successfully! " << std::endl;
- m_resources.erase(m_resources.begin() + (index - 1));
- }
- else
- {
- std::cout << "Failed to delete resource!" << std::endl;
- }
+ SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]);
+ std::cout << "Resource deleted successfully! " << std::endl;
+ m_resources.erase(m_resources.begin() + (index - 1));
+
} break;
case 2:
{
break;
}
- if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResources(resourceType))
+ SimulatorManager::getInstance()->deleteResources(resourceType);
+ std::cout << "Resources of type \"" << resourceType << "\"" << " deleted successfully! " <<
+ std::endl;
+ std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
+ while (ite != m_resources.end())
{
- std::cout << "Resources of type \"" << resourceType << "\"" << " deleted successfully! " <<
- std::endl;
- std::vector<SimulatorResourceServerPtr>::iterator ite = m_resources.begin();
- while (ite != m_resources.end())
+ if (!resourceType.compare((*ite)->getResourceType()))
{
- if (!resourceType.compare((*ite)->getResourceType()))
- {
- ite = m_resources.erase(ite);
- continue;
- }
- ite++;
+ ite = m_resources.erase(ite);
+ continue;
}
- }
- else
- {
- std::cout << "Failed to delete resources of type \"" << resourceType << "\"!" << std::endl;
+ ite++;
}
} break;
case 3:
{
- if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResources())
- {
- std::cout << "All resources deleted successfully! " << std::endl;
- m_resources.clear();
- }
- else
- {
- std::cout << "Failed to delete all resources!" << std::endl;
- }
+ SimulatorManager::getInstance()->deleteResources();
+ std::cout << "All resources deleted successfully! " << std::endl;
+ m_resources.clear();
} break;
}
if (-1 == index)
return;
- SimulatorResourceServerPtr resource = m_resources[index - 1];
+ SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
SimulatorResourceModel::Attribute powerAttribute;
resModel.getAttribute("power", powerAttribute);
for (int index = 0; index < allowedValuesSize; index++)
{
// Update the new value and display the resource model after modifying
- resource->updateAttributeFromAllowedValues("power", index);
+ resource->updateFromAllowedValues("power", index);
std::cout << "Attribute value is modified ####" << std::endl;
// Display the resource to user to verify the changed attribute value
if (-1 == index)
return;
- SimulatorResourceServerPtr resource = m_resources[index - 1];
+ SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
SimulatorResourceModel::Attribute intensityAttribute;
resModel.getAttribute("intensity", intensityAttribute);
- int allowedValuesSize = intensityAttribute.getAllowedValuesSize();
- if (0 == allowedValuesSize)
+ int min, max;
+ intensityAttribute.getRange(min, max);
+ if (!min && !max)
{
- std::cout << "This attribute does not have allowed values!" << std::endl;
+ std::cout << "This attribute does not have range!" << std::endl;
return;
}
std::cout << "Setting the new values from allowed values list to intensity attribute" << std::endl;
// Update all possible values from allowed values
- for (int index = 0; index < allowedValuesSize; index++)
+ for (int index = min; index <= max; index++)
{
// Update the new value and display the resource model after modifying
- resource->updateAttributeFromAllowedValues("intensity", index);
+ resource->updateAttributeValue("intensity", index);
std::cout << "Attribute value is modified ####" << std::endl;
// Display the resource to user to verify the changed attribute value
std::cout << std::endl << std::endl;
// Get user input for continuing this operation
- if ((index + 1) < allowedValuesSize)
+ if ((index + 1) <= max)
{
int choice;
std::cout << "Would you like to continue the attribute values changing process? (1/0): ";
if (-1 == index)
return;
- SimulatorResourceServerPtr resource = m_resources[index - 1];
+ SimulatorResourceServerSP resource = m_resources[index - 1];
displayResource(resource);
}
- void displayResource(SimulatorResourceServerPtr resource)
+ void displayResource(SimulatorResourceServerSP resource)
{
std::cout << "#############################" << std::endl;
std::cout << "Name: " << resource->getName().c_str() << std::endl;
(attribute.second).getRange(min, max);
std::cout << "min: " << min << std::endl;
std::cout << "max: " << max << std::endl;
- std::cout << "allowed values : " << (attribute.second).allowedValuesToString() << std::endl;
+ std::cout << "allowed values : ";
+ std::cout << "[ ";
+ for (auto &value : (attribute.second).allowedValuesToString())
+ std::cout << value << " ";
+ std::cout << "]" << std::endl;
std::cout << "}" << std::endl << std::endl;
}
std::cout << "#############################" << std::endl;
if (1 == choice)
type = AutomationType::RECURRENT;
- int id;
- if (SIMULATOR_SUCCESS != m_resources[index - 1]->startUpdateAutomation(type,
- std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
- std::placeholders::_2),
- id))
- std::cout << "startUpdateAutomation() returned error!" << std::endl;
- else
+ try
+ {
+ int id = m_resources[index - 1]->startUpdateAutomation(type,
+ std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
+ std::placeholders::_2));
+
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+ }
+ catch (SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " << e.what() << "]" << std::endl;
+ }
}
void automateAttributeUpdate()
if (-1 == index)
return;
- SimulatorResourceServerPtr resource = m_resources[index - 1];
+ SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes = resModel.getAttributes();
int size = 0;
type = AutomationType::RECURRENT;
std::cout << "Requesting attribute automation for " << attributeName.c_str() << std::endl;
- int id;
- if (SIMULATOR_SUCCESS != resource->startUpdateAutomation(attributeName, type,
- std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
- std::placeholders::_2),
- id))
- std::cout << "startUpdateAutomation() returned error!" << std::endl;
- else
+
+ try
+ {
+
+ int id = resource->startUpdateAutomation(attributeName, type,
+ std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
+ std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+ }
+ catch (SimulatorException &e)
+ {
+ std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " << e.what() << "]" << std::endl;
+ }
}
void stopAutomation()
if (-1 == index)
return;
- SimulatorResourceServerPtr resource = m_resources[index - 1];
+ SimulatorResourceServerSP resource = m_resources[index - 1];
// Select the automation to stop
std::vector<int> ids;
resource->stopUpdateAutomation(automationid);
}
+ void onObserverChanged(const std::string &uri, ObservationStatus state, const ObserverInfo &observerInfo)
+ {
+ std::cout << "[callback] Observer notification received..." << uri.c_str() << std::endl;
+ std::ostringstream out;
+ out << "ID: " << (int) observerInfo.id << std::endl;
+ out << " [address: " << observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+ std::cout << out.str();
+ }
+
+ void getObservers()
+ {
+ int index = selectResource();
+ if (-1 == index)
+ return;
+
+ SimulatorResourceServerSP resource = m_resources[index - 1];
+
+ SimulatorResourceServer::ObserverCB callback = std::bind(
+ &SimLightResource::onObserverChanged, this, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3);
+ resource->setObserverCallback(callback);
+
+ std::vector<ObserverInfo> observersList = resource->getObserversList();
+
+ std::cout << "##### Number of Observers [" << observersList.size() << "]" << std::endl;
+ for (auto & observerInfo : observersList)
+ {
+ std::cout << " ID : " << (int) observerInfo.id << " [address: " << observerInfo.address <<" port: " << observerInfo.port << "]" << std::endl;
+ }
+ std::cout << "########################" << std::endl;
+ }
+
private:
- std::vector<SimulatorResourceServerPtr> m_resources;
+ std::vector<SimulatorResourceServerSP> m_resources;
};
void printMainMenu()
"To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
<< std::endl;
std::cout <<
- "Example: ./simulator-server ../../../../../../../../service/simulator/examples/resources/light.raml"
+ "Example: ./simulator-server PATH-TO-RAML-FILE"
<< std::endl;
std::cout << "######################################" << std::endl;
}
int main(int argc, char *argv[])
{
std::string configPath = "";
+
if (argc == 2)
{
char *value = argv[1];
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_CLIENT_TYPES_H_
+#define SIMULATOR_CLIENT_TYPES_H_
+
+#include <iostream>
+#include <functional>
+#include <memory>
+#include "simulator_error_codes.h"
+
+enum class ObserveType
+{
+ OBSERVE,
+ OBSERVE_ALL
+};
+
+enum class RequestType
+{
+ RQ_TYPE_GET,
+ RQ_TYPE_PUT,
+ RQ_TYPE_POST,
+ RQ_TYPE_DELETE
+};
+
+typedef struct
+{
+ bool isVerified;
+ SimulatorResult errorCode;
+} ValidationStatus;
+
+typedef enum
+{
+ OP_START,
+ OP_COMPLETE,
+ OP_ABORT
+} OperationState;
+
+typedef enum
+{
+ /** use when defaults are ok. */
+ SIMULATOR_CT_DEFAULT = 0,
+
+ /** IPv4 and IPv6, including 6LoWPAN.*/
+ SIMULATOR_CT_ADAPTER_IP = (1 << 16),
+
+ /** GATT over Bluetooth LE.*/
+ SIMULATOR_CT_ADAPTER_GATT_BTLE = (1 << 17),
+
+ /** RFCOMM over Bluetooth EDR.*/
+ SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR = (1 << 18),
+
+#ifdef RA_ADAPTER
+ /** Remote Access over XMPP.*/
+ SIMULATOR_CT_ADAPTER_REMOTE_ACCESS = (1 << 19),
+#endif
+
+ /** Insecure transport is the default (subject to change).*/
+
+ /** secure the transport path.*/
+ SIMULATOR_CT_FLAG_SECURE = (1 << 4),
+
+ /** IPv4 & IPv6 autoselection is the default.*/
+
+ /** IP adapter only.*/
+ SIMULATOR_CT_IP_USE_V6 = (1 << 5),
+
+ /** IP adapter only.*/
+ SIMULATOR_CT_IP_USE_V4 = (1 << 6),
+
+ /** Link-Local multicast is the default multicast scope for IPv6.
+ * These are placed here to correspond to the IPv6 address bits.*/
+
+ /** IPv6 Interface-Local scope(loopback).*/
+ SIMULATOR_CT_SCOPE_INTERFACE = 0x1,
+
+ /** IPv6 Link-Local scope (default).*/
+ SIMULATOR_CT_SCOPE_LINK = 0x2,
+
+ /** IPv6 Realm-Local scope.*/
+ SIMULATOR_CT_SCOPE_REALM = 0x3,
+
+ /** IPv6 Admin-Local scope.*/
+ SIMULATOR_CT_SCOPE_ADMIN = 0x4,
+
+ /** IPv6 Site-Local scope.*/
+ SIMULATOR_CT_SCOPE_SITE = 0x5,
+
+ /** IPv6 Organization-Local scope.*/
+ SIMULATOR_CT_SCOPE_ORG = 0x8,
+
+ /** IPv6 Global scope.*/
+ SIMULATOR_CT_SCOPE_GLOBAL = 0xE,
+} SimulatorConnectivityType;
+
+class SimulatorRemoteResource;
+typedef std::function<void(std::shared_ptr<SimulatorRemoteResource>)>
+ResourceFindCallback;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_DEVICE_INFO_H_
+#define SIMULATOR_DEVICE_INFO_H_
+
+#include <iostream>
+
+/**
+ * @class DeviceInfo
+ *
+ * @brief This class contains remote device information and provide APIs access it.
+ */
+class DeviceInfo
+{
+ public:
+ DeviceInfo(const std::string &, const std::string &, const std::string &, const std::string &);
+
+ /**
+ * This method is for getting device name.
+ *
+ * @return Device name.
+ */
+ std::string getName() const;
+
+ /**
+ * This method is for getting device id.
+ *
+ * @return Device id.
+ */
+ std::string getID() const;
+
+ /**
+ * This method is for getting device specification version.
+ *
+ * @return Device id.
+ */
+ std::string getSpecVersion() const;
+
+ /**
+ * This method is for getting device data model version.
+ *
+ * @return Device data model version.
+ */
+ std::string getDataModelVersion() const;
+
+ private:
+ std::string m_name;
+ std::string m_id;
+ std::string m_specVersion;
+ std::string m_DMV;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_ERROR_CODES_H_
+#define SIMULATOR_ERROR_CODES_H_
+
+#include <iostream>
+
+typedef enum
+{
+ /** STACK error codes - START */
+ SIMULATOR_OK = 0,
+ SIMULATOR_RESOURCE_CREATED,
+ SIMULATOR_RESOURCE_DELETED,
+ SIMULATOR_CONTINUE,
+ SIMULATOR_INVALID_URI = 20,
+ SIMULATOR_INVALID_QUERY,
+ SIMULATOR_INVALID_IP,
+ SIMULATOR_INVALID_PORT,
+ SIMULATOR_INVALID_CALLBACK,
+ SIMULATOR_INVALID_METHOD,
+ SIMULATOR_INVALID_PARAM,
+ SIMULATOR_INVALID_OBSERVE_PARAM,
+ SIMULATOR_NO_MEMORY,
+ SIMULATOR_COMM_ERROR,
+ SIMULATOR_TIMEOUT,
+ SIMULATOR_ADAPTER_NOT_ENABLED,
+ SIMULATOR_NOTIMPL,
+ SIMULATOR_NO_RESOURCE,
+ SIMULATOR_RESOURCE_ERROR,
+ SIMULATOR_SLOW_RESOURCE,
+ SIMULATOR_DUPLICATE_REQUEST,
+ SIMULATOR_NO_OBSERVERS,
+ SIMULATOR_OBSERVER_NOT_FOUND,
+ SIMULATOR_VIRTUAL_DO_NOT_HANDLE,
+ SIMULATOR_INVALID_OPTION,
+ SIMULATOR_MALFORMED_RESPONSE,
+ SIMULATOR_PERSISTENT_BUFFER_REQUIRED,
+ SIMULATOR_INVALID_REQUEST_HANDLE,
+ SIMULATOR_INVALID_DEVICE_INFO,
+ SIMULATOR_INVALID_JSON,
+ SIMULATOR_UNAUTHORIZED_REQ,
+#ifdef WITH_PRESENCE
+ SIMULATOR_PRESENCE_STOPPED = 128,
+ SIMULATOR_PRESENCE_TIMEOUT,
+ SIMULATOR_PRESENCE_DO_NOT_HANDLE,
+#endif
+ /** STACK error codes - END */
+
+ /** Simulator specific error codes - START */
+ SIMULATOR_INVALID_TYPE,
+ SIMULATOR_NOT_SUPPORTED,
+ SIMULATOR_OPERATION_NOT_ALLOWED,
+ SIMULATOR_OPERATION_IN_PROGRESS,
+
+ SIMULATOR_INVALID_RESPONSE_CODE,
+ SIMULATOR_UKNOWN_PROPERTY,
+ SIMULATOR_TYPE_MISMATCH,
+ SIMULATOR_BAD_VALUE,
+ /** Simulator specific error codes - START */
+
+ SIMULATOR_ERROR = 255
+} SimulatorResult;
+#endif //SIMULATOR_ERROR_CODES_H_
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_exceptions.h
+ *
+ * @brief This file provides exceptions which would be thrown from simualtor module.
+ *
+ */
+
+#ifndef SIMULATOR_EXCEPTIONS_H_
+#define SIMULATOR_EXCEPTIONS_H_
+
+#include <exception>
+#include "simulator_error_codes.h"
+
+/**
+ * @class SimulatorException
+ * @brief This is the base exception of all type of exception thrown from simulator module.
+ */
+class SimulatorException : public std::exception
+{
+ public:
+ /**
+ * Constructor of SimulatorException.
+ *
+ * @param errorCode - Error code.
+ * @param message - String describing the error messsage.
+ */
+ SimulatorException(SimulatorResult errorCode, const std::string &message);
+
+ /**
+ * API to get error message describing exception reason.
+ *
+ * @return Null terminated string.
+ */
+ virtual const char *what() const noexcept;
+
+ /**
+ * API to get error code with which exception is thrown.
+ *
+ * @return SimulatorResult - Error code.
+ */
+ virtual SimulatorResult code() const;
+ virtual ~SimulatorException() throw() {}
+
+ private:
+ SimulatorResult m_errorCode;
+ std::string m_message;
+};
+
+/**
+ * @class InvalidArgsException
+ * @brief This exception will be thrown to indicate invalid arguments case.
+ */
+class InvalidArgsException : public SimulatorException
+{
+ public:
+ InvalidArgsException(SimulatorResult errorCode, const std::string &message);
+};
+
+/**
+ * @class NoSupportException
+ * @brief This exception will be thrown to indicate not supported operation cases.
+ */
+class NoSupportException : public SimulatorException
+{
+ public:
+ NoSupportException(const std::string &message);
+};
+
+/**
+ * @class OperationInProgressException
+ * @brief This exception will be thrown to indicate requested operation is not allowed as other operation
+ * is in progress state.
+ */
+class OperationInProgressException : public SimulatorException
+{
+ public:
+ OperationInProgressException(const std::string &message);
+};
+
+#endif
{
public:
bool setDefaultConsoleTarget();
- bool setDefaultFileTarget(std::string &path);
- void setCustomTarget(std::shared_ptr<ILogger> target);
+ bool setDefaultFileTarget(const std::string &path);
+ void setCustomTarget(const std::shared_ptr<ILogger> &target);
void write(ILogger::Level level, std::ostringstream &str);
private:
#ifndef SIMULATOR_MANAGER_H_
#define SIMULATOR_MANAGER_H_
-#include <vector>
+#include "simulator_server_types.h"
+#include "simulator_client_types.h"
+#include "simulator_device_info.h"
+#include "simulator_platform_info.h"
#include "simulator_resource_server.h"
#include "simulator_remote_resource.h"
-#include "simulator_error_codes.h"
+#include "simulator_exceptions.h"
#include "simulator_logger.h"
+typedef std::function<void(DeviceInfo &deviceInfo)> DeviceInfoCallback;
+typedef std::function<void(PlatformInfo &platformInfo)> PlatformInfoCallback;
+
/**
* @class SimulatorManager
*
static SimulatorManager *getInstance();
/**
- * This method is called for creating a single resource from RAML configuration file.
+ * This method is for simulating/creating a resource based on the input data provided from
+ * RAML file.
*
* @param configPath - RAML configuration file path.
- * @param callback - Callback method for receive notifications when resource model changes.
+ * @param callback - Callback method for receiving notifications when resource model changes.
+ *
+ * @return SimulatorResourceServer shared object representing simulated/created resource.
*
- * @return SimulatorResourceServerPtr - Shared pointer of SimulatorResourceServer on success, otherwise NULL.
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+ * @SimulatorException if any other error occured.
*/
- SimulatorResourceServerPtr createResource(const std::string &configPath,
+ std::shared_ptr<SimulatorResourceServer> createResource(const std::string &configPath,
SimulatorResourceServer::ResourceModelChangedCB callback);
/**
- * This method is called for creating a collection of resources from RAML configuration file.
+ * This method is for creating multiple resources of same type based on the input data
+ * provided from RAML file.
*
* @param configPath - RAML configuration file path.
* @param count - Number of resource to be created.
- * @param callback - Callback method for receive notifications when resource model changes.
+ * @param callback - Callback method for receiving notifications when resource model changes.
+ *
+ * @return vector of SimulatorResourceServer shared objects representing simulated/created
+ * resources.
*
- * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+ * @SimulatorException if any other error occured.
*/
- std::vector<SimulatorResourceServerPtr> createResource(const std::string &configPath,
- const int count,
- SimulatorResourceServer::ResourceModelChangedCB callback);
+ std::vector<std::shared_ptr<SimulatorResourceServer>> createResource(
+ const std::string &configPath, unsigned short count,
+ SimulatorResourceServer::ResourceModelChangedCB callback);
/**
- * This method is called for obtaining a list of created resources.
+ * This method is for obtaining a list of created resources.
+ *
+ * @param resourceType - Resource type. Empty value will fetch all resources.
+ * Default value is empty string.
*
- * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+ * @return vector of SimulatorResourceServer shared objects representing simulated/created
*/
- std::vector<SimulatorResourceServerPtr> getResources(const std::string &resourceType = "");
+ std::vector<std::shared_ptr<SimulatorResourceServer>> getResources(
+ const std::string &resourceType = "");
/**
- * This method is called for deleting a single resource.
+ * This method is for deleting/unregistering resource.
*
- * @param resource - Shared pointer of the SimulatorResourceServer to be deleted.
+ * @param resource - SimulatorResourceServer shared object.
*
- * @return SimulatorResult
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed
*/
- SimulatorResult deleteResource(SimulatorResourceServerPtr &resource);
+ void deleteResource(const std::shared_ptr<SimulatorResourceServer> &resource);
/**
- * This method is called for deleting multiple resources.
- * If this method is called without any parameter, then all resources will be deleted.
- * If thie method is called with a specific resourcetype as a parameter, then all the resources
- * of that particular type will be deleted.
+ * This method is for deleting multiple resources based on resource type.
*
- * @param resourceType - Resource type of the resource
+ * @param resourceType - Resource type. Empty value will delete all the resources.
+ * Default value is empty string.
*
- * @return SimulatorResult
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed
*/
- SimulatorResult deleteResources(const std::string &resourceType = "");
+ void deleteResources(const std::string &resourceType = "");
+
+ /**
+ * API for discovering all type of resources.
+ * Discovered resources will be notified through the callback set using @callback parameter.
+ *
+ * @param callback - Method of type @ResourceFindCallback through which discoverd resources
+ * will be notified.
+ *
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+ * @SimulatorException if any other error occured.
+ */
+ void findResources(ResourceFindCallback callback);
/**
* API for discovering resources of a particular resource type.
- * Callback is called when a resource is found.
+ * Discovered resources will be notified through the callback set using @callback parameter.
*
- * @param resourceType - required resource type
- * @param callback - Returns SimulatorRemoteResource.
+ * @param resourceType - Type of resource to be searched for
+ * @param callback - Method of type @ResourceFindCallback through which discoverd resources
+ * will be notified.
*
- * @return SimulatorResult - return value of this API.
- * It returns SIMULATOR_SUCCESS if success.
+ * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
+ * @SimulatorException if any other error occured.
+ */
+ void findResources(const std::string &resourceType, ResourceFindCallback callback);
+
+ /**
+ * API for getting device information from remote device.
+ * Received device information will be notified through the callback set using
+ * @callback parameter.
+ *
+ * @param callback - Method of type @DeviceInfoCallback through which device information
+ * will be notified.
*
- * NOTE: SimulatorResult is defined in simulator_error_codes.h.
+ * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
*/
- SimulatorResult findResource(const std::string &resourceType, ResourceFindCallback callback);
+ void getDeviceInfo(DeviceInfoCallback callback);
/**
- * API for getting list of already found resources.
+ * API for registering device information with stack.
+ *
+ * @param deviceName - Device name to be registered.
*
- * @param resourceType - resource type
+ * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
+ */
+ void setDeviceInfo(const std::string &deviceName);
+
+ /**
+ * API for getting platform information from remote device.
+ * Received platform information will be notified through the callback set using
+ * @callback parameter.
+ *
+ * @param callback - Method of type @PlatformInfoCallback through which platform
+ * information will be notified.
+ *
+ * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
+ */
+ void getPlatformInfo(PlatformInfoCallback callback);
+
+ /**
+ * API for registering platform information with stack.
*
- * @return List of SimulatorRemoteResource
+ * @param platformInfo - PlatformInfo contains all platform related information.
*
+ * NOTE: API throws @SimulatorException on error.
*/
- std::vector<SimulatorRemoteResourcePtr> getFoundResources(
- const std::string resourceType = "");
+ void setPlatformInfo(PlatformInfo &platformInfo);
/**
* API for setting logger target for receiving the log messages.
* @param logger - ILogger interface for handling the log messages.
*
*/
- void setLogger(std::shared_ptr<ILogger> logger);
+ void setLogger(const std::shared_ptr<ILogger> &logger);
/**
* API for setting console as logger target.
* otherwise false.
*
*/
- bool setDefaultFileLogger(std::string &path);
+ bool setDefaultFileLogger(const std::string &path);
private:
SimulatorManager();
~SimulatorManager() = default;
+ SimulatorManager(const SimulatorManager &) = delete;
+ SimulatorManager &operator=(const SimulatorManager &) = delete;
+ SimulatorManager(const SimulatorManager &&) = delete;
+ SimulatorManager &operator=(const SimulatorManager && ) = delete;
};
#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+#ifndef SIMULATOR_PLATFORM_INFO_H_
+#define SIMULATOR_PLATFORM_INFO_H_
+
+#include <iostream>
+
+/**
+ * @class PlatformInfo
+ *
+ * @brief This class contains remote device platform information and provide APIs access it.
+ */
+class PlatformInfo
+{
+ public:
+ /**
+ * This method is for getting platfom id.
+ *
+ * @return Platform id.
+ */
+ std::string getPlatformID() const;
+
+ /**
+ * This method is for getting platform version.
+ *
+ * @return Platform version.
+ */
+ std::string getPlatformVersion() const;
+
+ /**
+ * This method is for getting manufacturer name.
+ *
+ * @return manufacturer name.
+ */
+ std::string getManufacturerName() const;
+
+ /**
+ * This method is for getting manufacturer URL.
+ *
+ * @return manufacturer URL.
+ */
+ std::string getManufacturerUrl() const;
+
+ /**
+ * This method is for getting model number.
+ *
+ * @return Model number.
+ */
+ std::string getModelNumber() const;
+
+ /**
+ * This method is for getting date of manufacture.
+ *
+ * @return Date of manufacture.
+ */
+ std::string getDateOfManfacture() const;
+
+ /**
+ * This method is for getting operating system version.
+ *
+ * @return Operating system version.
+ */
+ std::string getOSVersion() const;
+
+ /**
+ * This method is for getting hardware version.
+ *
+ * @return Hardware version.
+ */
+ std::string getHardwareVersion() const;
+
+ /**
+ * This method is for getting firmware version.
+ *
+ * @return Firmware version.
+ */
+ std::string getFirmwareVersion() const;
+
+ /**
+ * This method is for getting support link URL.
+ *
+ * @return URL of support link.
+ */
+ std::string getSupportUrl() const;
+
+ /**
+ * This method is for getting system time.
+ *
+ * @return System time.
+ */
+ std::string getSystemTime() const;
+
+ void setPlatformID(const std::string &platformId);
+ void setPlatformVersion(const std::string &platformVersion);
+ void setManufacturerName(const std::string &manufacturerName);
+ void setManufacturerUrl(const std::string &manufacturerUrl);
+ void setModelNumber(const std::string &modelNumber);
+ void setDateOfManfacture(const std::string &dateOfManufacture);
+ void setOSVersion(const std::string &osVersion);
+ void setHardwareVersion(const std::string &hwVersion);
+ void setFirmwareVersion(const std::string &firmwareVersion);
+ void setSupportUrl(const std::string &supportUrl);
+ void setSystemTime(const std::string &systemTime);
+
+ private:
+ std::string m_platformID;
+ std::string m_manufacturerName;
+ std::string m_manufacturerUrl;
+ std::string m_modelNumber;
+ std::string m_dateOfManufacture;
+ std::string m_platformVersion;
+ std::string m_operationSystemVersion;
+ std::string m_hardwareVersion;
+ std::string m_firmwareVersion;
+ std::string m_supportUrl;
+ std::string m_systemTime;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_remote_resource.h
+ *
+ * @brief This file provides a class for handling discovered resources.
+ *
+ */
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_H_
+#define SIMULATOR_REMOTE_RESOURCE_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+
+/**
+ * @class SimulatorRemoteResource
+ * @brief This class provides a set of functions for the client to hande the resources currently running on the servers.
+ */
+class SimulatorRemoteResource
+{
+ public:
+
+ /**
+ * Callback method for receiving response for GET, PUT and POST requests.
+ *
+ */
+ typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP)>
+ ResponseCallback;
+
+ /**
+ * Callback method for receiving model change notifications from remote resource.
+ *
+ */
+ typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP, int)>
+ ObserveNotificationCallback;
+
+ /**
+ * Callback method for receiving auto request generation and verifiction progress state.
+ *
+ */
+ typedef std::function<void(std::string, int, OperationState)>
+ StateCallback;
+
+ /**
+ * API for getting URI of resource.
+ *
+ * @return URI of resource.
+ *
+ */
+ virtual std::string getURI() const = 0;
+
+ /**
+ * API for getting host address of resource.
+ *
+ * @return Host address of resource.
+ *
+ */
+ virtual std::string getHost() const = 0;
+
+ /**
+ * API for getting unique id of resource.
+ *
+ * @return ID of resource.
+ *
+ */
+ virtual std::string getID() const = 0;
+
+
+ /**
+ * API for getting connectivity type of resource.
+ *
+ * @return enum SimulatorConnectivityType value
+ *
+ */
+ virtual SimulatorConnectivityType getConnectivityType() const = 0;
+
+ /**
+ * API for getting resource types bound with the resource.
+ *
+ * @return vector of strings representing resource types.
+ *
+ */
+ virtual std::vector < std::string > getResourceTypes() const = 0;
+
+ /**
+ * API for getting interface types bound with the resource.
+ *
+ * @return vector of strings representing interface types.
+ *
+ */
+ virtual std::vector < std::string > getResourceInterfaces() const = 0;
+
+ /**
+ * API to check whether resource can be observed or not.
+ *
+ * @return true if resource is observable, otherwise false.
+ *
+ */
+ virtual bool isObservable() const = 0;
+
+ virtual void observe(ObserveType type, ObserveNotificationCallback callback) = 0;
+
+ virtual void cancelObserve() = 0;
+
+ virtual void get(const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback) = 0;
+
+ virtual void get(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback) = 0;
+
+ virtual void put(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback) = 0;
+
+ virtual void put(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback) = 0;
+
+ virtual void post(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback) = 0;
+
+ virtual void post(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback) = 0;
+
+ virtual int startVerification(RequestType type, StateCallback callback) = 0;
+
+ virtual void stopVerification(int id) = 0;
+
+ virtual void configure(const std::string &path) = 0;
+};
+
+typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourceSP;
+
+#endif
+
* resources and provides a set of functions for updating the model.
*/
-#ifndef SIMULATOR_RESOURCE_ATTRIBUTE_H_
-#define SIMULATOR_RESOURCE_ATTRIBUTE_H_
+#ifndef SIMULATOR_RESOURCE_MODEL_H_
+#define SIMULATOR_RESOURCE_MODEL_H_
#include <string>
#include <vector>
#include "OCPlatform.h"
-#include "OCApi.h"
+#include <climits>
-class SimulatorResourceServer;
-class SimulatorRemoteResource;
/**
* @class SimulatorResourceModel
* @brief This class provides a set of functions for accessing and manipulating the resource model.
*/
class SimulatorResourceModel
{
- friend class SimulatorResourceServer;
- friend class SimulatorRemoteResource;
-
public:
-
SimulatorResourceModel() = default;
SimulatorResourceModel(SimulatorResourceModel &&) = default;
SimulatorResourceModel(const SimulatorResourceModel &) = default;
SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
- SimulatorResourceModel &operator=(SimulatorResourceModel &&) = default;
-
- virtual ~SimulatorResourceModel() {}
+ SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
/**
* @class Attribute
typedef boost::variant <
int,
double,
+ bool,
std::string
> ValueVariant;
- Attribute() = default;
- Attribute(const std::string &attrName) : m_name(attrName) {}
+ Attribute()
+ {
+ m_min = INT_MIN;
+ m_max = INT_MAX;
+ m_updateInterval = -1;
+ }
+
+ Attribute(const std::string &attrName)
+ {
+ m_name = attrName;
+ m_min = INT_MIN;
+ m_max = INT_MAX;
+ m_updateInterval = -1;
+ }
+ /**
+ * API to get attribute's name.
+ *
+ * @return Attribute name.
+ */
std::string getName(void) const;
+
+ /**
+ * API to set the name of attribute.
+ *
+ * @param name - Attribute name.
+ */
void setName(const std::string &name);
+ /**
+ * API to get attribute's value.
+ *
+ * @return value of attribute.
+ */
template <typename T>
T getValue() const
{
return boost::get<T>(m_value);
}
+ /**
+ * API to get attribute's value.
+ *
+ * @return value of attribute as ValueVariant.
+ */
ValueVariant &getValue()
{
return m_value;
}
+ /**
+ * API to get attribute's value type.
+ *
+ * @return type of value.
+ */
int getValueType() const
{
return m_value.which();
}
+ /**
+ * API to set the attribute's value.
+ *
+ * @param value - value to be set.
+ */
template <typename T>
void setValue(const T &value)
{
m_value = value;
}
- void setFromAllowedValue(const int allowedValueIndex);
+ /**
+ * API to set the attribute's value from allowed values container.
+ *
+ * @param allowedValueIndex - Index of value to be set from allowed vaules container.
+ */
+ void setFromAllowedValue(unsigned int index);
+ /**
+ * API to get range of attribute's value.
+ */
void getRange(int &min, int &max) const;
+ /**
+ * API to set range of attribute's value.
+ *
+ * @param min - minimum value could be set as attribute value.
+ * @param max - maximum value could be set as attribute value.
+ */
void setRange(const int &min, const int &max);
+ /**
+ * API to set the values to allowed values set.
+ *
+ * @param values - vector of values which will be set as allowed values.
+ */
template <typename T>
bool setAllowedValues(const std::vector<T> &values)
{
}
/**
- * This method is used to get the size of the allowed values.
- *
- * @return Size of the allowed values
- */
+ * API to get the number of values present in allowed values set.
+ *
+ * @return Size of the allowed values.
+ */
int getAllowedValuesSize() const;
/**
- * This method is used to get the string representation of the value.
- *
- * @return Attribute's value as a string
- */
+ * API to get the string representation of the value.
+ *
+ * @return Attribute's value as a string.
+ */
std::string valueToString() const;
/**
- * This method is used to get the string representation of all the allowed values.
- *
- * @return All allowed values as a string
- */
- std::string allowedValuesToString() const;
- std::vector<std::string> allowedValuesToVectorString() const;
+ * API to get the string representation of all the allowed values.
+ *
+ * @return All allowed values as a string.
+ */
+ std::vector<std::string> allowedValuesToString() const;
void addValuetoRepresentation(OC::OCRepresentation &rep,
const std::string &key) const;
}
}
- ValueVariant &at(int index);
+ ValueVariant &at(unsigned int index);
int size() const;
- std::string toString() const;
- std::vector<std::string> toVectorString() const;
+ std::vector<std::string> toString() const;
std::vector<ValueVariant> getValues();
private:
std::vector<ValueVariant> m_values;
};
/**
- * This method is used to get the number of attributes in the resource.
+ * API to get the number of attributes in the resource model.
*
- * @return Count of attributes
+ * @return Number of attributes.
*/
int size() const { return m_attributes.size(); }
/**
- * This method is used to get the value of an attribute.
- *
- * @param attrName - Attribute name
- * @param value - Attribute value
- *
- * @return Boolean, true if attribute exists, otherwise false.
- */
+ * API to get the value of an attribute.
+ *
+ * @param attrName - Attribute name
+ * @param value - Attribute value
+ *
+ * @return true if attribute exists, otherwise false.
+ */
bool getAttribute(const std::string &attrName, Attribute &value);
/**
- * This method is used to get the entire list of attributes in the form of key-value pair.
- * Attribute name is the key and an instance of Attribute is the value.
- *
- * @return A map of all the attributes
- */
+ * API to get the entire list of attributes in the form of key-value pair.
+ * Attribute name is the key and an instance of Attribute is the value.
+ *
+ * @return A map of all the attributes
+ */
std::map<std::string, Attribute> getAttributes() const;
- static SimulatorResourceModel create(const OC::OCRepresentation &ocRep);
-
+ /**
+ * API to add new attribute to resource model.
+ *
+ * @param attrName - Attribute name
+ * @param attrValue - Attribute value
+ */
template <typename T>
void addAttribute(const std::string &attrName, const T &attrValue)
{
}
}
- private:
+ /**
+ * API to add new attribute to resource model.
+ *
+ * @param attr - Attribute pointer
+ *
+ */
+ void addAttribute(Attribute &attr)
+ {
+ std::string attrName = attr.getName();
+ m_attributes[attrName] = Attribute(attr);
+ }
+
+ /**
+ * API to set range of attribute value.
+ *
+ * @param attrName - Attribute name.
+ * @param min - Minimum value could be set as attribute value.
+ * @param max - Maximum value could be set as attribute value.
+ */
void setRange(const std::string &attrName, const int min, const int max);
+ OC::OCRepresentation getOCRepresentation() const;
+ static std::shared_ptr<SimulatorResourceModel> create(const OC::OCRepresentation &ocRep);
+
template <typename T>
void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
{
m_attributes[attrName].setAllowedValues(values);
}
- void setUpdateInterval(const std::string &attrName, int interval);
+ bool update(OC::OCRepresentation &ocRep);
+
+ bool update(std::shared_ptr<SimulatorResourceModel> &repModel);
template <typename T>
void updateAttribute(const std::string &attrName, const T &value)
m_attributes[attrName].setValue(value);
}
- void updateAttributeFromAllowedValues(const std::string &attrName, const int allowedValueIndex);
+ void updateAttributeFromAllowedValues(const std::string &attrName, unsigned int index);
void removeAttribute(const std::string &attrName);
- OC::OCRepresentation getOCRepresentation() const;
-
- bool update(OC::OCRepresentation &ocRep);
-
- bool update(SimulatorResourceModel &repModel);
+ void setUpdateInterval(const std::string &attrName, int interval);
+ private:
std::map<std::string, Attribute> m_attributes;
};
+typedef std::shared_ptr<SimulatorResourceModel> SimulatorResourceModelSP;
+typedef std::shared_ptr<SimulatorResourceModel::Attribute> AttributeSP;
+
#endif
#ifndef SIMULATOR_RESOURCE_SERVER_H_
#define SIMULATOR_RESOURCE_SERVER_H_
+#include "simulator_server_types.h"
#include "simulator_resource_model.h"
-#include "simulator_attribute_automation.h"
-#include "simulator_error_codes.h"
+#include "simulator_exceptions.h"
+
+enum class ObservationStatus : unsigned char
+{
+ OBSERVE_REGISTER,
+ OBSERVE_UNREGISTER
+};
+
+typedef struct
+{
+ uint8_t id;
+ std::string address;
+ uint16_t port;
+} ObserverInfo;
-class ResourceManager;
/**
* @class SimulatorResourceServer
* @brief This class provides a set of functions for operating and automating a resource.
*/
class SimulatorResourceServer
{
- friend class ResourceManager;
-
public:
+ /**
+ * Callback method for receiving notifications when resource model gets changed.
+ *
+ * @param uri - Resource URI
+ * @param resModel - Resource model
+ */
typedef std::function<void (const std::string &uri, const SimulatorResourceModel &resModel)>
ResourceModelChangedCB;
- SimulatorResourceServer();
-
/**
- * This method is used to set the resource URI.
+ * Callback method for receiving notifications when observer is registered/unregistered
+ * with resource.
*
* @param uri - Resource URI
- *
- * @return SimulatorResult
+ * @param state - OBSERVE_REGISTER if observer is registered, otherwise OBSERVE_UNREGISTER.
+ * @param observerInfo - Information about observer.
*/
- SimulatorResult setURI(const std::string &uri);
+ typedef std::function<void (const std::string &uri, ObservationStatus state, const ObserverInfo &observerInfo)>
+ ObserverCB;
+
+ SimulatorResourceServer();
+
+ virtual ~SimulatorResourceServer() {};
/**
- * This method is used to get the resource URI.
+ * API to get the resource URI.
*
* @return Resource URI
*/
std::string getURI() const;
/**
- * This method is used to set the resource type.
- *
- * @param resourceType - Resource Type
- *
- * @return SimulatorResult
- */
- SimulatorResult setResourceType(const std::string &resourceType);
-
- /**
- * This method is used to get the resource URI.
+ * API to get the resource URI.
*
* @return Resource Type
*/
std::string getResourceType() const;
/**
- * This method is used to set the interface type of the resource.
- *
- * @param interfaceType - Interface Type of the resource
- *
- * @return SimulatorResult
- */
- SimulatorResult setInterfaceType(const std::string &interfaceType);
-
- /**
- * This method is used to get the interface type of the resource.
+ * API to get the interface type of the resource.
*
* @return Interface type of the resource
*/
std::string getInterfaceType() const;
/**
- * This method is used to set the name of the resource.
- *
- * @param name - Name of the resource
- *
- * @return void
- */
- void setName(const std::string &name);
-
- /**
- * This method is used to get the name of the resource.
+ * API to get the name of the resource.
*
* @return Resource name
*/
std::string getName() const;
/**
- * This method is used to set whether resource can be observable or not.
- *
- * @param state - true for resource observable, otherwise false.
- *
- * @return SimulatorResult
- */
- SimulatorResult setObservable(bool state);
-
- /**
- * This method is used to get the observable state of resource.
+ * API to add a new attribute to the resource model.
*
- * @return bool - true if resource is observable, otherwise false.
+ * @param attribute - Attribute to be add to model.
*/
- bool isObservable() const;
+ void addAttribute(SimulatorResourceModel::Attribute &attribute);
/**
- * This method is used to start the attribute value automation for all attributes.
- * Once started, values for the attributes will be selected randomly from their allowed range
- * and the updated values will be notified to all the observers of the resource.
- *
- * @param id - Identifier for automation will be returned
- *
- * @return SimulatorResult
- */
- SimulatorResult startUpdateAutomation(AutomationType type,
- updateCompleteCallback callback, int &id);
-
- /**
- * This method is used to start the attribute value automation for a specific attribute.
- * Once started, values for the attribute will be selected randomly from its allowed range
- * and the updated value will be notified to all the observers of the resource.
- *
- * @param attrName - Name of the attribute to be automated
- * @param id - Identifier for automation will be returned
- *
- * @return SimulatorResult
- */
- SimulatorResult startUpdateAutomation(const std::string &attrName, AutomationType type,
- updateCompleteCallback callback, int &id);
-
- /**
- * This method is used to get the Ids of all ongoing resource update automation .
- *
- * @return Ids as vector of int
- */
- std::vector<int> getResourceAutomationIds();
-
- /**
- * This method is used to get the Ids of all ongoing attribute update automation .
- *
- * @return Ids as vector of int
- */
- std::vector<int> getAttributeAutomationIds();
-
- /**
- * This method is used to stop the automation.
- *
- * @param id - Identifier for automation
- */
- void stopUpdateAutomation(const int id);
-
- /**
- * This method is used to add a new attribute to the resource model.
- *
- * @param attrName - Name of the attribute
- * @param attrValue - Value of the attribute
- *
- * @return void
- */
- template <typename T>
- void addAttribute(const std::string &attrName, const T &attrValue)
- {
- m_resModel.addAttribute(attrName, attrValue);
- notifyListOfObservers();
- }
-
- /**
- * This method is used to set the value range of an attribute.
+ * API to set the value range of an attribute.
* This method is intended to be used for attributes whose values are numbers only.
*
* @param attrName - Name of the attribute
* @param min - Minimum value of the range
* @param max - Maximum value of the range
- *
- * @return void
*/
void setRange(const std::string &attrName, const int min, const int max);
/**
- * This method is used to set the allowed values of an attribute.
+ * API to set the allowed values of an attribute.
*
* @param attrName - Name of the attribute
* @param values - Allowed values
- *
- * @return void
*/
template <typename T>
void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
}
/**
- * This method is used to set the update interval time for automation.
+ * API to set the update interval time for automation.
*
* @param attrName - Name of the attribute
* @param interval - Interval time in miliseconds for attribute value update automation
- *
- * @return void
*/
void setUpdateInterval(const std::string &attrName, int interval);
/**
- * This method is used to update the value of an attribute.
+ * API to update the value of an attribute.
*
* @param attrName - Name of the attribute
* @param value - Value of the attribute
- *
- * @return void
*/
template <typename T>
- void updateAttribute(const std::string &attrName, const T &value)
+ void updateAttributeValue(const std::string &attrName, const T &value)
{
m_resModel.updateAttribute(attrName, value);
- notifyListOfObservers();
}
/**
- * This method is used to update the attribute's value by taking the index of the value
+ * API to update the attribute's value by taking the index of the value
* in the allowed values range.
*
* @param attrName - Name of the attribute
* @param allowedValueIndex - Index of the value in the allowed values range
- *
- * @return void
*/
- void updateAttributeFromAllowedValues(const std::string &attrName, const int allowedValueIndex);
+ void updateFromAllowedValues(const std::string &attrName, unsigned int index);
/**
- * This method is used to remove an attribute from the resource model.
+ * API to remove an attribute from the resource model.
*
* @param attName - Name of the attribute to be removed
- *
- * @return void
*/
void removeAttribute(const std::string &attName);
/**
- * This method is used to get the object of SimulatorResourceModel.
+ * API to get the object of SimulatorResourceModel.
* Attributes of the resource are accessed using this object.
*
- * @return SimulatorResourceModel - Resource model of the resource
+ * @return Resource model of the resource.
*/
SimulatorResourceModel getModel() const;
/**
- * This method is used to set the callback for receiving the notifications when the
+ * API to get the observable state of resource.
+ *
+ * @return bool - true if resource is observable, otherwise false.
+ */
+ virtual bool isObservable() const = 0;
+
+ /**
+ * API to start the attribute value automation for all attributes.
+ * Once started, values for the attributes will be selected randomly from their allowed range
+ * and the updated values will be notified to all the observers of the resource.
+ *
+ * @param type - Automation type.
+ * @param callback - Callback to get notifiy when update automation is finished.
+ * @param id - Identifier for automation.
+ *
+ * @return ID representing update automation session.
+ * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+ */
+ virtual int startUpdateAutomation(AutomationType type,
+ updateCompleteCallback callback) = 0;
+
+ /**
+ * This method is used to start the attribute value automation for a specific attribute.
+ * Once started, values for the attribute will be selected randomly from its allowed range
+ * and the updated value will be notified to all the observers of the resource.
+ *
+ * @param attrName - Name of the attribute to be automated.
+ * @param type - Automation type.
+ * @param callback - Callback to get notifiy when update automation is finished.
+ * @param id - Identifier for automation.
+ *
+ * @return ID representing update automation session.
+ * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+ */
+ virtual int startUpdateAutomation(const std::string &attrName, AutomationType type,
+ updateCompleteCallback callback) = 0;
+
+ /**
+ * API to get the Ids of all ongoing resource update automation .
+ *
+ * @return vector of resource automation ids.
+ */
+ virtual std::vector<int> getResourceAutomationIds() = 0;
+
+ /**
+ * API to get the Ids of all ongoing attribute update automation .
+ *
+ * @return vector of attribute automation ids.
+ */
+ virtual std::vector<int> getAttributeAutomationIds() = 0;
+
+ /**
+ * API to stop the resource/attribute automation.
+ *
+ * @param id - Identifier for automation.
+ */
+ virtual void stopUpdateAutomation(const int id) = 0;
+
+ /**
+ * API to set the callback for receiving the notifications when the
* resource model changes.
*
* @param callback - Callback to be set for receiving the notifications.
+ */
+ virtual void setModelChangeCallback(ResourceModelChangedCB callback) = 0;
+
+ /**
+ * API to set the callback for receiving the notifications when
+ * observer is registered or unregistered with resource.
+ *
+ * @param callback - Callback to be set for receiving the notifications.
+ */
+ virtual void setObserverCallback(ObserverCB callback) = 0;
+
+ /**
+ * API to get observers which are registered with resource.
*
- * @return SimulatorResourceModel - Resource model of the resource
+ * @return vector of ObserverInfo.
*/
- void setModelChangeCallback(ResourceModelChangedCB callback);
+ virtual std::vector<ObserverInfo> getObserversList() = 0;
- private:
- SimulatorResult start();
- SimulatorResult stop();
- OC::OCRepresentation getOCRepresentation();
- bool modifyResourceModel(OC::OCRepresentation &ocRep);
- OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
- void notifyListOfObservers ();
+ /**
+ * API to notify current resource model to specific observer.
+ *
+ * NOTE: API throws @SimulatorException exception.
+ */
+ virtual void notify(uint8_t id) = 0;
- SimulatorResourceModel m_resModel;
+ /**
+ * API to notify all registered observers.
+ *
+ * NOTE: API throws @SimulatorException exception.
+ */
+ virtual void notifyAll() = 0;
+
+ protected:
+ std::string m_name;
std::string m_uri;
std::string m_resourceType;
std::string m_interfaceType;
- std::string m_name;
- ResourceModelChangedCB m_callback;
- UpdateAutomationManager m_updateAutomationMgr;
-
- OCResourceHandle m_resourceHandle;
- OCResourceProperty m_property;
- OC::ObservationIds m_interestedObservers;
+ SimulatorResourceModel m_resModel;
};
-typedef std::shared_ptr<SimulatorResourceServer> SimulatorResourceServerPtr;
+typedef std::shared_ptr<SimulatorResourceServer> SimulatorResourceServerSP;
#endif
*
******************************************************************/
-#ifndef SIMULATOR_ERROR_CODES_H_
-#define SIMULATOR_ERROR_CODES_H_
+#ifndef SIMULATOR_SERVER_TYPES_H_
+#define SIMULATOR_SERVER_TYPES_H_
#include <iostream>
+#include <functional>
-typedef enum
+enum class AutomationType
{
- SIMULATOR_SUCCESS = 0,
- SIMULATOR_BAD_INPUT,
- SIMULATOR_RESOURCE_NOT_FOUND,
- SIMULATOR_RESOURCE_BUSY,
- SIMULATOR_RESOURCE_ALREADY_REGISTERED,
- SIMULATOR_RESOURCE_NOT_REGISTERED,
- SIMULATOR_OPERATION_NOT_ALLOWED,
- SIMULATOR_RESOURCE_ALREADY_OBSERVING,
+ NORMAL,
+ RECURRENT
+};
- // Attribute udpate automation related
- SIMULATOR_AUTOMATION_ALREADY_STARTED,
+typedef std::function<void (const std::string &, const int)> updateCompleteCallback;
- SIMULATOR_ERROR = 255
-} SimulatorResult;
-#endif //SIMULATOR_ERROR_CODES_H_
\ No newline at end of file
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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_attributes_jni.h"
+#include "simulator_resource_model.h"
+#include "simulator_common_jni.h"
+#include "simulator_error_codes.h"
+#include <climits>
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+class attribute_value_visitor : public boost::static_visitor<jobject>
+{
+ public:
+ attribute_value_visitor(JNIEnv *env) : m_Env(env) {}
+
+ // Integer type value conversion
+ jobject operator ()(const int &value) const
+ {
+ jobject result = m_Env->NewObject(gSimulatorClassRefs.classInteger,
+ gSimulatorClassRefs.classIntegerCtor, value);
+ return result;
+ }
+
+ // Double type value conversion
+ jobject operator ()(const double &value) const
+ {
+ jobject result = m_Env->NewObject(gSimulatorClassRefs.classDouble,
+ gSimulatorClassRefs.classDoubleCtor, value);
+ return result;
+ }
+
+ // String type value conversion
+ jobject operator ()(const std::string &value) const
+ {
+ jstring str = m_Env->NewStringUTF(value.c_str());
+ return static_cast<jobject>(str);
+ }
+
+#if 0
+ // Boolean type value conversion
+ jobject operator ()(const bool &value) const
+ {
+ jobject result = m_Env->NewObject(gSimulatorClassRefs.classBoolean,
+ gSimulatorClassRefs.classBooleanCtor, value);
+ return result;
+ }
+
+ // SimulatorResourceModel::Attribute type value conversion
+ jobject operator ()(const SimulatorResourceModel::Attribute &value) const
+ {
+ JResourceAttributeConverter converter(value);
+ return converter.toJava();
+ }
+#endif
+
+ private:
+ JNIEnv *m_Env;
+};
+
+jobject JResourceAttributeConverter::toJava(JNIEnv *env)
+{
+ // Create an object of ResourceAttribute java class
+ jobject jattributeObj = (jobject) env->NewObject(gSimulatorClassRefs.classResourceAttribute,
+ gSimulatorClassRefs.classResourceAttributeCtor);
+ if (env->ExceptionCheck() || !jattributeObj)
+ {
+ return nullptr;
+ }
+
+ // Set attribute name
+ if (!setName(env, jattributeObj))
+ {
+ return nullptr;
+ }
+
+ // Set types
+ if (!setType(env, jattributeObj))
+ {
+ return nullptr;
+ }
+
+ // Set value
+ if (!setValue(env, jattributeObj))
+ {
+ return nullptr;
+ }
+
+ // Set Range
+ if (!setRange(env, jattributeObj))
+ {
+ return nullptr;
+ }
+
+ // Set Allowed values
+ if (!setAllowedValues(env, jattributeObj))
+ {
+ return nullptr;
+ }
+
+ return jattributeObj;
+}
+
+bool JResourceAttributeConverter::setName(JNIEnv *env, jobject &jattributeObj)
+{
+ // Get field reference to "ResourceAttribute::m_name"
+ static jfieldID fidName = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, "m_name",
+ "Ljava/lang/String;");
+ if (!fidName)
+ {
+ return false;
+ }
+
+ // Set the attribute name
+ std::string name = m_attribute.getName();
+ jstring jname = env->NewStringUTF(name.c_str());
+ env->SetObjectField(jattributeObj, fidName, jname);
+ if (env->ExceptionCheck())
+ {
+ return false;
+ }
+
+ return true;
+}
+
+bool JResourceAttributeConverter::setType(JNIEnv *env, jobject &jattributeObj)
+{
+ // Get class refs to ResourceAttribute::Type class
+ static jclass clsType = env->FindClass("org/oic/simulator/ResourceAttribute$Type");
+ if (!clsType)
+ {
+ return false;
+ }
+
+ // Get method ref to static method to ResourceAttribute::Type::getType
+ static jmethodID midGetType = env->GetStaticMethodID(clsType, "getType",
+ "(I)Lorg/oic/simulator/ResourceAttribute$Type;");
+ if (!midGetType)
+ {
+ return false;
+ }
+
+ // Get field reference to "ResourceAttribute::m_type"
+ static jfieldID fidType = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
+ "m_type", "Lorg/oic/simulator/ResourceAttribute$Type;");
+ if (!fidType)
+ {
+ return false;
+ }
+
+ int type = m_attribute.getValueType();
+ jobject jtype = env->CallStaticObjectMethod(clsType, midGetType, type);
+ if (env->ExceptionCheck())
+ {
+ return false;
+ }
+
+ env->SetObjectField(jattributeObj, fidType, jtype);
+ if (env->ExceptionCheck())
+ {
+ return false;
+ }
+
+ return true;
+}
+
+bool JResourceAttributeConverter::setValue(JNIEnv *env, jobject &jattributeObj)
+{
+ // Get field reference to "ResourceAttribute::m_value"
+ static jfieldID fidValue = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
+ "m_value", "Ljava/lang/Object;");
+ if (!fidValue)
+ {
+ return false;
+ }
+ jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), m_attribute.getValue());
+ env->SetObjectField(jattributeObj, fidValue, jvalue);
+ return true;
+}
+
+bool JResourceAttributeConverter::setRange(JNIEnv *env, jobject &jattributeObj)
+{
+ int min = INT_MIN;
+ int max = INT_MAX;
+ m_attribute.getRange(min, max);
+ if (INT_MIN == min || INT_MAX == max)
+ {
+ return true;
+ }
+ env->CallVoidMethod(jattributeObj, gSimulatorClassRefs.classResourceAttributeSetRange, min, max);
+ if (env->ExceptionCheck())
+ {
+ return false;
+ }
+
+ return true;
+}
+
+bool JResourceAttributeConverter::setAllowedValues(JNIEnv *env, jobject &jattributeObj)
+{
+ // Get field reference to "ResourceAttribute::m_AllowedValues"
+ static jfieldID fidAllowedValues = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute,
+ "m_AllowedValues", "Ljava/lang/Object;");
+ if (!fidAllowedValues)
+ {
+ return false;
+ }
+
+ jobjectArray jallowedValues = env->NewObjectArray(m_attribute.getAllowedValuesSize(),
+ gSimulatorClassRefs.classObject, NULL);
+ if (!jallowedValues)
+ {
+ return false;
+ }
+
+ int index = 0;
+ for (auto & value : m_attribute.getAllowedValues())
+ {
+ jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), value);
+ env->SetObjectArrayElement(jallowedValues, index++, jvalue);
+ }
+
+ env->SetObjectField(jattributeObj, fidAllowedValues, jallowedValues);
+ if (env->ExceptionCheck())
+ {
+ return false;
+ }
+
+ return true;
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef RESOURCE_ATTRIBUTE_JNI_H_
+#define RESOURCE_ATTRIBUTE_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_model.h"
+
+class JResourceAttributeConverter
+{
+ public:
+ JResourceAttributeConverter(SimulatorResourceModel::Attribute &attribute) {m_attribute = attribute;}
+ JResourceAttributeConverter(const JResourceAttributeConverter &) = delete;
+ JResourceAttributeConverter &operator=(const JResourceAttributeConverter &) = delete;
+ JResourceAttributeConverter(const JResourceAttributeConverter &&) = delete;
+ JResourceAttributeConverter &operator=(const JResourceAttributeConverter && ) = delete;
+ jobject toJava(JNIEnv *env);
+
+ private:
+ bool setName(JNIEnv *env, jobject &jaAttributeObj);
+ bool setType(JNIEnv *env, jobject &jaAttributeObj);
+ bool setValue(JNIEnv *env, jobject &jaAttributeObj);
+ bool setRange(JNIEnv *env, jobject &jaAttributeObj);
+ bool setAllowedValues(JNIEnv *env, jobject &jaAttributeObj);
+
+ SimulatorResourceModel::Attribute m_attribute;
+};
+
+#endif //SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
typedef struct
{
+ jclass classObject;
jclass classInteger;
jclass classDouble;
jclass classString;
jclass classHashMap;
jclass classVector;
- jclass classSimulatorResource;
- jclass classSimulatorResourceModel;
- jclass classSimulatorResourceAttribute;
- jclass classSimulatorRemoteResource;
- jclass classSimulatorCallback;
jclass classMap;
jclass classMapEntry;
jclass classSet;
jclass classIterator;
+ jclass classLinkedList;
+
+ jclass classSimulatorResource;
+ jclass classSimulatorResourceModel;
+ jclass classResourceAttribute;
+ jclass classSimulatorRemoteResource;
+ jclass classSimulatorCallback;
+ jclass classObserverInfo;
+ jclass classDeviceInfo;
+ jclass classPlatformInfo;
+ jclass classSimulatorException;
+ jclass classInvalidArgsException;
+ jclass classNoSupportException;
+ jclass classOperationInProgressException;
jmethodID classIntegerCtor;
jmethodID classDoubleCtor;
jmethodID classHashMapPut;
jmethodID classVectorCtor;
jmethodID classVectorAddElement;
- jmethodID classSimulatorResourceCtor;
- jmethodID classSimulatorResourceSetURI;
- jmethodID classSimulatorResourceSetResourceType;
- jmethodID classSimulatorResourceSetInterfaceType;
- jmethodID classSimulatorResourceSetName;
- jmethodID classSimulatorResourceModelCtor;
- jmethodID classSimulatorResourceAttributeCtor;
- jmethodID classSimulatorResourceModelId;
jmethodID classMapEntrySet;
jmethodID classMapGetKey;
jmethodID classMapGetValue;
jmethodID classIteratorId;
jmethodID classHasNextId;
jmethodID classNextId;
+ jmethodID classLinkedListCtor;
+ jmethodID classLinkedListAddObject;
+
+ jmethodID classSimulatorResourceCtor;
+ jmethodID classSimulatorResourceModelCtor;
+ jmethodID classResourceAttributeCtor;
+ jmethodID classResourceAttributeSetRange;
+ jmethodID classSimulatorResourceModelId;
+ jmethodID classObserverInfoCtor;
+ jmethodID classSimulatorExceptionCtor;
+ jmethodID classInvalidArgsExceptionCtor;
+ jmethodID classNoSupportExceptionCtor;
+ jmethodID classOperationInProgressExceptionCtor;
+
} SimulatorClassRefs;
static jfieldID GetHandleField(JNIEnv *env, jobject jobj)
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_device_info_jni.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo)
+{
+ if (!m_env)
+ return nullptr;
+
+ jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
+ if (constr)
+ return nullptr;
+
+ jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, constr);
+ if (jDeviceInfo)
+ return nullptr;
+
+ setFieldValue(jDeviceInfo, "mName", deviceInfo.getName());
+ setFieldValue(jDeviceInfo, "mID", deviceInfo.getID());
+ setFieldValue(jDeviceInfo, "mSpecVersion", deviceInfo.getSpecVersion());
+ setFieldValue(jDeviceInfo, "mDMVVersion", deviceInfo.getDataModelVersion());
+
+ return jDeviceInfo;
+}
+
+void JDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
+ const std::string &value)
+{
+ jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classDeviceInfo, fieldName.c_str(),
+ "Ljava/lang/String;");
+ jstring valueStr = m_env->NewStringUTF(value.c_str());
+ m_env->SetObjectField(jDeviceInfo, fieldID, valueStr);
+}
+
+void JniDeviceInfoListener::onDeviceInfoReceived(DeviceInfo &deviceInfo)
+{
+ // Get the environment
+ JNIEnv *env = getEnv();
+ if (!env)
+ return;
+
+ jobject listener = env->NewLocalRef(m_listener);
+ if (!listener)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jclass listenerCls = env->GetObjectClass(listener);
+ if (!listenerCls)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jmethodID listenerMId = env->GetMethodID(listenerCls, "onDeviceFound",
+ "(Lorg/oic/simulator/DeviceInfo;)V");
+ if (!listenerMId)
+ {
+ releaseEnv();
+ return;
+ }
+
+ // Convert CPP to Java DeviceInfo object
+ jobject jDeviceInfo = JDeviceInfo(env).toJava(deviceInfo);
+ if (!jDeviceInfo)
+ {
+ releaseEnv();
+ return;
+ }
+
+ // Invoke java listener with DeviceInfo
+ env->CallVoidMethod(listener, listenerMId, jDeviceInfo);
+ if (env->ExceptionCheck())
+ {
+ releaseEnv();
+ return;
+ }
+
+ releaseEnv();
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_DEVICE_INFO_JNI_H_
+#define SIMULATOR_DEVICE_INFO_JNI_H_
+
+#include "simulator_device_info.h"
+#include <jni.h>
+
+class JDeviceInfo
+{
+ public:
+ JDeviceInfo(JNIEnv *env) : m_env(env) {}
+ JDeviceInfo(const JDeviceInfo &) = delete;
+ JDeviceInfo &operator=(const JDeviceInfo &) = delete;
+ JDeviceInfo(const JDeviceInfo &&) = delete;
+ JDeviceInfo &operator=(const JDeviceInfo && ) = delete;
+ jobject toJava(DeviceInfo &deviceInfo);
+
+ private:
+ void setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
+ const std::string &value);
+
+ JNIEnv *m_env;
+};
+
+class JniDeviceInfoListener
+{
+ public:
+ JniDeviceInfoListener(JNIEnv *env, jobject listener)
+ {
+ m_listener = env->NewWeakGlobalRef(listener);
+ }
+
+ void onDeviceInfoReceived(DeviceInfo &deviceInfo);
+
+ private:
+ jweak m_listener;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_jni_utils.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
+{
+ jobject ex = env->NewObject(gSimulatorClassRefs.classSimulatorException,
+ gSimulatorClassRefs.classSimulatorExceptionCtor, errCode,
+ env->NewStringUTF(errMessage));
+ if (!ex)
+ {
+ return;
+ }
+ env->Throw((jthrowable)ex);
+}
+
+void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
+{
+ jobject ex = env->NewObject(gSimulatorClassRefs.classInvalidArgsException,
+ gSimulatorClassRefs.classInvalidArgsExceptionCtor, errCode,
+ env->NewStringUTF(errMessage));
+ if (!ex)
+ {
+ return;
+ }
+ env->Throw((jthrowable)ex);
+}
+
+void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
+{
+ jobject ex = env->NewObject(gSimulatorClassRefs.classNoSupportException,
+ gSimulatorClassRefs.classNoSupportExceptionCtor, errCode,
+ env->NewStringUTF(errMessage));
+ if (!ex)
+ {
+ return;
+ }
+ env->Throw((jthrowable)ex);
+}
+
+void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode, const char *errMessage)
+{
+ jobject ex = env->NewObject(gSimulatorClassRefs.classOperationInProgressException,
+ gSimulatorClassRefs.classOperationInProgressExceptionCtor, errCode,
+ env->NewStringUTF(errMessage));
+ if (!ex)
+ {
+ return;
+ }
+ env->Throw((jthrowable)ex);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_jni_util.h
+ *
+ * @brief This file contains the utility functions for conversions from java to CPP
+ * and viceversa
+ */
+
+#ifndef __SIMULATOR_JNI_UTILS_H_
+#define __SIMULATOR_JNI_UTILS_H_
+
+#include <jni.h>
+#include "simulator_error_codes.h"
+
+void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
+
+void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
+
+void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage);
+
+void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode,
+ const char *errMessage);
+
+#endif //__SIMULATOR_JNI_UTILS_H_
#include "simulator_manager.h"
#include "simulator_remote_resource_jni.h"
#include "simulator_resource_model_jni.h"
+#include "simulator_device_info_jni.h"
+#include "simulator_platform_info_jni.h"
+#include "simulator_resource_jni_util.h"
+#include "simulator_jni_utils.h"
SimulatorClassRefs gSimulatorClassRefs;
std::mutex gEnvMutex;
jobject simulatorResource = SimulatorRemoteResourceToJava(env,
reinterpret_cast<jlong>(jniSimulatorResource));
+ jfieldID fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mUri",
+ "Ljava/lang/String;");
+ jstring jUri = env->NewStringUTF(resource->getURI().c_str());
+ env->SetObjectField(simulatorResource, fieldID, jUri);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mConnType", "I");
+ jint jConnType = resource->getConnectivityType();
+ env->SetIntField(simulatorResource, fieldID, jConnType);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mHost",
+ "Ljava/lang/String;");
+ jstring jHost = env->NewStringUTF(resource->getHost().c_str());
+ env->SetObjectField(simulatorResource, fieldID, jHost);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mId",
+ "Ljava/lang/String;");
+ jstring jUid = env->NewStringUTF(resource->getID().c_str());
+ env->SetObjectField(simulatorResource, fieldID, jUid);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mResTypes",
+ "Ljava/util/LinkedList;");
+ std::vector<std::string> resourceTypes = resource->getResourceTypes();
+ jobject jResTypes = convertStringVectorToJavaList(env, resourceTypes);
+ env->SetObjectField(simulatorResource, fieldID, jResTypes);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mResInterfaces",
+ "Ljava/util/LinkedList;");
+ std::vector<std::string> interfaceTypes = resource->getResourceInterfaces();
+ jobject jResInterfaces = convertStringVectorToJavaList(env, interfaceTypes);
+ env->SetObjectField(simulatorResource, fieldID, jResInterfaces);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mIsObservable", "Z");
+ env->SetBooleanField(simulatorResource, fieldID, resource->isObservable());
+
env->CallVoidMethod(foundResourceListener, foundResourceMId, simulatorResource);
if ((env)->ExceptionCheck())
{
}
jmethodID foundModelChangeMId = env->GetMethodID(modelChangeCls, "onResourceModelChanged",
- "(Ljava/lang/String;Lorg/oic/simulator/serviceprovider/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!foundModelChangeMId)
{
releaseEnv();
return;
}
- JniSimulatorResourceModel *jniModel = new JniSimulatorResourceModel(resModel);
+ JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(resModel);
if (!jniModel)
{
releaseEnv();
return;
}
- jobject jModel = JniSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+ jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
jstring jUri = env->NewStringUTF(uri.c_str());
(JNIEnv *env, jclass object, jstring configPath, jobject listener)
{
if (!configPath)
- return NULL;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+ "Resource creation failed. Configuration file path is empty!");
+ return nullptr;
+ }
if (!listener)
- return NULL;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+ "Resource creation failed. Resource model change callback not set!");
+ return nullptr;
+ }
jweak jlistenerRef = env->NewWeakGlobalRef(listener);
SimulatorResourceServer::ResourceModelChangedCB callback = [jlistenerRef](const std::string & uri,
};
const char *configPathCStr = env->GetStringUTFChars(configPath, NULL);
- SimulatorResourceServerPtr resource = SimulatorManager::getInstance()->createResource(
- configPathCStr, callback);
- if (nullptr == resource)
+ SimulatorResourceServerSP resource = NULL;
+ try
{
- if (configPathCStr)
- env->ReleaseStringUTFChars(configPath, configPathCStr);
- return NULL;
+ resource = SimulatorManager::getInstance()->createResource(
+ configPathCStr, callback);
+ if (nullptr == resource)
+ {
+ if (configPathCStr)
+ env->ReleaseStringUTFChars(configPath, configPathCStr);
+ return NULL;
+ }
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return nullptr;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return nullptr;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return nullptr;
}
JniSimulatorResource *jniSimResource = new JniSimulatorResource(resource);
(JNIEnv *env, jclass object, jstring configPath, jint count, jobject listener)
{
if (!configPath)
- return NULL;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+ "Resource(s) creation failed. Configuration file path is empty!");
+ return nullptr;
+ }
if (!listener)
- return NULL;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+ "Resource(s) creation failed. Resource model change callback not set!");
+ return nullptr;
+ }
jweak jlistenerRef = env->NewWeakGlobalRef(listener);
SimulatorResourceServer::ResourceModelChangedCB callback = [jlistenerRef](const std::string & uri,
onResourceModelChange(jlistenerRef, uri, resModel);
};
-
const char *configPathCStr = env->GetStringUTFChars(configPath, NULL);
- std::vector<SimulatorResourceServerPtr> resources =
- SimulatorManager::getInstance()->createResource(configPathCStr, count, callback);
+ std::vector<SimulatorResourceServerSP> resources;
+ try
+ {
+ resources = SimulatorManager::getInstance()->createResource(configPathCStr, count, callback);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return nullptr;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return nullptr;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return nullptr;
+ }
// Construct the object array and send it java layer
jobjectArray resourceArray = env->NewObjectArray(resources.size(),
return resourceArray;
}
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getResources
-(JNIEnv *env, jclass object)
-{
- //TODO: Need to implement this method
- return nullptr;
-}
-
JNIEXPORT void JNICALL
Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
(JNIEnv *env, jclass object, jobject jResource)
{
if (!jResource)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+ "Deletion failed. No resource has been passed!");
return;
+ }
- SimulatorResourceServerPtr resource =
- JniSimulatorResource::getJniSimulatorResourcePtr(env, jResource);
+ SimulatorResourceServerSP resource =
+ JniSimulatorResource::getJniSimulatorResourceSP(env, jResource);
if (!resource)
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE,
+ "Deletion failed. Native resource not found!");
return;
+ }
- SimulatorManager::getInstance()->deleteResource(resource);
+ try
+ {
+ SimulatorManager::getInstance()->deleteResource(resource);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
}
JNIEXPORT void JNICALL
type = typeCStr;
}
- SimulatorManager::getInstance()->deleteResources(type);
+ try
+ {
+ SimulatorManager::getInstance()->deleteResources(type);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
+
if (typeCStr)
env->ReleaseStringUTFChars(resourceType, typeCStr);
}
-JNIEXPORT jint JNICALL
+JNIEXPORT void JNICALL
Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
-(JNIEnv *env, jobject object, jstring resourceType, jobject listener)
+(JNIEnv *env, jobject object, jobject listener)
{
- const char *typeCStr = NULL;
+ JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
+ resourceListener->setJavaFoundResourceListener(env, listener);
+ try
+ {
+ SimulatorManager::getInstance()->findResources(
+ std::bind(&JNIFoundResourceListener::onFoundResource,
+ resourceListener, std::placeholders::_1));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
+}
- if (resourceType)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResources
+(JNIEnv *env, jobject object, jstring jResourceType, jobject listener)
+{
+ const char *typeCStr = NULL;
+ std::string resourceType;
+ if (jResourceType)
{
- typeCStr = env->GetStringUTFChars(resourceType, NULL);
+ typeCStr = env->GetStringUTFChars(jResourceType, NULL);
+ resourceType = typeCStr;
}
JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
resourceListener->setJavaFoundResourceListener(env, listener);
- SimulatorResult result = SimulatorManager::getInstance()->findResource(typeCStr,
- std::bind(&JNIFoundResourceListener::onFoundResource, resourceListener, std::placeholders::_1));
+ try
+ {
+ SimulatorManager::getInstance()->findResources(resourceType,
+ std::bind(&JNIFoundResourceListener::onFoundResource,
+ resourceListener, std::placeholders::_1));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
if (typeCStr)
- env->ReleaseStringUTFChars(resourceType, typeCStr);
- return result;
+ env->ReleaseStringUTFChars(jResourceType, typeCStr);
}
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getFoundResources
-(JNIEnv *env, jobject object, jstring resourceType)
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
+(JNIEnv *env, jclass object, jobject logger)
{
- const char *typeCStr = NULL;
- if (resourceType)
+ static std::shared_ptr<ILogger> target(new JNILogger());
+ dynamic_cast<JNILogger *>(target.get())->setJavaLogger(env, logger);
+ SimulatorManager::getInstance()->setLogger(target);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo
+(JNIEnv *env, jobject interfaceObject, jstring deviceInfo)
+{
+ if (!deviceInfo)
{
- typeCStr = env->GetStringUTFChars(resourceType, NULL);
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid device info!");
+ return;
}
- std::vector<SimulatorRemoteResourcePtr> resourceList;
- resourceList = SimulatorManager::getInstance()->getFoundResources(typeCStr);
- if (resourceList.empty())
+ const char *deviceName = env->GetStringUTFChars(deviceInfo, NULL);
+
+ try
{
- if (typeCStr)
- env->ReleaseStringUTFChars(resourceType, typeCStr);
- return NULL;
+ SimulatorManager::getInstance()->setDeviceInfo(deviceName);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
}
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+
+ env->ReleaseStringUTFChars(deviceInfo, deviceName);
+}
- jobject vectorObj = env->NewObject(gSimulatorClassRefs.classVector,
- gSimulatorClassRefs.classVectorCtor);
- if (!vectorObj)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener)
+{
+ if (!jListener)
{
- if (typeCStr)
- env->ReleaseStringUTFChars(resourceType, typeCStr);
- return NULL;
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
}
- // Convert to java SimulatorRemoteResource object
- for (unsigned int i = 0; i < resourceList.size(); i++)
+ JniDeviceInfoListener *deviceInfoListener = new JniDeviceInfoListener(env, jListener);
+ DeviceInfoCallback callback = std::bind([deviceInfoListener](DeviceInfo & deviceInfo)
{
- JniSimulatorRemoteResource *jniSimulatorResource = new JniSimulatorRemoteResource(resourceList[i]);
- if (!jniSimulatorResource)
- {
- if (typeCStr)
- env->ReleaseStringUTFChars(resourceType, typeCStr);
- return NULL;
- }
+ deviceInfoListener->onDeviceInfoReceived(deviceInfo);
+ delete deviceInfoListener;
+ }, std::placeholders::_1);
- jobject resource = SimulatorRemoteResourceToJava(env,
- reinterpret_cast<jlong>(jniSimulatorResource));
- env->CallVoidMethod(vectorObj, gSimulatorClassRefs.classVectorAddElement, resource);
+ try
+ {
+ SimulatorManager::getInstance()->getDeviceInfo(callback);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
}
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+}
- if (typeCStr)
- env->ReleaseStringUTFChars(resourceType, typeCStr);
- return vectorObj;
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject jPlatformInfo)
+{
+ if (!jPlatformInfo)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid platform info!");
+ return;
+ }
+
+ JPlatformInfo jniPlatformInfo(env);
+ try
+ {
+ PlatformInfo platformInfo = jniPlatformInfo.toCPP(jPlatformInfo);
+ SimulatorManager::getInstance()->setPlatformInfo(platformInfo);
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
-(JNIEnv *env, jclass object, jobject logger)
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener)
{
- static std::shared_ptr<ILogger> target(new JNILogger());
- dynamic_cast<JNILogger *>(target.get())->setJavaLogger(env, logger);
- SimulatorManager::getInstance()->setLogger(target);
+ if (!jListener)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
+ }
+
+ JniPlatformInfoListener *platformInfoListener = new JniPlatformInfoListener(env, jListener);
+ PlatformInfoCallback callback = std::bind([platformInfoListener](PlatformInfo & platformInfo)
+ {
+ platformInfoListener->onPlatformInfoReceived(platformInfo);
+ delete platformInfoListener;
+ }, std::placeholders::_1);
+
+ try
+ {
+ SimulatorManager::getInstance()->getPlatformInfo(callback);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
}
static bool getClassRef(JNIEnv *env, const char *className, jclass &classRef)
}
// Get the class references
+ if (false == getClassRef(env, "java/lang/Object", gSimulatorClassRefs.classObject))
+ {
+ return JNI_ERR;
+ }
+
if (false == getClassRef(env, "java/lang/Integer", gSimulatorClassRefs.classInteger))
{
return JNI_ERR;
return JNI_ERR;
}
+ if (false == getClassRef(env, "java/util/LinkedList", gSimulatorClassRefs.classLinkedList))
+ {
+ return JNI_ERR;
+ }
+
if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceServer",
gSimulatorClassRefs.classSimulatorResource))
{
return JNI_ERR;
}
- if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceModel",
+ if (false == getClassRef(env, "org/oic/simulator/SimulatorResourceModel",
gSimulatorClassRefs.classSimulatorResourceModel))
{
return JNI_ERR;
}
- if (false == getClassRef(env, "org/oic/simulator/SimulatorResourceAttribute",
- gSimulatorClassRefs.classSimulatorResourceAttribute))
+ if (false == getClassRef(env, "org/oic/simulator/ResourceAttribute",
+ gSimulatorClassRefs.classResourceAttribute))
{
return JNI_ERR;
}
return JNI_ERR;
}
+ if (false == getClassRef(env, "org/oic/simulator/serviceprovider/ObserverInfo",
+ gSimulatorClassRefs.classObserverInfo))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/DeviceInfo",
+ gSimulatorClassRefs.classDeviceInfo))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/PlatformInfo",
+ gSimulatorClassRefs.classPlatformInfo))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/SimulatorException",
+ gSimulatorClassRefs.classSimulatorException))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/InvalidArgsException",
+ gSimulatorClassRefs.classInvalidArgsException))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/NoSupportException",
+ gSimulatorClassRefs.classNoSupportException))
+ {
+ return JNI_ERR;
+ }
+
+ if (false == getClassRef(env, "org/oic/simulator/OperationInProgressException",
+ gSimulatorClassRefs.classOperationInProgressException))
+ {
+ return JNI_ERR;
+ }
+
// Get the reference to methods
gSimulatorClassRefs.classIntegerCtor = env->GetMethodID(gSimulatorClassRefs.classInteger, "<init>",
"(I)V");
if (!gSimulatorClassRefs.classNextId)
return JNI_ERR;
+ gSimulatorClassRefs.classLinkedListCtor = env->GetMethodID(gSimulatorClassRefs.classLinkedList,
+ "<init>", "()V");
+ if (!gSimulatorClassRefs.classLinkedListCtor)
+ return JNI_ERR;
+
+ gSimulatorClassRefs.classLinkedListAddObject = env->GetMethodID(gSimulatorClassRefs.classLinkedList,
+ "add", "(Ljava/lang/Object;)Z");
+ if (!gSimulatorClassRefs.classLinkedListAddObject)
+ return JNI_ERR;
+
gSimulatorClassRefs.classSimulatorResourceCtor = env->GetMethodID(
gSimulatorClassRefs.classSimulatorResource, "<init>", "(J)V");
if (!gSimulatorClassRefs.classSimulatorResourceCtor)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceSetURI = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResource, "setURI", "(Ljava/lang/String;)V");
- if (!gSimulatorClassRefs.classSimulatorResourceSetURI)
+ gSimulatorClassRefs.classSimulatorResourceModelCtor = env->GetMethodID(
+ gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
+ if (!gSimulatorClassRefs.classSimulatorResourceModelCtor)
+ return JNI_ERR;
+
+ gSimulatorClassRefs.classResourceAttributeCtor = env->GetMethodID(
+ gSimulatorClassRefs.classResourceAttribute, "<init>", "()V");
+ if (!gSimulatorClassRefs.classResourceAttributeCtor)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceSetResourceType = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResource, "setResourceType", "(Ljava/lang/String;)V");
- if (!gSimulatorClassRefs.classSimulatorResourceSetResourceType)
+ gSimulatorClassRefs.classResourceAttributeSetRange = env->GetMethodID(
+ gSimulatorClassRefs.classResourceAttribute, "setRange", "(II)V");
+ if (!gSimulatorClassRefs.classResourceAttributeSetRange)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceSetInterfaceType = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResource, "setInterfaceType", "(Ljava/lang/String;)V");
- if (!gSimulatorClassRefs.classSimulatorResourceSetInterfaceType)
+ gSimulatorClassRefs.classSimulatorResourceModelId = env->GetMethodID(
+ gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
+ if (!gSimulatorClassRefs.classSimulatorResourceModelId)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceSetName = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResource, "setName", "(Ljava/lang/String;)V");
- if (!gSimulatorClassRefs.classSimulatorResourceSetName)
+ gSimulatorClassRefs.classObserverInfoCtor = env->GetMethodID(
+ gSimulatorClassRefs.classObserverInfo, "<init>",
+ "(ILjava/lang/String;I)V");
+ if (!gSimulatorClassRefs.classObserverInfoCtor)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceModelCtor = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
- if (!gSimulatorClassRefs.classSimulatorResourceModelCtor)
+ gSimulatorClassRefs.classSimulatorExceptionCtor = env->GetMethodID(
+ gSimulatorClassRefs.classSimulatorException, "<init>",
+ "(ILjava/lang/String;)V");
+ if (!gSimulatorClassRefs.classSimulatorExceptionCtor)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceAttributeCtor = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResourceAttribute, "<init>", "(J)V");
- if (!gSimulatorClassRefs.classSimulatorResourceAttributeCtor)
+ gSimulatorClassRefs.classInvalidArgsExceptionCtor = env->GetMethodID(
+ gSimulatorClassRefs.classInvalidArgsException, "<init>",
+ "(ILjava/lang/String;)V");
+ if (!gSimulatorClassRefs.classInvalidArgsExceptionCtor)
return JNI_ERR;
- gSimulatorClassRefs.classSimulatorResourceModelId = env->GetMethodID(
- gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
- if (!gSimulatorClassRefs.classSimulatorResourceModelId)
+ gSimulatorClassRefs.classNoSupportExceptionCtor = env->GetMethodID(
+ gSimulatorClassRefs.classNoSupportException, "<init>",
+ "(ILjava/lang/String;)V");
+ if (!gSimulatorClassRefs.classNoSupportExceptionCtor)
+ return JNI_ERR;
+
+ gSimulatorClassRefs.classOperationInProgressExceptionCtor = env->GetMethodID(
+ gSimulatorClassRefs.classOperationInProgressException, "<init>",
+ "(ILjava/lang/String;)V");
+ if (!gSimulatorClassRefs.classOperationInProgressExceptionCtor)
return JNI_ERR;
gvm = vm;
#ifdef __cplusplus
}
-#endif
\ No newline at end of file
+#endif
Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
(JNIEnv *env, jclass object, jstring jConfigPath, jint count, jobject jListener);
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_SimulatorManageNativeInterface_getResources
-(JNIEnv *env, jclass object);
-
JNIEXPORT void JNICALL
Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
(JNIEnv *env, jclass object, jobject jResource);
(JNIEnv *env, jclass object, jstring resourceType);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
-(JNIEnv *env, jclass object, jobject logger);
-
-JNIEXPORT jint JNICALL
Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
+(JNIEnv *env, jobject interfaceObject, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResources
(JNIEnv *env, jobject interfaceObject, jstring jResourceType, jobject jListener);
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getFoundResources
-(JNIEnv *env, jobject interfaceObject, jstring jResourceType);
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo
+(JNIEnv *env, jobject interfaceObject, jstring deviceInfo);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject platformInfo);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
+(JNIEnv *env, jclass object, jobject logger);
#ifdef __cplusplus
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_platform_info_jni.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+jobject JPlatformInfo::toJava(PlatformInfo &platformInfo)
+{
+ if (!m_env)
+ return nullptr;
+
+ jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classPlatformInfo, "<init>", "(V)V");
+ if (constr)
+ return nullptr;
+
+ jobject jPlatformInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classPlatformInfo, constr);
+ if (jPlatformInfo)
+ return nullptr;
+
+ setFieldValue(jPlatformInfo, "mPlatformId", platformInfo.getPlatformID());
+ setFieldValue(jPlatformInfo, "m_manufacturerName", platformInfo.getManufacturerName());
+ setFieldValue(jPlatformInfo, "m_manufacturerUrl", platformInfo.getManufacturerUrl());
+ setFieldValue(jPlatformInfo, "m_modelNumber", platformInfo.getModelNumber());
+ setFieldValue(jPlatformInfo, "m_dateOfManufacture", platformInfo.getDateOfManfacture());
+ setFieldValue(jPlatformInfo, "m_platformVersion", platformInfo.getPlatformVersion());
+ setFieldValue(jPlatformInfo, "m_operationSystemVersion", platformInfo.getOSVersion());
+ setFieldValue(jPlatformInfo, "m_hardwareVersion", platformInfo.getHardwareVersion());
+ setFieldValue(jPlatformInfo, "m_firmwareVersion", platformInfo.getFirmwareVersion());
+ setFieldValue(jPlatformInfo, "m_supportUrl", platformInfo.getSupportUrl());
+ setFieldValue(jPlatformInfo, "m_systemTime", platformInfo.getSystemTime());
+
+ return jPlatformInfo;
+}
+
+PlatformInfo JPlatformInfo::toCPP(jobject jPlatformInfo)
+{
+ PlatformInfo platformInfo;
+ if (!m_env || !jPlatformInfo)
+ return platformInfo;
+
+ platformInfo.setPlatformID(getFieldValue(jPlatformInfo, "mPlatformId"));
+ platformInfo.setManufacturerName(getFieldValue(jPlatformInfo, "m_manufacturerName"));
+ platformInfo.setManufacturerUrl(getFieldValue(jPlatformInfo, "m_manufacturerUrl"));
+ platformInfo.setModelNumber(getFieldValue(jPlatformInfo, "m_modelNumber"));
+ platformInfo.setDateOfManfacture(getFieldValue(jPlatformInfo, "m_dateOfManufacture"));
+ platformInfo.setPlatformVersion(getFieldValue(jPlatformInfo, "m_platformVersion"));
+ platformInfo.setOSVersion(getFieldValue(jPlatformInfo, "m_operationSystemVersion"));
+ platformInfo.setHardwareVersion(getFieldValue(jPlatformInfo, "m_hardwareVersion"));
+ platformInfo.setFirmwareVersion(getFieldValue(jPlatformInfo, "m_firmwareVersion"));
+ platformInfo.setSupportUrl(getFieldValue(jPlatformInfo, "m_supportUrl"));
+ platformInfo.setSystemTime(getFieldValue(jPlatformInfo, "m_systemTime"));
+
+ return std::move(platformInfo);
+}
+
+void JPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
+ const std::string &value)
+{
+ jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(),
+ "Ljava/lang/String;");
+ jstring valueStr = m_env->NewStringUTF(value.c_str());
+ m_env->SetObjectField(jPlatformInfo, fieldID, valueStr);
+}
+
+std::string JPlatformInfo::getFieldValue(jobject jPlatformInfo, const std::string &fieldName)
+{
+ jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(),
+ "Ljava/lang/String;");
+ jstring jvalue = (jstring) m_env->GetObjectField(jPlatformInfo, fieldID);
+ const char *valueCStr = m_env->GetStringUTFChars(jvalue, NULL);
+ if (valueCStr)
+ return std::string(valueCStr);
+ return std::string();
+}
+
+void JniPlatformInfoListener::onPlatformInfoReceived(PlatformInfo &platformInfo)
+{
+ // Get the environment
+ JNIEnv *env = getEnv();
+ if (!env)
+ return;
+
+ jobject listener = env->NewLocalRef(m_listener);
+ if (!listener)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jclass listenerCls = env->GetObjectClass(listener);
+ if (!listenerCls)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jmethodID listenerMId = env->GetMethodID(listenerCls, "onPlatformFound",
+ "(Lorg/oic/simulator/PlatformInfo;)V");
+ if (!listenerMId)
+ {
+ releaseEnv();
+ return;
+ }
+
+ // Convert CPP to Java DeviceInfo object
+ jobject jPlatformInfo = JPlatformInfo(env).toJava(platformInfo);
+ if (!jPlatformInfo)
+ {
+ releaseEnv();
+ return;
+ }
+
+ // Invoke java listener with DeviceInfo
+ env->CallVoidMethod(listener, listenerMId, jPlatformInfo);
+ if (env->ExceptionCheck())
+ {
+ releaseEnv();
+ return;
+ }
+
+ releaseEnv();
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_PLATFORM_INFO_JNI_H_
+#define SIMULATOR_PLATFORM_INFO_JNI_H_
+
+#include "simulator_platform_info.h"
+#include <jni.h>
+
+class JPlatformInfo
+{
+ public:
+ JPlatformInfo(JNIEnv *env) : m_env(env) {}
+ JPlatformInfo(const JPlatformInfo &) = delete;
+ JPlatformInfo &operator=(const JPlatformInfo &) = delete;
+ JPlatformInfo(const JPlatformInfo &&) = delete;
+ JPlatformInfo &operator=(const JPlatformInfo && ) = delete;
+ jobject toJava(PlatformInfo &platformInfo);
+ PlatformInfo toCPP(jobject jPlatformInfo);
+
+ private:
+ void setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
+ const std::string &value);
+ std::string getFieldValue(jobject jPlatformInfo, const std::string &fieldName);
+
+ JNIEnv *m_env;
+};
+
+class JniPlatformInfoListener
+{
+ public:
+ JniPlatformInfoListener(JNIEnv *env, jobject listener)
+ {
+ m_listener = env->NewWeakGlobalRef(listener);
+ }
+
+ void onPlatformInfoReceived(PlatformInfo &platformInfo);
+
+ private:
+ jweak m_listener;
+};
+
+#endif
#include "simulator_error_codes.h"
#include "simulator_resource_jni_util.h"
#include "simulator_resource_model_jni.h"
+#include "simulator_client_types.h"
+#include "simulator_exceptions.h"
+#include "simulator_jni_utils.h"
extern SimulatorClassRefs gSimulatorClassRefs;
-SimulatorRemoteResourcePtr JniSimulatorRemoteResource::getResourceHandle
+SimulatorRemoteResourceSP JniSimulatorRemoteResource::getResourceHandle
(JNIEnv *env, jobject object)
{
JniSimulatorRemoteResource *jniResource = GetHandle<JniSimulatorRemoteResource>(env, object);
m_listener = env->NewWeakGlobalRef(listener);
}
- void onObserveCallback(const int eCode,
- const SimulatorResourceModel &representation,
- const int sequenceNumber)
+ void onObserveCallback(const std::string &uId, const int errorCode,
+ SimulatorResourceModelSP representation,
+ const int seqNumber)
{
JNIEnv *env = getEnv();
if (nullptr == env)
return;
}
- if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
- && OC_STACK_RESOURCE_DELETED != eCode)
+ if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
+ && OC_STACK_RESOURCE_DELETED != errorCode)
{
jmethodID midL = env->GetMethodID(onObserveCls, "onObserveFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
}
else
{
- SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
- gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+ JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
+ if (!jniModel)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+
if (!jRepresentation)
{
releaseEnv();
}
jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted",
- "(Lorg/oic/simulator/SimulatorResourceModel;I)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
if (!midL)
{
releaseEnv();
return;
}
- env->CallVoidMethod(onObserveListener, midL, jRepresentation,
- static_cast<jint>(sequenceNumber));
+ jstring jUid = env->NewStringUTF(uId.c_str());
+
+ env->CallVoidMethod(onObserveListener, midL, jUid, jRepresentation,
+ static_cast<jint>(seqNumber));
if (env->ExceptionCheck())
{
releaseEnv();
m_listener = env->NewWeakGlobalRef(listener);
}
- void onGetCallback(const int eCode,
- const SimulatorResourceModel &representation)
+ void onGetCallback(const std::string &uId, int errorCode,
+ SimulatorResourceModelSP representation)
{
JNIEnv *env = getEnv();
if (nullptr == env)
return;
}
- if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
- && OC_STACK_RESOURCE_DELETED != eCode)
+ // TODO: Revisit is it required?
+ if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
+ && OC_STACK_RESOURCE_DELETED != errorCode)
{
jmethodID midL = env->GetMethodID(onGetCls, "onGetFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
}
else
{
- SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
- gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+ JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
+ if (!jniModel)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+
if (!jRepresentation)
{
releaseEnv();
}
jmethodID midL = env->GetMethodID(onGetCls, "onGetCompleted",
- "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
releaseEnv();
return;
}
- env->CallVoidMethod(onGetListener, midL, jRepresentation);
+ jstring jUid = env->NewStringUTF(uId.c_str());
+
+ env->CallVoidMethod(onGetListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
releaseEnv();
m_listener = env->NewWeakGlobalRef(listener);
}
- void onPutCallback(const int eCode,
- const SimulatorResourceModel &representation)
+ void onPutCallback(const std::string &uId, int errorCode,
+ SimulatorResourceModelSP representation)
{
JNIEnv *env = getEnv();
if (nullptr == env)
return;
}
- if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
- && OC_STACK_RESOURCE_DELETED != eCode)
+ // TODO: Revisit is it required?
+ if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
+ && OC_STACK_RESOURCE_DELETED != errorCode)
{
jmethodID midL = env->GetMethodID(onGetCls, "onPutFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
}
else
{
- SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
- gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+ JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
+ if (!jniModel)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+
if (!jRepresentation)
{
releaseEnv();
}
jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted",
- "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
releaseEnv();
return;
}
- env->CallVoidMethod(onPutListener, midL, jRepresentation);
+ jstring jUid = env->NewStringUTF(uId.c_str());
+
+ env->CallVoidMethod(onPutListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
releaseEnv();
m_listener = env->NewWeakGlobalRef(listener);
}
- void onPostCallback(const int eCode,
- const SimulatorResourceModel &representation)
+ void onPostCallback(const std::string &uId, int errorCode,
+ SimulatorResourceModelSP representation)
{
JNIEnv *env = getEnv();
if (nullptr == env)
return;
}
- if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
- && OC_STACK_RESOURCE_DELETED != eCode)
+ // TODO: Revisit is it required?
+ if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode
+ && OC_STACK_RESOURCE_DELETED != errorCode)
{
jmethodID midL = env->GetMethodID(onGetCls, "onPostFailed", "(Ljava/lang/Throwable;)V");
if (!midL)
}
else
{
- SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
- jlong handle = reinterpret_cast<jlong>(rep);
- jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
- gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+ JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation);
+ if (!jniModel)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+
if (!jRepresentation)
{
releaseEnv();
}
jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted",
- "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
releaseEnv();
return;
}
- env->CallVoidMethod(onPostListener, midL, jRepresentation);
+ jstring jUid = env->NewStringUTF(uId.c_str());
+
+ env->CallVoidMethod(onPostListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
releaseEnv();
};
+class JNIOnVerificationListener
+{
+ public:
+ void setJavaOnVerificationListener(JNIEnv *env, jobject listener)
+ {
+ m_listener = env->NewWeakGlobalRef(listener);
+ }
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_observe
+ void onVerificationCallback(const std::string &uId, int id, OperationState opState)
+ {
+ JNIEnv *env = getEnv();
+ if (nullptr == env)
+ return;
+
+ jobject onVerificationListener = env->NewLocalRef(m_listener);
+ if (!onVerificationListener)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jclass onVerificationCls = env->GetObjectClass(onVerificationListener);
+ if (!onVerificationCls)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jmethodID midL;
+
+ if (OP_START == opState)
+ {
+ midL = env->GetMethodID(onVerificationCls, "onVerificationStarted", "(Ljava/lang/String;I)V");
+ }
+ else if (OP_COMPLETE == opState)
+ {
+ midL = env->GetMethodID(onVerificationCls, "onVerificationCompleted", "(Ljava/lang/String;I)V");
+ }
+ else
+ {
+ midL = env->GetMethodID(onVerificationCls, "onVerificationAborted", "(Ljava/lang/String;I)V");
+ }
+
+ if (!midL)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jstring jUid = env->NewStringUTF(uId.c_str());
+
+ env->CallVoidMethod(onVerificationListener, midL, jUid, (jint)id);
+
+ if (env->ExceptionCheck())
+ {
+ releaseEnv();
+ }
+ }
+
+ private:
+ jweak m_listener;
+
+};
+
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_observe
(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
{
if (!jListener)
- return SIMULATOR_BAD_INPUT;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
+ }
- SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
- thiz);
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
if (nullptr == resource)
- return SIMULATOR_RESOURCE_NOT_FOUND;
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
+ }
std::map<std::string, std::string> queryParams;
if (jQueryParamsMap)
convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
- SimulatorRemoteResource::ObserveType type = SimulatorRemoteResource::OBSERVE;
+ ObserveType type = ObserveType::OBSERVE;
if (1 == observeType)
- type = SimulatorRemoteResource::OBSERVE_ALL;
+ type = ObserveType::OBSERVE_ALL;
JNIOnObserveListener *onObserveListener = new JNIOnObserveListener();
onObserveListener->setJavaOnObserveListener(env, jListener);
- return resource->observe(type, queryParams,
- std::bind(&JNIOnObserveListener::onObserveCallback,
- onObserveListener, std::placeholders::_1,
- std::placeholders::_2, std::placeholders::_3));
+ try
+ {
+ resource->observe(type,
+ std::bind(&JNIOnObserveListener::onObserveCallback,
+ onObserveListener, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3,
+ std::placeholders::_4));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
}
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_cancelObserve
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
(JNIEnv *env, jobject thiz)
{
- SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
- thiz);
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
if (nullptr == resource)
- return SIMULATOR_RESOURCE_NOT_FOUND;
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
+ }
- return resource->cancelObserve();
+ try
+ {
+ resource->cancelObserve();
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
}
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_get
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jQueryParamsMap, jobject jListener)
{
if (!jListener)
- return SIMULATOR_BAD_INPUT;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
+ }
- SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
- thiz);
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
if (nullptr == resource)
- return SIMULATOR_RESOURCE_NOT_FOUND;
-
- // Resource type
- const char *typeCStr = NULL;
- std::string resourceType;
- if (jResourceType)
{
- typeCStr = env->GetStringUTFChars(jResourceType, NULL);
- resourceType = typeCStr;
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
}
// Interface type
JNIOnGetListener *onGetListener = new JNIOnGetListener();
onGetListener->setJavaOnGetListener(env, jListener);
- SimulatorResult result = resource->get(resourceType, interfaceType,
- queryParams,
- std::bind(&JNIOnGetListener::onGetCallback,
- onGetListener, std::placeholders::_1,
- std::placeholders::_2));
-
- if (typeCStr)
- env->ReleaseStringUTFChars(jResourceType, typeCStr);
+ try
+ {
+ resource->get(interfaceType,
+ queryParams,
+ std::bind(&JNIOnGetListener::onGetCallback,
+ onGetListener, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.code(), e.what());
+ return;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
if (interfaceCStr)
env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
-
- return result;
}
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_put
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
{
if (!jListener)
- return SIMULATOR_BAD_INPUT;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
+ }
- SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
- thiz);
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
if (nullptr == resource)
- return SIMULATOR_RESOURCE_NOT_FOUND;
-
- // Resource type
- const char *typeCStr = NULL;
- std::string resourceType;
- if (jResourceType)
{
- typeCStr = env->GetStringUTFChars(jResourceType, NULL);
- resourceType = typeCStr;
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
}
// Interface type
if (jQueryParamsMap)
convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
- SimulatorResourceModel resourceModel;
- JniSimulatorResourceModel::getResourceModel(env, jRepresentation, resourceModel);
+ SimulatorResourceModelSP resourceModel =
+ JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
// Create listener
JNIOnPutListener *onPutListener = new JNIOnPutListener();
onPutListener->setJavaOnPutListener(env, jListener);
- SimulatorResult result = resource->put(resourceType, interfaceType,
- resourceModel, queryParams,
- std::bind(&JNIOnPutListener::onPutCallback,
- onPutListener, std::placeholders::_1,
- std::placeholders::_2));
-
- if (typeCStr)
- env->ReleaseStringUTFChars(jResourceType, typeCStr);
+ try
+ {
+ resource->put(interfaceType,
+ queryParams,
+ resourceModel,
+ std::bind(&JNIOnPutListener::onPutCallback,
+ onPutListener, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.code(), e.what());
+ return;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
if (interfaceCStr)
env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
-
- return result;
}
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_post
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
{
if (!jListener)
- return SIMULATOR_BAD_INPUT;
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
+ }
- SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
- thiz);
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
if (nullptr == resource)
- return SIMULATOR_RESOURCE_NOT_FOUND;
-
- // Resource type
- const char *typeCStr = NULL;
- std::string resourceType;
- if (jResourceType)
{
- typeCStr = env->GetStringUTFChars(jResourceType, NULL);
- resourceType = typeCStr;
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
}
// Interface type
if (jQueryParamsMap)
convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
- SimulatorResourceModel resourceModel;
- JniSimulatorResourceModel::getResourceModel(env, jRepresentation, resourceModel);
+ SimulatorResourceModelSP resourceModel =
+ JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
// Create listener
JNIOnPostListener *onPostListener = new JNIOnPostListener();
onPostListener->setJavaOnPostListener(env, jListener);
- SimulatorResult result = resource->post(resourceType, interfaceType,
- resourceModel, queryParams,
- std::bind(&JNIOnPostListener::onPostCallback,
- onPostListener, std::placeholders::_1,
- std::placeholders::_2));
-
- if (typeCStr)
- env->ReleaseStringUTFChars(jResourceType, typeCStr);
+ try
+ {
+ resource->post(interfaceType,
+ queryParams,
+ resourceModel,
+ std::bind(&JNIOnPostListener::onPostCallback,
+ onPostListener, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.code(), e.what());
+ return;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
if (interfaceCStr)
env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+(JNIEnv *env, jobject thiz, jstring jConfigPath)
+{
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
+ if (nullptr == resource)
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
+ }
+
+ // Interface type
+ const char *configCStr = NULL;
+ std::string configPath;
+ if (jConfigPath)
+ {
+ configCStr = env->GetStringUTFChars(jConfigPath, NULL);
+ configPath = configCStr;
+ }
+
+ try
+ {
+ resource->configure(configPath);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
+
+ if (configCStr)
+ env->ReleaseStringUTFChars(jConfigPath, configCStr);
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification
+(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener)
+{
+ if (!jListener)
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return -1;
+ }
+
+
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
+ if (nullptr == resource)
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return -1;
+ }
- return result;
+ // Convert RequestType
+ RequestType reqType;
+
+ switch (jReqType)
+ {
+ case 0:
+ reqType = RequestType::RQ_TYPE_GET;
+ break;
+
+ case 1:
+ reqType = RequestType::RQ_TYPE_PUT;
+ break;
+
+ case 2:
+ reqType = RequestType::RQ_TYPE_POST;
+ break;
+
+ case 3:
+ reqType = RequestType::RQ_TYPE_DELETE;
+ break;
+
+ default:
+ return -1;
+ }
+
+ // Create listener
+ JNIOnVerificationListener *onVerificationListener = new JNIOnVerificationListener();
+ onVerificationListener->setJavaOnVerificationListener(env, jListener);
+
+ int automationId = -1;
+
+ try
+ {
+ automationId = resource->startVerification(reqType,
+ std::bind(&JNIOnVerificationListener::onVerificationCallback,
+ onVerificationListener, std::placeholders::_1,
+ std::placeholders::_2, std::placeholders::_3));
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.code(), e.what());
+ }
+ catch (OperationInProgressException &e)
+ {
+ throwOperationInProgressException(env, e.code(), e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
+
+ return automationId;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
+(JNIEnv *env, jobject thiz, jint jId)
+{
+ SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+ thiz);
+ if (nullptr == resource)
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ return;
+ }
+
+ try
+ {
+ resource->stopVerification((int)jId);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
}
class JniSimulatorRemoteResource
{
public:
- JniSimulatorRemoteResource(SimulatorRemoteResourcePtr &resource)
- : m_resource(resource) {};
- static SimulatorRemoteResourcePtr getResourceHandle(JNIEnv *env, jobject object);
+ JniSimulatorRemoteResource(SimulatorRemoteResourceSP &resource)
+ : m_resource(resource) {};
+ static SimulatorRemoteResourceSP getResourceHandle(JNIEnv *env, jobject object);
private:
- SimulatorRemoteResourcePtr m_resource;
+ SimulatorRemoteResourceSP m_resource;
};
#ifdef __cplusplus
extern "C" {
#endif
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_observe
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_observe
(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener);
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_cancelObserve
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
(JNIEnv *env, jobject thiz);
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_get
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jQueryParamsMap, jobject jListener);
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_put
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorRemoteResource_post
-(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+(JNIEnv *env, jobject thiz, jstring jConfigPath);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification
+(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
+(JNIEnv *env, jobject thiz, jint jId);
#ifdef __cplusplus
}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "simulator_resource_attributes_jni.h"
-#include "simulator_resource_model.h"
-#include "simulator_common_jni.h"
-#include "simulator_error_codes.h"
-
-extern SimulatorClassRefs gSimulatorClassRefs;
-
-jobject JniSimulatorResourceAttribute::toJava(JNIEnv *env, jlong resource)
-{
- jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceAttribute,
- gSimulatorClassRefs.classSimulatorResourceAttributeCtor, resource);
- if (NULL == resourceObj)
- {
- return NULL;
- }
-
- return resourceObj;
-}
-
-class attribute_value_visitor : public boost::static_visitor<jobject>
-{
- public:
- attribute_value_visitor(JNIEnv *env) : m_Env(env) {}
-
- jobject operator ()(const int &value) const
- {
- jobject result = m_Env->NewObject(gSimulatorClassRefs.classInteger,
- gSimulatorClassRefs.classIntegerCtor, value);
- return result;
- }
-
- jobject operator ()(const double &value) const
- {
- jobject result = m_Env->NewObject(gSimulatorClassRefs.classDouble,
- gSimulatorClassRefs.classDoubleCtor, value);
- return result;
- }
-
- jobject operator ()(const std::string &value) const
- {
- jstring str = m_Env->NewStringUTF(value.c_str());
- return static_cast<jobject>(str);
- }
-
- private:
- JNIEnv *m_Env;
-};
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_create
-(JNIEnv *env, jobject object, jstring attrName)
-{
- if (!attrName)
- {
- std::cout << "SimulatorResourceAttribute_create: AttributeName is Empty";
- return;
- }
-
- const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
- if (!attrNamePtr)
- return;
-
- std::string attrNameStr(attrNamePtr);
- SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute(attrNameStr);
- SetHandle<SimulatorResourceModel::Attribute>(env, object, attribute);
- if (env->ExceptionCheck())
- {
- delete attribute;
- }
-
- env->ReleaseStringUTFChars(attrName, attrNamePtr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_dispose
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- delete attribute;
-}
-
-JNIEXPORT int JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesSize
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- if (env->ExceptionCheck() || !attribute)
- {
- return SIMULATOR_ERROR;
- }
-
- return attribute->getAllowedValuesSize();
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_valueToString
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- if (env->ExceptionCheck() || !attribute)
- {
- return NULL;
- }
-
- std::string str = attribute->valueToString();
- return env->NewStringUTF(str.c_str());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesToString
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- if (env->ExceptionCheck() || !attribute)
- {
- return NULL;
- }
-
- std::string str = attribute->allowedValuesToString();
- return env->NewStringUTF(str.c_str());
-}
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_getName
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- if (env->ExceptionCheck() || !attribute)
- {
- return NULL;
- }
-
- std::string str = attribute->getName();
- return env->NewStringUTF(str.c_str());
-}
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_getValue
-(JNIEnv *env, jobject object)
-{
- SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
- object);
- if (env->ExceptionCheck() || !attribute)
- {
- return NULL;
- }
-
- return boost::apply_visitor(attribute_value_visitor(env), attribute->getValue());
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
-#define SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
-
-#include <jni.h>
-#include "simulator_resource_model.h"
-
-class JniSimulatorResourceAttribute
-{
- public:
- static jobject toJava(JNIEnv *env, jlong resource);
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_create
-(JNIEnv *, jobject, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_dispose
-(JNIEnv *, jobject);
-
-JNIEXPORT int JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesSize
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_valueToString
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesToString
-(JNIEnv *, jobject);
-
-JNIEXPORT jstring JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_getName
-(JNIEnv *, jobject);
-
-JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_SimulatorResourceAttribute_getValue
-(JNIEnv *, jobject);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
if (!jValue) return;
queryParams.insert(std::make_pair(env->GetStringUTFChars(jKey, NULL),
- env->GetStringUTFChars(jValue, NULL)));
+ env->GetStringUTFChars(jValue, NULL)));
if (env->ExceptionCheck()) return;
env->DeleteLocalRef(jEntry);
}
}
+jobject convertHashMapToJavaMap(JNIEnv *env,
+ const std::map<std::string, uint8_t> &observersList)
+{
+ if (observersList.empty())
+ {
+ std::cout << "observersList Map is empty";
+ return NULL;
+ }
+
+ jobject jObserverListMap = env->NewObject(gSimulatorClassRefs.classHashMap,
+ gSimulatorClassRefs.classHashMapCtor);
+
+ for (auto it = observersList.begin(); it != observersList.end(); ++it)
+ {
+ jstring key = (*env).NewStringUTF( (*it).first.c_str() );
+ jint value = (*it).second;
+ env->CallObjectMethod(jObserverListMap, gSimulatorClassRefs.classHashMapPut, key, value);
+ }
+
+ return jObserverListMap;
+}
+
+jobject convertStringVectorToJavaList(JNIEnv *env, std::vector<std::string> &vector)
+{
+ jobject jList = env->NewObject(gSimulatorClassRefs.classLinkedList,
+ gSimulatorClassRefs.classLinkedListCtor);
+ if (!jList) return nullptr;
+ for (size_t i = 0; i < vector.size(); ++i)
+ {
+ jstring jStr = env->NewStringUTF(vector[i].c_str());
+ if (!jStr) return nullptr;
+ env->CallBooleanMethod(jList, gSimulatorClassRefs.classLinkedListAddObject, jStr);
+ if (env->ExceptionCheck()) return nullptr;
+ env->DeleteLocalRef(jStr);
+ }
+ return jList;
+}
+
+
std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString);
void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,
- std::map<std::string, std::string> &map);
+ std::map<std::string, std::string> &map);
+
+jobject convertHashMapToJavaMap(JNIEnv *env,
+ const std::map<std::string, uint8_t> &observersList);
+
+jobject convertStringVectorToJavaList(JNIEnv *env, std::vector<std::string> &vector);
#endif //__SIMULATOR_RESOURCE_JNI_UTIL_H_
#include "simulator_resource_model_jni.h"
#include "simulator_common_jni.h"
-#include "simulator_resource_attributes_jni.h"
+#include "resource_attributes_jni.h"
#include "simulator_error_codes.h"
using namespace std;
extern SimulatorClassRefs gSimulatorClassRefs;
-JniSimulatorResourceModel::JniSimulatorResourceModel(SimulatorResourceModel resourceModel)
- : m_resourceModel(resourceModel)
+JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModel resModel)
+ : m_resourceModel(resModel)
{}
-bool JniSimulatorResourceModel::getResourceModel(JNIEnv *env, jobject thiz,
- SimulatorResourceModel &resourceModel)
+JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModelSP resModel)
+ : m_resModelPtr(resModel)
+{}
+
+bool JSimulatorResourceModel::getResourceModel(JNIEnv *env, jobject thiz,
+ SimulatorResourceModel &resModel)
{
- JniSimulatorResourceModel *resource = GetHandle<JniSimulatorResourceModel>(env, thiz);
+ JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
if (env->ExceptionCheck())
{
- cout << "Exception while converting the nativeHandle to JniSimulatorResourceModel" << endl;
+ cout << "Exception while converting the nativeHandle to JSimulatorResourceModel" << endl;
return false;
}
- resourceModel = resource->m_resourceModel;
+
+ if (nullptr != resource->m_resModelPtr)
+ resModel = *(resource->m_resModelPtr.get());
+ else
+ resModel = resource->m_resourceModel;
return true;
}
-jobject JniSimulatorResourceModel::toJava(JNIEnv *env, jlong resource)
+SimulatorResourceModelSP JSimulatorResourceModel::getResourceModelPtr(JNIEnv *env, jobject thiz)
+{
+ JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
+ if (env->ExceptionCheck())
+ {
+ return nullptr;
+ }
+
+ if (nullptr != resource->m_resModelPtr)
+ return resource->m_resModelPtr;
+ return nullptr;
+}
+
+jobject JSimulatorResourceModel::toJava(JNIEnv *env, jlong nativeHandle)
{
jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
- gSimulatorClassRefs.classSimulatorResourceModelCtor, resource);
+ gSimulatorClassRefs.classSimulatorResourceModelCtor, nativeHandle);
if (!resourceObj)
{
return NULL;
return resourceObj;
}
+void JSimulatorResourceModel::toJava(JNIEnv *env, jobject thiz, jlong nativeHandle)
+{
+ if (env && thiz && nativeHandle)
+ {
+ env->SetLongField(thiz, GetHandleField(env, thiz), nativeHandle);
+ }
+}
+
static jobject createHashMap(JNIEnv *env)
{
jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap,
env->CallObjectMethod(mapobj, gSimulatorClassRefs.classHashMapPut, key, value);
}
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_create
+(JNIEnv *env, jobject thiz)
+{
+ SimulatorResourceModelSP resModel = std::make_shared<SimulatorResourceModel>();
+ JSimulatorResourceModel *jresModel = new JSimulatorResourceModel(resModel);
+ JSimulatorResourceModel::toJava(env, thiz, reinterpret_cast<jlong>(jresModel));
+}
+
JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_size
+Java_org_oic_simulator_SimulatorResourceModel_size
(JNIEnv *env, jobject thiz)
{
SimulatorResourceModel resourceModel;
- bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+ bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
if (!result)
{
return SIMULATOR_ERROR;
}
JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttributes
+Java_org_oic_simulator_SimulatorResourceModel_getAttributes
(JNIEnv *env, jobject thiz)
{
SimulatorResourceModel resourceModel;
- bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+ bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
if (!result)
{
return NULL;
for (auto & attributeEntry : attributesMap)
{
+ SimulatorResourceModel::Attribute attribute(attributeEntry.second);
- // Create JniSimulatorResourceAttribute object and put the attribute.second into it
- SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute(
- attributeEntry.second);
-
- // Create a java object for SimulatorResourceAttribute
- jobject jAttribute = JniSimulatorResourceAttribute::toJava(env, reinterpret_cast<jlong>(attribute));
+ // Create a object of ResourceAttribute java class
+ JResourceAttributeConverter converter(attribute);
+ jobject jAttribute = converter.toJava(env);
// Add an entry with attribute.first and javaSimualatorResourceAttribute to the HashMap
jstring jAttrName = env->NewStringUTF((attributeEntry.first).c_str());
addEntryToHashMap(env, jHashMap, static_cast<jobject>(jAttrName), jAttribute);
env->DeleteLocalRef(jAttrName);
}
+
return jHashMap;
}
JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttribute
+Java_org_oic_simulator_SimulatorResourceModel_getAttribute
(JNIEnv *env, jobject thiz, jstring jAttrName)
{
if (!jAttrName)
{
- std::cout << "getAttribute: AttributeName is Empty";
return NULL;
}
const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
if (!attrName)
{
- std::cout << "getAttribute: Failed to convert jstring to char string!";
return NULL;
}
SimulatorResourceModel resourceModel;
- bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+ bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
if (!result)
{
- std::cout << "getAttribute: getResourceModel failed!";
env->ReleaseStringUTFChars(jAttrName, attrName);
return NULL;
}
- SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute();
- bool found = resourceModel.getAttribute(attrName, *attribute);
+ SimulatorResourceModel::Attribute attribute;
+ bool found = resourceModel.getAttribute(attrName, attribute);
if (!found)
{
- std::cout << "getAttribute: Attribute not found in ResourceModel!";
env->ReleaseStringUTFChars(jAttrName, attrName);
- delete attribute;
return NULL;
}
env->ReleaseStringUTFChars(jAttrName, attrName);
- // Create a java object for SimulatorResourceAttribute
- jobject jsimulatorResourceAttribute = JniSimulatorResourceAttribute::toJava(env,
- reinterpret_cast<jlong>(attribute));
- return jsimulatorResourceAttribute;
+ // Create a object of ResourceAttribute java class
+ JResourceAttributeConverter converter(attribute);
+ return converter.toJava(env);
}
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAllowedValues
-(JNIEnv *env, jobject thiz, jstring jAttrName)
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
+(JNIEnv *env, jobject thiz, jstring jname, jint jvalue)
{
- if (!jAttrName)
+ SimulatorResourceModelSP resModelPtr;
+ resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+ if (!resModelPtr)
{
- std::cout << "getAllowedValues: AttributeName is Empty";
- return NULL;
+ return;
}
- const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
- if (!attrName)
+ const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+ if (!nameCstr)
{
- std::cout << "getAllowedValues: Failed to convert jstring to char string!";
- env->ReleaseStringUTFChars(jAttrName, attrName);
- return NULL;
+ return;
}
- SimulatorResourceModel resourceModel;
- bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
- if (!result)
+ std::string attrName(nameCstr);
+ int value = static_cast<int>(jvalue);
+ resModelPtr->addAttribute(attrName, value);
+
+ // Release created c string
+ env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
+(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue)
+{
+ SimulatorResourceModelSP resModelPtr;
+ resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+ if (!resModelPtr)
{
- std::cout << "getAllowedValues: getResourceModel failed!";
- env->ReleaseStringUTFChars(jAttrName, attrName);
- return NULL;
+ return;
}
- SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute();
- bool found = resourceModel.getAttribute(attrName, *attribute);
- if (!found)
+ const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+ if (!nameCstr)
{
- std::cout << "getAllowedValues: Attribute not found in ResourceModel!";
- env->ReleaseStringUTFChars(jAttrName, attrName);
- delete attribute;
- return NULL;
+ return;
}
- env->ReleaseStringUTFChars(jAttrName, attrName);
+ std::string attrName(nameCstr);
+ double value = static_cast<double>(jvalue);
+ resModelPtr->addAttribute(attrName, value);
+
+ // Release created c string
+ env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
+(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue)
+{
+ SimulatorResourceModelSP resModelPtr;
+ resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+ if (!resModelPtr)
+ {
+ return;
+ }
+
+ const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+ if (!nameCstr)
+ {
+ return;
+ }
- std::vector<std::string> values = attribute->allowedValuesToVectorString();
+ std::string attrName(nameCstr);
+ bool value = static_cast<bool>(jvalue);
+ resModelPtr->addAttribute(attrName, value);
- int size = attribute->getAllowedValuesSize();
+ // Release created c string
+ env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
+(JNIEnv *env, jobject thiz, jstring jname, jstring jvalue)
+{
+ SimulatorResourceModelSP resModelPtr;
+ resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+ if (!resModelPtr)
+ {
+ return;
+ }
- // Create a jObjectArray for AllowedValues vector.
- jobjectArray allowedValuesArr = env->NewObjectArray(size, env->FindClass("java/lang/String"),
- env->NewStringUTF(""));
+ const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+ if (!nameCstr)
+ {
+ return;
+ }
- int i = 0;
- for (std::vector<std::string>::iterator it = values.begin(); it != values.end(); ++it, i++)
+ const char *valueCstr = env->GetStringUTFChars(jvalue, NULL);
+ if (!valueCstr)
{
- env->SetObjectArrayElement(allowedValuesArr, i, env->NewStringUTF((*it).c_str()));
+ env->ReleaseStringUTFChars(jname, nameCstr);
+ return;
}
- return allowedValuesArr;
+
+ std::string attrName(nameCstr);
+ std::string value(valueCstr);
+ resModelPtr->addAttribute(attrName, value);
+
+ // Release created c string
+ env->ReleaseStringUTFChars(jname, nameCstr);
+ env->ReleaseStringUTFChars(jvalue, valueCstr);
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_dispose
+Java_org_oic_simulator_SimulatorResourceModel_dispose
(JNIEnv *env, jobject thiz)
{
- JniSimulatorResourceModel *resourceModel = GetHandle<JniSimulatorResourceModel>(env, thiz);
+ JSimulatorResourceModel *resourceModel = GetHandle<JSimulatorResourceModel>(env, thiz);
delete resourceModel;
}
#include <jni.h>
#include "simulator_resource_model.h"
-class JniSimulatorResourceModel
+class JSimulatorResourceModel
{
-
public:
- JniSimulatorResourceModel(SimulatorResourceModel);
+ JSimulatorResourceModel(SimulatorResourceModel resModel);
+ JSimulatorResourceModel(SimulatorResourceModelSP resModel);
+
+ static jobject toJava(JNIEnv *env, jlong nativeHandle);
+ static void toJava(JNIEnv *env, jobject thiz, jlong nativeHandle);
+ static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resModel);
+ static SimulatorResourceModelSP getResourceModelPtr(JNIEnv *env, jobject thiz);
- static jobject toJava(JNIEnv *, jlong);
- static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resourceModel);
private:
SimulatorResourceModel m_resourceModel;
+ SimulatorResourceModelSP m_resModelPtr;
};
extern "C" {
#endif
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_create
+(JNIEnv *, jobject);
+
JNIEXPORT jint JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_size
+Java_org_oic_simulator_SimulatorResourceModel_size
(JNIEnv *, jobject);
JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttributes
+Java_org_oic_simulator_SimulatorResourceModel_getAttributes
(JNIEnv *, jobject);
JNIEXPORT jobject JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttribute
+Java_org_oic_simulator_SimulatorResourceModel_getAttribute
(JNIEnv *, jobject, jstring);
-JNIEXPORT jobjectArray JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAllowedValues
-(JNIEnv *, jobject, jstring);
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
+(JNIEnv *, jobject, jstring, jint);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
+(JNIEnv *, jobject, jstring, jdouble);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
+(JNIEnv *, jobject, jstring, jboolean);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
+(JNIEnv *, jobject, jstring, jstring);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_dispose
+Java_org_oic_simulator_SimulatorResourceModel_dispose
(JNIEnv *, jobject);
#include "simulator_resource_jni_util.h"
#include "simulator_common_jni.h"
#include "simulator_resource_model_jni.h"
+#include "simulator_jni_utils.h"
+#include "simulator_logger.h"
+#include "simulator_jni_utils.h"
extern SimulatorClassRefs gSimulatorClassRefs;
-JniSimulatorResource::JniSimulatorResource(SimulatorResourceServerPtr &resource)
+JniSimulatorResource::JniSimulatorResource(SimulatorResourceServerSP &resource)
: m_sharedResource(resource) {}
-SimulatorResourceServerPtr JniSimulatorResource::getJniSimulatorResourcePtr(JNIEnv *env,
+SimulatorResourceServerSP JniSimulatorResource::getJniSimulatorResourceSP(JNIEnv *env,
jobject thiz)
{
JniSimulatorResource *resource = GetHandle<JniSimulatorResource>(env, thiz);
std::string name = m_sharedResource->getName();
std::string interfaceType = m_sharedResource->getInterfaceType();
- jstring jURI = env->NewStringUTF(uri.c_str());
- if (jURI)
- {
- env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetURI, jURI);
- env->DeleteLocalRef(jURI);
- }
-
- jstring jResourceType = env->NewStringUTF(resourceType.c_str());
- if (jResourceType)
- {
- env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetResourceType, jResourceType);
- env->DeleteLocalRef(jResourceType);
- }
+ jfieldID fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceURI",
+ "Ljava/lang/String;");
+ jstring jUri = env->NewStringUTF(uri.c_str());
+ env->SetObjectField(jobj, fieldID, jUri);
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceName",
+ "Ljava/lang/String;");
jstring jName = env->NewStringUTF(name.c_str());
- if (jName)
- {
- env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetName, jName);
- env->DeleteLocalRef(jName);
- }
+ env->SetObjectField(jobj, fieldID, jName);
+
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceType",
+ "Ljava/lang/String;");
+ jstring jResourceType = env->NewStringUTF(resourceType.c_str());
+ env->SetObjectField(jobj, fieldID, jResourceType);
+ fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "interfaceType",
+ "Ljava/lang/String;");
jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str());
- if (jInterfaceType)
- {
- env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetInterfaceType,
- jInterfaceType);
- env->DeleteLocalRef(jInterfaceType);
- }
+ env->SetObjectField(jobj, fieldID, jInterfaceType);
+
+ env->DeleteLocalRef(jUri);
+ env->DeleteLocalRef(jName);
+ env->DeleteLocalRef(jResourceType);
+ env->DeleteLocalRef(jInterfaceType);
}
void onAutomationComplete(jweak jlistenerRef, const std::string &uri,
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel
(JNIEnv *env, jobject object)
{
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (nullptr == resource.get())
{
- std::cout << "getModel: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return nullptr;
}
SimulatorResourceModel resModel = resource->getModel();
- JniSimulatorResourceModel *model = new JniSimulatorResourceModel(resModel);
- jobject jModel = JniSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(model));
+ JSimulatorResourceModel *model = new JSimulatorResourceModel(resModel);
+ jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(model));
return jModel;
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
-(JNIEnv *env, jobject object, jstring attrName, jint index)
-{
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
- {
- std::cout << "updateAttributeFromAllowedValues: Resource is NULL";
- return;
- }
-
- const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
- if (!attrNamePtr)
- {
- std::cout << "updateAttributeFromAllowedValues: Failed to convert jstring to char string!";
- return;
- }
-
- resource->updateAttributeFromAllowedValues(attrNamePtr, static_cast<int>(index));
- env->ReleaseStringUTFChars(attrName, attrNamePtr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
-(JNIEnv *env, jobject object, jstring attrName, jint min, jint max)
-{
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
- {
- std::cout << "setRange: Resource is NULL";
- return;
- }
-
- const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
- if (!attrNamePtr)
- {
- std::cout << "setRange: Failed to convert jstring to char string!";
- return;
- }
-
- resource->setRange(attrNamePtr, static_cast<int>(min), static_cast<int>(max));
- env->ReleaseStringUTFChars(attrName, attrNamePtr);
-}
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setInterfaceType
-(JNIEnv *env, jobject jobject, const std::string &interfaceType)
-{
- jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str());
- if (!jInterfaceType)
- {
- std::cout << "setInterfaceType: InterfaceType is NULL";
- return;
- }
-
- env->CallVoidMethod(jobject, gSimulatorClassRefs.classSimulatorResourceSetInterfaceType,
- jInterfaceType);
- env->DeleteLocalRef(jInterfaceType);
-}
-
-JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger
(JNIEnv *env, jobject jobject, jstring jKey, jint jValue)
{
if (!jKey)
{
- std::cout << "addAttributeInteger: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "addAttributeInteger: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->addAttribute(str, static_cast<int>(jValue));
+ SimulatorResourceModel::Attribute att;
+ att.setName(str);
+ att.setValue(static_cast<int>(jValue));
+ resource->addAttribute(att);
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "addAttributeDouble: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "addAttributeDouble: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->addAttribute(str, static_cast<double>(jValue));
+ SimulatorResourceModel::Attribute att;
+ att.setName(str);
+ att.setValue(static_cast<double>(jValue));
+ resource->addAttribute(att);
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "addAttributeBoolean: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "addAttributeBoolean: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->addAttribute(str, static_cast<bool>(jValue));
+ SimulatorResourceModel::Attribute att;
+ att.setName(str);
+ att.setValue(static_cast<bool>(jValue));
+ resource->addAttribute(att);
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString
(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
{
if (!jKey)
{
- std::cout << "addAttributeStringN: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "addAttributeStringN: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string key = env->GetStringUTFChars(jKey, NULL);
std::string value = env->GetStringUTFChars(jValue, NULL);
-
- resource->addAttribute(key, value);
+ SimulatorResourceModel::Attribute att;
+ att.setName(key);
+ att.setValue(value);
+ resource->addAttribute(att);
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "updateAttributeInteger: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "updateAttributeInteger: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->updateAttribute(str, static_cast<int>(jValue));
+ resource->updateAttributeValue(str, static_cast<int>(jValue));
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "updateAttributeDouble: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "updateAttributeDouble: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->updateAttribute(str, static_cast<double>(jValue));
+ resource->updateAttributeValue(str, static_cast<double>(jValue));
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "updateAttributeBoolean: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "updateAttributeBoolean: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->updateAttribute(str, static_cast<bool>(jValue));
+ resource->updateAttributeValue(str, static_cast<bool>(jValue));
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString
(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
{
if (!jKey)
{
- std::cout << "updateAttributeStringN: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "updateAttributeStringN: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
std::string key = env->GetStringUTFChars(jKey, NULL);
std::string value = env->GetStringUTFChars(jValue, NULL);
- resource->updateAttribute(key, value);
+ resource->updateAttributeValue(key, value);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
+(JNIEnv *env, jobject object, jstring attrName, jint index)
+{
+ if (!attrName || index < 0)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
+ return;
+ }
+
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (resource)
+ {
+ throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return;
+ }
+
+ const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL);
+ if (!attrNameCStr)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return;
+ }
+
+ resource->updateAttributeValue(attrNameCStr, static_cast<int>(index));
+ env->ReleaseStringUTFChars(attrName, attrNameCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
+(JNIEnv *env, jobject object, jstring attrName, jint min, jint max)
+{
+ if (!attrName)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
+ return;
+ }
+
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (resource)
+ {
+ throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return;
+ }
+
+ const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL);
+ if (!attrNameCStr)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return;
+ }
+
+ resource->setRange(attrNameCStr, static_cast<int>(min), static_cast<int>(max));
+ env->ReleaseStringUTFChars(attrName, attrNameCStr);
}
JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger
(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
{
- if (!jKey)
+ if (!jKey || jAllowedValues)
{
- std::cout << "setAllowedValuesInteger: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (resource)
{
- std::cout << "setAllowedValuesInteger: Resource is NULL";
+ throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
- std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->setAllowedValues(str, convertIntegerVector(env, jAllowedValues));
+ const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
+ if (!keyCStr)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return;
+ }
+
+ resource->setAllowedValues(keyCStr, convertIntegerVector(env, jAllowedValues));
+ env->ReleaseStringUTFChars(jKey, keyCStr);
}
JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble
(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
{
- if (!jKey)
+ if (!jKey || jAllowedValues)
{
- std::cout << "setAllowedValuesDouble: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (resource)
{
- std::cout << "setAllowedValuesDouble: Resource is NULL";
+ throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
- std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->setAllowedValues(str, convertDoubleVector(env, jAllowedValues));
+ const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
+ if (!keyCStr)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return;
+ }
+
+ resource->setAllowedValues(keyCStr, convertDoubleVector(env, jAllowedValues));
+ env->ReleaseStringUTFChars(jKey, keyCStr);
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString
(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
{
- if (!jKey)
+ if (!jKey || jAllowedValues)
{
- std::cout << "setAllowedValuesStringN: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (resource)
{
- std::cout << "setAllowedValuesStringN: Resource is NULL";
+ throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
- std::string str = env->GetStringUTFChars(jKey, NULL);
- resource->setAllowedValues(str, convertStringVector(env, jAllowedValues));
+ const char *keyCStr = env->GetStringUTFChars(jKey, NULL);
+ if (!keyCStr)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return;
+ }
+
+ resource->setAllowedValues(keyCStr, convertStringVector(env, jAllowedValues));
+ env->ReleaseStringUTFChars(jKey, keyCStr);
}
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
(JNIEnv *env, jobject object, jint automationType, jobject listener)
{
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
- if (nullptr == resource.get())
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (!resource)
{
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return -1;
}
if (!listener)
{
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+ "Start Resource Automation failed! Callback not set");
return -1;
}
type = AutomationType::RECURRENT;
}
- int automationId;
- if (SIMULATOR_SUCCESS != resource->startUpdateAutomation(type, callback,
- automationId))
- return -1;
+ int automationId = -1;
+ try
+ {
+ automationId = resource->startUpdateAutomation(type, callback);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
return automationId;
}
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
{
- std::cout << "starAttributeAutomation JNI" << std::endl;
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (nullptr == resource.get())
{
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return -1;
}
if (!attrName)
{
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return -1;
}
if (!listener)
{
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+ "Start Attribute Automation failed! Callback not set");
return -1;
}
}
int automationId = -1;
- resource->startUpdateAutomation(attrNamePtr, type, callback, automationId);
-
+ try
+ {
+ automationId = resource->startUpdateAutomation(attrNamePtr, type, callback);
+ }
+ catch (InvalidArgsException &e)
+ {
+ throwInvalidArgsException(env, e.code(), e.what());
+ return -1;
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ return -1;
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return -1;
+ }
env->ReleaseStringUTFChars(attrName, attrNamePtr);
return automationId;
}
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
(JNIEnv *env, jobject object, jint automationId)
{
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (nullptr == resource.get())
{
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
resource->stopUpdateAutomation(automationId);
+ SIM_LOG(ILogger::INFO, "Automation has been forcibly stopped.")
}
JNIEXPORT void JNICALL
{
if (!jKey)
{
- std::cout << "removeAttribute: AttributeName is Empty";
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
return;
}
- SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
- jobject);
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+ jobject);
if (nullptr == resource.get())
{
- std::cout << "removeAttribute: Resource is NULL";
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
return;
}
resource->removeAttribute(str);
}
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList
+(JNIEnv *env, jobject object)
+{
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (nullptr == resource.get())
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return nullptr;
+ }
+
+ std::vector<ObserverInfo> observersList;
+ observersList = resource->getObserversList();
+
+ // Construct the object array and send it java layer
+ jobjectArray jobserversArray = env->NewObjectArray(observersList.size(),
+ gSimulatorClassRefs.classObserverInfo, NULL);
+ if (jobserversArray)
+ {
+ for (size_t i = 0; i < observersList.size(); i++)
+ {
+ jstring jaddress = env->NewStringUTF(observersList[i].address.c_str());
+ jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo,
+ gSimulatorClassRefs.classObserverInfoCtor, observersList[i].id,
+ jaddress, observersList[i].port);
+
+ env->SetObjectArrayElement(jobserversArray, i, jobserver);
+ env->DeleteLocalRef(jaddress);
+ }
+ }
+
+ return jobserversArray;
+}
+
+void onObserverChange(jweak jlistenerRef, const std::string &uri,
+ ObservationStatus state, const ObserverInfo &observerInfo)
+{
+ JNIEnv *env = getEnv();
+ if (nullptr == env)
+ return;
+
+ jobject observerChangeListener = env->NewLocalRef(jlistenerRef);
+ if (!observerChangeListener)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jclass observerChangeCls = env->GetObjectClass(observerChangeListener);
+ if (!observerChangeCls)
+ {
+ releaseEnv();
+ return;
+ }
+
+ jmethodID observerChangeMId = env->GetMethodID(observerChangeCls, "onObserverChanged",
+ "(Ljava/lang/String;ILorg/oic/simulator/serviceprovider/ObserverInfo;)V");
+ if (!observerChangeMId)
+ {
+ releaseEnv();
+ return;
+ }
+
+ // Convert URI
+ jstring jUri = env->NewStringUTF(uri.c_str());
+
+ // Convert state
+ jint jstate = (state == ObservationStatus::OBSERVE_REGISTER) ? 0 : 1;
+
+ // Construct the java object of observerinfo
+ jstring jaddress = env->NewStringUTF(observerInfo.address.c_str());
+ jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo,
+ gSimulatorClassRefs.classObserverInfoCtor, observerInfo.id,
+ jaddress, observerInfo.port);
+
+ env->CallVoidMethod(observerChangeListener, observerChangeMId, jUri, jstate, jobserver);
+ env->DeleteLocalRef(jaddress);
+ if ((env)->ExceptionCheck())
+ {
+ releaseEnv();
+ return;
+ }
+
+ env->DeleteLocalRef(jUri);
+
+ releaseEnv();
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback
+(JNIEnv *env, jobject object, jobject jcallback)
+{
+ if (!jcallback)
+ return;
+
+ jweak jlistenerRef = env->NewWeakGlobalRef(jcallback);
+ SimulatorResourceServer::ObserverCB callback = [jlistenerRef](const std::string & uri,
+ ObservationStatus state, const ObserverInfo & observerInfo)
+ {
+ onObserverChange(jlistenerRef, uri, state, observerInfo);
+ };
+
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (nullptr == resource.get())
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return;
+ }
+
+ resource->setObserverCallback(callback);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver
+(JNIEnv *env, jobject object, jint jId)
+{
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (nullptr == resource.get())
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return;
+ }
+
+ try
+ {
+ resource->notify(jId);
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers
+(JNIEnv *env, jobject object)
+{
+ SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+ if (nullptr == resource.get())
+ {
+ throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ return;
+ }
+
+ try
+ {
+ resource->notifyAll();
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ }
+}
+
JNIEXPORT void JNICALL Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
(JNIEnv *env, jobject thiz)
{
class JniSimulatorResource
{
public:
- JniSimulatorResource(SimulatorResourceServerPtr &resource);
+ JniSimulatorResource(SimulatorResourceServerSP &resource);
static jobject toJava(JNIEnv *env, jlong resource);
void setResourceInfo(JNIEnv *env, jobject jobj);
- static SimulatorResourceServerPtr getJniSimulatorResourcePtr(JNIEnv *env, jobject thiz);
+ static SimulatorResourceServerSP getJniSimulatorResourceSP(JNIEnv *env, jobject thiz);
private:
- SimulatorResourceServerPtr m_sharedResource;
+ SimulatorResourceServerSP m_sharedResource;
};
(JNIEnv *, jobject);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
-(JNIEnv *, jobject, jstring, jint);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
-(JNIEnv *, jobject, jstring, jint, jint);
-
-JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger
(JNIEnv *, jobject, jstring, jint);
(JNIEnv *, jobject, jstring, jboolean);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString
(JNIEnv *, jobject, jstring, jstring);
JNIEXPORT void JNICALL
(JNIEnv *, jobject, jstring, jboolean);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString
(JNIEnv *, jobject, jstring, jstring);
JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
+(JNIEnv *, jobject, jstring, jint);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
+(JNIEnv *, jobject, jstring, jint, jint);
+
+JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger
(JNIEnv *, jobject, jstring, jobject);
(JNIEnv *, jobject, jstring, jobject);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesStringN
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString
(JNIEnv *, jobject, jstring, jobject);
JNIEXPORT jint JNICALL
(JNIEnv *, jobject, jstring);
JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback
+(JNIEnv *env, jobject object, jobject observer);
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList
+(JNIEnv *env, jobject object);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver
+(JNIEnv *env, jobject object, jint jId);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers
+(JNIEnv *env, jobject object);
+
+JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
(JNIEnv *, jobject);
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "attribute_generator.h"
+
+AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+{
+ m_name.assign(attribute.getName());
+ m_type = attribute.getValueType();
+
+ if (!attribute.getValueType())
+ attribute.getRange(m_min, m_max);
+ if (m_max > 0)
+ {
+ m_hasRange = true;
+ }
+
+ if (!m_type)
+ m_rangeIndex = m_min;
+
+ m_allowedValues = attribute.getAllowedValues();
+ if (0 != m_allowedValues.size())
+ {
+ m_hasAllowedValue = true;
+ }
+ m_nextAllowedValueIndex = 0;
+ m_prevAllowedValueIndex = m_allowedValues.size();
+}
+
+AttributeGenerator::~AttributeGenerator()
+{
+ m_rangeIndex = 0;
+ m_min = 0;
+ m_max = 0;
+ m_nextAllowedValueIndex = 0;
+ m_prevAllowedValueIndex = 0;
+ m_type = 0;
+}
+
+bool AttributeGenerator::hasNext()
+{
+ if (m_hasRange && m_rangeIndex <= m_max && !m_type)
+ {
+ return true;
+ }
+
+ if (m_hasAllowedValue && m_nextAllowedValueIndex < m_allowedValues.size())
+ {
+ return true;
+ }
+
+ return false;
+}
+
+AttributeSP AttributeGenerator::next()
+{
+ AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+
+ if (!attr)
+ return nullptr;
+
+ if (m_hasRange && !m_type)
+ {
+ attr->setName(m_name);
+ attr->setValue(m_rangeIndex++);
+ return attr;
+ }
+
+ if (m_hasAllowedValue)
+ {
+ switch (m_type)
+ {
+ case 1:
+ {
+ attr->setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+ }
+ break;
+
+ case 3:
+ {
+ attr->setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+ }
+ break;
+ }
+
+ return attr;
+ }
+}
+
+AttributeSP AttributeGenerator::previous()
+{
+ AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+
+ if (!attr)
+ return nullptr;
+
+ if (m_hasRange && !m_type)
+ {
+ attr->setValue(m_rangeIndex - 1);
+ return attr;
+ }
+
+ if (m_hasAllowedValue)
+ {
+ switch (m_type)
+ {
+ case 1:
+ {
+ attr->setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+ }
+ break;
+
+ case 3:
+ {
+ attr->setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+ }
+ break;
+ }
+
+ return attr;
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef ATTRIBUTE_GENERATOR_H_
+#define ATTRIBUTE_GENERATOR_H_
+
+#include <map>
+#include <vector>
+#include "simulator_resource_model.h"
+
+class AttributeGenerator
+{
+ public:
+ AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
+ ~AttributeGenerator();
+ bool hasNext();
+ AttributeSP next();
+ AttributeSP previous();
+
+ private:
+ std::string m_name;
+ int m_type;
+ int m_max;
+ int m_min;
+ int m_rangeIndex;
+ int m_nextAllowedValueIndex;
+ int m_prevAllowedValueIndex;
+ bool m_hasRange;
+ bool m_hasAllowedValue;
+ std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
+};
+
+#endif
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "auto_request_gen.h"
+
+AutoRequestGeneration::AutoRequestGeneration(RequestType type, int id,
+ RequestSenderSP &requestSender, ProgressStateCallback callback)
+ : m_type(type),
+ m_id(id),
+ m_requestSender(requestSender),
+ m_callback(callback),
+ m_requestsSent(false),
+ m_requestCnt(0),
+ m_responseCnt(0) {}
+
+void AutoRequestGeneration::start()
+{
+ startSending();
+}
+
+void AutoRequestGeneration::stop()
+{
+ stopSending();
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef AUTO_REQUEST_GEN_H_
+#define AUTO_REQUEST_GEN_H_
+
+#include "request_sender.h"
+
+class AutoRequestGeneration
+{
+ public:
+ typedef std::function<void (int, OperationState)> ProgressStateCallback;
+
+ AutoRequestGeneration(RequestType type, int id,
+ RequestSenderSP &requestSender, ProgressStateCallback callback);
+ RequestType type() const { return m_type;}
+ int id() const {return m_id;}
+ void start();
+ void stop();
+
+ protected:
+ virtual void startSending() = 0;
+ virtual void stopSending() = 0;
+
+ RequestType m_type;
+ int m_id;
+ RequestSenderSP m_requestSender;
+ ProgressStateCallback m_callback;
+ bool m_requestsSent;
+ int m_requestCnt;
+ int m_responseCnt;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "auto_request_gen_mngr.h"
+#include "get_request_generator.h"
+#include "put_request_generator.h"
+#include "post_request_generator.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "AUTO_REQ_GEN_MNGR"
+
+int AutoRequestGenMngr::startOnGET(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ AutoRequestGeneration::ProgressStateCallback callback)
+{
+ // Input validation
+ if (!requestSender)
+ {
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
+ }
+
+ if (!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!");
+ }
+
+ // Create request generation session
+ AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
+ &AutoRequestGenMngr::onProgressChange, this,
+ std::placeholders::_1, std::placeholders::_2, callback);
+
+ std::lock_guard<std::mutex> lock(m_lock);
+ std::shared_ptr<AutoRequestGeneration> requestGen(
+ new GETRequestGenerator(m_id, requestSender, queryParams, localCallback));
+ m_requestGenList[m_id] = requestGen;
+
+ try
+ {
+ requestGen->start();
+ }
+ catch (OperationInProgressException &e)
+ {
+ m_requestGenList.erase(m_requestGenList.find(m_id));
+ throw;
+ }
+
+ return m_id++;
+}
+
+int AutoRequestGenMngr::startOnPUT(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP resModel,
+ AutoRequestGeneration::ProgressStateCallback callback)
+{
+ // Input validation
+ if (!requestSender)
+ {
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
+ }
+
+ if (!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!");
+ }
+
+ // Create request generation session
+ AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
+ &AutoRequestGenMngr::onProgressChange, this,
+ std::placeholders::_1, std::placeholders::_2, callback);
+
+ // Create and make the entry in list
+ std::lock_guard<std::mutex> lock(m_lock);
+ std::shared_ptr<AutoRequestGeneration> requestGen(
+ new PUTRequestGenerator(m_id, requestSender, queryParams, resModel, localCallback));
+ m_requestGenList[m_id] = requestGen;
+
+ try
+ {
+ requestGen->start();
+ }
+ catch (OperationInProgressException &e)
+ {
+ m_requestGenList.erase(m_requestGenList.find(m_id));
+ throw;
+ }
+
+ return m_id++;
+}
+
+int AutoRequestGenMngr::startOnPOST(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP resModel,
+ AutoRequestGeneration::ProgressStateCallback callback)
+{
+ // Input validation
+ if (!requestSender)
+ {
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid request sender given!");
+ }
+
+ if (!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!");
+ }
+
+ // Create request generation session
+ AutoRequestGeneration::ProgressStateCallback localCallback = std::bind(
+ &AutoRequestGenMngr::onProgressChange, this,
+ std::placeholders::_1, std::placeholders::_2, callback);
+
+ // Create and make the entry in list
+ std::lock_guard<std::mutex> lock(m_lock);
+ std::shared_ptr<AutoRequestGeneration> requestGen(
+ new POSTRequestGenerator(m_id, requestSender, queryParams, resModel, localCallback));
+ m_requestGenList[m_id] = requestGen;
+
+ try
+ {
+ requestGen->start();
+ }
+ catch (OperationInProgressException &e)
+ {
+ m_requestGenList.erase(m_requestGenList.find(m_id));
+ throw;
+ }
+
+ return m_id++;
+}
+
+void AutoRequestGenMngr::stop(int id)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ if (m_requestGenList.end() != m_requestGenList.find(id))
+ {
+ m_requestGenList[id]->stop();
+ OC_LOG_V(INFO, TAG, "Auto request generation session stopped [%d]", id);
+ return;
+ }
+
+ OC_LOG_V(ERROR, TAG, "Invalid verification id : %d", id);
+}
+
+void AutoRequestGenMngr::onProgressChange(int sessionId, OperationState state,
+ AutoRequestGeneration::ProgressStateCallback clientCallback)
+{
+ if (!isValid(sessionId))
+ return;
+
+ // Remove the request generator from list if it is completed
+ if (state == OP_COMPLETE || state == OP_ABORT)
+ {
+ remove(sessionId);
+ }
+
+ // Delegate notification to app callback
+ clientCallback(sessionId, state);
+}
+
+bool AutoRequestGenMngr::isValid(int id)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ if (m_requestGenList.end() != m_requestGenList.find(id))
+ {
+ return true;
+ }
+
+ return false;
+}
+
+bool AutoRequestGenMngr::isInProgress(RequestType type)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ for (auto & session : m_requestGenList)
+ {
+ if ((session.second)->type() == type)
+ return true;
+ }
+
+ return false;
+}
+
+void AutoRequestGenMngr::remove(int id)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ if (m_requestGenList.end() != m_requestGenList.find(id))
+ {
+ m_requestGenList.erase(m_requestGenList.find(id));
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file auto_request_gen_mngr.h
+ *
+ * @brief This file provides class for managing auto request generation sessions.
+ *
+ */
+
+#ifndef AUTO_REQUEST_GEN_MNGR_H_
+#define AUTO_REQUEST_GEN_MNGR_H_
+
+#include "auto_request_gen.h"
+
+class AutoRequestGenMngr
+{
+ public:
+ AutoRequestGenMngr() : m_id(0) {};
+
+ int startOnGET(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ AutoRequestGeneration::ProgressStateCallback callback);
+
+ int startOnPUT(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP resModel,
+ AutoRequestGeneration::ProgressStateCallback callback);
+
+ int startOnPOST(RequestSenderSP requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP resModel,
+ AutoRequestGeneration::ProgressStateCallback callback);
+
+ void stop(int id);
+
+ private:
+ void onProgressChange(int sessionId, OperationState state,
+ AutoRequestGeneration::ProgressStateCallback clientCallback);
+ bool isValid(int id);
+ bool isInProgress(RequestType type);
+ void remove(int id);
+
+ std::mutex m_lock;
+ std::map<int, std::shared_ptr<AutoRequestGeneration>> m_requestGenList;
+ int m_id;
+};
+
+typedef std::shared_ptr<AutoRequestGenMngr> AutoRequestGenMngrSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "get_request_generator.h"
+#include "simulator_resource_model.h"
+#include "logger.h"
+
+#define TAG "GET_REQUEST_GEN"
+
+GETRequestGenerator::GETRequestGenerator(int id, RequestSenderSP &requestSender,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_status(false),
+ m_stopRequested(false) {}
+
+GETRequestGenerator::GETRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_queryParamGen(queryParams),
+ m_status(false),
+ m_stopRequested(false) {}
+
+void GETRequestGenerator::startSending()
+{
+ // Check if the operation is already in progress
+ std::lock_guard<std::mutex> lock(m_statusLock);
+ if (m_status)
+ {
+ OC_LOG(ERROR, TAG, "Operation already in progress !");
+ throw OperationInProgressException("Another GET request generation session is already in progress!");
+ }
+
+ // Create thread and start sending requests in dispatched thread
+ m_thread = std::make_shared<std::thread>(&GETRequestGenerator::SendAllRequests, this);
+ m_status = true;
+ m_thread->detach();
+}
+
+void GETRequestGenerator::stopSending()
+{
+ m_stopRequested = true;
+}
+
+void GETRequestGenerator::SendAllRequests()
+{
+ // Notify the progress status
+ OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ m_callback(m_id, OP_START);
+
+ do
+ {
+ if (!m_stopRequested)
+ {
+ // Get the next possible queryParameter
+ std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+ // 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();
+ }
+ }
+ }
+ while (m_queryParamGen.hasNext());
+
+ m_requestsSent = true;
+ completed();
+}
+
+void GETRequestGenerator::onResponseReceived(SimulatorResult result,
+ SimulatorResourceModelSP repModel)
+{
+ OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
+ m_responseCnt++;
+ completed();
+}
+
+void GETRequestGenerator::completed()
+{
+ if (m_requestCnt == m_responseCnt)
+ {
+ if (m_stopRequested)
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+ m_callback(m_id, OP_ABORT);
+ }
+ else
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+ m_callback(m_id, OP_COMPLETE);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef GET_REQUEST_GEN_H_
+#define GET_REQUEST_GEN_H_
+
+#include "auto_request_gen.h"
+#include "query_param_generator.h"
+
+class GETRequestGenerator : public AutoRequestGeneration
+{
+ public:
+ GETRequestGenerator(int id, RequestSenderSP &requestSender, ProgressStateCallback callback);
+
+ GETRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ ProgressStateCallback callback);
+
+ void startSending();
+ void stopSending();
+
+ private:
+ void SendAllRequests();
+ void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
+ void completed();
+
+ QPGenerator m_queryParamGen;
+ std::mutex m_statusLock;
+ bool m_status;
+ bool m_stopRequested;
+ std::shared_ptr<std::thread> m_thread;
+};
+
+typedef std::shared_ptr<GETRequestGenerator> GETRequestGeneratorSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "post_request_generator.h"
+#include "simulator_resource_model.h"
+#include "logger.h"
+
+#define TAG "POST_REQUEST_GEN"
+
+POSTRequestGenerator::POSTRequestGenerator(int id, RequestSenderSP &requestSender,
+ SimulatorResourceModelSP &representation,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_rep(representation),
+ m_status(false),
+ m_stopRequested(false) {}
+
+POSTRequestGenerator::POSTRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP &representation,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_queryParamGen(queryParams),
+ m_rep(representation),
+ m_status(false),
+ m_stopRequested(false) {}
+
+void POSTRequestGenerator::startSending()
+{
+ // Check the representation
+ if (!m_rep)
+ {
+ OC_LOG(ERROR, TAG, "Invalid Representation given!");
+ throw SimulatorException(SIMULATOR_ERROR, "Invalid representation detected!");
+ }
+
+ // Check if the operation is already in progress
+ std::lock_guard<std::mutex> lock(m_statusLock);
+ if (m_status)
+ {
+ OC_LOG(ERROR, TAG, "Operation already in progress !");
+ throw OperationInProgressException("Another POST request generation session is already in progress!");
+ }
+
+ // Create thread and start sending requests in dispatched thread
+ m_thread = std::make_shared<std::thread>(&POSTRequestGenerator::SendAllRequests, this);
+ m_status = true;
+ m_thread->detach();
+}
+
+void POSTRequestGenerator::stopSending()
+{
+ m_stopRequested = true;
+}
+
+void POSTRequestGenerator::SendAllRequests()
+{
+ // Notify the progress status
+ OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ m_callback(m_id, OP_START);
+
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_rep->getAttributes();
+ if (!attributes.size())
+ return;
+
+ std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
+ for (auto & attribute : attributes)
+ {
+ attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+ }
+
+ do
+ {
+ if (!m_stopRequested)
+ {
+ // Get the next possible queryParameter
+ std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+ for (auto & attributeGen : attributeGenList)
+ {
+ while (attributeGen->hasNext())
+ {
+ SimulatorResourceModelSP repModel = std::make_shared<SimulatorResourceModel>();
+ AttributeSP attr = attributeGen->next();
+ int type = attr->getValueType();
+
+ switch (type)
+ {
+ case 0:
+ {
+ int attributeValue = attr->getValue<int>();
+ std::string attributeName = attr->getName();
+ repModel->addAttribute(attributeName, attributeValue);
+ }
+ break;
+
+ case 3:
+ {
+ std::string attributeValue = attr->getValue<std::string>();
+ std::string attributeName = attr->getName();
+ repModel->addAttribute(attributeName, attributeValue);
+ }
+ break;
+ }
+
+ // Send the request
+ m_requestSender->sendRequest(queryParam, repModel,
+ std::bind(&POSTRequestGenerator::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2), true);
+
+ m_requestCnt++;
+ }
+ }
+ }
+ }
+ while (m_queryParamGen.hasNext());
+
+ m_requestsSent = true;
+ completed();
+}
+
+void POSTRequestGenerator::onResponseReceived(SimulatorResult result,
+ SimulatorResourceModelSP repModel)
+{
+ OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
+ m_responseCnt++;
+ completed();
+}
+
+void POSTRequestGenerator::completed()
+{
+ if (m_requestCnt == m_responseCnt)
+ {
+ if (m_stopRequested)
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+ m_callback(m_id, OP_ABORT);
+ }
+ else
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+ m_callback(m_id, OP_COMPLETE);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef POST_REQUEST_GEN_H_
+#define POST_REQUEST_GEN_H_
+
+#include "auto_request_gen.h"
+#include "query_param_generator.h"
+#include "attribute_generator.h"
+
+class POSTRequestGenerator : public AutoRequestGeneration
+{
+ public:
+ POSTRequestGenerator(int id, RequestSenderSP &requestSender,
+ SimulatorResourceModelSP &representation,
+ ProgressStateCallback callback);
+
+ POSTRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP &representation,
+ ProgressStateCallback callback);
+
+ void startSending();
+ void stopSending();
+
+ private:
+ void SendAllRequests();
+ void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
+ void completed();
+
+ QPGenerator m_queryParamGen;
+ SimulatorResourceModelSP m_rep;
+ std::mutex m_statusLock;
+ bool m_status;
+ bool m_stopRequested;
+ std::shared_ptr<std::thread> m_thread;
+};
+
+typedef std::shared_ptr<POSTRequestGenerator> POSTRequestGeneratorSP;
+
+#endif
+
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "put_request_generator.h"
+#include "simulator_resource_model.h"
+#include "logger.h"
+
+#define TAG "PUT_REQUEST_GEN"
+
+PUTRequestGenerator::PUTRequestGenerator(int id, RequestSenderSP &requestSender,
+ SimulatorResourceModelSP &representation,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_rep(representation),
+ m_status(false),
+ m_stopRequested(false) {}
+
+PUTRequestGenerator::PUTRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP &representation,
+ AutoRequestGeneration::ProgressStateCallback callback)
+ : AutoRequestGeneration(RequestType::RQ_TYPE_GET, id, requestSender, callback),
+ m_queryParamGen(queryParams),
+ m_rep(representation),
+ m_status(false),
+ m_stopRequested(false) {}
+
+void PUTRequestGenerator::startSending()
+{
+ // Check the representation
+ if (!m_rep)
+ {
+ OC_LOG(ERROR, TAG, "Invalid Representation given!");
+ throw SimulatorException(SIMULATOR_ERROR, "Invalid representation detected!");
+ }
+
+ // Check if the operation is already in progress
+ std::lock_guard<std::mutex> lock(m_statusLock);
+ if (m_status)
+ {
+ OC_LOG(ERROR, TAG, "Operation already in progress !");
+ throw OperationInProgressException("Another PUT request generation session is already in progress!");
+ }
+
+ // Create thread and start sending requests in dispatched thread
+ m_thread = std::make_shared<std::thread>(&PUTRequestGenerator::SendAllRequests, this);
+ m_status = true;
+ m_thread->detach();
+}
+
+void PUTRequestGenerator::stopSending()
+{
+ m_stopRequested = true;
+}
+
+void PUTRequestGenerator::SendAllRequests()
+{
+ OC_LOG(DEBUG, TAG, "Sending OP_START event");
+ m_callback(m_id, OP_START);
+
+ bool hasNext = false;
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_rep->getAttributes();
+ if (!attributes.size())
+ return;
+
+ std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
+ for (auto & attribute : attributes)
+ {
+ attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+ }
+
+ do
+ {
+ if (!m_stopRequested)
+ {
+ // Get the next possible queryParameter
+ std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+ while (true)
+ {
+ SimulatorResourceModelSP repModel = std::make_shared<SimulatorResourceModel>();
+
+ for (auto & attributeGen : attributeGenList)
+ {
+ if (attributeGen->hasNext())
+ {
+ AttributeSP attr = attributeGen->next();
+ int type = attr->getValueType();
+ if (!type)
+ {
+ int attributeValue = attr->getValue<int>();
+ std::string attributeName = attr->getName();
+ repModel->addAttribute(attributeName, attributeValue);
+ }
+ else
+ {
+ std::string attributeValue = attr->getValue<std::string>();
+ std::string attributeName = attr->getName();
+ repModel->addAttribute(attr->getName(), attributeValue);
+ }
+
+ hasNext = true;
+ }
+ else
+ {
+ AttributeSP attr = attributeGen->previous();
+ int type = attr->getValueType();
+ if (!type)
+ {
+ int attributeValue = attr->getValue<int>();
+ repModel->addAttribute(attr->getName(), attributeValue);
+ }
+ else
+ {
+ std::string attributeValue = attr->getValue<std::string>();
+ repModel->addAttribute(attr->getName(), attributeValue);
+ }
+ }
+ }
+
+ if (hasNext)
+ {
+ // Send the request
+ m_requestSender->sendRequest(queryParam, repModel,
+ std::bind(&PUTRequestGenerator::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2), true);
+
+ m_requestCnt++;
+ hasNext = false;
+ continue;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+ }
+ while (m_queryParamGen.hasNext());
+
+ m_requestsSent = true;
+ completed();
+}
+
+void PUTRequestGenerator::onResponseReceived(SimulatorResult result,
+ SimulatorResourceModelSP repModel)
+{
+ OC_LOG_V(INFO, TAG, "Response recieved result:%d", result);
+ m_responseCnt++;
+ completed();
+}
+
+void PUTRequestGenerator::completed()
+{
+ if (m_requestCnt == m_responseCnt)
+ {
+ if (m_stopRequested)
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_ABORT event");
+ m_callback(m_id, OP_ABORT);
+ }
+ else
+ {
+ OC_LOG(DEBUG, TAG, "Sending OP_COMPLETE event");
+ m_callback(m_id, OP_COMPLETE);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef PUT_REQUEST_GEN_H_
+#define PUT_REQUEST_GEN_H_
+
+#include "auto_request_gen.h"
+#include "query_param_generator.h"
+#include "attribute_generator.h"
+
+class PUTRequestGenerator : public AutoRequestGeneration
+{
+ public:
+ PUTRequestGenerator(int id, RequestSenderSP &requestSender,
+ SimulatorResourceModelSP &representation,
+ ProgressStateCallback callback);
+
+ PUTRequestGenerator(int id, RequestSenderSP &requestSender,
+ const std::map<std::string, std::vector<std::string>> &queryParams,
+ SimulatorResourceModelSP &representation,
+ ProgressStateCallback callback);
+
+ void startSending();
+ void stopSending();
+
+ private:
+ void SendAllRequests();
+ void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel);
+ void completed();
+
+ QPGenerator m_queryParamGen;
+ SimulatorResourceModelSP m_rep;
+ std::mutex m_statusLock;
+ bool m_status;
+ bool m_stopRequested;
+ std::shared_ptr<std::thread> m_thread;
+};
+
+typedef std::shared_ptr<PUTRequestGenerator> PUTRequestGeneratorSP;
+
+#endif
+
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "query_param_generator.h"
+
+QPGenerator::QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams)
+{
+ for (auto entry : queryParams)
+ {
+ if (entry.second.size())
+ {
+ QPDetail detail;
+ detail.key.assign(entry.first.c_str());
+ detail.values = entry.second;
+ detail.index = 0;
+ m_qpDetails.push_back(detail);
+ }
+ }
+}
+
+bool QPGenerator::hasNext()
+{
+ if (m_qpDetails.size() &&
+ (m_qpDetails[0].index < m_qpDetails[0].values.size()))
+ {
+ return true;
+ }
+
+ return false;
+}
+
+std::map<std::string, std::string> QPGenerator::next()
+{
+ std::map<std::string, std::string> queryParams;
+ if (!hasNext())
+ return queryParams;
+
+ for (auto ele : m_qpDetails)
+ queryParams[ele.key] = ele.values[ele.index];
+
+ for (int index = m_qpDetails.size(); index >= 0; index--)
+ {
+ m_qpDetails[index].index++;
+ if (m_qpDetails[index].index >= m_qpDetails[index].values.size()) // Boundary check
+ {
+ if (index != 0)
+ {
+ m_qpDetails[index].index = 0;
+ continue;
+ }
+ }
+ break;
+ }
+
+ return queryParams;
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef QUERY_PARAM_GENERATOR_H_
+#define QUERY_PARAM_GENERATOR_H_
+
+#include <string>
+#include <map>
+#include <vector>
+
+class QPGenerator
+{
+ public:
+ typedef struct
+ {
+ std::string key;
+ std::vector<std::string> values;
+ std::size_t index;
+ } QPDetail;
+
+ QPGenerator() = default;
+ QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams);
+ bool hasNext();
+ std::map<std::string, std::string> next();
+
+ private:
+ std::vector<QPDetail> m_qpDetails;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_LIST_H_
+#define REQUEST_LIST_H_
+
+#include <map>
+#include <mutex>
+
+template <typename T>
+class RequestList
+{
+ public:
+ RequestList() : m_id(0) {}
+
+ int add(T request)
+ {
+ if (!request)
+ return -1;
+
+ std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+ m_requestList[m_id++] = request;
+ return m_id - 1;
+ }
+
+ T get(int id)
+ {
+ std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+ if (m_requestList.end() != m_requestList.find(id))
+ return m_requestList[id];
+
+ return nullptr;
+ }
+
+ T remove(int id)
+ {
+ std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+ if (m_requestList.end() != m_requestList.find(id))
+ {
+ T request = m_requestList[id];
+ m_requestList.erase(m_requestList.find(id));
+ return request;
+ }
+
+ return nullptr;
+ }
+
+ int size()
+ {
+ std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+ return m_requestList.size();
+ }
+
+ void clear()
+ {
+ std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+ m_requestList.clear();
+ }
+
+ private:
+ int m_id;
+ std::recursive_mutex m_listMutex;
+ std::map<int, T> m_requestList;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "request_sender.h"
+#include "simulator_logger.h"
+#include "simulator_utils.h"
+#include "logger.h"
+
+#define TAG "GET_REQUEST_SNDR"
+
+RequestSender::RequestSender(RequestType type, std::shared_ptr<OC::OCResource> &ocResource)
+ : m_type(type), m_ocResource(ocResource) {}
+
+void RequestSender::sendRequest(const std::map<std::string, std::string> &queryParam,
+ ResponseCallback responseCb, bool verifyResponse)
+{
+ sendRequest(std::string(), queryParam, nullptr, responseCb, verifyResponse);
+}
+
+void RequestSender::sendRequest(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParam,
+ ResponseCallback responseCb, bool verifyResponse)
+{
+ sendRequest(interfaceType, queryParam, nullptr, responseCb, verifyResponse);
+}
+
+void RequestSender::sendRequest(const std::map<std::string, std::string> &queryParam,
+ SimulatorResourceModelSP repModel,
+ ResponseCallback responseCb, bool verifyResponse)
+{
+ sendRequest(std::string(), queryParam, repModel, responseCb, verifyResponse);
+}
+
+void RequestSender::sendRequest(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParam,
+ SimulatorResourceModelSP repModel,
+ ResponseCallback responseCb, bool verifyResponse)
+{
+ // Add query paramter "if" if interfaceType is not empty
+ OC::QueryParamsMap queryParamCpy(queryParam);
+ if (!interfaceType.empty())
+ queryParamCpy["if"] = interfaceType;
+
+ // Add the request into request list
+ RequestDetailSP requestDetail(new RequestDetail);
+ requestDetail->type = m_type;
+ requestDetail->queryParam = queryParamCpy;
+ requestDetail->body = repModel;
+ requestDetail->verifyResponse = verifyResponse;
+ requestDetail->responseCb = responseCb;
+
+ int requestId = m_requestList.add(requestDetail);
+
+ OCStackResult ocResult = send(queryParamCpy, repModel, std::bind(
+ &RequestSender::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, requestId));
+ if (OC_STACK_OK != ocResult)
+ {
+ OC_LOG_V(ERROR, TAG, "Sending request failed [errorcode: %d]", ocResult);
+ m_requestList.remove(requestId);
+ throw SimulatorException(static_cast<SimulatorResult>(ocResult), "Failed to send request!");
+ }
+}
+
+void RequestSender::setRequestModel(const RequestModelSP &requestModel)
+{
+ m_requestModel = requestModel;
+}
+
+void RequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int errorCode, int requestId)
+{
+ SIM_LOG(ILogger::INFO, "Response recieved..." << "\n" << getPayloadString(rep));
+
+ // Ignore the response recieved for invalid requests
+ RequestDetailSP request = m_requestList.remove(requestId);
+ if (!request)
+ {
+ return;
+ }
+
+ // Validate the response as per the schema given by RAML
+ ValidationStatus validationStatus {false, SIMULATOR_ERROR};
+ if (request->verifyResponse && m_requestModel
+ && !errorCode) // TODO: Validate responses other than "200"
+ {
+ validationStatus.errorCode = m_requestModel->validateResponse(200, rep);
+ validationStatus.isVerified = true;
+ }
+
+ SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep);
+ request->responseCb(static_cast<SimulatorResult>(errorCode), repModel);
+}
+
+GETRequestSender::GETRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
+ : RequestSender(RequestType::RQ_TYPE_GET, ocResource) {}
+
+OCStackResult GETRequestSender::send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback)
+{
+ SIM_LOG(ILogger::INFO, "Sending GET request..." << "\n" << getRequestString(queryParams));
+
+ return m_ocResource->get(queryParams, callback);
+}
+
+PUTRequestSender::PUTRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
+ : RequestSender(RequestType::RQ_TYPE_PUT, ocResource) {}
+
+OCStackResult PUTRequestSender::send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback)
+{
+ OC::OCRepresentation ocRep;
+ if (!repModel)
+ {
+ ocRep = repModel->getOCRepresentation();
+ }
+
+ SIM_LOG(ILogger::INFO, "Sending PUT request..." << "\n" << getRequestString(queryParams, ocRep));
+ return m_ocResource->put(ocRep, queryParams, callback);
+}
+
+POSTRequestSender::POSTRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
+ : RequestSender(RequestType::RQ_TYPE_POST, ocResource) {}
+
+OCStackResult POSTRequestSender::send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback)
+{
+ OC::OCRepresentation ocRep;
+ if (!repModel)
+ ocRep = repModel->getOCRepresentation();
+
+ SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n" << getRequestString(queryParams, ocRep));
+ return m_ocResource->post(ocRep, queryParams, callback);
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_SENDER_H_
+#define REQUEST_SENDER_H_
+
+#include "request_list.h"
+#include "simulator_resource_model.h"
+#include "request_model.h"
+#include "simulator_exceptions.h"
+#include "simulator_error_codes.h"
+
+struct RequestDetail;
+class RequestSender
+{
+ public:
+ typedef std::function<void (SimulatorResult, SimulatorResourceModelSP)> ResponseCallback;
+
+ RequestSender(RequestType type, std::shared_ptr<OC::OCResource> &ocResource);
+ virtual ~RequestSender() {}
+
+ void sendRequest(const std::map<std::string, std::string> &queryParam,
+ ResponseCallback responseCb, bool verifyResponse = false);
+
+ void sendRequest(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParam,
+ ResponseCallback responseCb, bool verifyResponse = false);
+
+ void sendRequest(const std::map<std::string, std::string> &queryParam,
+ SimulatorResourceModelSP repModel,
+ ResponseCallback responseCb, bool verifyResponse = false);
+
+ void sendRequest(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParam,
+ SimulatorResourceModelSP repModel,
+ ResponseCallback responseCb, bool verifyResponse = false);
+
+ void setRequestModel(const RequestModelSP &requestModel);
+
+ protected:
+ virtual OCStackResult send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback) = 0;
+
+ void onResponseReceived(const OC::HeaderOptions &headerOptions,
+ const OC::OCRepresentation &rep, const int errorCode, int requestId);
+
+ RequestType m_type;
+ RequestList<std::shared_ptr<RequestDetail>> m_requestList;
+ RequestModelSP m_requestModel;
+ std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+struct RequestDetail
+{
+ RequestType type;
+ std::map<std::string, std::string> queryParam;
+ SimulatorResourceModelSP body;
+ bool verifyResponse;
+ RequestSender::ResponseCallback responseCb;
+};
+
+typedef std::shared_ptr<RequestDetail> RequestDetailSP;
+
+class GETRequestSender : public RequestSender
+{
+ public:
+ GETRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
+
+ OCStackResult send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback);
+};
+
+class PUTRequestSender : public RequestSender
+{
+ public:
+ PUTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
+
+ OCStackResult send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback);
+};
+
+class POSTRequestSender : public RequestSender
+{
+ public:
+ POSTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
+
+ OCStackResult send(OC::QueryParamsMap &queryParams,
+ SimulatorResourceModelSP &repModel, OC::GetCallback callback);
+};
+
+typedef std::shared_ptr<RequestSender> RequestSenderSP;
+typedef std::shared_ptr<GETRequestSender> GETRequestSenderSP;
+typedef std::shared_ptr<PUTRequestSender> PUTRequestSenderSP;
+typedef std::shared_ptr<POSTRequestSender> POSTRequestSenderSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_client.h"
+#include "simulator_remote_resource_impl.h"
+#include "simulator_logger.h"
+#include "simulator_utils.h"
+#include "logger.h"
+
+#define TAG "SIMULATOR_CLIENT"
+
+SimulatorClient *SimulatorClient::getInstance()
+{
+ static SimulatorClient s_instance;
+ return &s_instance;
+}
+
+void SimulatorClient::findResources(ResourceFindCallback callback)
+{
+ if (!callback)
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+ typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
+ OCConnectivityType, OC::FindCallback);
+
+ invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "",
+ OC_MULTICAST_DISCOVERY_URI,
+ CT_DEFAULT,
+ static_cast<OC::FindCallback>(std::bind(&SimulatorClient::onResourceFound, this,
+ std::placeholders::_1, callback)));
+}
+
+void SimulatorClient::findResources(const std::string &resourceType,
+ ResourceFindCallback callback)
+{
+ if (resourceType.empty())
+ throw InvalidArgsException(SIMULATOR_INVALID_TYPE, "resource type is empty!");
+
+ if (!callback)
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+ std::ostringstream query;
+ query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType;
+
+ typedef OCStackResult (*FindResource)(const std::string &, const std::string &,
+ OCConnectivityType, OC::FindCallback);
+
+ invokeocplatform(static_cast<FindResource>(OC::OCPlatform::findResource), "", query.str(),
+ CT_DEFAULT,
+ static_cast<OC::FindCallback>(std::bind(&SimulatorClient::onResourceFound,
+ this, std::placeholders::_1, callback)));
+}
+
+void SimulatorClient::onResourceFound(std::shared_ptr<OC::OCResource> ocResource,
+ ResourceFindCallback callback)
+{
+ if (!ocResource)
+ {
+ OC_LOG(ERROR, TAG, "Invalid OCResource !");
+ return;
+ }
+
+ // Construct SimulatorRemoteResource
+ SimulatorRemoteResourceSP simulatorResource =
+ std::make_shared<SimulatorRemoteResourceImpl>(ocResource);
+ if (!simulatorResource)
+ {
+ OC_LOG(ERROR, TAG, "Failed to create simulator remote resource !");
+ return;
+ }
+
+ OC_LOG(DEBUG, TAG, "Invoking resource found client callback !");
+ callback(simulatorResource);
+}
+
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_client.h
+ *
+ * @brief This file provides a class for realizing simulator client functionality.
+ *
+ */
+
+#ifndef SIMULATOR_CLIENT_H_
+#define SIMULATOR_CLIENT_H_
+
+#include "simulator_client_types.h"
+#include "simulator_remote_resource.h"
+#include "simulator_exceptions.h"
+
+/**
+ * @class SimulatorClient
+ * @brief This class provides a set of functions for discovering the resources over the network.
+ */
+class SimulatorClient
+{
+ public:
+
+ /**
+ * API for getting singleton instance of SimulatorClient class.
+ *
+ * @return Singleton instance of SimulatorClient class.
+ *
+ */
+ static SimulatorClient *getInstance(void);
+
+ /**
+ * API for discovering all type of resources.
+ * Discovered resources will be notified through the callback set using @callback parameter.
+ *
+ * @param callback - Method of type @ResourceFindCallback through which discoverd resources
+ * will be notified.
+ *
+ * NOTE: API throws @InvalidArgsException and @SimulatorException.
+ */
+ void findResources(ResourceFindCallback callback);
+
+ /**
+ * API for discovering resources of a particular resource type.
+ * Discovered resources will be notified through the callback set using @callback parameter.
+ *
+ * @param resourceType - Type of resource to be searched for
+ * @param callback - Method of type @ResourceFindCallback through which discoverd resources
+ * will be notified.
+ *
+ * NOTE: API throws @InvalidArgsException and @SimulatorException.
+ */
+ void findResources(const std::string &resourceType, ResourceFindCallback callback);
+
+ private:
+ SimulatorClient() = default;
+ ~SimulatorClient() = default;
+ SimulatorClient(const SimulatorClient &) = delete;
+ SimulatorClient &operator=(const SimulatorClient &) = delete;
+ SimulatorClient(const SimulatorClient &&) = delete;
+ SimulatorClient &operator=(const SimulatorClient && ) = delete;
+
+ void onResourceFound(std::shared_ptr<OC::OCResource> resource,
+ ResourceFindCallback callback);
+};
+
+#endif
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_remote_resource_impl.h"
+#include "request_model_builder.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
+
+#define TAG "SIMULATOR_REMOTE_RESOURCE"
+
+SimulatorRemoteResourceImpl::SimulatorRemoteResourceImpl(std::shared_ptr<OC::OCResource>
+ &ocResource)
+ : m_observeState(false),
+ m_getRequestSender(new GETRequestSender(ocResource)),
+ m_putRequestSender(new PUTRequestSender(ocResource)),
+ m_postRequestSender(new POSTRequestSender(ocResource)),
+ m_autoRequestGenMngr(nullptr),
+ m_ocResource(ocResource)
+{
+ m_id = m_ocResource->sid().append(m_ocResource->uri());
+}
+
+std::string SimulatorRemoteResourceImpl::getURI() const
+{
+ return m_ocResource->uri();
+}
+
+std::string SimulatorRemoteResourceImpl::getHost() const
+{
+ return m_ocResource->host();
+}
+
+std::string SimulatorRemoteResourceImpl::getID() const
+{
+ return m_id;
+}
+
+SimulatorConnectivityType SimulatorRemoteResourceImpl::getConnectivityType() const
+{
+ return convertConnectivityType(m_ocResource->connectivityType());
+}
+
+std::vector < std::string > SimulatorRemoteResourceImpl::getResourceTypes() const
+{
+ return m_ocResource->getResourceTypes();
+}
+
+std::vector < std::string > SimulatorRemoteResourceImpl::getResourceInterfaces() const
+{
+ return m_ocResource->getResourceInterfaces();
+}
+
+bool SimulatorRemoteResourceImpl::isObservable() const
+{
+ return m_ocResource->isObservable();
+}
+
+void SimulatorRemoteResourceImpl::observe(ObserveType type,
+ ObserveNotificationCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ std::lock_guard<std::mutex> lock(m_observeMutex);
+ if (m_observeState)
+ {
+ OC_LOG(WARNING, TAG, "Resource already in observe state !");
+ throw SimulatorException(SIMULATOR_ERROR, "Resource is already being observed!");
+ }
+
+ OC::ObserveCallback observeCallback = [this, callback](const OC::HeaderOptions & headerOptions,
+ const OC::OCRepresentation & rep, const int errorCode,
+ const int sequenceNum)
+ {
+ // Convert OCRepresentation to SimulatorResourceModel
+ SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep);
+ callback(m_id, static_cast<SimulatorResult>(errorCode), repModel, sequenceNum);
+ };
+
+ OC::ObserveType observeType = OC::ObserveType::Observe;
+ if (type == ObserveType::OBSERVE_ALL)
+ {
+ observeType = OC::ObserveType::ObserveAll;
+ }
+
+ try
+ {
+ OCStackResult ocResult = m_ocResource->observe(observeType, OC::QueryParamsMap(), observeCallback);
+ if (OC_STACK_OK != ocResult)
+ {
+ throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+ }
+ }
+ catch (OC::OCException &e)
+ {
+ throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+ }
+
+ m_observeState = true;
+}
+
+void SimulatorRemoteResourceImpl::cancelObserve()
+{
+ try
+ {
+ OCStackResult ocResult = m_ocResource->cancelObserve(OC::QualityOfService::HighQos);
+ if (OC_STACK_OK != ocResult)
+ {
+ throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+ }
+ }
+ catch (OC::OCException &e)
+ {
+ throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+ }
+
+ std::lock_guard<std::mutex> lock(m_observeMutex);
+ m_observeState = false;
+}
+
+void SimulatorRemoteResourceImpl::get(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_getRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid GET request sender!");
+ throw NoSupportException("Can not send GET request on this resource!");
+ }
+
+ m_getRequestSender->sendRequest(interfaceType, queryParams,
+ nullptr, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::get(const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_getRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid GET request sender !");
+ throw NoSupportException("Can not send GET request on this resource!");
+ }
+
+ m_getRequestSender->sendRequest(std::string(), queryParams,
+ nullptr, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::put(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_putRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid PUT request sender !");
+ throw NoSupportException("Can not send PUT request on this resource!");
+ }
+
+ m_putRequestSender->sendRequest(interfaceType, queryParams,
+ representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_putRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid PUT request sender !");
+ throw NoSupportException("Can not send PUT request on this resource!");
+ }
+
+ m_putRequestSender->sendRequest(std::string(), queryParams,
+ representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::post(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_postRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid POST request sender !");
+ throw NoSupportException("Can not send POST request on this resource!");
+ }
+
+ m_postRequestSender->sendRequest(interfaceType, queryParams,
+ representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_postRequestSender)
+ {
+ OC_LOG(ERROR, TAG, "Invalid POST request sender !");
+ throw NoSupportException("Can not send POST request on this resource!");
+ }
+
+ m_postRequestSender->sendRequest(std::string(), queryParams,
+ representation, std::bind(
+ &SimulatorRemoteResourceImpl::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+int SimulatorRemoteResourceImpl::startVerification(RequestType type,
+ StateCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_autoRequestGenMngr)
+ {
+ OC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
+ throw NoSupportException("Resource is not configured with RAML!");
+ }
+
+ if (m_requestModelList.end() != m_requestModelList.find(type))
+ throw NoSupportException("Resource does not support this request type!");
+
+ // Local callback for handling progress sate callback
+ AutoRequestGeneration::ProgressStateCallback localCallback = [this, callback](
+ int sessionId, OperationState state)
+ {
+ callback(m_id, sessionId, state);
+ };
+
+ switch (type)
+ {
+ case RequestType::RQ_TYPE_GET:
+ if (m_getRequestSender)
+ {
+ return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
+ m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+ localCallback);
+ }
+ break;
+
+ 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_putRequestSender,
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+ localCallback);
+ }
+ break;
+
+ case RequestType::RQ_TYPE_DELETE:
+ default:
+ throw NoSupportException("Resource does not support this request type!");
+ }
+
+ return -1; // Code should not reach here
+}
+
+void SimulatorRemoteResourceImpl::stopVerification(int id)
+{
+ if (id < 0)
+ {
+ OC_LOG(ERROR, TAG, "Invalid session id!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid ID!");
+ }
+
+ if (!m_autoRequestGenMngr)
+ {
+ OC_LOG(ERROR, TAG, "Invalid auto request generation manager !");
+ throw NoSupportException("Resource is not configured with RAML!");
+ }
+
+ m_autoRequestGenMngr->stop(id);
+}
+
+void SimulatorRemoteResourceImpl::configure(const std::string &path)
+{
+ if (path.empty())
+ {
+ OC_LOG(ERROR, TAG, "Invalid path given for configuration !");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Empty path string!");
+ }
+
+ RAML::RamlParser *ramlParser = new RAML::RamlParser(path);
+ RAML::RamlPtr raml = ramlParser->getRamlPtr();
+
+ configure(raml);
+}
+
+void SimulatorRemoteResourceImpl::configure(std::shared_ptr<RAML::Raml> &raml)
+{
+ 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]);
+ }
+
+ if (m_putRequestSender &&
+ m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_PUT))
+ {
+ m_putRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_PUT]);
+ }
+
+ if (m_postRequestSender &&
+ m_requestModelList.end() != m_requestModelList.find(RequestType::RQ_TYPE_POST))
+ {
+ m_postRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_POST]);
+ }
+
+ if (m_autoRequestGenMngr)
+ {
+ m_autoRequestGenMngr = std::make_shared<AutoRequestGenMngr>();
+ }
+}
+
+void SimulatorRemoteResourceImpl::onResponseReceived(SimulatorResult result,
+ SimulatorResourceModelSP repModel,
+ ResponseCallback clientCallback)
+{
+ clientCallback(m_id, result, repModel);
+}
+
+SimulatorConnectivityType SimulatorRemoteResourceImpl::convertConnectivityType(
+ OCConnectivityType type) const
+{
+ switch (type)
+ {
+ case CT_ADAPTER_IP:
+ return SIMULATOR_CT_ADAPTER_IP;
+
+ case CT_IP_USE_V4:
+ return SIMULATOR_CT_IP_USE_V4 ;
+
+ case CT_IP_USE_V6:
+ return SIMULATOR_CT_IP_USE_V6;
+
+ case CT_ADAPTER_GATT_BTLE:
+ return SIMULATOR_CT_ADAPTER_GATT_BTLE;
+
+ case CT_ADAPTER_RFCOMM_BTEDR:
+ return SIMULATOR_CT_ADAPTER_RFCOMM_BTEDR;
+
+ default:
+ return SIMULATOR_CT_DEFAULT;
+ }
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_remote_resource_impl.h
+ *
+ * @brief This file provides internal implementation of simulator remote resource functionalities.
+ *
+ */
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_IMPL_H_
+#define SIMULATOR_REMOTE_RESOURCE_IMPL_H_
+
+#include "simulator_remote_resource.h"
+#include "auto_request_gen_mngr.h"
+#include "RamlParser.h"
+#include "request_model.h"
+
+#include <mutex>
+
+class SimulatorRemoteResourceImpl : public SimulatorRemoteResource
+{
+ public:
+ SimulatorRemoteResourceImpl(std::shared_ptr<OC::OCResource> &ocResource);
+ std::string getURI() const;
+ std::string getHost() const;
+ std::string getID() const;
+ SimulatorConnectivityType getConnectivityType() const;
+ std::vector < std::string > getResourceTypes() const;
+ std::vector < std::string > getResourceInterfaces() const;
+ bool isObservable() const;
+
+ void observe(ObserveType type, ObserveNotificationCallback callback);
+
+ void cancelObserve();
+
+ void get(const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback);
+
+ void get(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ ResponseCallback callback);
+
+ void put(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback);
+
+ void put(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback);
+
+ void post(const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback);
+
+ void post(const std::string &interfaceType,
+ const std::map<std::string, std::string> &queryParams,
+ SimulatorResourceModelSP representation,
+ ResponseCallback callback);
+
+ int startVerification(RequestType type, StateCallback callback);
+ void stopVerification(int id);
+ void configure(const std::string &path);
+
+ private:
+ void configure(std::shared_ptr<RAML::Raml> &raml);
+ void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel,
+ ResponseCallback clientCallback);
+ SimulatorConnectivityType convertConnectivityType(OCConnectivityType type) const;
+
+ std::string m_id;
+ std::mutex m_observeMutex;
+ bool m_observeState;
+ GETRequestSenderSP m_getRequestSender;
+ PUTRequestSenderSP m_putRequestSender;
+ POSTRequestSenderSP m_postRequestSender;
+ AutoRequestGenMngrSP m_autoRequestGenMngr;
+ std::map<RequestType, RequestModelSP> m_requestModelList;
+ std::shared_ptr<OC::OCResource> m_ocResource;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "request_model.h"
+#include "logger.h"
+
+RequestModel::RequestModel(RequestType type) : m_type(type) {}
+
+RequestType RequestModel::type() const
+{
+ return m_type;
+}
+
+SupportedQueryParams RequestModel::getQueryParams()
+{
+ return m_queryParams;
+}
+
+std::vector<std::string> RequestModel::getQueryParams(const std::string &key)
+{
+ if (m_queryParams.end() != m_queryParams.find(key))
+ {
+ return m_queryParams[key];
+ }
+
+ return std::vector<std::string>();
+}
+
+void RequestModel::setQueryParams(
+ const SupportedQueryParams &queryParams)
+{
+ m_queryParams = queryParams;
+}
+
+void RequestModel::addQueryParams(const std::string &key,
+ const std::vector<std::string> &values)
+{
+ if (0 != values.size())
+ m_queryParams[key] = values;
+}
+
+void RequestModel::addQueryParam(const std::string &key, const std::string &value)
+{
+ m_queryParams[key].push_back(value);
+}
+
+void RequestModel::addResponseModel(int code, ResponseModelSP &responseModel)
+{
+ if (!responseModel)
+ m_responseList[code] = responseModel;
+}
+
+void RequestModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+{
+ m_repSchema = repSchema;
+}
+
+SimulatorResourceModelSP RequestModel::getRepSchema()
+{
+ return m_repSchema;
+}
+
+SimulatorResult RequestModel::validateResponse(int responseCode, const OC::OCRepresentation &rep)
+{
+ if (m_responseList.end() == m_responseList.find(responseCode))
+ {
+ return SIMULATOR_INVALID_RESPONSE_CODE;
+ }
+
+ return m_responseList[responseCode]->verifyResponse(rep);
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_MODEL_H_
+#define REQUEST_MODEL_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+#include "response_model.h"
+#include "Raml.h"
+
+typedef std::map<std::string, std::vector<std::string>> SupportedQueryParams;
+
+class RequestModelBuilder;
+class RequestModel
+{
+ public:
+ friend class RequestModelBuilder;
+
+ RequestType type() const;
+ SupportedQueryParams getQueryParams();
+ std::vector<std::string> getQueryParams(const std::string &key);
+ SimulatorResourceModelSP getRepSchema();
+ SimulatorResult validateResponse(int responseCode, const OC::OCRepresentation &rep);
+
+ private:
+ RequestModel(RequestType type);
+ void setQueryParams(const SupportedQueryParams &queryParams);
+ void addQueryParams(const std::string &key, const std::vector<std::string> &values);
+ void addQueryParam(const std::string &key, const std::string &value);
+ void addResponseModel(int code, ResponseModelSP &responseModel);
+ void setRepSchema(SimulatorResourceModelSP &repSchema);
+
+ RequestType m_type;
+ SupportedQueryParams m_queryParams;
+ std::map<int, ResponseModelSP> m_responseList;
+ SimulatorResourceModelSP m_repSchema;
+};
+
+typedef std::shared_ptr<RequestModel> RequestModelSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "request_model_builder.h"
+#include "logger.h"
+
+#define TAG "REQ_MODEL_BUILDER"
+
+RequestModelBuilder::RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml)
+ : m_raml (raml) {}
+
+std::map<RequestType, RequestModelSP> RequestModelBuilder::build(const std::string &uri)
+{
+ std::map<RequestType, RequestModelSP> modelList;
+ if (!m_raml)
+ {
+ return modelList;
+ }
+
+ for (auto & resource : m_raml->getResources())
+ {
+ // Pick the resource based on the resource uri.
+ if (std::string::npos == uri.find((resource.second)->getResourceUri()))
+ continue;
+
+ // Construcut Request and Response Model from RAML::Action
+ for (auto & action : (resource.second)->getActions())
+ {
+ RequestModelSP requestModel = createRequestModel(action.second);
+ if (!requestModel)
+ modelList[requestModel->type()] = requestModel;
+ }
+ }
+
+ return modelList;
+}
+
+RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+{
+ OC_LOG(DEBUG, TAG, "Creating request model");
+
+ // 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::PUT
+ && actionType != RAML::ActionType::POST
+ && actionType != RAML::ActionType::DELETE)
+ {
+ OC_LOG(ERROR, TAG, "Failed to create request model as it is of unknown type!");
+ return nullptr;
+ }
+
+ // Construcut RequestModel
+ RequestModelSP requestModel(new RequestModel(getRequestType(actionType)));
+
+ // Get the allowed query parameters of the request
+ for (auto & qpEntry : action->getQueryParameters())
+ {
+ for (auto & value : (qpEntry.second)->getEnumeration())
+ {
+ requestModel->addQueryParam(qpEntry.first, value);
+ }
+ }
+
+ RAML::RequestResponseBodyPtr requestBody = action->getRequestBody("application/json");
+ SimulatorResourceModelSP repSchema = createRepSchema(requestBody);
+ requestModel->setRepSchema(repSchema);
+
+ // Corresponsing responses
+ for (auto & responseEntry : action->getResponses())
+ {
+ std::string codeStr = responseEntry.first;
+ int code = boost::lexical_cast<int>(codeStr);
+ ResponseModelSP responseModel = createResponseModel(code, responseEntry.second);
+ if (nullptr != responseModel)
+ {
+ requestModel->addResponseModel(code, responseModel);
+ }
+ }
+
+ return requestModel;
+}
+
+ResponseModelSP RequestModelBuilder::createResponseModel(int code,
+ const RAML::ResponsePtr &response)
+{
+ ResponseModelSP responseModel(new ResponseModel(code));
+ RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");
+ SimulatorResourceModelSP repSchema = createRepSchema(responseBody);
+ responseModel->setRepSchema(repSchema);
+ return responseModel;
+}
+
+SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::RequestResponseBodyPtr
+ &rep)
+{
+ RAML::SchemaPtr schema = rep->getSchema();
+ if (!schema)
+ {
+ return nullptr;
+ }
+
+ RAML::JsonSchemaPtr properties = schema->getProperties();
+ if (!properties || 0 == properties->getProperties().size())
+ return nullptr;
+
+ SimulatorResourceModelSP repSchema = std::make_shared<SimulatorResourceModel>();
+ for (auto & propertyEntry : properties->getProperties())
+ {
+ int valueType = propertyEntry.second->getValueType();
+ switch (valueType)
+ {
+ case 0: // Integer
+ {
+ // Add the attribute with value
+ std::cout << "[createRepresentationSchema] Adding Attribute of type int" << std::endl;
+ repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<int>());
+
+ // Set the range
+ int min, max, multipleof;
+ propertyEntry.second->getRange(min, max, multipleof);
+ repSchema->setRange(propertyEntry.second->getName(), min, max);
+ }
+ break;
+
+ case 1: // Double
+ {
+ // Add the attribute with value
+ std::cout << "[createRepresentationSchema] Adding Attribute of type double" << std::endl;
+ repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<double>());
+
+ std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
+ propertyEntry.second->getAllowedValues();
+
+ // TODO: Use RAML function once available
+ if (0 < propertyEntry.second->getAllowedValuesSize())
+ {
+ std::vector<double> allowedValues;
+ for (auto & propValue : propValues)
+ {
+ double value = boost::lexical_cast<double> (propValue);
+ allowedValues.push_back(value);
+ }
+ repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
+ }
+ }
+ break;
+
+ case 2: // Boolean
+ {
+ // Add the attribute with value
+ std::cout << "[createRepresentationSchema] Adding Attribute of type boolean" << std::endl;
+ repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<bool>());
+ }
+ break;
+
+ case 3: // String
+ {
+ // Add the attribute with value
+ std::cout << "[createRepresentationSchema] Adding Attribute of type string" << std::endl;
+ repSchema->addAttribute(propertyEntry.second->getName(),
+ propertyEntry.second->getValue<std::string>());
+
+ std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
+ propertyEntry.second->getAllowedValues();
+
+ // TODO: Use RAML function once available
+ if (0 < propertyEntry.second->getAllowedValuesSize())
+ {
+ std::vector<std::string> allowedValues;
+ for (auto & propValue : propValues)
+ {
+ std::string value = boost::lexical_cast<std::string> (propValue);
+ allowedValues.push_back(value);
+ }
+ repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
+ }
+ }
+ break;
+ }
+ }
+
+ return repSchema;
+}
+
+RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType)
+{
+ switch (actionType)
+ {
+ case RAML::ActionType::GET:
+ return RequestType::RQ_TYPE_GET;
+ case RAML::ActionType::PUT:
+ return RequestType::RQ_TYPE_PUT;
+ case RAML::ActionType::POST:
+ return RequestType::RQ_TYPE_POST;
+ case RAML::ActionType::DELETE:
+ return RequestType::RQ_TYPE_DELETE;
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_MODEL_BUILDER_H_
+#define REQUEST_MODEL_BUILDER_H_
+
+#include "request_model.h"
+#include "response_model.h"
+
+class RequestModelBuilder
+{
+ public:
+ RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml);
+ std::map<RequestType, RequestModelSP> build(const std::string &uri);
+
+ private:
+ RequestModelSP createRequestModel(const RAML::ActionPtr &action);
+ ResponseModelSP createResponseModel(int code, const RAML::ResponsePtr &response);
+ SimulatorResourceModelSP createRepSchema(const RAML::RequestResponseBodyPtr &rep);
+ RequestType getRequestType(RAML::ActionType actionType);
+
+ std::shared_ptr<RAML::Raml> m_raml;
+};
+
+#endif
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "response_model.h"
+
+ResponseModel::ResponseModel(int code) : m_code(code) {}
+
+void ResponseModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+{
+ m_repSchema = repSchema;
+}
+
+SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &rep)
+{
+ for (auto & ocAttribute : rep)
+ {
+ SimulatorResourceModel::Attribute attribute;
+ if (false == m_repSchema->getAttribute(ocAttribute.attrname(), attribute))
+ {
+ return SIMULATOR_UKNOWN_PROPERTY;
+ }
+
+ int type = attribute.getValueType();
+ switch (type)
+ {
+ case 0: // Integer
+ {
+ SimulatorResult result = validateAttributeInteger(attribute, ocAttribute);
+ if (SIMULATOR_OK != result)
+ {
+ return result;
+ }
+ }
+ break;
+
+ case 1: // Double
+ {
+ SimulatorResult result = validateAttributeDouble(attribute, ocAttribute);
+ if (SIMULATOR_OK != result)
+ {
+ return result;
+ }
+ }
+ break;
+
+ case 2: // String
+ {
+ SimulatorResult result = validateAttributeString(attribute, ocAttribute);
+ if (SIMULATOR_OK != result)
+ {
+ return result;
+ }
+ }
+ break;
+ }
+ }
+
+ return SIMULATOR_OK;
+}
+
+SimulatorResult ResponseModel::validateAttributeInteger(
+ SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute)
+{
+ // Check the value type
+ if (OC::AttributeType::Integer != ocAttribute.type())
+ {
+ return SIMULATOR_TYPE_MISMATCH;
+ }
+
+ // Check value if it is in range
+ int min, max, value;
+ attrSchema.getRange(min, max);
+ value = ocAttribute.getValue<int>();
+ if (value < min || value > max)
+ {
+ return SIMULATOR_BAD_VALUE;
+ }
+
+ return SIMULATOR_OK;
+}
+
+SimulatorResult ResponseModel::validateAttributeDouble(
+ SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute)
+{
+ // Check the value type
+ if (OC::AttributeType::Double != ocAttribute.type())
+ {
+ return SIMULATOR_TYPE_MISMATCH;
+ }
+
+ return SIMULATOR_OK;
+}
+
+SimulatorResult ResponseModel::validateAttributeString(
+ SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute)
+{
+ // Check the value type
+ if (OC::AttributeType::String != ocAttribute.type())
+ {
+ return SIMULATOR_TYPE_MISMATCH;
+ }
+
+ // TODO: Check the allowed values
+ return SIMULATOR_OK;
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef RESPONSE_MODEL_H_
+#define RESPONSE_MODEL_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+
+class RequestModelBuilder;
+class ResponseModel
+{
+ public:
+ friend class RequestModelBuilder;
+
+ SimulatorResult verifyResponse(const OC::OCRepresentation &rep);
+
+ private:
+ ResponseModel(int code);
+ void setRepSchema(SimulatorResourceModelSP &repSchema);
+ SimulatorResult validateAttributeInteger(SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute);
+ SimulatorResult validateAttributeDouble(SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute);
+ SimulatorResult validateAttributeString(SimulatorResourceModel::Attribute &attrSchema,
+ const OC::OCRepresentation::AttributeItem &ocAttribute);
+
+ int m_code;
+ SimulatorResourceModelSP m_repSchema;
+};
+
+typedef std::shared_ptr<ResponseModel> ResponseModelSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_exceptions.h"
+
+SimulatorException::SimulatorException(SimulatorResult errorCode, const std::string &message)
+ : m_errorCode(errorCode), m_message(message) {}
+
+const char *SimulatorException::what() const noexcept
+{
+ return m_message.c_str();
+}
+
+SimulatorResult SimulatorException::code() const
+{
+ return m_errorCode;
+}
+
+InvalidArgsException::InvalidArgsException(SimulatorResult errorCode, const std::string &message)
+ : SimulatorException(errorCode, message) {}
+
+NoSupportException::NoSupportException(const std::string &message)
+ : SimulatorException(SIMULATOR_NOT_SUPPORTED, message) {}
+
+OperationInProgressException::OperationInProgressException(const std::string &message)
+ : SimulatorException(SIMULATOR_OPERATION_IN_PROGRESS, message) {}
return true;
}
-bool Logger::setDefaultFileTarget(std::string &path)
+bool Logger::setDefaultFileTarget(const std::string &path)
{
if (nullptr != m_target || path.empty())
return false;
return false;
}
-void Logger::setCustomTarget(std::shared_ptr<ILogger> target)
+void Logger::setCustomTarget(const std::shared_ptr<ILogger> &target)
{
m_target = target;
}
******************************************************************/
#include "simulator_resource_model.h"
+#include "OCPlatform.h"
#include <sstream>
#include <boost/lexical_cast.hpp>
return false;
}
+ bool operator ()(bool &value)
+ {
+ return true;
+ }
+
bool operator ()(std::string &value)
{
std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
};
SimulatorResourceModel::Attribute::ValueVariant
-&SimulatorResourceModel::Attribute::AllowedValues::at(int index)
+&SimulatorResourceModel::Attribute::AllowedValues::at(unsigned int index)
{
return m_values.at(index);
}
return m_values.size();
}
-std::string SimulatorResourceModel::Attribute::AllowedValues::toString() const
-{
- std::ostringstream stream;
- stream << "[ ";
- for (auto & value : m_values)
- {
- to_string_visitor visitor;
- stream << boost::apply_visitor(visitor, value) << " ";
- }
- stream << "]";
- return stream.str();
-}
-
-std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toVectorString() const
+std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toString() const
{
std::vector<std::string> values;
return m_allowedValues.size();
}
-void SimulatorResourceModel::Attribute::setFromAllowedValue(const int allowedValueIndex)
+void SimulatorResourceModel::Attribute::setFromAllowedValue(unsigned int index)
{
- m_value = m_allowedValues.at(allowedValueIndex);
+ m_value = m_allowedValues.at(index);
}
std::string SimulatorResourceModel::Attribute::valueToString() const
return boost::apply_visitor(visitor, m_value);
}
-std::string SimulatorResourceModel::Attribute::allowedValuesToString() const
+std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToString() const
{
return m_allowedValues.toString();
}
-std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToVectorString() const
-{
- return m_allowedValues.toVectorString();
-}
-
void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep,
const std::string &key) const
{
}
void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName,
- const int allowedValueIndex)
+ unsigned int index)
{
if (m_attributes.end() != m_attributes.find(attrName))
- m_attributes[attrName].setFromAllowedValue(allowedValueIndex);
+ m_attributes[attrName].setFromAllowedValue(index);
}
void SimulatorResourceModel::removeAttribute(const std::string &attrName)
return true;
// Convert OCRepresentation to SimulatorResourceModel
- SimulatorResourceModel resModel = create(ocRep);
+ SimulatorResourceModelSP resModel = create(ocRep);
return update(resModel);
}
-bool SimulatorResourceModel::update(SimulatorResourceModel &repModel)
+bool SimulatorResourceModel::update(SimulatorResourceModelSP &repModel)
{
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel->getAttributes();
for (auto & attributeItem : attributes)
{
// Check the attribute presence
return true;
}
-SimulatorResourceModel SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
+SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
{
- SimulatorResourceModel resModel;
+ SimulatorResourceModelSP resModel(new SimulatorResourceModel);
for (auto & attributeItem : ocRep)
{
SimulatorResourceModel::Attribute attribute;
attribute.setValue(attributeItem.getValue<std::string>());
attribute.setName(attributeItem.attrname());
- resModel.m_attributes[attributeItem.attrname()] = attribute;
+ resModel->m_attributes[attributeItem.attrname()] = attribute;
}
-
return resModel;
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_utils.h"
+#include "OCRepresentation.h"
+
+std::string getPayloadString(const OC::OCRepresentation &rep)
+{
+ std::ostringstream data;
+ OCRepPayload *payload = rep.getPayload();
+ if (!payload)
+ {
+ return "Payload: No payload";
+ }
+
+ // URI
+ data << "URI: " << payload->uri << std::endl;
+
+ // Attributes
+ data << "Attributes:" << std::endl;
+ OCRepPayloadValue *values = payload->values;
+ while (NULL != values)
+ {
+ data << values->name << ":" << rep.getValueToString(values->name) << std::endl;
+ values = values->next;
+ }
+
+ return data.str();
+}
+
+std::string getRequestString(const std::map<std::string, std::string> &queryParams,
+ const OC::OCRepresentation &rep)
+{
+ std::ostringstream data;
+ data << "qp: ";
+ if (queryParams.size() > 0)
+ {
+ for (auto & qp : queryParams)
+ data << qp.second << ",";
+ }
+
+ data << getPayloadString(rep);
+ return data.str();
+}
+
+std::string getRequestString(const std::map<std::string, std::string> &queryParams)
+{
+ std::ostringstream data;
+ data << "qp: ";
+ if (queryParams.size() > 0)
+ {
+ for (auto & qp : queryParams)
+ data << qp.second << ",";
+ }
+
+ data << "Payload: No payload";
+ return data.str();
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_utils.h
+ *
+ * @brief This file provides utility methods used by both client and servers.
+ */
+
+#ifndef SIMULATOR_UTILS_H_
+#define SIMULATOR_UTILS_H_
+
+#include "simulator_exceptions.h"
+#include "octypes.h"
+#include "OCException.h"
+
+#include <map>
+
+/**
+ * Utilities for Invokation of OC platfrom level APIs.
+ */
+template <typename FnT, typename... ArgsT>
+typename std::enable_if<std::is_same<OCStackResult, decltype(std::declval<FnT>()(std::declval<ArgsT>()...))>::value>::type
+invokeocplatform(FnT fn, ArgsT &&...args)
+{
+ try
+ {
+ OCStackResult ocResult = fn(std::forward<ArgsT>(args)...);
+ if (OC_STACK_OK != ocResult)
+ {
+ // Throw SimulatorException converting error codes
+ throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+ }
+ }
+ catch (OC::OCException &e)
+ {
+ // Throw SimulatorException converting error codes
+ throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+ }
+}
+
+namespace OC
+{
+ class OCRepresentation;
+}
+
+std::string getPayloadString(const OC::OCRepresentation &);
+std::string getRequestString(const std::map<std::string, std::string> &queryParams,
+ const OC::OCRepresentation &rep);
+std::string getRequestString(const std::map<std::string, std::string> &queryParams);
+
+#endif
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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_manager.h"
-#include "simulator_logger.h"
-
-int ResourceManager::id;
-ResourceManager *ResourceManager::getInstance()
-{
- static ResourceManager s_instance;
- return &s_instance;
-}
-
-ResourceManager::ResourceManager()
- : m_resourceCreator(new SimulatorResourceCreator()) {}
-
-ResourceManager::~ResourceManager()
-{
- delete m_resourceCreator;
-}
-
-SimulatorResourceServerPtr ResourceManager::createResource(const std::string &configPath,
- SimulatorResourceServer::ResourceModelChangedCB callback)
-{
- /**
- * TODO: Temporarily creating the light resource for testing the basic flow
- * Once the config parser is included this method will simulate the resource based on the config file
- */
- SimulatorResourceServerPtr simulatorResource = m_resourceCreator->createResource(configPath);
- simulatorResource->setModelChangeCallback(callback);
- std::string uri = getURI(simulatorResource->getURI());
- if(uri.empty())
- {
- SIM_LOG(ILogger::ERROR, "Cannot register resource. Resource URI is empty");
- return NULL;
- }
- simulatorResource->setURI(uri);
- SimulatorResult result = simulatorResource->start();
- if (SIMULATOR_SUCCESS != result)
- {
- SIM_LOG(ILogger::ERROR, "Failed to register resource [" << simulatorResource->getURI() <<
- "] with platform");
- return NULL;
- }
-
- // Add the resource to resource list table
- std::lock_guard<std::recursive_mutex> lock(m_listMutex);
- m_resourceList[simulatorResource->getResourceType()].insert(
- std::pair<std::string, SimulatorResourceServerPtr>(simulatorResource->getURI(), simulatorResource));
- return simulatorResource;
-}
-
-std::vector<SimulatorResourceServerPtr> ResourceManager::createResource(
- const std::string &configPath,
- const int count, SimulatorResourceServer::ResourceModelChangedCB callback)
-{
- std::vector<SimulatorResourceServerPtr> resourceList;
- for (int i = 0; i < count; i++)
- {
- /**
- * TODO: Temporarily creating the light resource for testing the basic flow
- * Once the config parser is included this method will simulate the resource based on the config file
- */
- SimulatorResourceServerPtr simulatorResource = m_resourceCreator->createResource(configPath);
- simulatorResource->setModelChangeCallback(callback);
- std::string uri = getURI(simulatorResource->getURI());
- if(uri.empty())
- {
- SIM_LOG(ILogger::ERROR, "Cannot register resource. Resource URI is empty");
- break;
- }
- simulatorResource->setURI(uri);
- SimulatorResult result = simulatorResource->start();
- if (SIMULATOR_SUCCESS != result)
- {
- resourceList.clear();
- SIM_LOG(ILogger::ERROR, "Failed to register resources!");
- break;
- }
- else
- {
- resourceList.push_back(simulatorResource);
- }
- }
-
- // Add the resource to resource list table
- std::lock_guard<std::recursive_mutex> lock(m_listMutex);
- for (auto & resource : resourceList)
- {
- m_resourceList[resource->getResourceType()].insert(
- std::pair<std::string, SimulatorResourceServerPtr>(resource->getURI(), resource));
- }
-
- return resourceList;
-}
-
-std::vector<SimulatorResourceServerPtr> ResourceManager::getResources(
- const std::string &resourceType)
-{
- std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-
- std::vector<SimulatorResourceServerPtr> resourceList;
- for (auto resourceTableEntry : m_resourceList)
- {
- if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
- continue;
-
- for (auto resourceEntry : resourceTableEntry.second)
- {
- resourceList.push_back(resourceEntry.second);
- }
- }
-
- return resourceList;
-}
-
-SimulatorResult ResourceManager::deleteResource(SimulatorResourceServerPtr &resource)
-{
- std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-
- if (nullptr == resource)
- return SIMULATOR_BAD_INPUT;
-
- SimulatorResult result = SIMULATOR_RESOURCE_NOT_FOUND;
-
- try
- {
- auto resourceTableEntry = m_resourceList.find(resource->getResourceType());
- if (m_resourceList.end() != resourceTableEntry)
- {
- auto resourceEntry = resourceTableEntry->second.find(resource->getURI());
- if (resourceTableEntry->second.end() != resourceEntry)
- {
- if (SIMULATOR_SUCCESS == resource->stop())
- {
- resourceTableEntry->second.erase(resourceEntry);
- result = SIMULATOR_SUCCESS;
- }
- else
- {
- result = SIMULATOR_ERROR;
- }
- }
- }
- }
- catch (OC::OCException &except)
- {
- SIM_LOG(ILogger::ERROR, except.reason() << except.code())
- result = SIMULATOR_ERROR;
- }
-
- return result;
-}
-
-SimulatorResult ResourceManager::deleteResources(const std::string &resourceType)
-{
- std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-
- SimulatorResult result = SIMULATOR_RESOURCE_NOT_FOUND;
- try
- {
- for (auto & resourceTableEntry : m_resourceList)
- {
- if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
- continue;
-
- for (auto & resourceEntry : resourceTableEntry.second)
- {
- SimulatorResourceServerPtr resource = resourceEntry.second;
- if (SIMULATOR_SUCCESS == resource->stop())
- {
- resourceTableEntry.second.erase(resourceTableEntry.second.find(resource->getURI()));
- result = SIMULATOR_SUCCESS;
- }
- else
- {
- return SIMULATOR_ERROR;
- }
- }
- }
- }
- catch (OC::OCException &except)
- {
- SIM_LOG(ILogger::ERROR, except.reason() << except.code())
- result = SIMULATOR_ERROR;
- }
-
- return result;
-}
-
-std::string ResourceManager::getURI(std::string uri)
-{
- if(uri.empty())
- {
- return uri;
- }
- std::ostringstream os;
- os << uri;
- if ('/' != uri[uri.length() - 1])
- os << '/';
- os << "simulator/" << id++;
- return os.str();
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-/**
- * @file resource_manager.h
- *
- * @brief This file provides a class for a set of APIs relating to resource management
- * in the Service Provider side.
- */
-
-#ifndef RESOURCE_MANAGER_H_
-#define RESOURCE_MANAGER_H_
-
-#include <string>
-#include <vector>
-#include <map>
-#include <mutex>
-#include "simulator_resource_server.h"
-#include "simulator_resource_creator.h"
-#include "simulator_error_codes.h"
-
-/**
- * @class ResourceManager
- * @brief This class provides a set of functions for managing the resource(s) in the Service Provider Module.
- */
-class ResourceManager
-{
- public:
- /**
- * This method is used to create/obtain the singleton instance of ResourceManager.
- *
- * @return ResourceManager - Singleton instance of ResourceManager.
- */
- static ResourceManager *getInstance(void);
-
- /**
- * This method is called for creating a single resource from the configuration file.
- *
- * @param configPath - RAML configuration file path.
- * @param callback - Callback method for receive notifications when resource model changes.
- *
- * @return SimulatorResourceServerPtr - Shared pointer of SimulatorResourceServer on success, otherwise NULL.
- */
- SimulatorResourceServerPtr createResource(const std::string &configPath,
- SimulatorResourceServer::ResourceModelChangedCB callback);
-
- /**
- * This method is called for creating a collection of resources from the configuration file.
- *
- * @param configPath - RAML configuration file path.
- * @param count - Number of resource to be created.
- * @param callback - Callback method for receive notifications when resource model changes.
- *
- * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
- */
- std::vector<SimulatorResourceServerPtr> createResource(const std::string &configPath,
- const int count,
- SimulatorResourceServer::ResourceModelChangedCB callback);
-
- /**
- * This method is called for obtaining a list of created resources.
- *
- * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
- */
- std::vector<SimulatorResourceServerPtr> getResources(const std::string &resourceType = "");
-
- /**
- * This method is called for deleting a single resource.
- *
- * @param resource - Shared pointer of the SimulatorResourceServer to be deleted.
- *
- * @return SimulatorResult
- */
- SimulatorResult deleteResource(SimulatorResourceServerPtr &resource);
-
- /**
- * This method is called for deleting multiple resources.
- * If this method is called without any parameter, then all resources will be deleted.
- * If thie method is called with a specific resourcetype as a parameter, then all the resources
- * of that particular type will be deleted.
- *
- * @param resourceType - Resource type of the resource
- *
- * @return SimulatorResult
- */
- SimulatorResult deleteResources(const std::string &resourceType = "");
-
- private:
- /**
- * This method is called for obtaining a unique URI when creating multiple resources using createResource API.
- * It appends a unique key to the given URI.
- * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource
- * and "/a/light/simulator/1" for the second resource and so on.
- *
- * @param uri - URI of the resource
- *
- * @return Unique URI for the resource
- */
- std::string getURI(std::string uri);
-
- ResourceManager();
- ~ResourceManager();
-
- SimulatorResourceCreator *m_resourceCreator;
- static int id;
-
- /**
- * This multi-level map organizes the resources in the form of ResourceType as the key
- * and a set of resources of that resourceType as the value.
- * The value is another map which has the ResourceURI as the key and the shared pointer
- * of the SimulatorResourceServer object as the value.
- */
- std::map<std::string, std::map<std::string, SimulatorResourceServerPtr>> m_resourceList;
- std::recursive_mutex m_listMutex;
-};
-
-#endif
-
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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_manager.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "RESOURCE_MANAGER"
+
+ResourceManager *ResourceManager::getInstance()
+{
+ static ResourceManager s_instance;
+ return &s_instance;
+}
+
+SimulatorResourceServerSP ResourceManager::createResource(const std::string &configPath,
+ SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+ OC_LOG_V(INFO, "Create resource request : config=%s", configPath.c_str());
+
+ // Input validation
+ if (configPath.empty())
+ {
+ OC_LOG(ERROR, TAG, "Invalid config file path!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid RAML file path!");
+ }
+
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ return buildResource(configPath, callback);
+}
+
+std::vector<SimulatorResourceServerSP> ResourceManager::createResource(
+ const std::string &configPath, unsigned short count,
+ SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+ OC_LOG_V(INFO, "Create multiple resource request : config=%s, count=%d", configPath.c_str(),
+ count);
+
+ // Input validation
+ if (configPath.empty())
+ {
+ OC_LOG(ERROR, TAG, "Invalid config file path!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid RAML file path!");
+ }
+
+ if (0 == count)
+ {
+ OC_LOG(ERROR, TAG, "Invalid count value!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid count value!");
+ }
+
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ std::vector<SimulatorResourceServerSP> resourceList;
+
+ // Create resources
+ for (unsigned short i = 0; i < count; i++)
+ {
+ OC_LOG_V(INFO, TAG, "Creating resource [%d]", i + 1);
+ SIM_LOG(ILogger::INFO, "Creating resource [" << i + 1 << "]");
+
+ SimulatorResourceServerSP resource = buildResource(configPath, callback);
+ if (!resource)
+ {
+ break;
+ }
+
+ resourceList.push_back(resource);
+ }
+
+ SIM_LOG(ILogger::INFO, "[" << resourceList.size() << " out of " << count <<
+ "] resource(s) created successfully.");
+
+ return resourceList;
+}
+
+std::vector<SimulatorResourceServerSP> ResourceManager::getResources(
+ const std::string &resourceType)
+{
+ std::lock_guard<std::recursive_mutex> lock(m_lock);
+
+ std::vector<SimulatorResourceServerSP> resourceList;
+ for (auto resourceTableEntry : m_resources)
+ {
+ if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
+ continue;
+
+ for (auto resourceEntry : resourceTableEntry.second)
+ {
+ resourceList.push_back(resourceEntry.second);
+ }
+ }
+
+ return resourceList;
+}
+
+void ResourceManager::deleteResource(const SimulatorResourceServerSP &resource)
+{
+ if (!resource)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource object!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid resource object!");
+ }
+
+ std::lock_guard<std::recursive_mutex> lock(m_lock);
+ auto resourceTableEntry = m_resources.find(resource->getResourceType());
+ if (m_resources.end() != resourceTableEntry)
+ {
+ auto resourceEntry = resourceTableEntry->second.find(resource->getURI());
+ if (resourceTableEntry->second.end() != resourceEntry)
+ {
+ SimulatorResourceServerImplSP resourceImpl =
+ std::dynamic_pointer_cast<SimulatorResourceServerImpl>(resource);
+ resourceImpl->stop();
+ resourceTableEntry->second.erase(resourceEntry);
+ SIM_LOG(ILogger::INFO, "Resource (" << resource->getURI() <<
+ ") deleted successfully.");
+ }
+ }
+}
+
+void ResourceManager::deleteResources(const std::string &resourceType)
+{
+ std::lock_guard<std::recursive_mutex> lock(m_lock);
+ for (auto & resourceTableEntry : m_resources)
+ {
+ if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
+ continue;
+
+ for (auto & resourceEntry : resourceTableEntry.second)
+ {
+ SimulatorResourceServerSP resource = resourceEntry.second;
+ SimulatorResourceServerImplSP resourceImpl =
+ std::dynamic_pointer_cast<SimulatorResourceServerImpl>(resource);
+ resourceImpl->stop();
+ SIM_LOG(ILogger::INFO, "Resource (" << resource->getURI() <<
+ ") deleted successfully.");
+ }
+
+ // Erase the entry for resource type from resources list
+ m_resources.erase(resourceTableEntry.first);
+ }
+}
+
+/**
+ * This method does not validate the input given, thus Caller of this method must validate
+ * the inputs before invoking this private method.
+ */
+SimulatorResourceServerSP ResourceManager::buildResource(const std::string &configPath,
+ SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+ // Create resource based on the RAML file.
+ SimulatorResourceServerImplSP resourceImpl = m_resourceCreator.createResource(configPath);
+ if (!resourceImpl)
+ {
+ OC_LOG(ERROR, TAG, "Failed to create resource!");
+ throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+ }
+
+ resourceImpl->setModelChangeCallback(callback);
+ resourceImpl->start();
+
+ // Add the resource to resource list table
+ std::lock_guard<std::recursive_mutex> lock(m_lock);
+ SimulatorResourceServerSP resource =
+ std::dynamic_pointer_cast<SimulatorResourceServer>(resourceImpl);
+ m_resources[resourceImpl->getResourceType()].insert(
+ std::pair<std::string, SimulatorResourceServerSP>(resourceImpl->getURI(), resourceImpl));
+
+ SIM_LOG(ILogger::INFO, "Created an OIC resource of type [" <<
+ resourceImpl->getResourceType() << "]");
+ return resourceImpl;
+}
+
+/**
+ * This method appends a unique key to the given URI to make the URI unique in simulator.
+ * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource
+ * and "/a/light/simulator/1" for the second resource and so on.
+ */
+std::string ResourceManager::constructURI(const std::string &uri)
+{
+ std::ostringstream os;
+ os << uri;
+ if (!uri.empty() && '/' != uri[uri.length() - 1])
+ os << '/';
+ os << "simulator/" << m_id++;
+ return os.str();
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file resource_manager.h
+ *
+ * @brief This file provides APIs for simulated resource management.
+ */
+
+#ifndef RESOURCE_MANAGER_H_
+#define RESOURCE_MANAGER_H_
+
+#include "simulator_resource_server_impl.h"
+#include "simulator_resource_creator.h"
+#include "simulator_error_codes.h"
+
+/**
+ * @class ResourceManager
+ * @brief This class provides a set of APIs for managing the simulated resource(s).
+ */
+class ResourceManager
+{
+ public:
+ /**
+ * This method is to create/obtain the singleton instance of ResourceManager.
+ */
+ static ResourceManager *getInstance(void);
+
+ /**
+ * This method is for simulating/creating a resource based on the input data provided from
+ * RAML file.
+ *
+ * @param configPath - RAML configuration file path.
+ * @param callback - Callback method for receiving notifications when resource model changes.
+ *
+ * @return SimulatorResourceServer shared object representing simulated/created resource.
+ */
+ SimulatorResourceServerSP createResource(const std::string &configPath,
+ SimulatorResourceServer::ResourceModelChangedCB callback);
+
+ /**
+ * This method is for creating multiple resources of same type based on the input data
+ * provided from RAML file.
+ *
+ * @param configPath - RAML configuration file path.
+ * @param count - Number of resource to be created.
+ * @param callback - Callback method for receiving notifications when resource model changes.
+ *
+ * @return vector of SimulatorResourceServer shared objects representing simulated/created
+ * resources.
+ */
+ std::vector<SimulatorResourceServerSP> createResource(const std::string &configPath,
+ unsigned short count, SimulatorResourceServer::ResourceModelChangedCB callback);
+
+ /**
+ * This method is for obtaining a list of created resources.
+ *
+ * @param resourceType - Resource type. Empty value will fetch all resources.
+ * Default value is empty string.
+ *
+ * @return vector of SimulatorResourceServer shared objects representing simulated/created
+ */
+ std::vector<SimulatorResourceServerSP> getResources(const std::string &resourceType = "");
+
+ /**
+ * This method is for deleting/unregistering resource.
+ *
+ * @param resource - SimulatorResourceServer shared object.
+ *
+ */
+ void deleteResource(const SimulatorResourceServerSP &resource);
+
+ /**
+ * This method is for deleting multiple resources based on resource type.
+ *
+ * @param resourceType - Resource type. Empty value will delete all the resources.
+ * Default value is empty string.
+ *
+ */
+ void deleteResources(const std::string &resourceType = "");
+
+ private:
+ ResourceManager(): m_id(0) {}
+ ~ResourceManager() = default;
+ ResourceManager(const ResourceManager &) = delete;
+ ResourceManager &operator=(const ResourceManager &) = delete;
+ ResourceManager(const ResourceManager &&) = delete;
+ ResourceManager &operator=(const ResourceManager && ) = delete;
+
+ SimulatorResourceServerSP buildResource(const std::string &configPath,
+ SimulatorResourceServer::ResourceModelChangedCB callback);
+ std::string constructURI(const std::string &uri);
+
+ /*Member variables*/
+ int m_id;
+ SimulatorResourceCreator m_resourceCreator;
+ std::recursive_mutex m_lock;
+ std::map<std::string, std::map<std::string, SimulatorResourceServerSP>> m_resources;
+};
+
+#endif
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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_update_automation.h"
+#include "simulator_resource_server_impl.h"
+#include "simulator_exceptions.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define ATAG "ATTRIBUTE_AUTOMATION"
+#define RTAG "RESOURCE_AUTOMATION"
+
+#define SLEEP_FOR(X) if (X > 0) std::this_thread::sleep_for(std::chrono::milliseconds(X));
+
+AttributeUpdateAutomation::AttributeUpdateAutomation(int id, SimulatorResourceServer *resource,
+ const std::string &attrName, AutomationType type, int interval,
+ updateCompleteCallback callback, std::function<void (const int)> finishedCallback)
+ : m_resource(resource),
+ m_attrName(attrName),
+ m_type(type),
+ m_id(id),
+ m_stopRequested(false),
+ m_updateInterval(interval),
+ m_callback(callback),
+ m_finishedCallback(finishedCallback) {}
+
+void AttributeUpdateAutomation::start()
+{
+ // Check the validity of attribute
+ SimulatorResourceModel resModel = m_resource->getModel();
+ if (false == resModel.getAttribute(m_attrName, m_attribute))
+ {
+ OC_LOG_V(ERROR, ATAG, "Attribute:%s not present in resource!", m_attrName.c_str());
+ throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
+ }
+
+ if (m_updateInterval < 0)
+ {
+ m_updateInterval = m_attribute.getUpdateFrequencyTime();
+ if (0 > m_updateInterval)
+ m_updateInterval = 0;
+ }
+
+ m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
+}
+
+void AttributeUpdateAutomation::stop()
+{
+ m_stopRequested = true;
+ m_thread->join();
+}
+
+void AttributeUpdateAutomation::updateAttribute()
+{
+ do
+ {
+ try
+ {
+ setAttributeValue();
+ }
+ catch(SimulatorException &e)
+ {
+ break;
+ }
+ if (m_stopRequested)
+ break;
+ }
+ while (AutomationType::RECURRENT == m_type);
+
+ if (!m_stopRequested)
+ {
+ OC_LOG_V(DEBUG, ATAG, "Attribute:%s automation is completed!", m_attrName.c_str());
+ SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
+ }
+
+ // Notify application through callback
+ if (m_callback)
+ m_callback(m_resource->getURI(), m_id);
+
+ if (m_finishedCallback && !m_stopRequested)
+ m_finishedCallback(m_id);
+}
+
+void AttributeUpdateAutomation::setAttributeValue()
+{
+ if (0 == m_attribute.getValueType()) // For integer type values
+ {
+ int min;
+ int max;
+ SimulatorResourceServerImpl *resourceImpl;
+ resourceImpl = dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+ m_attribute.getRange(min, max);
+ for (int value = min; value <= max; value++)
+ {
+ if (m_stopRequested)
+ break;
+ m_resource->updateAttributeValue(m_attribute.getName(), value);
+ resourceImpl->resourceModified();
+ SLEEP_FOR(m_updateInterval);
+ }
+ }
+ else
+ {
+ SimulatorResourceServerImpl *resourceImpl;
+ resourceImpl = dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+ for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++)
+ {
+ if (m_stopRequested)
+ break;
+ m_resource->updateFromAllowedValues(m_attribute.getName(), index);
+ resourceImpl->resourceModified();
+ SLEEP_FOR(m_updateInterval);
+ }
+ }
+}
+
+ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorResourceServer *resource,
+ AutomationType type, int interval, updateCompleteCallback callback,
+ std::function<void (const int)> finishedCallback)
+ : m_resource(resource),
+ m_type(type),
+ m_id(id),
+ m_updateInterval(interval),
+ m_callback(callback),
+ m_finishedCallback(finishedCallback) {}
+
+void ResourceUpdateAutomation::start()
+{
+ m_resModel = m_resource->getModel();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
+ if (0 == attributes.size())
+ {
+ OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
+ throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
+ }
+
+ int id = 0;
+ for (auto & attribute : attributes)
+ {
+ AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
+ id, m_resource, attribute.first, m_type, m_updateInterval, nullptr,
+ std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1)));
+
+ m_attrUpdationList[id++] = attributeAutomation;
+ try
+ {
+ attributeAutomation->start();
+ }
+ catch (SimulatorException &e)
+ {
+ stop();
+ throw;
+ }
+ }
+}
+
+void ResourceUpdateAutomation::finished(int id)
+{
+ if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+ {
+ m_attrUpdationList.erase(m_attrUpdationList.find(id));
+ }
+
+ if (!m_attrUpdationList.size())
+ {
+ // Notify application through callback
+ if (m_callback)
+ m_callback(m_resource->getURI(), m_id);
+
+ if (m_finishedCallback)
+ m_finishedCallback(m_id);
+ }
+}
+
+void ResourceUpdateAutomation::stop()
+{
+ // Stop all the attributes updation
+ for (auto & attrAutomation : m_attrUpdationList)
+ {
+ (attrAutomation.second)->stop();
+ }
+
+ m_attrUpdationList.clear();
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef RESOURCE_UPDATE_AUTOMATION_H_
+#define RESOURCE_UPDATE_AUTOMATION_H_
+
+#include "simulator_resource_server.h"
+#include <thread>
+
+class AttributeUpdateAutomation
+{
+ public:
+ AttributeUpdateAutomation(int id, SimulatorResourceServer *resource,
+ const std::string &attrName, AutomationType type, int interval,
+ updateCompleteCallback callback,
+ std::function<void (const int)> finishedCallback);
+
+ void start();
+
+ void stop();
+
+ private:
+ void updateAttribute();
+ void setAttributeValue();
+
+ SimulatorResourceServer *m_resource;
+ std::string m_attrName;
+ AutomationType m_type;
+ int m_id;
+ std::thread *m_thread;
+ bool m_stopRequested;
+ int m_updateInterval;
+ SimulatorResourceModel::Attribute m_attribute;
+ updateCompleteCallback m_callback;
+ std::function<void (const int)> m_finishedCallback;
+};
+
+typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationSP;
+
+class ResourceUpdateAutomation
+{
+ public:
+ ResourceUpdateAutomation(int id, SimulatorResourceServer *resource,
+ AutomationType type, int interval,
+ updateCompleteCallback callback,
+ std::function<void (const int)> finishedCallback);
+
+ void start();
+
+ void stop();
+
+ void finished(int id);
+
+ private:
+ SimulatorResourceServer *m_resource;
+ AutomationType m_type;
+ int m_id;
+ std::thread *m_thread;
+ int m_updateInterval;
+ SimulatorResourceModel m_resModel;
+ std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
+ updateCompleteCallback m_callback;
+ std::function<void (const int)> m_finishedCallback;
+};
+
+typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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_update_automation_mngr.h"
+#include "simulator_exceptions.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "UPDATE_AUTOMATION_MNGR"
+
+UpdateAutomationMngr::UpdateAutomationMngr()
+ : m_id(0) {}
+
+int UpdateAutomationMngr::startResourceAutomation(SimulatorResourceServer *resource,
+ AutomationType type, int interval, updateCompleteCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ ResourceUpdateAutomationSP resourceAutomation(new ResourceUpdateAutomation(
+ m_id, resource, type, interval, callback,
+ std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
+
+ std::lock_guard<std::mutex> lock(m_lock);
+ resourceAutomation->start();
+
+ OC_LOG_V(DEBUG, TAG, "Resource automation successfully started [id: %d]", m_id);
+ SIM_LOG(ILogger::INFO, "Resource automation successfully started : " << m_id);
+
+ m_resourceUpdationList[m_id] = resourceAutomation;
+ return m_id++;
+}
+
+int UpdateAutomationMngr::startAttributeAutomation(SimulatorResourceServer *resource,
+ const std::string &attrName, AutomationType type, int interval,
+ updateCompleteCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
+ m_id, resource, attrName, type, interval, callback,
+ std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1)));
+
+ std::lock_guard<std::mutex> lock(m_lock);
+ attributeAutomation->start();
+
+ OC_LOG_V(DEBUG, TAG, "Attribute automation successfully started [name: %s, id: %d]",
+ attrName.c_str(), m_id);
+ SIM_LOG(ILogger::INFO, "Automation for " << attrName << " attribute has successfully started : " <<
+ m_id);
+
+ m_attrUpdationList[m_id] = attributeAutomation;
+ return m_id++;
+}
+
+std::vector<int> UpdateAutomationMngr::getResourceAutomationIds()
+{
+ std::vector<int> ids;
+ std::lock_guard<std::mutex> lock(m_lock);
+ for (auto & automation : m_resourceUpdationList)
+ ids.push_back(automation.first);
+
+ return ids;
+}
+
+std::vector<int> UpdateAutomationMngr::getAttributeAutomationIds()
+{
+ std::vector<int> ids;
+ std::lock_guard<std::mutex> lock(m_lock);
+ for (auto & automation : m_attrUpdationList)
+ ids.push_back(automation.first);
+
+ return ids;
+}
+
+void UpdateAutomationMngr::stop(int id)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
+ {
+ m_resourceUpdationList[id]->stop();
+ m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
+ }
+ else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+ {
+ m_attrUpdationList[id]->stop();
+ m_attrUpdationList.erase(m_attrUpdationList.find(id));
+ }
+}
+
+void UpdateAutomationMngr::stopAll()
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ std::for_each(m_resourceUpdationList.begin(),
+ m_resourceUpdationList.end(), [] (std::pair<int, ResourceUpdateAutomationSP> element)
+ {
+ element.second->stop();
+ });
+ m_resourceUpdationList.clear();
+
+ std::for_each(m_attrUpdationList.begin(),
+ m_attrUpdationList.end(), [] (std::pair<int, AttributeUpdateAutomationSP> element)
+ {
+ element.second->stop();
+ });
+
+ m_attrUpdationList.clear();
+}
+
+void UpdateAutomationMngr::automationCompleted(int id)
+{
+ std::lock_guard<std::mutex> lock(m_lock);
+ if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
+ {
+ m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
+ }
+ else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+ {
+ m_attrUpdationList.erase(m_attrUpdationList.find(id));
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+#define RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+
+#include "simulator_resource_server.h"
+#include "resource_update_automation.h"
+
+class UpdateAutomationMngr
+{
+ public:
+ UpdateAutomationMngr();
+
+ int startResourceAutomation(SimulatorResourceServer *resource,
+ AutomationType type, int interval, updateCompleteCallback callback);
+
+ int startAttributeAutomation(SimulatorResourceServer *resource,
+ const std::string &attrName, AutomationType type, int interval,
+ updateCompleteCallback callback);
+
+ std::vector<int> getResourceAutomationIds();
+
+ std::vector<int> getAttributeAutomationIds();
+
+ void stop(int id);
+
+ void stopAll();
+
+ private:
+ void automationCompleted(int id);
+
+ int m_id;
+ std::mutex m_lock;
+ std::map<int, ResourceUpdateAutomationSP> m_resourceUpdationList;
+ std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
+};
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_resource_creator.h"
+#include "simulator_logger.h"
+#include <RamlParser.h>
+#include <boost/lexical_cast.hpp>
+
+using namespace RAML;
+
+unsigned int SimulatorResourceCreator::s_id;
+SimulatorResourceServerImplSP SimulatorResourceCreator::createResource(
+ const std::string &configPath)
+{
+ RamlParser *ramlParser = new RamlParser(configPath);
+ RamlPtr raml = ramlParser->getRamlPtr();
+ for (auto resourceElement : raml->getResources())
+ {
+ SimulatorResourceServerImplSP resource(new SimulatorResourceServerImpl());
+ resource->setName(resourceElement.first);
+ resource->setURI(resourceElement.second->getResourceUri());
+
+ // TODO: Currently setting only baseline interface.
+ resource->setInterfaceType(OC::DEFAULT_INTERFACE);
+ // TODO: Need to modify based on the spec for observable property
+ resource->setObservable(true);
+
+ for (auto action : resourceElement.second->getActions())
+ {
+ for (auto response : action.second->getResponses())
+ {
+ for (auto bdy : response.second->getResponseBody())
+ {
+ auto resourceProperties = bdy.second->getSchema()->getProperties();
+
+ for ( auto property : resourceProperties->getProperties() )
+ {
+ std::string propName = property.second->getName();
+
+ if (propName == "rt")
+ {
+ resource->setResourceType(property.second->getValueString());
+ continue;
+ }
+
+ // Include more property names if required based on spec support.
+ if (propName == "if" || propName == "p" || propName == "n" || propName == "id")
+ continue;
+
+ SimulatorResourceModel::Attribute *attr = new SimulatorResourceModel::Attribute(propName);
+
+ int type = property.second->getValueType();
+ switch (type)
+ {
+ case 0: // Integer
+ {
+ int attributeValue = property.second->getValueInt();
+ attr->setValue(attributeValue);
+ }
+ break;
+
+ case 3: // String
+ {
+ std::string attributeValue = property.second->getValueString();
+ attr->setValue(attributeValue);
+ }
+ break;
+ }
+
+ attr->setUpdateFrequencyTime(property.second->getUpdateFrequencyTime());
+
+ int min = 0, max = 0, multipleof = 0;
+ property.second->getRange(min, max, multipleof);
+ attr->setRange(min, max);
+
+ if (property.second->getAllowedValuesSize() > 0)
+ attr->setAllowedValues(property.second->getAllowedValues());
+
+ resource->addAttribute(*attr);
+ }
+
+ resource->setURI(constructURI(resource->getURI()));
+ return resource;
+ }
+ }
+ }
+ }
+
+ return nullptr;
+}
+
+/**
+ * This method appends a unique key to the given URI to make the URI unique in simulator.
+ * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource
+ * and "/a/light/simulator/1" for the second resource and so on.
+ */
+std::string SimulatorResourceCreator::constructURI(const std::string &uri)
+{
+ std::ostringstream os;
+ os << uri;
+ if (!uri.empty() && '/' != uri[uri.length() - 1])
+ os << '/';
+ os << "simulator/" << s_id++;
+ return os.str();
+}
+
#ifndef SIMULATOR_RESOURCE_CREATOR_H_
#define SIMULATOR_RESOURCE_CREATOR_H_
-#include "simulator_resource_server.h"
+#include "simulator_resource_server_impl.h"
class SimulatorResourceCreator
{
public:
- /**
- * This is temporary method to get the light resource as parser
- * needs to implemented/integrated
- */
- SimulatorResourceServerPtr createResource(const std::string &configPath);
+ SimulatorResourceServerImplSP createResource(const std::string &configPath);
+
+ private:
+ std::string constructURI(const std::string &uri);
+ static unsigned int s_id;
};
-#endif
\ No newline at end of file
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_resource_server.h"
+
+SimulatorResourceServer::SimulatorResourceServer()
+{
+}
+
+std::string SimulatorResourceServer::getURI() const
+{
+ return m_uri;
+}
+
+std::string SimulatorResourceServer::getResourceType() const
+{
+ return m_resourceType;
+}
+
+std::string SimulatorResourceServer::getInterfaceType() const
+{
+ return m_interfaceType;
+}
+
+std::string SimulatorResourceServer::getName() const
+{
+ return m_name;
+}
+
+void SimulatorResourceServer::addAttribute(SimulatorResourceModel::Attribute &attribute)
+{
+ m_resModel.addAttribute(attribute);
+}
+
+void SimulatorResourceServer::setRange(const std::string &attrName, const int min, const int max)
+{
+ m_resModel.setRange(attrName, min, max);
+}
+
+SimulatorResourceModel SimulatorResourceServer::getModel() const
+{
+ return m_resModel;
+}
+
+void SimulatorResourceServer::updateFromAllowedValues(const std::string &attrName,
+ unsigned int index)
+{
+ m_resModel.updateAttributeFromAllowedValues(attrName, index);
+}
+
+void SimulatorResourceServer::removeAttribute(const std::string &attrName)
+{
+ m_resModel.removeAttribute(attrName);
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_resource_server_impl.h"
+#include "simulator_utils.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIM_RESOURCE_SERVER"
+
+SimulatorResourceServerImpl::SimulatorResourceServerImpl()
+ : m_resourceHandle(NULL)
+{
+ m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE);
+ m_interfaceType.assign(OC::DEFAULT_INTERFACE);
+}
+
+bool SimulatorResourceServerImpl::isObservable() const
+{
+ return (m_property & OC_OBSERVABLE);
+}
+
+void SimulatorResourceServerImpl::setURI(const std::string &uri)
+{
+ m_uri = uri;
+}
+
+void SimulatorResourceServerImpl::setResourceType(const std::string &resourceType)
+{
+ m_resourceType = resourceType;
+}
+
+void SimulatorResourceServerImpl::setInterfaceType(const std::string &interfaceType)
+{
+ m_interfaceType = interfaceType;
+}
+
+void SimulatorResourceServerImpl::setName(const std::string &name)
+{
+ m_name = name;
+}
+
+void SimulatorResourceServerImpl::setObservable(bool state)
+{
+ if (true == state)
+ m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+ else
+ m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+}
+
+int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
+ updateCompleteCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource!");
+ throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
+ }
+
+ return m_updateAutomationMgr.startResourceAutomation(this, type, -1, callback);
+}
+
+int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
+ AutomationType type,
+ updateCompleteCallback callback)
+{
+ if (!callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid callback!");
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ }
+
+ if (!m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource!");
+ throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
+ }
+
+ return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, -1, callback);
+}
+
+std::vector<int> SimulatorResourceServerImpl::getResourceAutomationIds()
+{
+ return m_updateAutomationMgr.getResourceAutomationIds();
+}
+
+std::vector<int> SimulatorResourceServerImpl::getAttributeAutomationIds()
+{
+ return m_updateAutomationMgr.getAttributeAutomationIds();
+}
+
+void SimulatorResourceServerImpl::stopUpdateAutomation(const int id)
+{
+ m_updateAutomationMgr.stop(id);
+}
+
+void SimulatorResourceServerImpl::setModelChangeCallback(ResourceModelChangedCB callback)
+{
+ m_callback = callback;
+}
+
+void SimulatorResourceServerImpl::setObserverCallback(ObserverCB callback)
+{
+ m_observeCallback = callback;
+}
+
+std::vector<ObserverInfo> SimulatorResourceServerImpl::getObserversList()
+{
+ return m_observersList;
+}
+
+void SimulatorResourceServerImpl::notify(uint8_t id)
+{
+ if (!m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource!");
+ throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
+ }
+
+ std::shared_ptr<OC::OCResourceResponse> resourceResponse =
+ {std::make_shared<OC::OCResourceResponse>()};
+
+ resourceResponse->setErrorCode(200);
+ resourceResponse->setResponseResult(OC_EH_OK);
+ resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
+
+ OC::ObservationIds observers;
+ observers.push_back(id);
+
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to observer with id " << id);
+
+ typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
+ const std::shared_ptr<OC::OCResourceResponse>);
+
+ invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
+ m_resourceHandle,
+ observers,
+ resourceResponse);
+}
+
+void SimulatorResourceServerImpl::notifyAll()
+{
+ if (!m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource!");
+ throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
+ }
+
+ if (!m_observersList.size())
+ {
+ OC_LOG(ERROR, TAG, "Observers list is empty!");
+ return;
+ }
+
+ std::shared_ptr<OC::OCResourceResponse> resourceResponse =
+ {std::make_shared<OC::OCResourceResponse>()};
+
+ resourceResponse->setErrorCode(200);
+ resourceResponse->setResponseResult(OC_EH_OK);
+ resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
+
+ OC::ObservationIds observers;
+ for (auto & observer : m_observersList)
+ observers.push_back(observer.id);
+
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to all observers");
+
+ typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
+ const std::shared_ptr<OC::OCResourceResponse>);
+
+ invokeocplatform(static_cast<NotifyListOfObservers>(OC::OCPlatform::notifyListOfObservers),
+ m_resourceHandle,
+ observers,
+ resourceResponse);
+}
+
+void SimulatorResourceServerImpl::start()
+{
+ if (m_uri.empty() || m_resourceType.empty() ||
+ m_interfaceType.empty() || m_name.empty() || !m_callback)
+ {
+ OC_LOG(ERROR, TAG, "Invalid data found to register the resource!");
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid data found to register the resource!");
+ }
+
+ if (m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Resource already registered!");
+ throw SimulatorException(SIMULATOR_ERROR, "Resource already registered!");
+ }
+
+ typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &, const std::string &,
+ const std::string &, OC::EntityHandler, uint8_t);
+
+ invokeocplatform(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
+ m_resourceHandle, m_uri, m_resourceType, m_interfaceType,
+ std::bind(&SimulatorResourceServerImpl::entityHandler,
+ this, std::placeholders::_1), m_property);
+}
+
+void SimulatorResourceServerImpl::stop()
+{
+ if (!m_resourceHandle)
+ {
+ OC_LOG(ERROR, TAG, "Invalid resource!");
+ throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
+ }
+
+ typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &);
+
+ invokeocplatform(static_cast<UnregisterResource>(OC::OCPlatform::unregisterResource),
+ m_resourceHandle);
+
+ m_resourceHandle = nullptr;
+}
+
+OC::OCRepresentation SimulatorResourceServerImpl::getOCRepresentation()
+{
+ return m_resModel.getOCRepresentation();
+}
+
+bool SimulatorResourceServerImpl::modifyResourceModel(OC::OCRepresentation &ocRep)
+{
+ bool status = m_resModel.update(ocRep);
+ if (true == status)
+ {
+ resourceModified();
+ }
+ return status;
+}
+
+void SimulatorResourceServerImpl::resourceModified()
+{
+ if (!m_resourceHandle)
+ {
+ return;
+ }
+
+ // Notify all the subscribers
+ notifyAll();
+
+ // Notify the application callback
+ if (m_callback)
+ {
+ m_callback(m_uri, m_resModel);
+ }
+}
+
+OCEntityHandlerResult SimulatorResourceServerImpl::entityHandler(
+ std::shared_ptr<OC::OCResourceRequest>
+ request)
+{
+ OCEntityHandlerResult errCode = OC_EH_ERROR;
+ if (!request)
+ {
+ return OC_EH_ERROR;
+ }
+
+ if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
+ {
+ auto response = std::make_shared<OC::OCResourceResponse>();
+ response->setRequestHandle(request->getRequestHandle());
+ response->setResourceHandle(request->getResourceHandle());
+
+ if ("GET" == request->getRequestType())
+ {
+ OC::OCRepresentation rep = request->getResourceRepresentation();
+ std::string payload = getPayloadString(rep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] GET request received. \n**Payload details**" << payload)
+
+ response->setErrorCode(200);
+ response->setResponseResult(OC_EH_OK);
+ response->setResourceRepresentation(getOCRepresentation());
+
+ if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
+ {
+ errCode = OC_EH_OK;
+ }
+ }
+ else if ("PUT" == request->getRequestType())
+ {
+ OC::OCRepresentation rep = request->getResourceRepresentation();
+ std::string payload = getPayloadString(rep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] PUT request received. \n**Payload details**" << payload)
+
+ if (true == modifyResourceModel(rep))
+ {
+ response->setErrorCode(200);
+ response->setResponseResult(OC_EH_OK);
+ response->setResourceRepresentation(getOCRepresentation());
+ }
+ else
+ {
+ response->setErrorCode(400);
+ response->setResponseResult(OC_EH_ERROR);
+ }
+
+ if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
+ {
+ errCode = OC_EH_OK;
+ }
+ }
+ else if ("POST" == request->getRequestType())
+ {
+ OC::OCRepresentation rep = request->getResourceRepresentation();
+ std::string payload = getPayloadString(rep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] POST request received. \n**Payload details**" << payload)
+
+ if (true == modifyResourceModel(rep))
+ {
+ response->setErrorCode(200);
+ response->setResponseResult(OC_EH_OK);
+ response->setResourceRepresentation(getOCRepresentation());
+ }
+ else
+ {
+ response->setErrorCode(400);
+ response->setResponseResult(OC_EH_ERROR);
+ }
+
+ if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
+ {
+ errCode = OC_EH_OK;
+ }
+ }
+ else if ("DELETE" == request->getRequestType())
+ {
+ OC::OCRepresentation rep = request->getResourceRepresentation();
+ std::string payload = getPayloadString(rep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] DELETE request received. \n**Payload details**" << payload)
+
+ // DELETE request handling not supported right now
+ response->setErrorCode(400);
+ response->setResponseResult(OC_EH_ERROR);
+ if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
+ {
+ errCode = OC_EH_OK;
+ }
+ }
+ else
+ {
+ OC::OCRepresentation rep = request->getResourceRepresentation();
+ std::string payload = getPayloadString(rep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] UNKNOWN type request received. \n**Payload details**" << payload)
+
+ response->setResponseResult(OC_EH_ERROR);
+ OC::OCPlatform::sendResponse(response);
+ errCode = OC_EH_ERROR;
+ }
+ }
+
+ if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
+ {
+ if (false == isObservable())
+ {
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received")
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state")
+ return OC_EH_ERROR;
+ }
+
+ OC::ObservationInfo observationInfo = request->getObservationInfo();
+ if (OC::ObserveAction::ObserveRegister == observationInfo.action)
+ {
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received");
+
+ ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port};
+ m_observersList.push_back(info);
+
+ //Inform about addition of observer
+ if (m_observeCallback)
+ {
+ m_observeCallback(m_uri, ObservationStatus::OBSERVE_REGISTER, info);
+ }
+ }
+ else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
+ {
+ SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
+
+ ObserverInfo info;
+ for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++)
+ {
+ if ((info = *iter), info.id == observationInfo.obsId)
+ {
+ m_observersList.erase(iter);
+ break;
+ }
+ }
+
+ // Inform about cancellation of observer
+ if (m_observeCallback)
+ {
+ m_observeCallback(m_uri, ObservationStatus::OBSERVE_UNREGISTER, info);
+ }
+ }
+ errCode = OC_EH_OK;
+ }
+
+ return errCode;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_SERVER_IMPL_H_
+#define SIMULATOR_RESOURCE_SERVER_IMPL_H_
+
+#include "simulator_resource_server.h"
+#include "resource_update_automation_mngr.h"
+
+class SimulatorResourceServerImpl : public SimulatorResourceServer
+{
+ public:
+ SimulatorResourceServerImpl();
+
+ void setURI(const std::string &uri);
+
+ void setResourceType(const std::string &resourceType);
+
+ void setInterfaceType(const std::string &interfaceType);
+
+ void setName(const std::string &name);
+
+ void setObservable(bool state);
+
+ bool isObservable() const;
+
+ int startUpdateAutomation(AutomationType type,
+ updateCompleteCallback callback);
+
+ int startUpdateAutomation(const std::string &attrName, AutomationType type,
+ updateCompleteCallback callback);
+
+ std::vector<int> getResourceAutomationIds();
+
+ std::vector<int> getAttributeAutomationIds();
+
+ void stopUpdateAutomation(const int id);
+
+ void setModelChangeCallback(ResourceModelChangedCB callback);
+
+ void setObserverCallback(ObserverCB callback);
+
+ std::vector<ObserverInfo> getObserversList();
+
+ void notify(uint8_t id);
+
+ void notifyAll();
+
+ void start();
+
+ void stop();
+
+ void resourceModified();
+
+ private:
+ OC::OCRepresentation getOCRepresentation();
+ bool modifyResourceModel(OC::OCRepresentation &ocRep);
+ OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
+
+ ResourceModelChangedCB m_callback;
+ ObserverCB m_observeCallback;
+ UpdateAutomationMngr m_updateAutomationMgr;
+ std::vector<ObserverInfo> m_observersList;
+
+ OCResourceProperty m_property;
+ OCResourceHandle m_resourceHandle;
+};
+
+typedef std::shared_ptr<SimulatorResourceServerImpl> SimulatorResourceServerImplSP;
+
+#endif
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "simulator_attribute_automation.h"
-#include "simulator_resource_server.h"
-#include <thread>
-
-#define SLEEP_FOR(X) if (X > 0) std::this_thread::sleep_for(std::chrono::milliseconds(X));
-
-AttributeUpdateAutomation::AttributeUpdateAutomation(
- SimulatorResourceServer *resource, const std::string &attrName, updateCompleteCallback callback,
- int automationId, std::function<void (const int)> finishedCallback, AutomationType type,
- int interval)
- : m_resource(resource),
- m_attrName(attrName),
- m_type(type),
- m_id(automationId),
- m_status(false),
- m_stopRequested(false),
- m_updateInterval(interval),
- m_callback(callback),
- m_finishedCallback(finishedCallback) {}
-
-SimulatorResult AttributeUpdateAutomation::start()
-{
- if (true == m_status)
- return SIMULATOR_AUTOMATION_ALREADY_STARTED;
-
- // Check the validity of attribute
- SimulatorResourceModel resModel = m_resource->getModel();
- if (false == resModel.getAttribute(m_attrName, m_attribute))
- return SIMULATOR_ERROR;
-
- if (m_updateInterval < 0)
- {
- m_updateInterval = m_attribute.getUpdateFrequencyTime();
- if (0 > m_updateInterval)
- m_updateInterval = 0;
- }
-
- m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
- m_status = true;
-
- return SIMULATOR_SUCCESS;
-}
-
-void AttributeUpdateAutomation::stop()
-{
- m_stopRequested = true;
- m_thread->join();
- m_status = false;
-}
-
-void AttributeUpdateAutomation::updateAttribute()
-{
- do
- {
- setAttributeValue();
- if (m_stopRequested)
- break;
- }
- while (AutomationType::RECURRENT == m_type);
-
- m_status = false;
-
- // Notify application through callback
- if (m_callback)
- m_callback(m_resource->getURI(), m_id);
- if (m_finishedCallback && !m_stopRequested)
- m_finishedCallback(m_id);
-}
-
-void AttributeUpdateAutomation::setAttributeValue()
-{
- if (0 == m_attribute.getValueType()) // For integer type values
- {
- int min;
- int max;
- m_attribute.getRange(min, max);
- for (int value = min; value <= max; value++)
- {
- if (m_stopRequested)
- break;
- m_resource->updateAttribute(m_attribute.getName(), value);
- SLEEP_FOR(m_updateInterval);
- }
- }
- else
- {
- for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++)
- {
- if (m_stopRequested)
- break;
- m_resource->updateAttributeFromAllowedValues(m_attribute.getName(), index);
- SLEEP_FOR(m_updateInterval);
- }
- }
-}
-
-
-ResourceUpdateAutomation::ResourceUpdateAutomation(
- SimulatorResourceServer *resource, updateCompleteCallback callback,
- int automationId, std::function<void (const int)> finishedCallback, AutomationType type,
- int interval)
- : m_resource(resource),
- m_type(type),
- m_id(automationId),
- m_status(false),
- m_updateInterval(interval),
- m_callback(callback),
- m_finishedCallback(finishedCallback) {}
-
-SimulatorResult ResourceUpdateAutomation::start()
-{
- if (true == m_status)
- return SIMULATOR_AUTOMATION_ALREADY_STARTED;
-
- m_resModel = m_resource->getModel();
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
- if (0 == attributes.size())
- {
- m_status = false;
- return SIMULATOR_ERROR;
- }
-
- int id = 0;
- for (auto & attribute : attributes)
- {
- AttributeUpdateAutomationPtr attributeAutomation = std::make_shared<AttributeUpdateAutomation>
- (m_resource, attribute.first, nullptr, id,
- std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1),
- m_type, m_updateInterval);
- m_attrUpdationList[id++] = attributeAutomation;
- if (SIMULATOR_SUCCESS != attributeAutomation->start())
- {
- m_status = false;
- stop();
- return SIMULATOR_ERROR;
- }
- }
-
- m_status = true;
- return SIMULATOR_SUCCESS;
-}
-
-void ResourceUpdateAutomation::finished(int id)
-{
- if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
- {
- m_attrUpdationList.erase(m_attrUpdationList.find(id));
- }
-
- if (!m_attrUpdationList.size())
- {
- // Notify application through callback
- if (m_callback)
- m_callback(m_resource->getURI(), m_id);
- if (m_finishedCallback)
- m_finishedCallback(m_id);
- }
-}
-void ResourceUpdateAutomation::stop()
-{
- // Stop all the attributes updation
- for (auto & attrAutomation : m_attrUpdationList)
- {
- (attrAutomation.second)->stop();
- }
-
- m_attrUpdationList.clear();
- m_status = false;
-}
-
-UpdateAutomationManager::UpdateAutomationManager()
- : m_automationId(0) {}
-
-SimulatorResult UpdateAutomationManager::startResourceAutomation(SimulatorResourceServer *resource,
- int &id, updateCompleteCallback callback, AutomationType type, int interval)
-{
- std::lock_guard<std::mutex> lock(m_mutex);
-
- ResourceUpdateAutomationPtr resourceAutomation(new ResourceUpdateAutomation(
- resource, callback, m_automationId,
- std::bind(&UpdateAutomationManager::automationFinished, this, std::placeholders::_1),
- type, interval));
- SimulatorResult result = resourceAutomation->start();
- if (SIMULATOR_SUCCESS != result)
- {
- id = -1;
- return result;
- }
-
- m_resourceUpdationList[m_automationId] = resourceAutomation;
- id = m_automationId++;
- return result;
-}
-
-SimulatorResult UpdateAutomationManager::startAttributeAutomation(SimulatorResourceServer *resource,
- const std::string &attrName, int &id, updateCompleteCallback callback, AutomationType type,
- int interval)
-{
- std::lock_guard<std::mutex> lock(m_mutex);
-
- AttributeUpdateAutomationPtr attributeAutomation(new AttributeUpdateAutomation(
- resource, attrName, callback, m_automationId,
- std::bind(&UpdateAutomationManager::automationFinished, this, std::placeholders::_1),
- type, interval));
- SimulatorResult result = attributeAutomation->start();
- if (SIMULATOR_SUCCESS != result)
- {
- id = -1;
- return result;
- }
-
- m_attrUpdationList[m_automationId] = attributeAutomation;
- id = m_automationId++;
- return result;
-}
-
-std::vector<int> UpdateAutomationManager::getResourceAutomationIds()
-{
- std::vector<int> ids;
- std::lock_guard<std::mutex> lock(m_mutex);
- for (auto & automation : m_resourceUpdationList)
- ids.push_back(automation.first);
-
- return ids;
-}
-
-std::vector<int> UpdateAutomationManager::getAttributeAutomationIds()
-{
- std::vector<int> ids;
- std::lock_guard<std::mutex> lock(m_mutex);
- for (auto & automation : m_attrUpdationList)
- ids.push_back(automation.first);
-
- return ids;
-}
-
-void UpdateAutomationManager::stop(int automationId)
-{
- std::lock_guard<std::mutex> lock(m_mutex);
- if (m_resourceUpdationList.end() != m_resourceUpdationList.find(automationId))
- {
- m_resourceUpdationList[automationId]->stop();
- m_resourceUpdationList.erase(m_resourceUpdationList.find(automationId));
- }
- else if (m_attrUpdationList.end() != m_attrUpdationList.find(automationId))
- {
- m_attrUpdationList[automationId]->stop();
- m_attrUpdationList.erase(m_attrUpdationList.find(automationId));
- }
-}
-
-void UpdateAutomationManager::stopAll()
-{
- std::lock_guard<std::mutex> lock(m_mutex);
- std::for_each(m_resourceUpdationList.begin(),
- m_resourceUpdationList.end(), [] (std::pair<int, ResourceUpdateAutomationPtr> element)
- {
- element.second->stop();
- });
- m_resourceUpdationList.clear();
-
- std::for_each(m_attrUpdationList.begin(),
- m_attrUpdationList.end(), [] (std::pair<int, AttributeUpdateAutomationPtr> element)
- {
- element.second->stop();
- });
- m_attrUpdationList.clear();
-}
-
-void UpdateAutomationManager::automationFinished(int id)
-{
- std::lock_guard<std::mutex> lock(m_mutex);
- if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
- {
- m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
- }
- else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
- {
- m_attrUpdationList.erase(m_attrUpdationList.find(id));
- }
-}
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-#ifndef SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
-#define SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
-
-#include "simulator_resource_model.h"
-#include "simulator_error_codes.h"
-
-class SimulatorResourceServer;
-
-enum class AutomationType
-{
- NORMAL,
- RECURRENT
-};
-
-typedef std::function<void (const std::string &, const int)> updateCompleteCallback;
-
-class AttributeUpdateAutomation
-{
- public:
- AttributeUpdateAutomation(SimulatorResourceServer *resource,
- const std::string &attrName, updateCompleteCallback callback, int automationId,
- std::function<void (const int)> finishedCallback, AutomationType type = AutomationType::NORMAL,
- int interval = -1);
- SimulatorResult start();
- void stop();
-
- private:
- void updateAttribute();
- void setAttributeValue();
-
- SimulatorResourceServer *m_resource;
- std::string m_attrName;
- AutomationType m_type;
- int m_id;
- bool m_status;
- std::thread *m_thread;
- bool m_stopRequested;
- int m_updateInterval;
- SimulatorResourceModel::Attribute m_attribute;
- updateCompleteCallback m_callback;
- std::function<void (const int)> m_finishedCallback;
-};
-
-typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationPtr;
-
-class ResourceUpdateAutomation
-{
- public:
- ResourceUpdateAutomation(SimulatorResourceServer *resource, updateCompleteCallback callback,
- int automationId, std::function<void (const int)> finishedCallback,
- AutomationType type = AutomationType::NORMAL, int interval = -1);
- SimulatorResult start();
- void stop();
- void finished(int id);
-
- private:
- void updateAttribute();
- void setAttributeValue();
-
- SimulatorResourceServer *m_resource;
- AutomationType m_type;
- int m_id;
- bool m_status;
- std::thread *m_thread;
- int m_updateInterval;
- SimulatorResourceModel m_resModel;
- std::map<int, AttributeUpdateAutomationPtr> m_attrUpdationList;
- updateCompleteCallback m_callback;
- std::function<void (const int)> m_finishedCallback;
-};
-
-typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationPtr;
-
-class UpdateAutomationManager
-{
- public:
- UpdateAutomationManager();
- SimulatorResult startResourceAutomation(SimulatorResourceServer *resource,
- int &id, updateCompleteCallback callback,
- AutomationType type = AutomationType::NORMAL, int interval = -1);
- SimulatorResult startAttributeAutomation(SimulatorResourceServer *resource,
- const std::string &attrName, int &id, updateCompleteCallback callback,
- AutomationType type = AutomationType::NORMAL, int interval = -1);
- std::vector<int> getResourceAutomationIds();
- std::vector<int> getAttributeAutomationIds();
- void stop(int automationId);
- void stopAll();
- void automationFinished(int id);
-
- private:
- std::map<int, ResourceUpdateAutomationPtr> m_resourceUpdationList;
- std::map<int, AttributeUpdateAutomationPtr> m_attrUpdationList;
- int m_automationId;
- std::mutex m_mutex;
-};
-
-typedef std::shared_ptr<UpdateAutomationManager> UpdateAutomationManagerPtr;
-
-#endif //SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "simulator_client.h"
-#include "simulator_logger.h"
-
-SimulatorClient *SimulatorClient::getInstance()
-{
- static SimulatorClient s_instance;
- return &s_instance;
-}
-
-SimulatorResult SimulatorClient::findResource(const std::string &resourceType,
- ResourceFindCallback callback)
-{
- // Construct the request query for discovery
- std::string query = OC_MULTICAST_DISCOVERY_URI;
- query.append("?rt=");
- query.append(resourceType);
-
- OCStackResult result = OC::OCPlatform::findResource("", query,
- CT_DEFAULT,
- std::bind(&SimulatorClient::onResourceFound, this,
- std::placeholders::_1, callback));
-
- if (OC_STACK_OK != result)
- {
- SIM_LOG(ILogger::ERROR, "Failed to find the resource!");
- return SIMULATOR_ERROR;
- }
-
- return SIMULATOR_SUCCESS;
-}
-
-std::vector<SimulatorRemoteResourcePtr> SimulatorClient::getFoundResources(
- const std::string &resourceType)
-{
- std::lock_guard<std::recursive_mutex> lock(m_resourceListMutex);
-
- std::map<std::string, SimulatorRemoteResourcePtr> tempList;
- for (auto resourceTableEntry : m_resourceList)
- {
- if (resourceType.compare(resourceTableEntry.first))
- {
- tempList = resourceTableEntry.second;
- break;
- }
- else
- {
- for (auto resourceEntry : resourceTableEntry.second)
- {
- tempList[resourceEntry.first] = resourceEntry.second;
- }
- }
- }
-
- // Convert map to vector
- std::vector<SimulatorRemoteResourcePtr> resourceList;
- for (auto & resource : tempList)
- resourceList.push_back(resource.second);
-
- return resourceList;
-}
-
-void SimulatorClient::onResourceFound(std::shared_ptr<OC::OCResource> resource,
- ResourceFindCallback callback)
-{
- if (nullptr == resource)
- {
- return;
- }
-
- std::string serverId = resource->sid();
-
- // Construct SimulatorRemoteResource
- SimulatorRemoteResourcePtr simulatorResource(new SimulatorRemoteResource(resource));
-
- // Add the resource to list
- for (auto & resourceType : resource->getResourceTypes())
- addResourceToList(resourceType, serverId, simulatorResource);
-
- callback(simulatorResource);
-}
-
-void SimulatorClient::addResourceToList(const std::string &resourceType, const std::string &sid,
- SimulatorRemoteResourcePtr &resource)
-{
- std::lock_guard<std::recursive_mutex> lock(m_resourceListMutex);
-
- if (!resourceType.empty() && !sid.empty() && nullptr != resource)
- {
- auto resourceTableEntry = m_resourceList.find(resourceType);
- if (m_resourceList.end() != resourceTableEntry)
- {
- auto resourceEntry = resourceTableEntry->second.find(sid);
- if (resourceTableEntry->second.end() != resourceEntry)
- {
- return;
- }
- }
-
- m_resourceList[resourceType].insert(std::pair<std::string, SimulatorRemoteResourcePtr>(sid,
- resource));
- }
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-/**
- * @file simulator_client.h
- *
- * @brief This file provides a class for realizing simulator client functionality.
- *
- */
-
-#ifndef SIMULATOR_CLIENT_H_
-#define SIMULATOR_CLIENT_H_
-
-#include "simulator_remote_resource.h"
-#include "simulator_error_codes.h"
-
-/**
- * @class SimulatorClient
- * @brief This class provides a set of functions for discovering the resources currently running on the servers.
- */
-class SimulatorClient
-{
- public:
-
- /**
- * API for getting singleton instance of SimulatorClient class.
- *
- * @return Instance of SimulatorClient class.
- *
- */
- static SimulatorClient *getInstance(void);
-
- /**
- * API for discovering resources of a particular resource type.
- * Callback is called when a resource is found.
- *
- * @param resourceType - required resource type
- * @param callback - Returns SimulatorRemoteResource.
- *
- * @return SimulatorResult - return value of this API.
- * It returns SIMULATOR_SUCCESS if success.
- *
- * NOTE: SimulatorResult is defined in simulator_error_codes.h.
- */
- SimulatorResult findResource(const std::string &resourceType, ResourceFindCallback callback);
-
- /**
- * API for getting list of already found resources.
- *
- * @param resourceType - resource type
- *
- * @return List of SimulatorRemoteResource
- *
- */
- std::vector<SimulatorRemoteResourcePtr> getFoundResources(
- const std::string &resourceType = "");
-
- private:
-
- SimulatorClient() = default;
- ~SimulatorClient() = default;
-
- void onResourceFound(std::shared_ptr<OC::OCResource> resource, ResourceFindCallback callback);
- void addResourceToList(const std::string &resourceType, const std::string &sid,
- SimulatorRemoteResourcePtr &resource);
-
- std::recursive_mutex m_resourceListMutex;
- std::map<std::string, std::map<std::string, SimulatorRemoteResourcePtr>> m_resourceList;
-};
-
-#endif //SIMULATOR_CLIENT_H_
-
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_device_info.h"
+
+DeviceInfo::DeviceInfo(const std::string &name, const std::string &id,
+ const std::string &specVersion, const std::string &dmv)
+ : m_name(name), m_id(id), m_specVersion(specVersion), m_DMV(dmv) {}
+
+std::string DeviceInfo::getName() const
+{
+ return m_name;
+}
+
+std::string DeviceInfo::getID() const
+{
+ return m_id;
+}
+
+std::string DeviceInfo::getSpecVersion() const
+{
+ return m_specVersion;
+}
+
+std::string DeviceInfo::getDataModelVersion() const
+{
+ return m_DMV;
+}
#include "simulator_manager.h"
#include "resource_manager.h"
#include "simulator_client.h"
-
-using namespace OC;
+#include "simulator_utils.h"
SimulatorManager *SimulatorManager::getInstance()
{
OC::OCPlatform::Configure(conf);
}
-SimulatorResourceServerPtr SimulatorManager::createResource(const std::string &configPath,
- SimulatorResourceServer::ResourceModelChangedCB callback)
+std::shared_ptr<SimulatorResourceServer> SimulatorManager::createResource(
+ const std::string &configPath,
+ SimulatorResourceServer::ResourceModelChangedCB callback)
{
return ResourceManager::getInstance()->createResource(configPath, callback);
}
-std::vector<SimulatorResourceServerPtr> SimulatorManager::createResource(
- const std::string &configPath,
- const int count, SimulatorResourceServer::ResourceModelChangedCB callback)
+std::vector<std::shared_ptr<SimulatorResourceServer>> SimulatorManager::createResource(
+ const std::string &configPath, unsigned short count,
+ SimulatorResourceServer::ResourceModelChangedCB callback)
{
return ResourceManager::getInstance()->createResource(configPath, count, callback);
}
-std::vector<SimulatorResourceServerPtr> SimulatorManager::getResources(
- const std::string &resourceType)
+std::vector<std::shared_ptr<SimulatorResourceServer>> SimulatorManager::getResources(
+ const std::string &resourceType)
{
return ResourceManager::getInstance()->getResources(resourceType);
}
-SimulatorResult SimulatorManager::deleteResource(SimulatorResourceServerPtr &resource)
+void SimulatorManager::deleteResource(
+ const std::shared_ptr<SimulatorResourceServer> &resource)
{
- return ResourceManager::getInstance()->deleteResource(resource);
+ ResourceManager::getInstance()->deleteResource(resource);
}
-SimulatorResult SimulatorManager::deleteResources(const std::string &resourceType)
+void SimulatorManager::deleteResources(const std::string &resourceType)
{
- return ResourceManager::getInstance()->deleteResources(resourceType);
+ ResourceManager::getInstance()->deleteResources(resourceType);
}
-SimulatorResult SimulatorManager::findResource(const std::string &resourceType,
- ResourceFindCallback callback)
+void SimulatorManager::findResources(ResourceFindCallback callback)
{
- return SimulatorClient::getInstance()->findResource(resourceType, callback);
+ SimulatorClient::getInstance()->findResources(callback);
}
-std::vector<SimulatorRemoteResourcePtr> SimulatorManager::getFoundResources(
- const std::string resourceType)
+void SimulatorManager::findResources(const std::string &resourceType,
+ ResourceFindCallback callback)
{
- return SimulatorClient::getInstance()->getFoundResources(resourceType);
+ SimulatorClient::getInstance()->findResources(resourceType, callback);
+}
+
+void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
+{
+ if (!callback)
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+ OC::FindDeviceCallback deviceCallback = [this, callback](const OC::OCRepresentation & rep)
+ {
+ std::string deviceName = rep.getValue<std::string>("n");
+ std::string deviceID = rep.getValue<std::string>("di");
+ std::string deviceSpecVersion = rep.getValue<std::string>("lcv");
+ std::string deviceDMV = rep.getValue<std::string>("dmv");
+
+ DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
+ callback(deviceInfo);
+ };
+
+ std::ostringstream uri;
+ uri << OC_MULTICAST_PREFIX << OC_RSRVD_DEVICE_URI;
+
+ typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &,
+ OCConnectivityType, OC::FindDeviceCallback);
+
+ invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), "",
+ uri.str(),
+ CT_DEFAULT,
+ deviceCallback);
+}
+
+void SimulatorManager::setDeviceInfo(const std::string &deviceName)
+{
+ if (deviceName.empty())
+ throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Device name is empty!");
+
+
+ typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo);
+
+ OCDeviceInfo ocDeviceInfo;
+ ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str());
+ invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo),
+ ocDeviceInfo);
+}
+
+void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
+{
+ if (!callback)
+ throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+ OC::FindPlatformCallback platformCallback = [this, callback](const OC::OCRepresentation & rep)
+ {
+ PlatformInfo platformInfo;
+ platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
+ platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv"));
+ platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn"));
+ platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml"));
+ platformInfo.setModelNumber(rep.getValue<std::string>("mnmo"));
+ platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt"));
+ platformInfo.setOSVersion(rep.getValue<std::string>("mnos"));
+ platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw"));
+ platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv"));
+ platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl"));
+ platformInfo.setSystemTime(rep.getValue<std::string>("st"));
+
+ callback(platformInfo);
+ };
+
+ std::ostringstream uri;
+ uri << OC_MULTICAST_PREFIX << OC_RSRVD_PLATFORM_URI;
+
+ typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &,
+ OCConnectivityType, OC::FindPlatformCallback);
+
+ invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), "",
+ uri.str(),
+ CT_DEFAULT,
+ platformCallback);
+}
+
+void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo)
+{
+ OCPlatformInfo ocPlatformInfo;
+ ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str());
+ ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str());
+ ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str());
+ ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str());
+ ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str());
+ ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str());
+ ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str());
+ ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str());
+ ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str());
+ ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str());
+ ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str());
+
+ typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo);
+ invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo),
+ ocPlatformInfo);
}
-void SimulatorManager::setLogger(std::shared_ptr<ILogger> logger)
+void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger)
{
simLogger().setCustomTarget(logger);
}
return simLogger().setDefaultConsoleTarget();
}
-bool SimulatorManager::setDefaultFileLogger(std::string &path)
+bool SimulatorManager::setDefaultFileLogger(const std::string &path)
{
return simLogger().setDefaultFileTarget(path);
}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "simulator_platform_info.h"
+
+std::string PlatformInfo::getPlatformID() const
+{
+ return m_platformID;
+}
+
+std::string PlatformInfo::getPlatformVersion() const
+{
+ return m_platformVersion;
+}
+
+std::string PlatformInfo::getManufacturerName() const
+{
+ return m_manufacturerName;
+}
+
+std::string PlatformInfo::getManufacturerUrl() const
+{
+ return m_manufacturerUrl;
+}
+
+std::string PlatformInfo::getModelNumber() const
+{
+ return m_modelNumber;
+}
+
+std::string PlatformInfo::getDateOfManfacture() const
+{
+ return m_dateOfManufacture;
+}
+
+std::string PlatformInfo::getOSVersion() const
+{
+ return m_operationSystemVersion;
+}
+
+std::string PlatformInfo::getHardwareVersion() const
+{
+ return m_hardwareVersion;
+}
+
+std::string PlatformInfo::getFirmwareVersion() const
+{
+ return m_firmwareVersion;
+}
+
+std::string PlatformInfo::getSupportUrl() const
+{
+ return m_supportUrl;
+}
+
+std::string PlatformInfo::getSystemTime() const
+{
+ return m_systemTime;
+}
+
+void PlatformInfo::setPlatformID(const std::string &platformId)
+{
+ m_platformID = platformId;
+}
+
+void PlatformInfo::setPlatformVersion(const std::string &platformVersion)
+{
+ m_platformVersion = platformVersion;
+}
+
+void PlatformInfo::setManufacturerName(const std::string &manufacturerName)
+{
+ m_manufacturerName = manufacturerName;
+}
+
+void PlatformInfo::setManufacturerUrl(const std::string &manufacturerUrl)
+{
+ m_manufacturerUrl = manufacturerUrl;
+}
+
+void PlatformInfo::setModelNumber(const std::string &modelNumber)
+{
+ m_modelNumber = modelNumber;
+}
+
+void PlatformInfo::setDateOfManfacture(const std::string &dateOfManufacture)
+{
+ m_dateOfManufacture = dateOfManufacture;
+}
+
+void PlatformInfo::setOSVersion(const std::string &osVersion)
+{
+ m_operationSystemVersion = osVersion;
+}
+
+void PlatformInfo::setHardwareVersion(const std::string &hwVersion)
+{
+ m_hardwareVersion = hwVersion;
+}
+
+void PlatformInfo::setFirmwareVersion(const std::string &firmwareVersion)
+{
+ m_firmwareVersion = firmwareVersion;
+}
+
+void PlatformInfo::setSupportUrl(const std::string &supportUrl)
+{
+ m_supportUrl = supportUrl;
+}
+
+void PlatformInfo::setSystemTime(const std::string &systemTime)
+{
+ m_systemTime = systemTime;
+}
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "simulator_remote_resource.h"
-#include "OCApi.h"
-
-SimulatorRemoteResource::SimulatorRemoteResource(std::shared_ptr<OC::OCResource> resource)
- : m_ocResource(resource) {}
-
-std::string SimulatorRemoteResource::getURI() const
-{
- return m_ocResource->uri();
-}
-
-std::string SimulatorRemoteResource::getHost() const
-{
- return m_ocResource->host();
-}
-
-std::string SimulatorRemoteResource::getSID() const
-{
- return m_ocResource->sid();
-}
-
-OCConnectivityType SimulatorRemoteResource::getConnectivityType() const
-{
- return m_ocResource->connectivityType();
-}
-
-std::vector < std::string > SimulatorRemoteResource::getResourceTypes() const
-{
- return m_ocResource->getResourceTypes();
-}
-
-std::vector < std::string > SimulatorRemoteResource::getResourceInterfaces() const
-{
- return m_ocResource->getResourceInterfaces();
-}
-
-bool SimulatorRemoteResource::isObservable() const
-{
- return m_ocResource->isObservable();
-}
-
-SimulatorResult SimulatorRemoteResource::observe(SimulatorRemoteResource::ObserveType type,
- const QueryParamsMap &queryParams, RepresentationChangeCallback callback)
-{
- std::lock_guard<std::mutex> lock(m_observeMutex);
-
- static int observeState = false;
- if (!observeState)
- {
- OC::ObserveCallback observeCallback = [callback](const OC::HeaderOptions & headerOptions,
- const OC::OCRepresentation & rep, const int errorCode,
- const int sequenceNum)
- {
- // Convert OCRepresentation to SimulatorResourceModel
- SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
- callback(errorCode, resModel, sequenceNum);
- };
-
- OC::ObserveType observeType =
- (type == SimulatorRemoteResource::OBSERVE_ALL) ? OC::ObserveType::ObserveAll :
- OC::ObserveType::Observe;
- OCStackResult error = m_ocResource->observe(observeType, queryParams, observeCallback);
- if (OC_STACK_OK == error)
- {
- observeState = true;
- return SIMULATOR_SUCCESS;
- }
- else
- {
- return SIMULATOR_ERROR;
- }
- }
-
- return SIMULATOR_RESOURCE_ALREADY_OBSERVING;
-}
-
-SimulatorResult SimulatorRemoteResource::cancelObserve()
-{
- OCStackResult error = m_ocResource->cancelObserve();
- if (OC_STACK_OK != error)
- return SIMULATOR_ERROR;
- return SIMULATOR_SUCCESS;
-}
-
-SimulatorResult SimulatorRemoteResource::get(const std::string &resourceType,
- const std::string &interfaceType,
- const QueryParamsMap &queryParams, ResponseCallback callback)
-{
- OC::GetCallback getCallback = [callback](const OC::HeaderOptions & headerOptions,
- const OC::OCRepresentation & rep, const int errorCode)
- {
- // Convert OCRepresentation to SimulatorResourceModel
- SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
- callback(errorCode, resModel);
- };
-
- // Convert SimulatorResourceModel to OcRepresentation
- OCStackResult result = m_ocResource->get(resourceType, interfaceType, queryParams,
- getCallback);
- if (OC_STACK_OK != result)
- {
- return SIMULATOR_ERROR;
- }
-
- return SIMULATOR_SUCCESS;
-}
-
-SimulatorResult SimulatorRemoteResource::get(const QueryParamsMap &queryParams,
- ResponseCallback callback)
-{
- std::string resourceType;
- std::string interfaceType;
- return get(resourceType, interfaceType, queryParams, callback);
-}
-
-SimulatorResult SimulatorRemoteResource::put(const std::string &resourceType,
- const std::string &interfaceType,
- const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback)
-{
- OC::PutCallback putCallback = [callback](const OC::HeaderOptions & headerOptions,
- const OC::OCRepresentation & rep, const int errorCode)
- {
- // Convert OCRepresentation to SimulatorResourceModel
- SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
- callback(errorCode, resModel);
- };
-
- // Convert SimulatorResourceModel to OcRepresentation
- OC::OCRepresentation ocRep = representation.getOCRepresentation();
- OCStackResult result = m_ocResource->put(resourceType, interfaceType, ocRep, queryParams,
- putCallback);
- if (OC_STACK_OK != result)
- {
- return SIMULATOR_ERROR;
- }
-
- return SIMULATOR_SUCCESS;
-}
-
-SimulatorResult SimulatorRemoteResource::put(const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback)
-{
- std::string resourceType;
- std::string interfaceType;
- return put(resourceType, interfaceType, representation, queryParams, callback);
-}
-
-SimulatorResult SimulatorRemoteResource::post(const std::string &resourceType,
- const std::string &interfaceType,
- const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback)
-{
- OC::PostCallback postCallback = [callback](const OC::HeaderOptions & headerOptions,
- const OC::OCRepresentation & rep, const int errorCode)
- {
- // Convert OCRepresentation to SimulatorResourceModel
- SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
- callback(errorCode, resModel);
- };
-
- // Convert SimulatorResourceModel to OcRepresentation
- OC::OCRepresentation ocRep = representation.getOCRepresentation();
- OCStackResult result = m_ocResource->post(resourceType, interfaceType, ocRep, queryParams,
- postCallback);
- if (OC_STACK_OK != result)
- {
- return SIMULATOR_ERROR;
- }
-
- return SIMULATOR_SUCCESS;
-}
-
-SimulatorResult SimulatorRemoteResource::post(const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback)
-{
- std::string resourceType;
- std::string interfaceType;
- return post(resourceType, interfaceType, representation, queryParams, callback);
-}
-
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-/**
- * @file simulator_remote_resource.h
- *
- * @brief This file provides a class for handling remote resources by the client.
- *
- */
-
-#ifndef SIMULATOR_REMOTE_RESOURCE_H_
-#define SIMULATOR_REMOTE_RESOURCE_H_
-
-#include "simulator_resource_model.h"
-#include "simulator_error_codes.h"
-
-#include <string>
-#include <vector>
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-/**
- * @class SimulatorRemoteResource
- * @brief This class represents the resource discovered in the network and provides APIs
- * for sending requests to discovered resource.
- */
-class SimulatorRemoteResource
-{
- public:
- typedef enum
- {
- OBSERVE,
- OBSERVE_ALL
- } ObserveType;
-
- // Typedef for query parameter map
- typedef std::map<std::string, std::string> QueryParamsMap;
-
- typedef std::function<void (int, const SimulatorResourceModel &, int)>
- RepresentationChangeCallback;
-
- typedef std::function<void (int, const SimulatorResourceModel &)>
- ResponseCallback;
-
- SimulatorRemoteResource(std::shared_ptr<OC::OCResource> resource);
-
- std::string getURI() const;
-
- std::string getHost() const;
-
- std::string getSID() const;
-
- OCConnectivityType getConnectivityType() const;
-
- std::vector < std::string > getResourceTypes() const;
-
- std::vector < std::string > getResourceInterfaces() const;
-
- bool isObservable() const;
-
- SimulatorResult observe(ObserveType type,
- const QueryParamsMap &queryParams, RepresentationChangeCallback callback);
-
- SimulatorResult cancelObserve();
-
- SimulatorResult get(const QueryParamsMap &queryParams,
- ResponseCallback callback);
-
- SimulatorResult get(const std::string &resourceType, const std::string &interfaceType,
- const QueryParamsMap &queryParams, ResponseCallback callback);
-
- SimulatorResult put(const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback);
-
- SimulatorResult put(const std::string &resourceType, const std::string &interfaceType,
- const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback);
-
- SimulatorResult post(const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback);
-
- SimulatorResult post(const std::string &resourceType, const std::string &interfaceType,
- const SimulatorResourceModel &representation,
- const QueryParamsMap &queryParams, ResponseCallback callback);
-
- private:
-
- std::shared_ptr<OC::OCResource> m_ocResource;
- std::mutex m_observeMutex;
-};
-
-typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourcePtr;
-typedef std::function<void(SimulatorRemoteResourcePtr)> ResourceFindCallback;
-
-#endif //SIMULATOR_REMOTE_RESOURCE_H_
-
+++ /dev/null
-/******************************************************************\r
- *\r
- * Copyright 2015 Samsung Electronics All Rights Reserved.\r
- *\r
- *\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- *\r
- ******************************************************************/\r
-\r
-#include "simulator_resource_creator.h"\r
-#include "simulator_logger.h"\r
-#include <RamlParser.h>\r
-#include <boost/lexical_cast.hpp>\r
-\r
-using namespace RAML;\r
-\r
-SimulatorResourceServerPtr SimulatorResourceCreator::createResource(const std::string &configPath)\r
-{\r
- std::shared_ptr<SimulatorResourceServer> resource(new SimulatorResourceServer);\r
-\r
- RamlParser *ramlParser = new RamlParser(configPath);\r
- RamlPtr raml = ramlParser->getRamlPtr();\r
- for (auto resours : raml->getResources())\r
- {\r
- resource->setName(resours.first);\r
- resource->setURI(resours.second->getResourceUri());\r
- // TODO: Currently setting only baseline interface.\r
- resource->setInterfaceType(OC::DEFAULT_INTERFACE);\r
- // TODO: Need to modify based on the spec for observable property\r
- resource->setObservable(true);\r
- for (auto action : resours.second->getActions())\r
- {\r
- for (auto response : action.second->getResponses())\r
- {\r
- for (auto bdy : response.second->getResponseBody())\r
- {\r
- auto resourceProperties = bdy.second->getSchema()->getProperties();\r
-\r
- for ( auto property : resourceProperties->getProperties() )\r
- {\r
- int type = property.second->getValueType();\r
- if (type)\r
- {\r
- std::string attributeValue = property.second->getValueString();\r
- resource->addAttribute(property.second->getName(), std::string(attributeValue));\r
- }\r
- else\r
- {\r
- int attributeValue = property.second->getValueInt();\r
- resource->addAttribute(property.second->getName(), int(attributeValue));\r
- }\r
-\r
- resource->setUpdateInterval(property.second->getName(), property.second->getUpdateFrequencyTime());\r
-\r
- int min = 0, max = 0, multipleof = 0;\r
- property.second->getRange(min, max, multipleof);\r
- resource->setRange(property.second->getName(), min, max);\r
-\r
-\r
- if (property.second->getAllowedValuesSize() > 0)\r
- resource->setAllowedValues(property.second->getName(), property.second->getAllowedValues());\r
- }\r
- SIM_LOG(ILogger::INFO, "Created sample resource");\r
- return resource;\r
- }\r
- }\r
-\r
- }\r
- }\r
-\r
- return resource;\r
-}\r
-\r
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "simulator_resource_server.h"
-#include "simulator_attribute_automation.h"
-#include "simulator_logger.h"
-
-SimulatorResourceServer::SimulatorResourceServer()
- : m_resourceHandle(NULL),
- m_property((OCResourceProperty) (OC_DISCOVERABLE | OC_OBSERVABLE)) {}
-
-SimulatorResult SimulatorResourceServer::setURI(const std::string &uri)
-{
- if (m_resourceHandle)
- return SIMULATOR_OPERATION_NOT_ALLOWED;
- m_uri = uri;
- return SIMULATOR_SUCCESS;
-}
-
-std::string SimulatorResourceServer::getURI() const
-{
- return m_uri;
-}
-
-SimulatorResult SimulatorResourceServer::setResourceType(const std::string &resourceType)
-{
- if (m_resourceHandle)
- return SIMULATOR_OPERATION_NOT_ALLOWED;
- m_resourceType = resourceType;
- return SIMULATOR_SUCCESS;
-}
-
-std::string SimulatorResourceServer::getResourceType() const
-{
- return m_resourceType;
-}
-
-SimulatorResult SimulatorResourceServer::setInterfaceType(const std::string &interfaceType)
-{
- if (m_resourceHandle)
- return SIMULATOR_OPERATION_NOT_ALLOWED;
- m_interfaceType = interfaceType;
- return SIMULATOR_SUCCESS;
-}
-
-std::string SimulatorResourceServer::getInterfaceType() const
-{
- return m_interfaceType;
-}
-
-void SimulatorResourceServer::setName(const std::string &name)
-{
- m_name = name;
-}
-
-std::string SimulatorResourceServer::getName() const
-{
- return m_name;
-}
-
-SimulatorResult SimulatorResourceServer::setObservable(bool state)
-{
- if (m_resourceHandle)
- return SIMULATOR_OPERATION_NOT_ALLOWED;
-
- if (true == state)
- m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
- else
- m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
-
- return SIMULATOR_SUCCESS;
-}
-
-bool SimulatorResourceServer::isObservable() const
-{
- return (m_property & OC_OBSERVABLE);
-}
-
-SimulatorResult SimulatorResourceServer::start()
-{
- if (m_resourceHandle)
- return SIMULATOR_RESOURCE_ALREADY_REGISTERED;
-
- if (m_uri.empty() || m_resourceType.empty() || m_interfaceType.empty()
- || !m_callback)
- {
- return SIMULATOR_BAD_INPUT;
- }
-
- OCStackResult result = OC::OCPlatform::registerResource(m_resourceHandle,
- m_uri,
- m_resourceType,
- m_interfaceType,
- std::bind(&SimulatorResourceServer::entityHandler,
- this, std::placeholders::_1), m_property);
-
- if (OC_STACK_OK != result)
- return SIMULATOR_ERROR;
- return SIMULATOR_SUCCESS;
-}
-
-SimulatorResult SimulatorResourceServer::stop()
-{
- if (nullptr == m_resourceHandle)
- {
- SIM_LOG(ILogger::ERROR, "Resourece is not registered!");
- return SIMULATOR_RESOURCE_NOT_REGISTERED;
- }
-
- OCStackResult result = OC::OCPlatform::unregisterResource(m_resourceHandle);
- if (OC_STACK_OK != result)
- return SIMULATOR_ERROR;
-
- m_resourceHandle = nullptr;
- return SIMULATOR_SUCCESS;
-}
-
-void SimulatorResourceServer::setRange(const std::string &attrName, const int min, const int max)
-{
- m_resModel.setRange(attrName, min, max);
-}
-
-void SimulatorResourceServer::setUpdateInterval(const std::string &attrName, int interval)
-{
- m_resModel.setUpdateInterval(attrName, interval);
-}
-
-void SimulatorResourceServer::removeAttribute(const std::string &attrName)
-{
- m_resModel.removeAttribute(attrName);
- notifyListOfObservers();
-}
-
-void SimulatorResourceServer::updateAttributeFromAllowedValues(const std::string &attrName,
- const int allowedValueIndex)
-{
- m_resModel.updateAttributeFromAllowedValues(attrName, allowedValueIndex);
- notifyListOfObservers();
-}
-
-SimulatorResourceModel SimulatorResourceServer::getModel() const
-{
- return m_resModel;
-}
-
-void SimulatorResourceServer::setModelChangeCallback(ResourceModelChangedCB callback)
-{
- m_callback = callback;
-}
-
-SimulatorResult SimulatorResourceServer::startUpdateAutomation(AutomationType type,
- updateCompleteCallback callback, int &id)
-{
- return m_updateAutomationMgr.startResourceAutomation(this, id, callback, type);
-}
-
-SimulatorResult SimulatorResourceServer::startUpdateAutomation(const std::string &attrName,
- AutomationType type, updateCompleteCallback callback, int &id)
-{
- return m_updateAutomationMgr.startAttributeAutomation(this, attrName, id, callback, type);
-}
-
-std::vector<int> SimulatorResourceServer::getResourceAutomationIds()
-{
- return m_updateAutomationMgr.getResourceAutomationIds();
-}
-
-std::vector<int> SimulatorResourceServer::getAttributeAutomationIds()
-{
- return m_updateAutomationMgr.getAttributeAutomationIds();
-}
-
-void SimulatorResourceServer::stopUpdateAutomation(const int id)
-{
- m_updateAutomationMgr.stop(id);
-}
-
-OC::OCRepresentation SimulatorResourceServer::getOCRepresentation()
-{
- return m_resModel.getOCRepresentation();
-}
-
-bool SimulatorResourceServer::modifyResourceModel(OC::OCRepresentation &ocRep)
-{
- bool status = m_resModel.update(ocRep);
- if (true == status)
- {
- notifyListOfObservers();
- }
- return status;
-}
-
-OCEntityHandlerResult SimulatorResourceServer::entityHandler(std::shared_ptr<OC::OCResourceRequest>
- request)
-{
- OCEntityHandlerResult errCode = OC_EH_ERROR;
- if (!request)
- {
- return OC_EH_ERROR;
- }
-
- if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
- {
- auto response = std::make_shared<OC::OCResourceResponse>();
- response->setRequestHandle(request->getRequestHandle());
- response->setResourceHandle(request->getResourceHandle());
-
- if ("GET" == request->getRequestType())
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] GET request received");
- response->setErrorCode(200);
- response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(getOCRepresentation());
-
- if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
- {
- errCode = OC_EH_OK;
- }
- }
- else if ("PUT" == request->getRequestType())
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] PUT request received");
- OC::OCRepresentation rep = request->getResourceRepresentation();
- if (true == modifyResourceModel(rep))
- {
- response->setErrorCode(200);
- response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(getOCRepresentation());
- }
- else
- {
- response->setErrorCode(400);
- response->setResponseResult(OC_EH_ERROR);
- }
-
- if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
- {
- errCode = OC_EH_OK;
- }
- }
- else if ("POST" == request->getRequestType())
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] POST request received");
- OC::OCRepresentation rep = request->getResourceRepresentation();
- if (true == modifyResourceModel(rep))
- {
- response->setErrorCode(200);
- response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(getOCRepresentation());
- }
- else
- {
- response->setErrorCode(400);
- response->setResponseResult(OC_EH_ERROR);
- }
-
- if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
- {
- errCode = OC_EH_OK;
- }
- }
- else if ("DELETE" == request->getRequestType())
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] DELETE request received!");
- OC::OCRepresentation rep = request->getResourceRepresentation();
-
- // DELETE request handling not supported right now
- response->setErrorCode(400);
- response->setResponseResult(OC_EH_ERROR);
- if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
- {
- errCode = OC_EH_OK;
- }
- }
- else
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] UNKNOWN type request received");
- response->setResponseResult(OC_EH_ERROR);
- OC::OCPlatform::sendResponse(response);
- errCode = OC_EH_ERROR;
- }
- }
-
- if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
- {
- if (false == isObservable())
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received");
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state");
- return OC_EH_ERROR;
- }
-
- OC::ObservationInfo observationInfo = request->getObservationInfo();
- if (OC::ObserveAction::ObserveRegister == observationInfo.action)
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received");
- m_interestedObservers.push_back(observationInfo.obsId);
- }
- else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
- {
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
- m_interestedObservers.erase(std::remove(m_interestedObservers.begin(),
- m_interestedObservers.end(),
- observationInfo.obsId),
- m_interestedObservers.end());
- }
- errCode = OC_EH_OK;
- }
-
- return errCode;
-}
-
-void SimulatorResourceServer::notifyListOfObservers ()
-{
- if (!m_resourceHandle)
- {
- return;
- }
-
- if (m_interestedObservers.size())
- {
- std::shared_ptr<OC::OCResourceResponse> resourceResponse =
- {std::make_shared<OC::OCResourceResponse>()};
-
- resourceResponse->setErrorCode(200);
- resourceResponse->setResponseResult(OC_EH_OK);
- resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
-
- SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to all observers" << m_uri);
- OC::OCPlatform::notifyListOfObservers(m_resourceHandle, m_interestedObservers, resourceResponse);
- }
-
- if (m_callback)
- {
- m_callback(m_uri, m_resModel);
- }
-}