for (auto & resourceEntry : m_resList)
{
std::cout << index++ << ": " << (resourceEntry.second)->getURI() << "[" <<
- (resourceEntry.second)->getHost() << "]" << std::endl;
+ (resourceEntry.second)->getHost() << "]" << std::endl;
ids.push_back((resourceEntry.second)->getID());
}
return nullptr;
}
- return m_resList[ids[choice-1]];
+ return m_resList[ids[choice - 1]];
}
void findResource()
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;
+ std::cout << "Resource with UID: " << resource->getID() << "already exist in the list!" <<
+ std::endl;
};
try
{
- SimulatorManager::getInstance()->findResources(resourceType, callback);
+ SimulatorManager::getInstance()->findResource(resourceType, callback);
std::cout << "SimulatorManager::findResource is successfull" << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
+ << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
+ 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())
+ for (auto & type : resource->getResourceTypes())
std::cout << type << " ";
std::cout << "\nInterface Types: ";
- for (auto &type : resource->getResourceInterfaces())
+ for (auto & type : resource->getResourceInterfaces())
std::cout << type << " ";
- std::cout << std::boolalpha << "\nisObservable : " << resource->isObservable() << std::endl;
+ std::cout << std::boolalpha << "\nisObservable : " << resource->isObservable()
+ << std::noboolalpha << std::endl;
std::cout << "#############################" << std::endl;
}
// callback implementaion
SimulatorRemoteResource::ObserveNotificationCallback callback =
- [](std::string uid, SimulatorResult errorCode, SimulatorResourceModelSP rep, int seq)
+ [](std::string uid, SimulatorResult errorCode, SimulatorResourceModelSP rep, int seq)
{
- std::cout << "\nObserve notificatoin received ###[errorcode: " << errorCode <<
- " seq: " << seq << "UID: " << uid << "]" << std::endl;
+ std::cout << "\nObserve notification received ###[errorcode: " << errorCode <<
+ " seq: " << seq << "UID: " << uid << "]" << std::endl;
std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep->getAttributes();
for (auto & attribute : attributes)
{
resource->observe(ObserveType::OBSERVE, callback);
std::cout << "Observe is successfull!" << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
resource->cancelObserve();
std::cout << "Cancelling observe is successfull!" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
- std::cout << "\nGET Response received ### [errorcode: " << errorCode << "]" << std::endl;
+ 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 << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+ std::cout << "value: " << (attribute.second).valueToString().c_str()
+ << std::endl;
std::cout << "}" << std::endl;
}
std::cout << std::endl;
resource->get(std::map <std::string, std::string>(), callback);
std::cout << "GET is successfull!" << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
- std::cout << "\nPUT Response received ![errorcode: " << errorCode << "]" << std::endl;
+ 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 << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+ std::cout << "value: " << (attribute.second).valueToString().c_str()
+ << std::endl;
std::cout << "}" << std::endl;
}
std::cout << std::endl;
resource->put(std::map <std::string, std::string>(), rep, callback);
std::cout << "PUT is successfull!" << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
// callback implementaion
SimulatorRemoteResource::ResponseCallback callback =
- [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
+ [](std::string uId, SimulatorResult errorCode, SimulatorResourceModelSP rep)
{
- std::cout << "\nPOST Response received ![errorcode: " << errorCode << "]" << std::endl;
+ 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 << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+ std::cout << "value: " << (attribute.second).valueToString().c_str()
+ << std::endl;
std::cout << "}" << std::endl;
}
std::cout << std::endl;
resource->post(std::map <std::string, std::string>(), rep, callback);
std::cout << "POST is successfull!" << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
SimulatorRemoteResourceSP resource = selectResource();
if (!resource) return;
- SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ 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;
+ 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;
+ std::cout << "startVerification for GET is successfull!id: " << id << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
SimulatorRemoteResourceSP resource = selectResource();
if (!resource) return;
- SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ 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;
+ 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;
+ std::cout << "startVerification for PUT is successfull!id: " << id << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
SimulatorRemoteResourceSP resource = selectResource();
if (!resource) return;
- SimulatorRemoteResource::StateCallback callback = [] (std::string uid, int sessionId, OperationState state)
+ 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;
+ 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;
+ std::cout << "startVerification for POST is successfull!id: " << id << std::endl;
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
+ << e.what() << "]" << std::endl;
}
- catch(NoSupportException &e)
+ catch (NoSupportException &e)
{
- std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "NoSupportException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
void configure()
{
SimulatorRemoteResourceSP resource = selectResource();
- if (!resource) return;
+ if (!resource)
+ return;
try
{
- resource->configure("../../../../../../../../service/simulator/ramlparser/example/oic.r.light.raml");
+ std::string configPath;
+ std::cout << "Enter the config path: ";
+ std::cin >> configPath;
+
+ resource->configure(configPath);
std::cout << "configuration is successfull!" << std::endl;
}
catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ 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;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
{
case 1:
{
- if (false == SimulatorManager::getInstance()->setDefaultConsoleLogger())
+ if (false == SimulatorManager::getInstance()->setConsoleLogger())
std::cout << "Failed to set the default console logger" << std::endl;
}
break;
std::string filePath;
std::cout << "Enter the file path (without file name) : ";
std::cin >> filePath;
- if (false == SimulatorManager::getInstance()->setDefaultFileLogger(filePath))
+ if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
std::cout << "Failed to set default file logger" << std::endl;
}
break;
{
try
{
- SimulatorManager::getInstance()->getDeviceInfo(std::bind([](DeviceInfo &deviceInfo)
+ SimulatorManager::getInstance()->getDeviceInfo(std::bind([](DeviceInfo & deviceInfo)
{
std::cout << "###Device Information received...." << std::endl;
std::ostringstream out;
std::cout << out.str() << std::endl;
}, std::placeholders::_1));
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]"
+ << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" <<
+ std::endl;
}
}
break;
{
try
{
- SimulatorManager::getInstance()->getPlatformInfo(std::bind([](PlatformInfo &platformInfo)
+ SimulatorManager::getInstance()->getPlatformInfo(std::bind([](PlatformInfo & platformInfo)
{
std::cout << "###Platform Information received...." << std::endl;
std::ostringstream out;
std::cout << out.str() << std::endl;
}, std::placeholders::_1));
}
- catch(InvalidArgsException &e)
+ catch (InvalidArgsException &e)
{
- std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "InvalidArgsException occured [code : " << e.code()
+ << " Detail: " << e.what() << "]" << std::endl;
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
- std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << e.what() << "]" << std::endl;
+ std::cout << "SimulatorException occured [code : " << e.code()
+ << " Detail: " << e.what() << "]" << std::endl;
}
}
break;
public:
void write(std::string time, ILogger::Level level, std::string message)
{
- std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " << message;
+ std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
+ << message;
}
};
std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
int choice = -1;
std::cout << "Enter your choice: ";
std::cin >> choice;
- if (choice < 0 || choice > 9)
+ if (choice < 0 || choice > 10)
{
std::cout << "Invaild choice !" << std::endl; continue;
}
void onResourceModelChanged(const std::string &uri,
const SimulatorResourceModel &resModel)
{
- std::cout << "[callback] Resource model is changed URI: " << uri.c_str() << " Count : " <<
- resModel.size() << std::endl;
+ std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
+ << " Count : " << resModel.size() << std::endl;
std::cout << "#### Modified attributes are ####" << std::endl;
for (auto & attribute : resModel.getAttributes())
{
- std::cout << attribute.second.getName() << " : " << attribute.second.valueToString().c_str() <<
- std::endl;
+ std::cout << attribute.second.getName() << " : "
+ << attribute.second.valueToString().c_str() << std::endl;
}
std::cout << "########################" << std::endl;
}
void simulateResource(std::string &configPath)
{
SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
- &SimLightResource::onResourceModelChanged, this, std::placeholders::_1, std::placeholders::_2);
- SimulatorResourceServerSP resource = SimulatorManager::getInstance()->createResource(configPath,
- callback);
- if (NULL == resource.get())
- std::cout << "Failed to create resource" << std::endl;
-
- m_resources.push_back(resource);
- std::cout << "Resource created successfully! URI= " << resource->getURI().c_str() << std::endl;
+ &SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
+ std::placeholders::_2);
+
+ try
+ {
+ SimulatorResourceServerSP resource =
+ SimulatorManager::getInstance()->createResource(configPath, callback);
+ m_resources.push_back(resource);
+ std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
+ << 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 deleteResource()
m_resources.erase(m_resources.begin() + (index - 1));
} break;
+
case 2:
{
std::string resourceType;
break;
}
- 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())
+ try
{
- if (!resourceType.compare((*ite)->getResourceType()))
+ SimulatorManager::getInstance()->deleteResource(resourceType);
+ std::cout << "Resources of type \"" << resourceType << "\"" <<
+ " deleted successfully! " << std::endl;
+ std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
+ while (ite != m_resources.end())
{
- ite = m_resources.erase(ite);
- continue;
+ if (!resourceType.compare((*ite)->getResourceType()))
+ {
+ ite = m_resources.erase(ite);
+ continue;
+ }
+ ite++;
}
- ite++;
+ }
+ 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:
{
- SimulatorManager::getInstance()->deleteResources();
+ SimulatorManager::getInstance()->deleteResource();
std::cout << "All resources deleted successfully! " << std::endl;
m_resources.clear();
} break;
return;
}
- std::cout << "Setting the new values from allowed values list to power attribute" << std::endl;
+ std::cout << "Setting the new values from allowed values list to power attribute" <<
+ std::endl;
// Update all possible values from allowed values
for (int index = 0; index < allowedValuesSize; index++)
{
if ((index + 1) < allowedValuesSize)
{
int choice;
- std::cout << "Would you like to continue the attribute values changing process? (1/0): ";
+ std::cout << "Would you like to change attribute value again ? (1/0): ";
std::cin >> choice;
if (0 == choice)
break;
return;
}
- std::cout << "Setting the new values from allowed values list to intensity attribute" << std::endl;
+ 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 = min; index <= max; index++)
{
if ((index + 1) <= max)
{
int choice;
- std::cout << "Would you like to continue the attribute values changing process? (1/0): ";
+ std::cout << "Would you like to change attribute value again ? (1/0): ";
std::cin >> choice;
if (0 == choice)
break;
// Attributes
SimulatorResourceModel resModel = resource->getModel();
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = resModel.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes =
+ resModel.getAttributes();
std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
for (auto & attribute : attributes)
{
std::cout << "max: " << max << std::endl;
std::cout << "allowed values : ";
std::cout << "[ ";
- for (auto &value : (attribute.second).allowedValuesToString())
+ for (auto & value : (attribute.second).allowedValuesToString())
std::cout << value << " ";
std::cout << "]" << std::endl;
std::cout << "}" << std::endl << std::endl;
void onUpdateAutomationCompleted(const std::string &uri,
const int id)
{
- std::cout << "Update automation is completed [URI: " << uri.c_str() << " AutomationID: " <<
- id << "] ###" << std::endl;
+ std::cout << "Update automation is completed [URI: " << uri.c_str()
+ << " AutomationID: " << id << "] ###" << std::endl;
}
void automateResourceUpdate()
try
{
int id = m_resources[index - 1]->startUpdateAutomation(type,
- std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
- std::placeholders::_2));
+ 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;
+ std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
+ e.what() << "]" << std::endl;
}
}
SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = resModel.getAttributes();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributes =
+ resModel.getAttributes();
int size = 0;
for (auto & attribute : attributes)
{
}
int choice = -1;
- std::cout << "Select the attribute which you want to automate for updation: " << std::endl;
+ std::cout << "Select the attribute which you want to automate for updation: " <<
+ std::endl;
std::cin >> choice;
if (choice < 0 || choice > size)
{
if (1 == choice)
type = AutomationType::RECURRENT;
- std::cout << "Requesting attribute automation for " << attributeName.c_str() << std::endl;
+ std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
+ std::endl;
try
{
int id = resource->startUpdateAutomation(attributeName, type,
- std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
- std::placeholders::_2));
+ 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;
+ std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
+ e.what() << "]" << std::endl;
}
}
if (!ids.size())
{
- std::cout << "No automation operation is going on this resource right now!" << std::endl;
+ std::cout << "No automation operation is going on this resource right now!" <<
+ std::endl;
return;
}
resource->stopUpdateAutomation(automationid);
}
- void onObserverChanged(const std::string &uri, ObservationStatus state, const ObserverInfo &observerInfo)
+ 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;
+ out << " [address: " << observerInfo.address << " port: " << observerInfo.port
+ << "]" << std::endl;
std::cout << out.str();
}
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 << " ID : " << (int) observerInfo.id << " [address: " <<
+ observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
}
std::cout << "########################" << std::endl;
}
{
case 1:
{
- if (false == SimulatorManager::getInstance()->setDefaultConsoleLogger())
+ if (false == SimulatorManager::getInstance()->setConsoleLogger())
std::cout << "Failed to set the default console logger" << std::endl;
} break;
case 2:
std::string filePath;
std::cout << "Enter the file path (without file name) : ";
std::cin >> filePath;
- if (false == SimulatorManager::getInstance()->setDefaultFileLogger(filePath))
+ if (false == SimulatorManager::getInstance()->setFileLogger(filePath))
std::cout << "Failed to set default file logger" << std::endl;
} break;
case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
SIMULATOR_UKNOWN_PROPERTY,
SIMULATOR_TYPE_MISMATCH,
SIMULATOR_BAD_VALUE,
+ SIMULATOR_BAD_OBJECT,
/** Simulator specific error codes - START */
SIMULATOR_ERROR = 255
*
* NOTE: API would throw @InvalidArgsException when invalid arguments passed
*/
- void deleteResources(const std::string &resourceType = "");
+ void deleteResource(const std::string &resourceType = "");
/**
* API for discovering all type of resources.
* NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
* @SimulatorException if any other error occured.
*/
- void findResources(ResourceFindCallback callback);
+ void findResource(ResourceFindCallback callback);
/**
* API for discovering resources of a particular resource type.
* NOTE: API would throw @InvalidArgsException when invalid arguments passed, and
* @SimulatorException if any other error occured.
*/
- void findResources(const std::string &resourceType, ResourceFindCallback callback);
+ void findResource(const std::string &resourceType, ResourceFindCallback callback);
/**
* API for getting device information from remote device.
* otherwise false.
*
*/
- bool setDefaultConsoleLogger();
+ bool setConsoleLogger();
/**
* API for setting file as logger target.
* otherwise false.
*
*/
- bool setDefaultFileLogger(const std::string &path);
+ bool setFileLogger(const std::string &path);
private:
SimulatorManager();
{
public:
SimulatorResourceModel() = default;
- SimulatorResourceModel(SimulatorResourceModel &&) = default;
SimulatorResourceModel(const SimulatorResourceModel &) = default;
SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
+ SimulatorResourceModel(SimulatorResourceModel &&) = default;
SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
/**
std::string
> ValueVariant;
+ enum class ValueType
+ {
+ UNKNOWN,
+ INTEGER,
+ DOUBLE,
+ BOOLEAN,
+ STRING
+ };
+
Attribute()
{
m_min = INT_MIN;
/**
* API to get attribute's value type.
*
- * @return type of value.
+ * @return ValueType enum.
*/
- int getValueType() const
- {
- return m_value.which();
- }
+ ValueType getValueType() const;
/**
* API to set the attribute's value.
* @param attr - Attribute pointer
*
*/
- void addAttribute(Attribute &attr)
- {
- std::string attrName = attr.getName();
- m_attributes[attrName] = Attribute(attr);
- }
+ void addAttribute(const Attribute &attribute);
/**
* API to set range of attribute value.
void updateAttributeValue(const std::string &attrName, const T &value)
{
m_resModel.updateAttribute(attrName, value);
+
+ // Notify all the subscribers
+ notifyAll();
}
/**
// Map with Server ID as key and the complete object as the value
private Map<String, RemoteResource> resourceMap;
private List<RemoteResource> favoriteResources;
- // TODO: Temporarily maintaining a list of favorite resource URIs.
+ // Maintaining a list of resource URIs for favorite resources feature.
private List<String> favoriteURIList;
+ // Maintaining a list of observed resource URIs.
+ private List<String> observedResourceURIList;
+
public ResourceManager() {
resourceMap = new HashMap<String, RemoteResource>();
favoriteResources = new ArrayList<RemoteResource>();
favoriteURIList = new ArrayList<String>();
+ observedResourceURIList = new ArrayList<String>();
findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
getUIListeners = new ArrayList<IGetUIListener>();
resource.setResource(resourceN);
- // Add the resource in local data structure
- addResourceDetails(resource);
-
- // Add resource to favorite list
String uri = resource.getResourceURI();
if (null != uri) {
+ // Add resource to favorite list if it was in
+ // favorites list during find/refresh operation.
if (favoriteURIList.contains(uri)) {
addResourcetoFavorites(resource);
}
+ // Add resource to observed resources list if it was
+ // in observe list during find/refresh operation.
+ if (observedResourceURIList.contains(uri)) {
+ resource.setObserved(true);
+ }
}
+
+ // Add the resource in local data structure
+ addResourceDetails(resource);
+
// Notify the UI listener
newResourceFoundNotification(resource);
}
}
+ public void addObservedResourceURI(String resourceURI) {
+ synchronized (observedResourceURIList) {
+ observedResourceURIList.add(resourceURI);
+ }
+ }
+
+ public void removeObservedResourceURI(String resourceURI) {
+ synchronized (observedResourceURIList) {
+ observedResourceURIList.remove(resourceURI);
+ }
+ }
+
+ public boolean isResourceObserved(String resourceURI) {
+ boolean observed = false;
+ synchronized (observedResourceURIList) {
+ observed = observedResourceURIList.contains(resourceURI);
+ }
+ return observed;
+ }
+
public synchronized RemoteResource getCurrentResourceInSelection() {
return currentResourceInSelection;
}
}
/*
* Type baseType = attribute.getAttValBaseType();
- *
+ *
* if(baseType == Type.INT) { //int[] values =
* attributeN.getAllowedValues();
* attribute.setAllowedValues
while (searchItr.hasNext()) {
rType = searchItr.next();
try {
- SimulatorManager.findResources(rType, findResourceListener);
+ SimulatorManager.findResource(rType, findResourceListener);
result = true;
} catch (SimulatorException e) {
Activator
if (exist) {
// Remove the resource
keyItr.remove();
+ // Remove the resource from favorites list.
removeResourceFromFavorites(resource);
}
}
return;
}
try {
- resourceN.observe(SimulatorObserveType.OBSERVE, null,
+ resourceN.startObserve(SimulatorObserveType.OBSERVE, null,
observeListener);
+ // Add observed resource URI to show the proper status after every
+ // find/refresh operations.
+ addObservedResourceURI(resource.getResourceURI());
} catch (SimulatorException e) {
Activator
.getDefault()
return;
}
try {
- resourceN.cancelObserve();
+ resourceN.stopObserve();
+ // Remove observed resource URI to show the proper status after
+ // every find/refresh operations.
+ removeObservedResourceURI(resource.getResourceURI());
} catch (SimulatorException e) {
Activator
.getDefault()
return;
}
try {
- resourceN.configureRAMLPath(configFilePath);
+ resourceN.setConfigInfo(configFilePath);
} catch (SimulatorException e) {
Activator
.getDefault()
import oic.simulator.clientcontroller.remoteresource.RemoteResource;
import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
import oic.simulator.clientcontroller.utils.Constants;
-import oic.simulator.clientcontroller.view.dialogs.VerificationDialog;
import oic.simulator.clientcontroller.view.dialogs.PostRequestDialog;
import oic.simulator.clientcontroller.view.dialogs.PutRequestDialog;
+import oic.simulator.clientcontroller.view.dialogs.VerificationDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CTabFolder;
-import org.eclipse.swt.custom.CTabFolder2Adapter;
-import org.eclipse.swt.custom.CTabFolderEvent;
-import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
private Button automateButton;
private Button observeResButton;
- private CTabFolder payloadFolder;
- private CTabItem requestPayloadTab;
- private CTabItem responsePayloadTab;
- private Text requestPayloadTxt;
- private Text responsePayloadTxt;
-
private final String[] attTblHeaders = {
"Attribute Name", "Attribute Value" };
private final Integer[] attTblColWidth = { 200, 200 };
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
+ gd.grabExcessVerticalSpace = true;
+ gd.verticalAlignment = SWT.FILL;
gd.horizontalSpan = 2;
- gd.heightHint = 175;
+ // gd.heightHint = 175;
attGroup.setLayoutData(gd);
attGroup.setText("Attributes");
attGroup.setBackground(color);
setupResourceLevelOpsArea(parent);
- setupTabArea(parent);
-
setUIListeners();
addManagerListeners();
observeResButton.setLayoutData(gd);
}
- private void setupTabArea(final Composite parent) {
- GridData gd;
- payloadFolder = new CTabFolder(parent, SWT.BORDER);
- gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- gd.horizontalSpan = 2;
- payloadFolder.setLayoutData(gd);
- payloadFolder.setSimple(false);
- payloadFolder.setUnselectedCloseVisible(false);
- payloadFolder.setUnselectedImageVisible(false);
- // payloadFolder.setMaximizeVisible(true);
- // payloadFolder.setMinimizeVisible(true);
-
- requestPayloadTab = new CTabItem(payloadFolder, SWT.NULL);
- requestPayloadTab.setText("Request Payload");
-
- requestPayloadTxt = new Text(payloadFolder, SWT.MULTI | SWT.V_SCROLL
- | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP);
- requestPayloadTab.setControl(requestPayloadTxt);
-
- responsePayloadTab = new CTabItem(payloadFolder, SWT.NULL);
- responsePayloadTab.setText("Response Payload");
-
- responsePayloadTxt = new Text(payloadFolder, SWT.MULTI | SWT.V_SCROLL
- | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP);
- responsePayloadTab.setControl(responsePayloadTxt);
-
- // Add Listeners
-
- payloadFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
- @Override
- public void minimize(CTabFolderEvent event) {
- payloadFolder.setMinimized(true);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
- gd.horizontalSpan = 2;
- payloadFolder.setLayoutData(gd);
- parent.layout(true);
- }
-
- @Override
- public void maximize(CTabFolderEvent event) {
- payloadFolder.setMaximized(true);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- gd.horizontalSpan = 2;
- payloadFolder.setLayoutData(gd);
- parent.layout(true);
- }
-
- @Override
- public void restore(CTabFolderEvent event) {
- payloadFolder.setMaximized(false);
- payloadFolder.setMinimized(false);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
- gd.horizontalSpan = 2;
- payloadFolder.setLayoutData(gd);
- parent.layout(true);
- }
- });
- }
-
private void setupAttributeTable(Group attGroup) {
attTblViewer = new TableViewer(attGroup, SWT.SINGLE | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
private Map<String, ArrayList<String>> orderedResourceUriMap;
+ private Map<String, String> displayNameMap;
+
private StandardConfiguration stdConfig;
private SimulatorResource currentResourceInSelection;
public ResourceManager() {
resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
orderedResourceUriMap = new HashMap<String, ArrayList<String>>();
+ displayNameMap = new HashMap<String, String>();
stdConfig = new StandardConfiguration();
resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
return result;
}
+ public void addResourceDisplayName(String displayName, String completeURI) {
+ synchronized (displayNameMap) {
+ displayNameMap.put(displayName, completeURI);
+ }
+ }
+
+ public void removeResourceDisplayName(String displayName) {
+ synchronized (displayNameMap) {
+ displayNameMap.remove(displayName);
+ }
+ }
+
+ public boolean isDisplayName(String displayName) {
+ boolean exist = false;
+ synchronized (displayNameMap) {
+ exist = displayNameMap.containsKey(displayName);
+ }
+ return exist;
+ }
+
+ public String getCompleteUriFromDisplayName(String displayName) {
+ String completeURI = null;
+ synchronized (displayNameMap) {
+ completeURI = displayNameMap.get(displayName);
+ }
+ return completeURI;
+ }
+
public void createResource(final String configFilePath) {
new Thread() {
@Override
SimulatorResource simulatorResource;
simulatorResource = fetchResourceData(resourceServerN);
if (null != simulatorResource) {
+ String uri = simulatorResource.getResourceURI();
addResourceToMap(simulatorResource);
addResourceUriToOrderedMap(
- simulatorResource.getResourceType(),
- simulatorResource.getResourceURI());
+ simulatorResource.getResourceType(), uri);
resourceCreatedUINotification();
+ // Form the display URI
+ String displayName = Utility.uriToDisplayName(uri);
+ if (null != displayName) {
+ addResourceDisplayName(displayName, uri);
+ } else {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "Converting the URI to display format for "
+ + uri + "failed!");
+ }
+
// Set the observer for the created resource
try {
resourceServerN.setObserverCallback(observer);
resourceTypeMap = new HashMap<String, SimulatorResource>();
SimulatorResource resource;
String uri;
+ String displayName;
for (SimulatorResourceServer resourceServerN : simulatorResourceServers) {
resource = fetchResourceData(resourceServerN);
if (null != resource) {
resourceTypeMap.put(uri, resource);
addResourceUriToOrderedMap(resource.getResourceType(),
uri);
+
+ // Form the display URI
+ displayName = Utility.uriToDisplayName(uri);
+ if (null != displayName) {
+ addResourceDisplayName(displayName, uri);
+ } else {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "Converting the URI to display format for "
+ + uri + "failed!");
+ }
}
// Set the observer for the created resource
try {
}
}
}
+ // Remove the display name from the map
+ if (null != resourceURI) {
+ String dispName = Utility.uriToDisplayName(resourceURI);
+ if (null != dispName)
+ removeResourceDisplayName(dispName);
+ }
}
private void resourceCreatedUINotification() {
public static final String START_RESOURCE_AUTOMATION = "Start Automation";
public static final String STOP_RESOURCE_AUTOMATION = "Stop Automation";
- public static final int PROPER_RESOURCE_URI_TOKEN_COUNT = 6;
public static final int DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2;
public static final AutomationType DEFAULT_AUTOMATION_TYPE = AutomationType.NORMAL;
String result = null;
if (null != uri) {
String tokens[] = uri.split(Constants.FORWARD_SLASH);
- if (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
- // Proper URI
- result = tokens[3] + Constants.UNDERSCORE + tokens[5];
- }
- }
- return result;
- }
-
- public static String displayNameToUri(String displayName) {
- String result = null;
- if (null != displayName) {
- String tokens[] = displayName.split(Constants.UNDERSCORE);
- if (Constants.DISPLAY_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
- // Proper Display Name
- result = Constants.OIC_PREFIX + Constants.FORWARD_SLASH
- + tokens[0] + Constants.FORWARD_SLASH
- + Constants.SIMULATOR + Constants.FORWARD_SLASH
- + tokens[1];
+ if (null != tokens && tokens.length > 2) {
+ result = tokens[tokens.length - 3] + Constants.UNDERSCORE
+ + tokens[tokens.length - 1];
}
}
return result;
return fileName;
}
- public static boolean isUriComplete(String uri) {
- boolean uriComplete = false;
- if (null != uri) {
- String tokens[] = uri.split(Constants.FORWARD_SLASH);
- if (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
- uriComplete = true;
- }
- }
- return uriComplete;
- }
-
public static String getAutomationStatus(boolean status) {
if (status) {
return Constants.ENABLED;
if (deleteCategory == DeleteCategory.BY_URI) {
String uri = deleteWizard.getDeleteCandidate();
if (null != uri) {
- boolean completeURI = Utility
- .isUriComplete(uri);
- if (!completeURI) {
- uri = Utility.displayNameToUri(uri);
+ boolean dispName = Activator.getDefault()
+ .getResourceManager()
+ .isDisplayName(uri);
+ if (dispName) {
+ uri = Activator
+ .getDefault()
+ .getResourceManager()
+ .getCompleteUriFromDisplayName(
+ uri);
}
resourceManager.deleteResourceByURI(uri);
}
TreeItem selectedItem = (TreeItem) e.item;
if (null != selectedItem) {
String selectedItemText = selectedItem.getText();
- selectedItemText = Utility
- .displayNameToUri(selectedItemText);
+ selectedItemText = resourceManager
+ .getCompleteUriFromDisplayName(selectedItemText);
// Propagate this selection change event to manager
resourceManager
.resourceSelectionChanged(selectedItemText);
// automation if any attribute level
// automation is in progress for the
// selected resource
- boolean started = resourceManager.isAttributeAutomationStarted(Utility
- .displayNameToUri(selectedItem));
+ boolean started = resourceManager
+ .isAttributeAutomationStarted(resourceManager
+ .getCompleteUriFromDisplayName(selectedItem));
if (started) {
MessageDialog
.openInformation(
+ "running attribute level automations to start resource level automation.");
} else {
boolean status = resourceManager
- .startResourceAutomationUIRequest(Utility
- .displayNameToUri(selectedItem));
+ .startResourceAutomationUIRequest(resourceManager
+ .getCompleteUriFromDisplayName(selectedItem));
String statusMsg = status ? "Automation started successfully!!!"
: "Automation request failed!!!";
MessageDialog.openInformation(Display
@Override
public void widgetSelected(SelectionEvent e) {
boolean status = resourceManager
- .stopResourceAutomationUIRequest(Utility
- .displayNameToUri(selectedItem));
+ .stopResourceAutomationUIRequest(resourceManager
+ .getCompleteUriFromDisplayName(selectedItem));
String statusMsg = status ? "Automation stop requested!!!"
: "Automation stop failed.";
MessageDialog.openInformation(Display
});
// Set the initial visibility of menu items
- boolean status = resourceManager
- .isResourceAutomationStarted(Utility
- .displayNameToUri(selectedItem));
+ boolean status = resourceManager.isResourceAutomationStarted(resourceManager
+ .getCompleteUriFromDisplayName(selectedItem));
startItem.setEnabled(!status);
stopItem.setEnabled(status);
}
import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.resource.DeleteCategory;
-import oic.simulator.serviceprovider.utils.Utility;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
// Check whether the uri is in full form or short form
// If it is in short form, expand it to its full form.
String uri = page.getDeleteCandidate();
- boolean uriComplete = Utility.isUriComplete(uri);
- if (!uriComplete) {
- uri = Utility.displayNameToUri(uri);
+ boolean dispName = Activator.getDefault().getResourceManager()
+ .isDisplayName(uri);
+ if (dispName) {
+ uri = Activator.getDefault().getResourceManager()
+ .getCompleteUriFromDisplayName(uri);
}
boolean exist = Activator.getDefault().getResourceManager()
.isResourceExist(uri);
return false;
}
- int type = m_attribute.getValueType();
+ int type = static_cast<int>(m_attribute.getValueType());
jobject jtype = env->CallStaticObjectMethod(clsType, midGetType, type);
if (env->ExceptionCheck())
{
}
JniSimulatorRemoteResource *jniSimulatorResource = new JniSimulatorRemoteResource(resource);
-
if (!jniSimulatorResource)
{
releaseEnv();
env->CallVoidMethod(foundResourceListener, foundResourceMId, simulatorResource);
if ((env)->ExceptionCheck())
{
+ delete jniSimulatorResource;
releaseEnv();
return;
}
}
jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-
jstring jUri = env->NewStringUTF(uri.c_str());
-
env->CallVoidMethod(modelChangeListener, foundModelChangeMId, jUri, jModel);
if ((env)->ExceptionCheck())
{
+ delete jniModel;
releaseEnv();
return;
}
if (!configPath)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
- "Resource creation failed. Configuration file path is empty!");
+ "Configuration file path is empty!");
return nullptr;
}
if (!listener)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
- "Resource creation failed. Resource model change callback not set!");
+ "Resource model change callback not set!");
return nullptr;
}
if (!configPath)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
- "Resource(s) creation failed. Configuration file path is empty!");
+ "Configuration file path is empty!");
return nullptr;
}
if (!listener)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
- "Resource(s) creation failed. Resource model change callback not set!");
+ "Resource model change callback not set!");
return nullptr;
}
if (!jResource)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
- "Deletion failed. No resource has been passed!");
+ "No resource has been passed!");
return;
}
JniSimulatorResource::getJniSimulatorResourceSP(env, jResource);
if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE,
- "Deletion failed. Native resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT,
+ "Simulator resource not found!");
return;
}
try
{
- SimulatorManager::getInstance()->deleteResources(type);
- }
- catch (InvalidArgsException &e)
- {
- throwInvalidArgsException(env, e.code(), e.what());
- return;
+ SimulatorManager::getInstance()->deleteResource(type);
}
catch (...)
{
JNIEXPORT void JNICALL
Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
-(JNIEnv *env, jobject object, jobject listener)
+(JNIEnv *env, jobject object, jstring jResourceType, jobject jListener)
{
- 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 (...)
+ if (!jListener)
{
- throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return;
}
-}
-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)
}
JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
- resourceListener->setJavaFoundResourceListener(env, listener);
+ resourceListener->setJavaFoundResourceListener(env, jListener);
try
{
- SimulatorManager::getInstance()->findResources(resourceType,
+ if (!jResourceType)
+ {
+ SimulatorManager::getInstance()->findResource(
std::bind(&JNIFoundResourceListener::onFoundResource,
resourceListener, std::placeholders::_1));
+ }
+ else
+ {
+ SimulatorManager::getInstance()->findResource(resourceType,
+ std::bind(&JNIFoundResourceListener::onFoundResource,
+ resourceListener, std::placeholders::_1));
+ }
+
}
catch (InvalidArgsException &e)
{
Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
(JNIEnv *env, jclass object, jobject logger)
{
- static std::shared_ptr<ILogger> target(new JNILogger());
- dynamic_cast<JNILogger *>(target.get())->setJavaLogger(env, logger);
+ static std::shared_ptr<JNILogger> target(new JNILogger());
+ target->setJavaLogger(env, logger);
SimulatorManager::getInstance()->setLogger(target);
}
JNIEXPORT void 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 void JNICALL
return;
}
- jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env,
+ reinterpret_cast<jlong>(jniModel));
if (!jRepresentation)
{
+ delete jniModel;
releaseEnv();
return;
}
jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted",
- "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
if (!midL)
{
+ delete jniModel;
releaseEnv();
return;
}
static_cast<jint>(seqNumber));
if (env->ExceptionCheck())
{
+ delete jniModel;
releaseEnv();
}
}
}
jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-
if (!jRepresentation)
{
+ delete jniModel;
releaseEnv();
return;
}
"(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
+ delete jniModel;
releaseEnv();
return;
}
jstring jUid = env->NewStringUTF(uId.c_str());
-
env->CallVoidMethod(onGetListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
+ delete jniModel;
releaseEnv();
}
}
return;
}
- jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env,
+ reinterpret_cast<jlong>(jniModel));
if (!jRepresentation)
{
+ delete jniModel;
releaseEnv();
return;
}
jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted",
- "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
+ delete jniModel;
releaseEnv();
return;
}
jstring jUid = env->NewStringUTF(uId.c_str());
-
env->CallVoidMethod(onPutListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
+ delete jniModel;
releaseEnv();
}
}
return;
}
- jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
-
+ jobject jRepresentation = JSimulatorResourceModel::toJava(env,
+ reinterpret_cast<jlong>(jniModel));
if (!jRepresentation)
{
+ delete jniModel;
releaseEnv();
return;
}
jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted",
- "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+ "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
if (!midL)
{
+ delete jniModel;
releaseEnv();
return;
}
env->CallVoidMethod(onPostListener, midL, jUid, jRepresentation);
if (env->ExceptionCheck())
{
+ delete jniModel;
releaseEnv();
}
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_observe
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve
(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
{
if (!jListener)
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve
(JNIEnv *env, jobject thiz)
{
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
(JNIEnv *env, jobject thiz, jstring jConfigPath)
{
+ if (!jConfigPath)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+ "Configuration file path is empty!");
+ return;
+ }
+
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
{
if (!jListener)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
- return -1;
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+ return SIMULATOR_INVALID_CALLBACK;
}
-
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
- return -1;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
+ return SIMULATOR_BAD_OBJECT;
}
// Convert RequestType
{
SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
thiz);
- if (nullptr == resource)
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
#endif
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_observe
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve
(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve
(JNIEnv *env, jobject thiz);
JNIEXPORT void JNICALL
jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
(JNIEnv *env, jobject thiz, jstring jConfigPath);
JNIEXPORT jint JNICALL
{
if (observersList.empty())
{
- std::cout << "observersList Map is empty";
return NULL;
}
#include "simulator_common_jni.h"
#include "resource_attributes_jni.h"
#include "simulator_error_codes.h"
+#include "simulator_jni_utils.h"
using namespace std;
JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
if (env->ExceptionCheck())
{
- cout << "Exception while converting the nativeHandle to JSimulatorResourceModel" << endl;
return false;
}
bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
if (!result)
{
- return SIMULATOR_ERROR;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
+ return SIMULATOR_BAD_OBJECT;
}
return resourceModel.size();
bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
if (!result)
{
- return NULL;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
+ return nullptr;
}
map<string, SimulatorResourceModel::Attribute> attributesMap = resourceModel.getAttributes();
jHashMap = createHashMap(env);
if (!jHashMap)
{
- return NULL;
+ throwSimulatorException(env, SIMULATOR_ERROR, "Java map creation failed!");
+ return nullptr;
}
for (auto & attributeEntry : attributesMap)
{
if (!jAttrName)
{
- return NULL;
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
+ return nullptr;
}
const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
if (!attrName)
{
- return NULL;
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
+ return nullptr;
}
SimulatorResourceModel resourceModel;
if (!result)
{
env->ReleaseStringUTFChars(jAttrName, attrName);
- return NULL;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
+ return nullptr;
}
SimulatorResourceModel::Attribute attribute;
if (!found)
{
env->ReleaseStringUTFChars(jAttrName, attrName);
- return NULL;
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute does not exist!");
+ return nullptr;
}
env->ReleaseStringUTFChars(jAttrName, attrName);
Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
(JNIEnv *env, jobject thiz, jstring jname, jint jvalue)
{
+ if (!jname)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
+ return;
+ }
+
SimulatorResourceModelSP resModelPtr;
resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
if (!resModelPtr)
{
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
return;
}
const char *nameCstr = env->GetStringUTFChars(jname, NULL);
if (!nameCstr)
{
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
return;
}
Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue)
{
+ if (!jname)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
+ return;
+ }
+
SimulatorResourceModelSP resModelPtr;
resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
if (!resModelPtr)
{
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
return;
}
const char *nameCstr = env->GetStringUTFChars(jname, NULL);
if (!nameCstr)
{
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
return;
}
Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue)
{
+ if (!jname)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
+ return;
+ }
+
SimulatorResourceModelSP resModelPtr;
resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
if (!resModelPtr)
{
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
return;
}
const char *nameCstr = env->GetStringUTFChars(jname, NULL);
if (!nameCstr)
{
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
return;
}
Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
(JNIEnv *env, jobject thiz, jstring jname, jstring jvalue)
{
+ if (!jname)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
+ return;
+ }
+
SimulatorResourceModelSP resModelPtr;
resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
if (!resModelPtr)
{
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
return;
}
const char *nameCstr = env->GetStringUTFChars(jname, NULL);
if (!nameCstr)
{
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
return;
}
if (!valueCstr)
{
env->ReleaseStringUTFChars(jname, nameCstr);
+ throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
return;
}
JSimulatorResourceModel *resourceModel = GetHandle<JSimulatorResourceModel>(env, thiz);
delete resourceModel;
}
-
void onAutomationComplete(jweak jlistenerRef, const std::string &uri,
const int automationID)
{
- std::cout << "onAutomationComplete JNI entry" << std::endl;
JNIEnv *env = getEnv();
if (nullptr == env)
return;
(JNIEnv *env, jobject object)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return nullptr;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (resource)
+ if (!resource)
{
- throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (resource)
+ if (!resource)
{
- throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (resource)
+ if (!resource)
{
- throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (resource)
+ if (!resource)
{
- throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (resource)
+ if (!resource)
{
- throwSimulatorException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
- return -1;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
+ return SIMULATOR_BAD_OBJECT;
}
if (!listener)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
"Start Resource Automation failed! Callback not set");
- return -1;
+ return SIMULATOR_INVALID_CALLBACK;
}
jweak jlistenerRef = env->NewWeakGlobalRef(listener);
(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
- return -1;
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
+ return SIMULATOR_BAD_OBJECT;
}
if (!attrName)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
- return -1;
+ return SIMULATOR_INVALID_PARAM;
}
if (!listener)
{
throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
"Start Attribute Automation failed! Callback not set");
- return -1;
+ return SIMULATOR_INVALID_CALLBACK;
}
jweak jlistenerRef = env->NewWeakGlobalRef(listener);
(JNIEnv *env, jobject object, jint automationId)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
jobject);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
(JNIEnv *env, jobject object)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return nullptr;
}
(JNIEnv *env, jobject object, jobject jcallback)
{
if (!jcallback)
+ {
+ throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Callback not set");
return;
+ }
jweak jlistenerRef = env->NewWeakGlobalRef(jcallback);
SimulatorResourceServer::ObserverCB callback = [jlistenerRef](const std::string & uri,
};
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
(JNIEnv *env, jobject object, jint jId)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
(JNIEnv *env, jobject object)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
- if (nullptr == resource.get())
+ if (!resource)
{
- throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+ throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
return;
}
/**
* This method is for getting the device name.
- *
+ *
* @return Device name.
*/
public String getName() {
/**
* This method is for getting the device id.
- *
+ *
* @return Device id.
*/
public String getID() {
/**
* This method is for getting device specification version.
- *
+ *
* @return Specification version.
*/
public String getSpecVersion() {
/**
* This method is for getting device data model version.
- *
+ *
* @return Device data model version.
*/
public String getDataModelVersion() {
public interface IAutomation {
/**
* Callback method for receiving automation complete notifications.
- *
+ *
* @param resourceURI
* URI of the resource on which the automation has occurred.
* @param automationId
public interface IDeviceInfo {
/**
* Callback method which provides remote device information.
- *
+ *
* @param devInfo
* {@link DeviceInfo} object holding the device information.
*/
public interface IPlatformInfo {
/**
* Callback method which provides remote device platform information.
- *
+ *
* @param platformInfo
* {@link PlatformInfo} object holding the platform information.
*/
/**
* This method is for getting platform id.
- *
+ *
* @return Platform id.
*/
public String getPlatformID() {
/**
* This method is for setting platform id.
- *
+ *
* @param mPlatformId
* Platform identifier.
*/
/**
* This method is for getting manufacturer name.
- *
+ *
* @return Manufacturer name.
*/
public String getManufacturerName() {
/**
* This method is for setting manufacturer name.
- *
+ *
* @param m_manufacturerName
* Manufacturer name.
*/
/**
* This method is for getting manufacturer URL.
- *
+ *
* @return Manufacturer URL.
*/
public String getManufacturerUrl() {
/**
* This method is for setting manufacturer URL.
- *
+ *
* @param m_manufacturerUrl
* Manufacturer URL.
*/
/**
* This method is for getting model number.
- *
+ *
* @return Model number.
*/
public String getModelNumber() {
/**
* This method is for setting model number.
- *
+ *
* @param m_modelNumber
* Model number.
*/
/**
* This method is for getting date of manufacture.
- *
+ *
* @return Date of manufacture.
*/
public String getDateOfManufacture() {
/**
* This method is for setting date of manufacture.
- *
+ *
* @param m_dateOfManufacture
* Date of manufacture.
*/
/**
* This method is for getting platform version.
- *
+ *
* @return Platform version.
*/
public String getPlatformVersion() {
/**
* This method is for setting platform version.
- *
+ *
* @param m_platformVersion
* Platform version.
*/
/**
* This method is for getting operating system version.
- *
+ *
* @return Operation system version.
*/
public String getOperationSystemVersion() {
/**
* This method is for setting operating system version.
- *
+ *
* @param m_operationSystemVersion
* Operation system version.
*/
/**
* This method is for getting hardware version.
- *
+ *
* @return Hardware version.
*/
public String getHardwareVersion() {
/**
* This method is for setting hardware version.
- *
+ *
* @param m_hardwareVersion
* Hardware version.
*/
/**
* This method is for getting firmware version.
- *
+ *
* @return Firmware version.
*/
public String getFirmwareVersion() {
/**
* This method is for setting firmware version.
- *
+ *
* @param m_firmwareVersion
* Firmware version.
*/
/**
* This method is for getting support link URL.
- *
+ *
* @return URL of support link.
*/
public String getSupportUrl() {
/**
* This method is for setting support link URL.
- *
+ *
* @param m_supportUrl
* URL of support link.
*/
/**
* This method is for getting system time.
- *
+ *
* @return System time.
*/
public String getSystemTime() {
/**
* This method is for setting system time.
- *
+ *
* @param m_systemTime
* System time.
*/
* Type of attribute value.
*/
public enum Type {
- INT, DOUBLE, BOOL, STRING;
+ UNKNOWN, INT, DOUBLE, BOOL, STRING;
private static Type[] m_cvalues = Type.values();
* @param listener
* Listener for receiving notifications whenever there is a
* change in the resource model.
- *
+ *
* @return {@link SimulatorResourceServer} - Created resource on success,
* otherwise null.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameters are empty.
* @throws SimulatorException
* @param listener
* Listener for receiving notifications whenever there is a
* change in the resource model.
- *
+ *
* @return Returns an array of {@link SimulatorResourceServer} objects one
* for each created resource on success, otherwise null.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameters are empty.
* @throws SimulatorException
*
* @param listener
* Interface to receive the discovered remote resources.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameter is empty.
* @throws SimulatorException
* Thrown for other errors.
*/
- public static void findResources(IFindResourceListener listener)
+ public static void findResource(IFindResourceListener listener)
throws InvalidArgsException, SimulatorException {
- SimulatorManagerNativeInterface.findResources(null, listener);
+ SimulatorManagerNativeInterface.findResource(null, listener);
}
/**
* Required resource type
* @param listener
* Interface to receive the discovered remote resources.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameter is empty.
* @throws SimulatorException
* Thrown for other errors.
*/
- public static void findResources(String resourceType,
+ public static void findResource(String resourceType,
IFindResourceListener listener) throws InvalidArgsException,
SimulatorException {
if (null == resourceType || resourceType.isEmpty()) {
SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
"Resource type is empty");
}
- SimulatorManagerNativeInterface.findResources(resourceType, listener);
+ SimulatorManagerNativeInterface.findResource(resourceType, listener);
}
/**
/**
* API to set the device information.
- *
+ *
* @param deviceInfo
* Device information.
*/
}
/**
- * API to get the device information asynchronously via the listener.
- *
+ * API to get the device information asynchronously via callback
+ * using {@link IDeviceInfo}.
+ *
* @param listener
* Interface for receiving the device information.
*/
/**
* API to set the platform information.
- *
+ *
* @param platformInfo
* {@link PlatformInfo} - Platform information.
*/
}
/**
- * API to get the platform information asynchronously via the listener.
- *
+ * API to get the platform information asynchronously via callback
+ * using {@link IPlatformInfo}..
+ *
* @param listener
* Interface for receiving the platform information.
*/
*
* @return {@link SimulatorResourceServer} object on success, otherwise
* null.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameters are empty.
* @throws SimulatorException
* @param resource
* {@link SimulatorResourceServer} object of the resource to be
* deleted.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameter is empty.
* @throws SimulatorException
*
* @param resourceType
* Type of the resource.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameter is empty.
* @throws SimulatorException
* Thrown for other errors.
*/
public static native void deleteResources(String resourceType)
- throws InvalidArgsException, SimulatorException;
+ throws SimulatorException;
/**
* Native function for discovering resources.
* required resource type
* @param listener
* Interface to receive the discovered remote resources.
- *
+ *
* @throws InvalidArgsException
* Thrown if the input parameter is empty.
* @throws SimulatorException
* Thrown for other errors.
*/
- public static native void findResources(String resourceType,
+ public static native void findResource(String resourceType,
IFindResourceListener listener) throws InvalidArgsException,
SimulatorException;
/**
* Native function to set the logger listener for receiving the log messages
* from native layer.
- *
+ *
* @param logger
* Interface to receive log.
*/
/**
* Native function to set the device information.
- *
+ *
* @param deviceInfo
* Device information.
*/
/**
* Native function to get the device information asynchronously via the
* listener.
- *
+ *
* @param listener
* Interface for receiving the device information.
*/
/**
* Native function to set the platform information.
- *
+ *
* @param platformInfo
* Platform information.
*/
/**
* Native function to get the platform information asynchronously via the
* listener.
- *
+ *
* @param listener
* Interface for receiving the platform information.
*/
}
/**
- * Method for adding an attribute whose value is of type int.
- *
+ * API to add an attribute of type integer.
+ *
* @param name
* Name of the attribute
* @param value
throws InvalidArgsException, SimulatorException;
/**
- * Method for adding an attribute whose value is of type double.
- *
+ * API to add an attribute of type double.
+ *
* @param name
* Name of the attribute
* @param value
throws InvalidArgsException, SimulatorException;
/**
- * Method for adding an attribute whose value is of type boolean.
- *
+ * API to add an attribute of type boolean.
+ *
* @param name
* Name of the attribute
* @param value
throws InvalidArgsException, SimulatorException;
/**
- * Method for adding an attribute whose value is of type string.
- *
+ * API to add an attribute of type string.
+ *
* @param name
* Name of the attribute
* @param value
throws InvalidArgsException, SimulatorException;
/**
- * Method for getting the number of attributes this model comprised of.
+ * API to get number of attributes for this model.
*
* @return Number of attributes.
- *
+ *
* @throws SimulatorException
* This exception will be thrown either if the resource model is
* not found or for some general errors.
public native int size() throws SimulatorException;
/**
- * Method for getting all attributes.
+ * API for getting all attributes.
*
* @return Map of attributes with attribute name as the key and its
* corresponding {@link ResourceAttribute} object as the value.
- *
+ *
* @throws SimulatorException
* This exception will be thrown either if the resource model is
* not found or for some general errors.
throws SimulatorException;
/**
- * Method for getting a specific attribute by its name.
+ * API to get attribute by its name.
*
- * @param attrName
+ * @param name
* Name of the attribute
*
* @return An object of {@link ResourceAttribute}.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if the attribute does not
* exist.
- *
+ *
* @throws SimulatorException
* This exception will be thrown either if the resource model is
* not found or for some general errors.
*/
- public native ResourceAttribute getAttribute(String attrName)
+ public native ResourceAttribute getAttribute(String name)
throws InvalidArgsException, SimulatorException;
private SimulatorResourceModel(long nativeHandle) {
result = SimulatorResult.values()[29];
else if (ordinal == 46)
result = SimulatorResult.values()[30];
-
+
else if (ordinal == 128)
result = SimulatorResult.values()[31];
else if (ordinal == 129)
result = SimulatorResult.values()[36];
else if (ordinal == 134 || ordinal == 50)
result = SimulatorResult.values()[37];
-
+
else if (ordinal == 135 || ordinal == 51)
result = SimulatorResult.values()[38];
else if (ordinal == 136 || ordinal == 52)
result = SimulatorResult.values()[40];
else if (ordinal == 138 || ordinal == 54)
result = SimulatorResult.values()[41];
-
+
else
result = SimulatorResult.values()[42];
return result;
/**
* This method will be called when response from the remote resource for GET
* request arrives.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param representation
/**
* Called when there is an error in GET request.
- *
+ *
* @param ex
* Error information.
*/
/**
* This method will be called when there is a change in the resource model
* of the remote resource.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param representation
/**
* Called when there is an error in observe request.
- *
+ *
* @param ex
* Error information.
*/
/**
* This method will be called when response from the remote resource for
* POST request arrives.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param representation
/**
* Called when there is an error in POST request.
- *
+ *
* @param ex
* Error information.
*/
/**
* This method will be called when response from the remote resource for PUT
* request arrives.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param representation
/**
* Called when there is an error in PUT request.
- *
+ *
* @param ex
* Error information.
*/
public void onPutFailed(Throwable ex);
}
+
public interface IVerificationListener {
/**
* Called when the verification request is accepted and started.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param id
/**
* Called when the verification is stopped before its completion.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param id
/**
* Called when the verification is done.
- *
+ *
* @param uId
* Unique Id of the resource.
* @param id
* Verification Id.
*/
public void onVerificationCompleted(String uId, int id);
-}
\ No newline at end of file
+}
/**
* Method to get the {@link SimulatorConnectivityType} from an integer
* value.
- *
+ *
* @param value
* Integral value of {@link SimulatorConnectivityType}.
* @return {@link SimulatorConnectivityType} corresponding to the given
}
/**
- * Method to get the URI for this resource.
- *
+ * API to get the URI for this resource.
+ *
* @return Resource URI
*/
public String getUri() {
}
/**
- * Method to get the observe capability of this resource.
- *
+ * API to get the observe policy of this resource.
+ *
* @return True if the resource is observable, otherwise false.
*/
public boolean getIsObservable() {
}
/**
- * Method to get the connectivity type for this resource.
- *
+ * API to get the connectivity type for this resource.
+ *
* @return Connectivity type.
*/
public SimulatorConnectivityType getConnectivityType() {
}
/**
- * Method to get the list of resource types.
- *
+ * API to get the list of resource types.
+ *
* @return List of resource types.
*/
public LinkedList<String> getResourceTypes() {
}
/**
- * Method to get the list of resource interfaces.
- *
+ * API to get the list of resource interfaces.
+ *
* @return List of resource interfaces.
*/
public LinkedList<String> getResourceInterfaces() {
}
/**
- * Method to get a string representation of the host address of the remote
- * resource.
- *
+ * API to get host address and port information of the resource.
+ *
* @return Host address.
*/
public String getHost() {
}
/**
- * Method to get a unique Id for the resource.
- *
+ * API to get a unique Id of the resource .
+ *
* @return Unique ID.
*/
public String getId() {
}
/**
- * Method to set observation on the remote resource.
- *
+ * API to start observing the resource.
+ *
* @param observeType
* Allows the client to specify how it wants to observe.
* @param queryParamsMap
* The handler method which will be invoked with a map of
* attribute names and values whenever there is a change in
* resource model of the remote resource.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
* @throws SimulatorException
* This exception will be thrown for other errors.
*/
- public native void observe(SimulatorObserveType observeType,
+ public native void startObserve(SimulatorObserveType observeType,
Map<String, String> queryParamsMap,
IObserveListener onObserveListener) throws InvalidArgsException,
SimulatorException;
/**
- * Method to cancel the observation on the resource.
- *
+ * API to stop observing the resource.
+ *
* @throws InvalidArgsException
* This exception will be thrown if the native remote resource
* object is unavailable.
* @throws SimulatorException
* This exception will be thrown for other errors.
*/
- public native void cancelObserve() throws InvalidArgsException,
+ public native void stopObserve() throws InvalidArgsException,
SimulatorException;
/**
- * Method to get the attributes of a resource.
- *
+ * API to send GET request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IGetListener}.
+ *
* @param queryParamsMap
* Map which can have the query parameter name and value.
* @param onGetListener
* Event handler which will be invoked with the response for GET
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
}
/**
- * Method to get the attributes of a resource.
- *
+ * API to send GET request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IGetListener}.
+ *
* @param resourceInterface
* Interface type of the resource to operate on.
* @param queryParamsMap
* @param onGetListener
* Event handler which will be invoked with the response for GET
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, NoSupportException, SimulatorException;
/**
- * Method to set the representation of a resource (via PUT)
- *
+ * API to send PUT request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IPutListener}.
+ *
* @param representation
* {@link SimulatorResourceModel} holding the representation of
* the resource.
* @param onPutListener
* Event handler which will be invoked with the response for PUT
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* value.
}
/**
- * Method to set the representation of a resource (via PUT).
- *
+ * API to send PUT request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IPutListener}.
+ *
* @param resourceInterface
* Interface type of the resource to operate on.
* @param representation
* @param onPutListener
* Event handler which will be invoked with the response for PUT
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* value.
throws InvalidArgsException, NoSupportException, SimulatorException;
/**
- * Method to POST on a resource.
- *
+ * API to send POST request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IPostListener}.
+ *
* @param representation
* {@link SimulatorResourceModel} holding the representation of
* the resource
* @param onPostListener
* Event handler which will be invoked with the response for POST
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* value.
}
/**
- * Method to POST on a resource.
- *
+ * API to send POST request to the resource. Response will be notified
+ * asynchronously via callback set for {@link IPostListener}.
+ *
* @param resourceInterface
* Interface type of the resource to operate on.
* @param representation
* @param onPostListener
* Event handler which will be invoked with the response for POST
* request with a map of attribute name and values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* value.
throws InvalidArgsException, NoSupportException, SimulatorException;
/**
- * Method to set the RAML file path from application
- *
- * @param ramlPath
- * RAML configuration file path
- *
+ * API to provide remote resource configure information,
+ * which is required for using automation feature.
+ *
+ * @param path
+ * Path to RAML file.
+ *
* @throws InvalidArgsException
* Thrown if the RAML configuration file path is invalid.
* @throws SimulatorException
* Thrown for other errors.
*/
- public native void configureRAMLPath(String ramlPath)
+ public native void setConfigInfo(String path)
throws InvalidArgsException, SimulatorException;
/**
- * Method to start verification of a resource using automation.
- *
+ * API to send multiple requests for the resource, based on
+ * the configure file provided from {@link setConfigInfo}.
+ * This verifies response received as well.
+ *
* @param requestType
* Request type to verify.
* @param onVerifyListener
* This event handler will be invoked with the current status of
* the automation.
- *
+ *
* @return Automation ID.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* value.
return startVerification(requestType.ordinal(), onVerifyListener);
}
- private native int startVerification(int requestType,
- IVerificationListener onVerifyListener)
- throws InvalidArgsException, NoSupportException,
- OperationInProgressException, SimulatorException;
-
/**
- * Method to stop verification of a resource previously started.
- *
+ * API to stop sending requests which has been started using {@link setConfigInfo}.
+ *
* @param id
* Automation ID.
- *
+ *
* @throws InvalidArgsException
* Thrown if the automation ID is invalid.
* @throws NoSupportException
public native void stopVerification(int id) throws InvalidArgsException,
NoSupportException, SimulatorException;
+ private native int startVerification(int requestType,
+ IVerificationListener onVerifyListener)
+ throws InvalidArgsException, NoSupportException,
+ OperationInProgressException, SimulatorException;
+
@Override
protected void finalize() throws Throwable {
super.finalize();
/**
* Method to get the {@link SimulatorVerificationType} from an integer
* value.
- *
+ *
* @param value
* Integral value of {@link SimulatorVerificationType}.
* @return {@link SimulatorVerificationType} corresponding to the given
/**
* This callback method will be called when a new observer is added or an
* existing observer is removed.
- *
+ *
* @param resourceURI
* URI of the resource.
* @param state
/**
* This method is used to return the observer's id.
- *
+ *
* @return Observer's Id.
*/
public int getId() {
/**
* This method is used to return the observer's address.
- *
+ *
* @return Observer's device address.
*/
public String getAddress() {
/**
* This method is used to return the observer's port number.
- *
+ *
* @return Observer's port number.
*/
public int getPort() {
return interfaceType;
}
- @Override
- protected void finalize() throws Throwable {
- try {
- dispose();
- } catch(Throwable t){
- throw t;
- } finally{
- System.out.println("Calling finalize of Super Class");
- super.finalize();
- }
- }
-
- /**
- * Native function to get the {@link SimulatorResourceModel} of the
- * corresponding resource.
+ /**
+ * API to get the {@link SimulatorResourceModel} of the
+ * simulated resource.
*
* @return {@link SimulatorResourceModel} object on success, otherwise null.
- *
- * @throws InvalidArgsException
- * This exception will be thrown if the native resource object
- * is invalid. values.
+ *
* @throws SimulatorException
- * This exception will be thrown for other errors.
+ * This exception will be thrown if simulated resource is not proper.
*/
public native SimulatorResourceModel getModel()
- throws InvalidArgsException, SimulatorException;
+ throws SimulatorException;
/**
- * Native function to add an attribute whose value is of type int.
+ * API to add an attribute whose value is of type int.
*
* @param key
* Name of the attribute.
* @param value
* Initial value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to add an attribute whose value is of type double.
+ * API to add an attribute whose value is of type double.
*
* @param key
* Name of the attribute.
* @param value
* Initial value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to add an attribute whose value is of type boolean.
+ * API to add an attribute whose value is of type boolean.
*
* @param key
* Name of the attribute.
* @param value
* Initial value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to add an attribute whose value is of type String.
+ * API to add an attribute whose value is of type String.
*
* @param key
* Name of the attribute.
* @param value
* Initial value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to update the value of an attribute whose value is of
+ * API to update the value of an attribute whose value is of
* type int.
*
* @param key
* Name of the attribute.
* @param value
* New value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to update the value of an attribute whose value is of
+ * API to update the value of an attribute whose value is of
* type double.
*
* @param key
* Name of the attribute.
* @param value
* New value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to update the value of an attribute whose value is of
+ * API to update the value of an attribute whose value is of
* type boolean.
*
* @param key
* Name of the attribute.
* @param value
* New value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to update the value of an attribute whose value is of
+ * API to update the value of an attribute whose value is of
* type String.
*
* @param key
* Name of the attribute.
* @param value
* New value of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to automatically update the value of an attribute from
+ * API to update the value of an attribute from
* its allowed values.
*
- * @param attrName
+ * @param key
* Name of the attribute.
* @param index
* Index of the value in the allowed values.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
* @throws SimulatorException
* This exception will be thrown for other errors.
*/
- public native void updateAttributeFromAllowedValues(String attrName,
+ public native void updateAttributeFromAllowedValues(String key,
int index) throws InvalidArgsException, SimulatorException;
/**
- * Native function to set the range of allowed values. This function is
- * intended to be used for integral type attributes.
+ * API to set the range of allowed values. This function is
+ * intended to be used for integer type attributes.
*
- * @param attrName
+ * @param key
* Name of the attribute.
* @param min
* Minimum value in the range.
* @param max
* Maximum value in the range.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
* @throws SimulatorException
* This exception will be thrown for other errors.
*/
- public native void setRange(String attrName, int min, int max)
+ public native void setRange(String key, int min, int max)
throws InvalidArgsException, SimulatorException;
/**
- * Native function to set the allowed values of attribute whose value is of
+ * API to set the allowed values of attribute whose value is of
* type int.
*
* @param key
* Name of the attribute.
* @param allowedValues
* Allowed values of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
SimulatorException;
/**
- * Native function to set the allowed values of attribute whose value is of
+ * API to set the allowed values of attribute whose value is of
* type double.
*
* @param key
* Name of the attribute.
* @param allowedValues
* Allowed values of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
SimulatorException;
/**
- * Native function to set the allowed values of attribute whose value is of
+ * API to set the allowed values of attribute whose value is of
* type String.
*
* @param key
* Name of the attribute.
* @param allowedValues
* Allowed values of the attribute.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
SimulatorException;
/**
- * Native function to start the resource level automation. This automation
+ * API to start the resource level automation. This automation
* involves automatically updating all the possible values for all the
* attributes sequentially.
*
* Listener to be notified when automation ends.
*
* @return Automation ID using which the automation can be stopped.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
return startResourceAutomation(typeOfAutomation.getValue(), listener);
}
- private native int startResourceAutomation(int typeOfAutomation,
- IAutomation listener) throws InvalidArgsException,
- SimulatorException;
-
/**
- * Native function to start the attribute level automation. This automation
+ * API to start the attribute level automation. This automation
* involves automatically updating all the possible values for a given
* attribute sequentially.
*
* Listener to be notified when automation ends.
*
* @return Automation ID using which the automation can be stopped.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if any parameter has invalid
* values.
listener);
}
- private native int startAttributeAutomation(String attrName,
- int typeOfAutomation, IAutomation listener)
- throws InvalidArgsException, SimulatorException;
-
/**
- * Native function to stop the automation.
+ * API to stop the automation based on automation id.
*
* @param automationId
* Using which a specific automation can be stopped.
- *
- * @throws InvalidArgsException
- * This exception will be thrown if the native resource object
- * does not exist.
+ *
* @throws SimulatorException
* This exception will be thrown for other errors.
*/
public native void stopAutomation(int automationId)
- throws InvalidArgsException, SimulatorException;
+ throws SimulatorException;
/**
- * Native function to remove an attribute from the resource model.
+ * API to remove an attribute from the simulated resource.
*
* @param key
* Name of the attribute to be deleted.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown either if the parameter has
* invalid value or the native resource object does not exist.
SimulatorException;
/**
- * Native function to get the details of a list of observers.
- *
+ * API to get observers information.
+ *
* @return An array of {@link ObserverInfo} objects.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if the native resource object
* does not exist.
throws InvalidArgsException, SimulatorException;
/**
- * Native function to set callback to receive the clients information who are started or stopped observing the simulated resource.
- *
+ * API to set callback to receive notifications when observer is added/removed.
+ *
* @param observer
* Listener to be notified when clients start/stop observing.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown either if the parameter has
* invalid value or the native resource object does not exist.
throws InvalidArgsException, SimulatorException;
/**
- * Native function which sends notification to a specific observer.
- *
+ * API to notify simulated resource's state to a specific observer.
+ *
* @param id
* Observer's Id.
- *
+ *
* @throws InvalidArgsException
* This exception will be thrown if the native resource object
* does not exist.
SimulatorException;
/**
- * Native function which sends notification to all observers.
- *
+ * API to notify simualted resource's state to all observers.
+ *
* @throws InvalidArgsException
* This exception will be thrown if the native resource object
* does not exist.
public native void notifyAllObservers() throws InvalidArgsException,
SimulatorException;
- /**
- * Native function to release the memory allocated to the native object for
- * SimulatorResourceServer.
- */
+ private native int startResourceAutomation(int typeOfAutomation,
+ IAutomation listener) throws InvalidArgsException,
+ SimulatorException;
+
+ private native int startAttributeAutomation(String attrName,
+ int typeOfAutomation, IAutomation listener)
+ throws InvalidArgsException, SimulatorException;
+
+ @Override
+ protected void finalize() throws Throwable {
+ try {
+ dispose();
+ } catch(Throwable t){
+ throw t;
+ } finally{
+ System.out.println("Calling finalize of Super Class");
+ super.finalize();
+ }
+ }
+
private native void dispose();
}
#include "attribute_generator.h"
AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+ : m_name(attribute.getName()),
+ m_min(INT_MIN),
+ m_max(INT_MAX),
+ m_rangeIndex(-1),
+ m_nextAllowedValueIndex(0),
+ m_prevAllowedValueIndex(0),
+ m_hasRange(false),
+ m_hasAllowedValue(false)
{
- m_name.assign(attribute.getName());
- m_type = attribute.getValueType();
-
- if (!attribute.getValueType())
- attribute.getRange(m_min, m_max);
- if (m_max > 0)
+ if (attribute.getValueType() ==
+ SimulatorResourceModel::Attribute::ValueType::INTEGER)
{
- m_hasRange = true;
+ attribute.getRange(m_min, m_max);
+ if (INT_MIN != m_min && INT_MAX != m_max)
+ {
+ m_hasRange = true;
+ m_rangeIndex = m_min;
+ }
}
-
- if (!m_type)
- m_rangeIndex = m_min;
-
- m_allowedValues = attribute.getAllowedValues();
- if (0 != m_allowedValues.size())
+ else
{
- m_hasAllowedValue = true;
+ m_allowedValues = attribute.getAllowedValues();
+ if (0 != m_allowedValues.size())
+ {
+ m_hasAllowedValue = true;
+ }
+ m_prevAllowedValueIndex = m_allowedValues.size();
}
- 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)
+ if (m_hasRange && m_rangeIndex <= m_max)
{
return true;
}
return false;
}
-AttributeSP AttributeGenerator::next()
+bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute)
{
- AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+ attribute.setName(m_name);
- if (!attr)
- return nullptr;
-
- if (m_hasRange && !m_type)
+ if (m_hasRange)
{
- attr->setName(m_name);
- attr->setValue(m_rangeIndex++);
- return attr;
+ attribute.setValue(m_rangeIndex++);
+ return true;
}
-
- if (m_hasAllowedValue)
+ else 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;
+ attribute.setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+ return true;
}
+
+ return false;
}
-AttributeSP AttributeGenerator::previous()
+bool AttributeGenerator::previous(SimulatorResourceModel::Attribute &attribute)
{
- AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+ attribute.setName(m_name);
- if (!attr)
- return nullptr;
-
- if (m_hasRange && !m_type)
+ if (m_hasRange)
{
- attr->setValue(m_rangeIndex - 1);
- return attr;
+ attribute.setValue(m_rangeIndex - 1);
+ return true;
}
-
- if (m_hasAllowedValue)
+ else 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;
+ attribute.setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+ return true;
}
+
+ return false;
}
{
public:
AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
- ~AttributeGenerator();
bool hasNext();
- AttributeSP next();
- AttributeSP previous();
+ bool next(SimulatorResourceModel::Attribute &attribute);
+ bool previous(SimulatorResourceModel::Attribute &attribute);
+ void reset();
private:
std::string m_name;
- int m_type;
- int m_max;
+ SimulatorResourceModel::Attribute::ValueType m_type;
int m_min;
+ int m_max;
int m_rangeIndex;
int m_nextAllowedValueIndex;
int m_prevAllowedValueIndex;
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;
+ // Create attribute generator for value manipulation
+ std::vector<AttributeGenerator> attributeGenList;
+ for (auto &attributeElement : m_rep->getAttributes())
+ attributeGenList.push_back(AttributeGenerator(attributeElement.second));
- std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
- for (auto & attribute : attributes)
+ if (!attributeGenList.size())
{
- attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+ OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+ return;
}
do
for (auto & attributeGen : attributeGenList)
{
- while (attributeGen->hasNext())
+ 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;
- }
+ SimulatorResourceModelSP repModel(new SimulatorResourceModel);
+ SimulatorResourceModel::Attribute attribute;
+ if (true == attributeGen.next(attribute))
+ repModel->addAttribute(attribute);
// Send the request
m_requestSender->sendRequest(queryParam, repModel,
- std::bind(&POSTRequestGenerator::onResponseReceived,
- this, std::placeholders::_1, std::placeholders::_2), true);
+ std::bind(&POSTRequestGenerator::onResponseReceived,
+ this, std::placeholders::_1, std::placeholders::_2), true);
m_requestCnt++;
}
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;
+ // Create attribute generator for value manipulation
+ std::vector<AttributeGenerator> attributeGenList;
+ for (auto &attributeElement : m_rep->getAttributes())
+ attributeGenList.push_back(AttributeGenerator(attributeElement.second));
- std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
- for (auto & attribute : attributes)
+ if (!attributeGenList.size())
{
- attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+ OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
+ return;
}
+ bool hasNext = false;
+
do
{
if (!m_stopRequested)
while (true)
{
- SimulatorResourceModelSP repModel = std::make_shared<SimulatorResourceModel>();
-
+ SimulatorResourceModelSP repModel(new SimulatorResourceModel);
for (auto & attributeGen : attributeGenList)
{
- if (attributeGen->hasNext())
+ 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);
- }
+ SimulatorResourceModel::Attribute attribute;
+ if (true == attributeGen.next(attribute))
+ repModel->addAttribute(attribute);
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);
- }
+ SimulatorResourceModel::Attribute attribute;
+ if (true == attributeGen.previous(attribute))
+ repModel->addAttribute(attribute);
}
}
{
// Send the request
m_requestSender->sendRequest(queryParam, repModel,
- std::bind(&PUTRequestGenerator::onResponseReceived, this,
- std::placeholders::_1, std::placeholders::_2), true);
+ std::bind(&PUTRequestGenerator::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2), true);
m_requestCnt++;
hasNext = false;
for (auto ele : m_qpDetails)
queryParams[ele.key] = ele.values[ele.index];
- for (int index = m_qpDetails.size(); index >= 0; index--)
+ for (int index = m_qpDetails.size() - 1; index >= 0; index--)
{
m_qpDetails[index].index++;
if (m_qpDetails[index].index >= m_qpDetails[index].values.size()) // Boundary check
SimulatorResourceModelSP &repModel, OC::GetCallback callback)
{
OC::OCRepresentation ocRep;
- if (!repModel)
+ if (repModel)
{
ocRep = repModel->getOCRepresentation();
}
SimulatorResourceModelSP &repModel, OC::GetCallback callback)
{
OC::OCRepresentation ocRep;
- if (!repModel)
+ if (repModel)
ocRep = repModel->getOCRepresentation();
SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n" << getRequestString(queryParams, ocRep));
throw NoSupportException("Resource is not configured with RAML!");
}
- if (m_requestModelList.end() != m_requestModelList.find(type))
+ if (m_requestModelList.end() == m_requestModelList.find(type))
throw NoSupportException("Resource does not support this request type!");
// Local callback for handling progress sate callback
if (m_getRequestSender)
{
return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+ localCallback);
}
break;
if (m_putRequestSender)
{
return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+ localCallback);
}
break;
if (m_postRequestSender)
{
return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
+ localCallback);
}
break;
m_postRequestSender->setRequestModel(m_requestModelList[RequestType::RQ_TYPE_POST]);
}
- if (m_autoRequestGenMngr)
+ if (!m_autoRequestGenMngr)
{
m_autoRequestGenMngr = std::make_shared<AutoRequestGenMngr>();
}
for (auto & action : (resource.second)->getActions())
{
RequestModelSP requestModel = createRequestModel(action.second);
- if (!requestModel)
+ if (requestModel)
modelList[requestModel->type()] = requestModel;
}
}
return nullptr;
}
- // Construcut RequestModel
+ // Construct RequestModel
RequestModelSP requestModel(new RequestModel(getRequestType(actionType)));
// Get the allowed query parameters of the request
SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::RequestResponseBodyPtr
&rep)
{
+ if (!rep)
+ {
+ return nullptr;
+ }
RAML::SchemaPtr schema = rep->getSchema();
if (!schema)
{
SimulatorResourceModelSP repSchema = std::make_shared<SimulatorResourceModel>();
for (auto & propertyEntry : properties->getProperties())
{
+ std::string propName = propertyEntry.second->getName();
+ if ("rt" == propName || "resourceType" == propName || "if" == propName
+ || "p" == propName || "n" == propName || "id" == propName)
+ continue;
+
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
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 =
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>());
return SIMULATOR_UKNOWN_PROPERTY;
}
- int type = attribute.getValueType();
- switch (type)
+ switch (attribute.getValueType())
{
- case 0: // Integer
+ case SimulatorResourceModel::Attribute::ValueType::INTEGER : // Integer
{
SimulatorResult result = validateAttributeInteger(attribute, ocAttribute);
if (SIMULATOR_OK != result)
}
break;
- case 1: // Double
+ case SimulatorResourceModel::Attribute::ValueType::DOUBLE : // Double
{
SimulatorResult result = validateAttributeDouble(attribute, ocAttribute);
if (SIMULATOR_OK != result)
}
break;
- case 2: // String
+ case SimulatorResourceModel::Attribute::ValueType::STRING : // String
{
SimulatorResult result = validateAttributeString(attribute, ocAttribute);
if (SIMULATOR_OK != result)
#include <sstream>
#include <boost/lexical_cast.hpp>
+template <typename T>
+struct TypeConverter
+{
+ constexpr static SimulatorResourceModel::Attribute::ValueType type =
+ SimulatorResourceModel::Attribute::ValueType::UNKNOWN;
+};
+
+template <>
+struct TypeConverter<int>
+{
+ constexpr static SimulatorResourceModel::Attribute::ValueType type =
+ SimulatorResourceModel::Attribute::ValueType::INTEGER;
+};
+
+template <>
+struct TypeConverter<double>
+{
+ constexpr static SimulatorResourceModel::Attribute::ValueType type =
+ SimulatorResourceModel::Attribute::ValueType::DOUBLE;
+};
+
+template <>
+struct TypeConverter<bool>
+{
+ constexpr static SimulatorResourceModel::Attribute::ValueType type =
+ SimulatorResourceModel::Attribute::ValueType::BOOLEAN;
+};
+
+template <>
+struct TypeConverter<std::string>
+{
+ constexpr static SimulatorResourceModel::Attribute::ValueType type =
+ SimulatorResourceModel::Attribute::ValueType::STRING;
+};
+
+class attribute_type_visitor : public boost::static_visitor<
+ SimulatorResourceModel::Attribute::ValueType>
+{
+ public:
+ template <typename T>
+ result_type operator ()(const T &)
+ {
+ return TypeConverter<T>::type;
+ }
+};
+
class to_string_visitor : public boost::static_visitor<std::string>
{
public:
template <typename T>
result_type operator ()(const T &value)
{
- return boost::lexical_cast<std::string>(value);
+ try
+ {
+ return boost::lexical_cast<std::string>(value);
+ }
+ catch (const boost::bad_lexical_cast &e)
+ {
+ return "";
+ }
}
};
m_value = m_allowedValues.at(index);
}
+SimulatorResourceModel::Attribute::ValueType SimulatorResourceModel::Attribute::getValueType() const
+{
+ attribute_type_visitor typeVisitor;
+ return boost::apply_visitor(typeVisitor, m_value);
+}
+
std::string SimulatorResourceModel::Attribute::valueToString() const
{
to_string_visitor visitor;
return m_attributes;
}
+void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute)
+{
+ if (!attribute.getName().empty() &&
+ m_attributes.end() == m_attributes.find(attribute.getName()))
+ {
+ m_attributes[attribute.getName()] = attribute;
+ }
+}
+
void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max)
{
if (m_attributes.end() != m_attributes.find(attrName))
m_stopRequested(false),
m_updateInterval(interval),
m_callback(callback),
- m_finishedCallback(finishedCallback) {}
+ m_finishedCallback(finishedCallback),
+ m_thread(nullptr) {}
void AttributeUpdateAutomation::start()
{
void AttributeUpdateAutomation::stop()
{
m_stopRequested = true;
- m_thread->join();
+ if (m_thread)
+ m_thread->join();
}
void AttributeUpdateAutomation::updateAttribute()
{
setAttributeValue();
}
- catch(SimulatorException &e)
+ catch (SimulatorException &e)
{
break;
}
void AttributeUpdateAutomation::setAttributeValue()
{
- if (0 == m_attribute.getValueType()) // For integer type values
+ SimulatorResourceServerImpl *resourceImpl =
+ dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+ if (!resourceImpl)
+ return;
+
+ if (SimulatorResourceModel::Attribute::ValueType::INTEGER ==
+ 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();
+ resourceImpl->updateAttributeValue(m_attribute.getName(), value);
+ resourceImpl->notifyApp();
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();
+ resourceImpl->updateFromAllowedValues(m_attribute.getName(), index);
+ resourceImpl->notifyApp();
SLEEP_FOR(m_updateInterval);
}
}
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;
+ std::thread *m_thread;
};
typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationSP;
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;
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);
+ SIM_LOG(ILogger::INFO, "Resource automation successfully started [ id: " << m_id << " ]");
m_resourceUpdationList[m_id] = resourceAutomation;
return m_id++;
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);
+ SIM_LOG(ILogger::INFO, "Automation for " << attrName << " attribute has successfully started [ id: "
+ <<
+ m_id << " ]");
m_attrUpdationList[m_id] = attributeAutomation;
return m_id++;
#include "simulator_resource_creator.h"
#include "simulator_logger.h"
#include <RamlParser.h>
-#include <boost/lexical_cast.hpp>
+#include "logger.h"
-using namespace RAML;
+#define TAG "SIM_RESOURCE_CREATOR"
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())
+ RAML::RamlPtr raml;
+
+ try
+ {
+ RAML::RamlParser *ramlParser = new RAML::RamlParser(configPath);
+ raml = ramlParser->getRamlPtr();
+ }
+ catch (RAML::RamlException &e)
+ {
+ OC_LOG_V(ERROR, TAG, "RAML Exception occured! [%s]", e.what());
+ throw;
+ }
+
+ std::map<std::string, RAML::RamlResourcePtr> ramlResources = raml->getResources();
+ RAML::RamlResourcePtr ramlResource;
+ if (0 == ramlResources.size() || (ramlResource = ramlResources.begin()->second) == nullptr)
{
- SimulatorResourceServerImplSP resource(new SimulatorResourceServerImpl());
- resource->setName(resourceElement.first);
- resource->setURI(resourceElement.second->getResourceUri());
+ OC_LOG(ERROR, TAG, "Zero resources detected from RAML!");
+ return nullptr;
+ }
- // 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);
+ if (ramlResource)
+ {
+ SimulatorResourceServerImplSP simResource(new SimulatorResourceServerImpl());
+ simResource->setName(ramlResource->getDisplayName());
+ simResource->setURI(ramlResource->getResourceUri());
- for (auto action : resourceElement.second->getActions())
+ // Get the resource representation schema from GET response body
+ RAML::ActionPtr action = ramlResource->getAction(RAML::ActionType::GET);
+ if (!action)
{
- for (auto response : action.second->getResponses())
+ OC_LOG(ERROR, TAG, "Failed to create resource representation schema as it does not"
+ "posess the GET request!");
+ return nullptr;
+ }
+
+ RAML::ResponsePtr getResponse = action->getResponse("200");
+ if (!getResponse)
+ {
+ OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!");
+ return nullptr;
+ }
+
+ RAML::RequestResponseBodyPtr responseBody = getResponse->getResponseBody("application/json");
+ if (responseBody)
+ {
+ RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();
+ for ( auto &propertyElement : resourceProperties->getProperties())
{
- for (auto bdy : response.second->getResponseBody())
+ if (!propertyElement.second)
+ continue;
+
+ std::string propName = propertyElement.second->getName();
+ if ("rt" == propName || "resourceType" == propName)
{
- 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;
+ simResource->setResourceType(propertyElement.second->getValueString());
+ continue;
}
+ else if ("if" == propName)
+ {
+ simResource->setInterfaceType(propertyElement.second->getValueString());
+ continue;
+ }
+ else if ("p" == propName || "n" == propName || "id" == propName)
+ {
+ continue;
+ }
+
+ // Build representation attribute
+ SimulatorResourceModel::Attribute attribute(propName);
+ switch (propertyElement.second->getValueType())
+ {
+ case 0: // Integer
+ attribute.setValue(propertyElement.second->getValue<int>());
+ break;
+
+ case 1: // Double
+ attribute.setValue(propertyElement.second->getValue<double>());
+ break;
+
+ case 2: // Boolean
+ attribute.setValue(propertyElement.second->getValue<bool>());
+ break;
+
+ case 3: // String
+ attribute.setValue(propertyElement.second->getValue<std::string>());
+ break;
+ }
+
+ // Set attriute update frequency interval
+ attribute.setUpdateFrequencyTime(propertyElement.second->getUpdateFrequencyTime());
+
+ // Set range/supported values set
+ int min = 0, max = 0, multipleof = 0;
+ propertyElement.second->getRange(min, max, multipleof);
+ attribute.setRange(min, max);
+
+ if (propertyElement.second->getAllowedValuesSize() > 0)
+ attribute.setAllowedValues(propertyElement.second->getAllowedValues());
+
+ simResource->addAttribute(attribute);
}
}
+
+ simResource->setURI(constructURI(simResource->getURI()));
+ return simResource;
}
return nullptr;
unsigned int index)
{
m_resModel.updateAttributeFromAllowedValues(attrName, index);
+
+ // Notify all the subscribers
+ notifyAll();
}
void SimulatorResourceServer::removeAttribute(const std::string &attrName)
#define TAG "SIM_RESOURCE_SERVER"
SimulatorResourceServerImpl::SimulatorResourceServerImpl()
- : m_resourceHandle(NULL)
+ : m_resourceHandle(NULL)
{
- m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE);
+ m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
m_interfaceType.assign(OC::DEFAULT_INTERFACE);
}
m_resourceHandle = nullptr;
}
+void SimulatorResourceServerImpl::notifyApp()
+{
+ // Notify the application callback
+ if (m_callback)
+ {
+ m_callback(m_uri, m_resModel);
+ }
+}
+
OC::OCRepresentation SimulatorResourceServerImpl::getOCRepresentation()
{
return m_resModel.getOCRepresentation();
void stop();
- void resourceModified();
+ void notifyApp();
private:
OC::OCRepresentation getOCRepresentation();
bool modifyResourceModel(OC::OCRepresentation &ocRep);
OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
+ void resourceModified();
ResourceModelChangedCB m_callback;
ObserverCB m_observeCallback;
ResourceManager::getInstance()->deleteResource(resource);
}
-void SimulatorManager::deleteResources(const std::string &resourceType)
+void SimulatorManager::deleteResource(const std::string &resourceType)
{
ResourceManager::getInstance()->deleteResources(resourceType);
}
-void SimulatorManager::findResources(ResourceFindCallback callback)
+void SimulatorManager::findResource(ResourceFindCallback callback)
{
SimulatorClient::getInstance()->findResources(callback);
}
-void SimulatorManager::findResources(const std::string &resourceType,
+void SimulatorManager::findResource(const std::string &resourceType,
ResourceFindCallback callback)
{
SimulatorClient::getInstance()->findResources(resourceType, callback);
simLogger().setCustomTarget(logger);
}
-bool SimulatorManager::setDefaultConsoleLogger()
+bool SimulatorManager::setConsoleLogger()
{
return simLogger().setDefaultConsoleTarget();
}
-bool SimulatorManager::setDefaultFileLogger(const std::string &path)
+bool SimulatorManager::setFileLogger(const std::string &path)
{
return simLogger().setDefaultFileTarget(path);
}
\ No newline at end of file