- Updating "links" attribute in resource model of collection when resource is added to
removed from collection.
- Changed from "Single resource" to "Simple resource" for maintaining UI consistency.
- Fix for compilation issue while compiling simulator in debug mode.
- Sending error response based on the schema provided in RAML file.
Change-Id: I33c1037f57128cdfacf10c06c2e3658bf0661f0e
Signed-off-by: Harish Kumara Marappa <h.marappa@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4203
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: RadhaBhavani <radha.p@samsung.com>
Reviewed-by: Madan Lanka <lanka.madan@samsung.com>
std::cout << "Resource type: " << resource->getResourceType() << std::endl;
std::cout << "Interface type:";
for (auto &interfaceType : resource->getInterface())
- std::cout << " " << interfaceType;
+ std::cout << " " << interfaceType << std::endl;
// Attributes
SimulatorResourceModel resModel = resource->getResourceModel();
import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
import oic.simulator.clientcontroller.remoteresource.RemoteResource;
import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
+import oic.simulator.clientcontroller.utils.AttributeValueBuilder;
import oic.simulator.clientcontroller.utils.Constants;
import oic.simulator.clientcontroller.utils.Utility;
private SimulatorResourceModel getUpdatedResourceModel(
Map<String, RemoteResourceAttribute> attMap,
List<PutPostAttributeModel> putPostModelList) throws Exception {
- String attName;
SimulatorResourceModel resourceModel = new SimulatorResourceModel();
- PutPostAttributeModel model;
- RemoteResourceAttribute attribute;
- ValueType attType;
- Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
- while (itr.hasNext()) {
- model = itr.next();
- attName = model.getAttName();
- attribute = attMap.get(attName);
- if (null == attribute) {
- continue;
- }
- attType = attribute.getAttValBaseType();
- if (attType == ValueType.INTEGER) {
- int attValue;
- attValue = Integer.parseInt(model.getAttValue());
- resourceModel.addAttribute(attName,
- new AttributeValue(attValue));
- } else if (attType == ValueType.DOUBLE) {
- double attValue;
- attValue = Double.parseDouble(model.getAttValue());
- resourceModel.addAttribute(attName,
- new AttributeValue(attValue));
- } else if (attType == ValueType.BOOLEAN) {
- String attValue = model.getAttValue();
- if (null != attValue && attValue.length() > 0) {
- attValue = attValue.toLowerCase();
- if (!(attValue.equals("true") || attValue.equals("false"))) {
- throw new Exception("Invalid attribute value");
- }
- }
- resourceModel.addAttribute(attName,
- new AttributeValue(attValue));
- } else if (attType == ValueType.STRING) {
- String attValue;
- attValue = model.getAttValue();
- resourceModel.addAttribute(attName,
- new AttributeValue(attValue));
- }
+ for (PutPostAttributeModel putPostAttribute : putPostModelList)
+ {
+ String attributeName = putPostAttribute.getAttName();
+ RemoteResourceAttribute resourceAttribute = attMap.get(attributeName);
+ AttributeValue attributeValue = AttributeValueBuilder.build(
+ putPostAttribute.getAttValue(), resourceAttribute.getAttValBaseType());
+ resourceModel.addAttribute(attributeName, attributeValue);
}
+
return resourceModel;
}
--- /dev/null
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.utils;
+
+import java.util.Vector;
+
+import org.oic.simulator.AttributeValue;
+
+public class AttributeValueBuilder {
+ public static AttributeValue build(String valueString,
+ AttributeValue.ValueType valueType) {
+ int depth = findDepth(valueString);
+ if (0 == depth) {
+ return handleDepth0(valueString, valueType);
+ } else if (1 == depth) {
+ return handleDepth1(valueString, valueType);
+ } else if (2 == depth) {
+ return handleDepth2(valueString, valueType);
+ } else if (3 == depth) {
+ return handleDepth3(valueString, valueType);
+ }
+
+ return null;
+ }
+
+ private static int findDepth(String value) {
+ int depth = 0;
+ for (char ch : value.toCharArray()) {
+ if (ch == '[')
+ depth++;
+ else
+ break;
+ }
+
+ return depth;
+ }
+
+ private static boolean isValidSyntax(String value) {
+ int count = 0;
+ for (char ch : value.toCharArray()) {
+ if (ch == '[')
+ count++;
+ if (ch == ']')
+ count--;
+ }
+
+ if (count == 0)
+ return true;
+ return false;
+
+ }
+
+ private static AttributeValue handleDepth0(String valueString,
+ AttributeValue.ValueType valueType) {
+ valueString = valueString.trim();
+ if (0 != findDepth(valueString))
+ return null;
+
+ if (valueType == AttributeValue.ValueType.INTEGER)
+ return new AttributeValue(Integer.parseInt(valueString));
+ else if (valueType == AttributeValue.ValueType.DOUBLE)
+ return new AttributeValue(Double.parseDouble(valueString));
+ else if (valueType == AttributeValue.ValueType.BOOLEAN)
+ return new AttributeValue(Boolean.parseBoolean(valueString));
+ else if (valueType == AttributeValue.ValueType.STRING)
+ return new AttributeValue(valueString);
+ return null;
+ }
+
+ private static String[] splitIntoArrays(String value) {
+ Vector<String> values = new Vector<String>();
+ String valueString = new String(value);
+ valueString = valueString.substring(valueString.indexOf('[') + 1,
+ valueString.lastIndexOf(']'));
+
+ int count = 0;
+ int startPos = 0;
+ char[] charArray = valueString.toCharArray();
+ for (int index = 0; index < charArray.length; index++) {
+ if (charArray[index] == '[' && 0 == count++) {
+ startPos = index;
+ }
+
+ if (charArray[index] == ']' && 0 == --count) {
+ values.add(valueString.substring(startPos, index + 1));
+ }
+ }
+
+ String[] result = new String[values.size()];
+ values.toArray(result);
+ return result;
+ }
+
+ private static AttributeValue handleDepth1(String valueString,
+ AttributeValue.ValueType valueType) {
+ valueString = valueString.trim();
+ if (1 != findDepth(valueString) || false == isValidSyntax(valueString))
+ return null;
+
+ valueString = valueString.substring(valueString.indexOf('[') + 1,
+ valueString.lastIndexOf(']'));
+ String[] valuesString = valueString.split(",");
+ if (null == valuesString || 0 == valuesString.length)
+ return null;
+
+ if (valueType == AttributeValue.ValueType.INTEGER) {
+ Integer[] result = new Integer[valuesString.length];
+ for (int index = 0; index < valuesString.length; index++) {
+ Integer value = (Integer) handleDepth0(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+ Double[] result = new Double[valuesString.length];
+ for (int index = 0; index < valuesString.length; index++) {
+ Double value = (Double) handleDepth0(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+ Boolean[] result = new Boolean[valuesString.length];
+ for (int index = 0; index < valuesString.length; index++) {
+ Boolean value = (Boolean) handleDepth0(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.STRING) {
+ return new AttributeValue(valuesString);
+ }
+
+ return null;
+ }
+
+ private static AttributeValue handleDepth2(String valueString,
+ AttributeValue.ValueType valueType) {
+ valueString = valueString.trim();
+ if (2 != findDepth(valueString) || false == isValidSyntax(valueString))
+ return null;
+
+ String[] valuesString = splitIntoArrays(valueString);
+ if (null == valuesString || 0 == valuesString.length)
+ return null;
+
+ if (valueType == AttributeValue.ValueType.INTEGER) {
+ Integer[][] result = new Integer[valuesString.length][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Integer[] value = (Integer[]) handleDepth1(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+ Double[][] result = new Double[valuesString.length][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Double[] value = (Double[]) handleDepth1(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+ Boolean[][] result = new Boolean[valuesString.length][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Boolean[] value = (Boolean[]) handleDepth1(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.STRING) {
+ String[][] result = new String[valuesString.length][];
+ for (int index = 0; index < valuesString.length; index++) {
+ String[] value = (String[]) handleDepth1(valuesString[index],
+ valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ }
+
+ return null;
+ }
+
+ public static AttributeValue handleDepth3(String valueString,
+ AttributeValue.ValueType valueType) {
+ valueString = valueString.trim();
+ if (3 != findDepth(valueString) || false == isValidSyntax(valueString))
+ return null;
+
+ String[] valuesString = splitIntoArrays(valueString);
+ if (null == valuesString || 0 == valuesString.length)
+ return null;
+
+ if (valueType == AttributeValue.ValueType.INTEGER) {
+ Integer[][][] result = new Integer[valuesString.length][][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Integer[][] value = (Integer[][]) handleDepth2(
+ valuesString[index], valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.DOUBLE) {
+ Double[][][] result = new Double[valuesString.length][][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Double[][] value = (Double[][]) handleDepth2(
+ valuesString[index], valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.BOOLEAN) {
+ Boolean[][][] result = new Boolean[valuesString.length][][];
+ for (int index = 0; index < valuesString.length; index++) {
+ Boolean[][] value = (Boolean[][]) handleDepth2(
+ valuesString[index], valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ } else if (valueType == AttributeValue.ValueType.STRING) {
+ String[][][] result = new String[valuesString.length][][];
+ for (int index = 0; index < valuesString.length; index++) {
+ String[][] value = (String[][]) handleDepth2(
+ valuesString[index], valueType).get();
+ if (null == value)
+ return null;
+ result[index] = value;
+ }
+ return new AttributeValue(result);
+ }
+
+ return null;
+ }
+}
@Override
public void createControl(Composite parent) {
- setPageComplete(false);
setTitle(Constants.FIND_PAGE_TITLE);
setMessage(Constants.FIND_PAGE_MESSAGE);
gd = new GridData();
gd.horizontalSpan = 2;
allRbtn.setLayoutData(gd);
+ allRbtn.setSelection(true);
resTypeRbtn = new Button(configGroup, SWT.RADIO);
resTypeRbtn.setText("Specific Resource types (seperated by commas)");
List<PutPostAttributeModel> modelList) {
super(parentShell);
this.modelList = modelList;
- resourceManager = Activator.getDefault().getResourceManager();
}
@Override
public static final String NOTIFY_BUTTON_UNSELECTED = "Notify_Unselected";
public static final String CREATE_PAGE_TITLE = "Create Resource";
- public static final String CREATE_PAGE_MESSAGE = "Create a simple resource from RAML file";
+ public static final String CREATE_PAGE_MESSAGE = "Create a resource from RAML file";
public static final String DELETE_PAGE_TITLE = "Delete Resource";
public static final String DELETE_PAGE_MESSAGE = "Select the resource(s) to be deleted";
private void createSimpleResourcesArea() {
singleResTab = new CTabItem(folder, SWT.NULL);
- singleResTab.setText("Single Resources");
+ singleResTab.setText("Simple Resources");
// Create a group to show all the discovered resources.
// Adding the group to the folder.
addResources.setMenu(addSubMenu);
MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE);
- simpleResources.setText("Single");
+ simpleResources.setText("Simple");
simpleResources.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageDialog
.openError(Display.getDefault().getActiveShell(),
"No possible candidates",
- "There are no possible single resources that can be added.");
+ "There are no possible simple resources that can be added.");
return;
}
removeResources.setMenu(removeSubMenu);
simpleResources = new MenuItem(removeSubMenu, SWT.NONE);
- simpleResources.setText("Single");
+ simpleResources.setText("Simple");
simpleResources.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageDialog
.openError(Display.getDefault().getActiveShell(),
"No possible candidates",
- "There are no possible single resources which can be removed.");
+ "There are no possible simple resources which can be removed.");
return;
}
addResources.setMenu(addSubMenu);
MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE);
- simpleResources.setText("Single");
+ simpleResources.setText("Simple");
simpleResources.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageDialog
.openError(Display.getDefault().getActiveShell(),
"No possible candidates",
- "There are no possible single resources that can be added.");
+ "There are no possible simple resources that can be added.");
return;
}
removeResources.setMenu(removeSubMenu);
simpleResources = new MenuItem(removeSubMenu, SWT.NONE);
- simpleResources.setText("Single");
+ simpleResources.setText("Simple");
simpleResources.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageDialog
.openError(Display.getDefault().getActiveShell(),
"No possible candidates",
- "There are no possible single resources which can be removed.");
+ "There are no possible simple resources which can be removed.");
return;
}
singleContainer.setLayout(layout);
Label lbl = new Label(singleContainer, SWT.NONE);
- lbl.setText("Single Resources:");
+ lbl.setText("Simple Resources:");
gd = new GridData(SWT.FILL, SWT.FILL, true, true);
// gd.grabExcessHorizontalSpace = true;
// gd.horizontalAlignment = SWT.FILL;
innerComp.setLayoutData(gd);
selectAllSingle = new Button(innerComp, SWT.PUSH);
- selectAllSingle.setText("Select All Single");
+ selectAllSingle.setText("Select All Simple");
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
});
deselectAllSingle = new Button(innerComp, SWT.PUSH);
- deselectAllSingle.setText("Deselect All Single");
+ deselectAllSingle.setText("Deselect All Simple");
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
description
.setText("Create a logical device that acts as a top-level logical classification.\n"
+ "\t1. Takes a device name for identication.\n"
- + "\t2. One or more single and collection resources can be added to it.");
+ + "\t2. One or more simple and collection resources can be added to it.");
resOption = ResourceOption.DEVICE;
getWizard().getContainer().updateButtons();
}
public void create() {
super.create();
setTitle("Remove from Collections");
- setMessage("Select one or more collection resources from which the single resource will be removed.");
+ setMessage("Select one or more collection resources from which the simple resource will be removed.");
}
@Override
public void create() {
super.create();
setTitle("Remove from Device");
- setMessage("Select one or more devices from which the single resource will be removed.");
+ setMessage("Select one or more devices from which the simple resource will be removed.");
}
@Override
#define ATTRIBUTE_TYPE_INFO_CLS "org/oic/simulator/AttributeValue$TypeInfo"
#define ATTRIBUTE_PROPERTY_CLS "org/oic/simulator/AttributeProperty"
#define ATTRIBUTE_PROPERTY_TYPE_CLS "org/oic/simulator/AttributeProperty$Type"
+#define AUTOMATION_TYPE_CLS "org/oic/simulator/server/SimulatorResource$AutoUpdateType"
#define SIMULATOR_REMOTE_RESOURCE_CLS "org/oic/simulator/client/SimulatorRemoteResource"
#define OBSERVER_CLS "org/oic/simulator/server/Observer"
getClassRef(env, ATTRIBUTE_TYPE_INFO_CLS, gSimulatorClassRefs.attributeTypeInfoCls);
getClassRef(env, ATTRIBUTE_PROPERTY_CLS, gSimulatorClassRefs.attributePropertyCls);
getClassRef(env, ATTRIBUTE_PROPERTY_TYPE_CLS, gSimulatorClassRefs.attributePropertyTypeCls);
+ getClassRef(env, AUTOMATION_TYPE_CLS, gSimulatorClassRefs.automationTypeCls);
getClassRef(env, OBSERVER_CLS, gSimulatorClassRefs.observerCls);
getClassRef(env, DEVICE_INFO_CLS, gSimulatorClassRefs.deviceInfoCls);
getClassRef(env, PLATFORM_INFO_CLS, gSimulatorClassRefs.platformInfoCls);
env->DeleteGlobalRef(gSimulatorClassRefs.attributeTypeInfoCls);
env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyCls);
env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyTypeCls);
+ env->DeleteGlobalRef(gSimulatorClassRefs.automationTypeCls);
env->DeleteGlobalRef(gSimulatorClassRefs.simulatorRemoteResourceCls);
env->DeleteGlobalRef(gSimulatorClassRefs.observerCls);
env->DeleteGlobalRef(gSimulatorClassRefs.deviceInfoCls);
return nullptr;
}
+static AutomationType AutomationTypeToCpp(JNIEnv *env, jobject jType)
+{
+ static jmethodID ordinalMID = env->GetMethodID(
+ gSimulatorClassRefs.automationTypeCls, "ordinal", "()I");
+
+ int ordinal = env->CallIntMethod(jType, ordinalMID);
+ return AutomationType(ordinal);
+}
+
static void onAutoUpdationComplete(jobject listener, const std::string &uri, const int id)
{
JNIEnv *env = getEnv();
JNIEXPORT jint JNICALL
Java_org_oic_simulator_server_SimulatorSingleResource_startAttributeUpdation
-(JNIEnv *env, jobject object, jstring attrName, jint type, jint interval, jobject listener)
+(JNIEnv *env, jobject object, jstring attrName, jobject type, jint interval, jobject listener)
{
VALIDATE_INPUT_RET(env, !attrName, "Attribute name is null!", -1)
VALIDATE_CALLBACK_RET(env, listener, -1)
};
JniString jniAttrName(env, attrName);
+ AutomationType automationType = AutomationTypeToCpp(env, type);
try
{
- int id = singleResource->startAttributeUpdation(jniAttrName.get(),
- (1 == type) ? AutomationType::RECURRENT : AutomationType::NORMAL,
+ int id = singleResource->startAttributeUpdation(jniAttrName.get(), automationType,
interval, callback);
return id;
}
jclass simulatorCollectionResourceCls;
jclass simulatorResourceModelCls;
jclass simulatorResourceAttributeCls;
+ jclass automationTypeCls;
jclass attributeValueCls;
jclass attributeValueTypeCls;
jclass attributeTypeInfoCls;
void operator ()(const std::vector<SimulatorResourceModel> &values)
{
- std::vector<OC::OCRepresentation> ocRepArray;
+ std::vector<OC::OCRepresentation> ocRepArray(values.size());
for (size_t i = 0; i < values.size(); i++)
{
for (auto &element : values[i].getValues())
}
else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
{
- std::vector<SimulatorResourceModel> subResModelArray;
std::vector<OC::OCRepresentation> ocSubRepArray =
ocAttribute.getValue<std::vector<OC::OCRepresentation>>();
+ std::vector<SimulatorResourceModel> subResModelArray(ocSubRepArray.size());
for (size_t i = 0; i < ocSubRepArray.size(); i++)
{
handleRepresentationType(subResModelArray[i], ocSubRepArray[i]);
}
else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
{
- std::vector<std::vector<SimulatorResourceModel>> subResModelArray;
std::vector<std::vector<OC::OCRepresentation>> ocSubRepArray =
ocAttribute.getValue<std::vector<std::vector<OC::OCRepresentation>>>();
+ std::vector<std::vector<SimulatorResourceModel>> subResModelArray(ocSubRepArray.size());
for (size_t i = 0; i < ocSubRepArray.size(); i++)
{
+ std::vector<SimulatorResourceModel> innerArray1(ocSubRepArray[i].size());
for (size_t j = 0; j < ocSubRepArray[i].size(); j++)
- {
- handleRepresentationType(subResModelArray[i][j], ocSubRepArray[i][j]);
- }
+ handleRepresentationType(innerArray1[j], ocSubRepArray[i][j]);
+ subResModelArray[i] = innerArray1;
}
resModel.add<std::vector<std::vector<SimulatorResourceModel>>>(
}
else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type())
{
- std::vector<std::vector<std::vector<SimulatorResourceModel>>> subResModelArray;
std::vector<std::vector<std::vector<OC::OCRepresentation>>> ocSubRepArray =
ocAttribute.getValue<std::vector<std::vector<std::vector<OC::OCRepresentation>>>>();
+ std::vector<std::vector<std::vector<SimulatorResourceModel>>> subResModelArray(ocSubRepArray.size());
for (size_t i = 0; i < ocSubRepArray.size(); i++)
{
+ std::vector<std::vector<SimulatorResourceModel>> innerArray1(ocSubRepArray[i].size());
for (size_t j = 0; j < ocSubRepArray[i].size(); j++)
{
- for (size_t k = 0; k < ocSubRepArray[i].size(); k++)
+ std::vector<SimulatorResourceModel> innerArray2(ocSubRepArray[i][j].size());
+ for (size_t k = 0; k < ocSubRepArray[i][j].size(); k++)
{
- handleRepresentationType(subResModelArray[i][j][k], ocSubRepArray[i][j][k]);
+ handleRepresentationType(innerArray2[k], ocSubRepArray[i][j][k]);
}
+ innerArray1[j] = innerArray2;
}
+ subResModelArray[i] = innerArray1;
}
resModel.add<std::vector<std::vector<std::vector<SimulatorResourceModel>>>>(
m_childProperty.reset(new SimulatorResourceModel::AttributeProperty(childProperty));
}
-std::shared_ptr<SimulatorResourceModel::AttributeProperty>
-SimulatorResourceModel::AttributeProperty::getChildProperty()
+std::shared_ptr<SimulatorResourceModel::AttributeProperty> SimulatorResourceModel::AttributeProperty::getChildProperty()
{
return m_childProperty;
}
{
if (false == m_resource->updateAttributeValue(attribute))
{
- OC_LOG_V(ERROR, TAG, "Failed to update the attribute![%s]", attribute.getName());
+ OC_LOG_V(ERROR, ATAG, "Failed to update the attribute![%s]", attribute.getName().c_str());
continue;
}
resourceImpl->notifyApp();
SimulatorResourceModel::Attribute attribute;
if (false == resource->getAttribute(attrName, attribute))
{
- OC_LOG_V(ERROR, ATAG, "Attribute:%s not present in resource!", m_attrName.c_str());
+ OC_LOG_V(ERROR, TAG, "Attribute:%s not present in resource!", attrName.c_str());
throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
}
}
m_childResources[resource->getURI()] = resource;
+ addLink(resource);
+
+ // Notify application and observers
+ if (m_modelCallback)
+ m_modelCallback(m_uri, m_resModel);
+ notifyAll();
}
void SimulatorCollectionResourceImpl::removeChildResource(SimulatorResourceSP &resource)
throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!");
}
+ removeLink(resource->getURI());
m_childResources.erase(m_childResources.find(resource->getURI()));
+
+ // Notify application and observers
+ if (m_modelCallback)
+ m_modelCallback(m_uri, m_resModel);
+ notifyAll();
}
void SimulatorCollectionResourceImpl::removeChildResource(const std::string &uri)
throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!");
}
+ removeLink(uri);
m_childResources.erase(m_childResources.find(uri));
+
+ // Notify application and observers
+ if (m_modelCallback)
+ m_modelCallback(m_uri, m_resModel);
+ notifyAll();
}
std::vector<SimulatorResourceSP> SimulatorCollectionResourceImpl::getChildResources()
if ("GET" == request->getRequestType())
{
// Construct the representation
- OC::OCRepresentation ocRep = prepareRepresentation();
+ OC::OCRepresentation ocRep = m_resModel.getOCRepresentation();
response = std::make_shared<OC::OCResourceResponse>();
response->setErrorCode(200);
response->setResponseResult(OC_EH_OK);
// Construct the representation
OC::OCRepresentation ocRep;
std::vector<OC::OCRepresentation> links;
- int index = 0;
for (auto &entry : m_childResources)
{
- links[index].setValue("href", entry.second->getURI());
- links[index].setValue("rt", entry.second->getResourceType());
- links[index].setValue("if", entry.second->getInterface()[0]);
+ OC::OCRepresentation oicLink;
+ oicLink.setValue("href", entry.second->getURI());
+ oicLink.setValue("rt", entry.second->getResourceType());
+ oicLink.setValue("if", entry.second->getInterface()[0]);
+ links.push_back(oicLink);
}
ocRep.setValue("links", links);
std::shared_ptr<OC::OCResourceResponse> response(new OC::OCResourceResponse());
response->setErrorCode(200);
response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(prepareRepresentation(), OC::DEFAULT_INTERFACE);
+
+ OC::OCRepresentation ocRep = m_resModel.getOCRepresentation();
+ response->setResourceRepresentation(ocRep, OC::DEFAULT_INTERFACE);
typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &,
const std::shared_ptr<OC::OCResourceResponse>);
m_resourceHandle, observers, response);
}
-OC::OCRepresentation SimulatorCollectionResourceImpl::prepareRepresentation()
+void SimulatorCollectionResourceImpl::addLink(SimulatorResourceSP &resource)
{
- OC::OCRepresentation ocRep;
+ std::lock_guard<std::mutex> lock(m_modelLock);
+ if (!m_resModel.containsAttribute("links"))
+ return;
- ocRep.setValue("n", getName());
- ocRep.setResourceTypes({m_resourceType});
- ocRep.setResourceInterfaces(m_interfaces);
+ // Create new OIC Link
+ SimulatorResourceModel newLink;
+ newLink.add("href", resource->getURI());
+ newLink.add("rt", resource->getResourceType());
+ newLink.add("if", resource->getInterface()[0]);
- // Add "rts" attribute
- std::ostringstream supportedTypes;
- for (auto &type : m_supportedTypes)
+ // Add OIC Link if it is not present
+ bool found = false;
+ std::vector<SimulatorResourceModel> links = m_resModel.get<std::vector<SimulatorResourceModel>>("links");
+ for (auto &link : links)
{
- if (!supportedTypes.str().empty())
- supportedTypes << " ,";
- supportedTypes << type;
+ std::string linkURI = link.get<std::string>("href");
+ if (linkURI == resource->getURI())
+ {
+ break;
+ found = true;
+ }
}
- ocRep.setValue("rts", supportedTypes.str());
- // Add "links" attribute
- std::vector<OC::OCRepresentation> links;
- int index = 0;
- for (auto &entry : m_childResources)
+ if (false == found)
{
- links[index].setValue("href", entry.second->getURI());
- links[index].setValue("rt", entry.second->getResourceType());
- links[index].setValue("if", entry.second->getInterface()[0]);
+ links.push_back(newLink);
+ m_resModel.updateValue("links", links);
}
+}
- ocRep.setValue("links", links);
+void SimulatorCollectionResourceImpl::removeLink(std::string uri)
+{
+ std::lock_guard<std::mutex> lock(m_modelLock);
+ if (!m_resModel.containsAttribute("links"))
+ return;
- return ocRep;
+ // Add OIC Link if it is not present
+ std::vector<SimulatorResourceModel> links = m_resModel.get<std::vector<SimulatorResourceModel>>("links");
+ for (size_t i = 0; i < links.size(); i++)
+ {
+ std::string linkURI = links[i].get<std::string>("href");
+ if (linkURI == uri)
+ {
+ links.erase(links.begin()+i);
+ m_resModel.updateValue("links", links);
+ break;
+ }
+ }
}
std::shared_ptr<OC::OCResourceResponse> requestOnBatchInterface(
std::shared_ptr<OC::OCResourceRequest> request);
void sendNotification(OC::ObservationIds &observers);
- OC::OCRepresentation prepareRepresentation();
+ void addLink(SimulatorResourceSP &resource);
+ void removeLink(std::string uri);
SimulatorResource::Type m_type;
std::string m_name;
#include "simulator_resource_factory.h"\r
#include "simulator_single_resource_impl.h"\r
#include "simulator_collection_resource_impl.h"\r
-#include "RamlParser.h"\r
#include "simulator_logger.h"\r
#include "logger.h"\r
\r
return itemModel;\r
}\r
\r
-std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(\r
- std::shared_ptr<RAML::RamlResource> ramlResource)\r
+RAML::RequestResponseBodyPtr SimulatorResourceFactory::getRAMLResponseBody(\r
+ std::shared_ptr<RAML::RamlResource> ramlResource, RAML::ActionType type, std::string responseCode)\r
{\r
- std::string name;\r
- std::string uri;\r
- std::string resourceType;\r
- std::vector<std::string> interfaceType;\r
-\r
- name = ramlResource->getDisplayName();\r
- uri = ramlResource->getResourceUri();\r
-\r
- // Get the resource representation schema from GET response body\r
- RAML::ActionPtr action = ramlResource->getAction(RAML::ActionType::GET);\r
+ // Get the resource representation schema from response body\r
+ RAML::ActionPtr action = ramlResource->getAction(type);\r
if (!action)\r
{\r
- OC_LOG(ERROR, TAG, "Resource does not possess the GET request!");\r
+ OC_LOG(ERROR, TAG, "Resource does not possess the request!");\r
return nullptr;\r
}\r
\r
- RAML::ResponsePtr getResponse = action->getResponse("200");\r
- if (!getResponse)\r
+ RAML::ResponsePtr response = action->getResponse(responseCode);\r
+ if (!response)\r
{\r
OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!");\r
return nullptr;\r
}\r
\r
- RAML::RequestResponseBodyPtr responseBody = getResponse->getResponseBody("application/json");\r
+ RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");\r
if (!responseBody)\r
{\r
OC_LOG(ERROR, TAG, "GET response is not of type \"application/json\" ");\r
return nullptr;\r
}\r
\r
- // Iterate throgh all resource property and extract information needed for simulating resource\r
- RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();\r
+ return responseBody;\r
+}\r
+\r
+SimulatorResourceModel SimulatorResourceFactory::buildModelFromResponseBody(\r
+ RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector<std::string> &interfaceType)\r
+{\r
SimulatorResourceModel resModel;\r
+\r
+ if (!responseBody)\r
+ return resModel;\r
+\r
+ // Iterate throgh all resource property and extract information needed for simulating resource.\r
+ RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();\r
+\r
+\r
for ( auto &propertyElement : resourceProperties->getProperties())\r
{\r
if (!propertyElement.second)\r
resModel.add("links", arrayResModel);\r
}\r
\r
+ return resModel;\r
+}\r
+\r
+std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(\r
+ std::shared_ptr<RAML::RamlResource> ramlResource)\r
+{\r
+ std::string name;\r
+ std::string uri;\r
+ std::string resourceType, rt;\r
+ std::vector<std::string> interfaceType, ifType;\r
+\r
+ name = ramlResource->getDisplayName();\r
+ uri = ramlResource->getResourceUri();\r
+\r
+ RAML::RequestResponseBodyPtr successResponseBody = getRAMLResponseBody(\r
+ ramlResource, RAML::ActionType::GET, "200");\r
+ RAML::RequestResponseBodyPtr putErrorResponseBody = getRAMLResponseBody(\r
+ ramlResource, RAML::ActionType::PUT, "403");\r
+ RAML::RequestResponseBodyPtr postErrorResponseBody = getRAMLResponseBody(\r
+ ramlResource, RAML::ActionType::POST, "403");\r
+\r
+ SimulatorResourceModel successResponseModel = buildModelFromResponseBody(\r
+ successResponseBody, resourceType, interfaceType);\r
+ SimulatorResourceModel putErrorResponseModel = buildModelFromResponseBody(\r
+ putErrorResponseBody, rt, ifType);\r
+ SimulatorResourceModel postErrorResponseModel = buildModelFromResponseBody(\r
+ postErrorResponseBody, rt, ifType);\r
+\r
// Create simple/collection resource\r
std::shared_ptr<SimulatorResource> simResource;\r
- if (resModel.containsAttribute("links"))\r
+ if (successResponseModel.containsAttribute("links"))\r
{\r
try\r
{\r
collectionRes->setInterface(interfaceType);\r
collectionRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri));\r
\r
- collectionRes->setResourceModel(resModel);\r
+ collectionRes->setResourceModel(successResponseModel);\r
simResource = std::dynamic_pointer_cast<SimulatorResource>(collectionRes);\r
}\r
catch (InvalidArgsException &e) {}\r
singleRes->setInterface(interfaceType);\r
singleRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri));\r
\r
- singleRes->setResourceModel(resModel);\r
+ singleRes->setResourceModel(successResponseModel);\r
+ singleRes->setPutErrorResponseModel(putErrorResponseModel);\r
+ singleRes->setPostErrorResponseModel(postErrorResponseModel);\r
+\r
simResource = std::dynamic_pointer_cast<SimulatorResource>(singleRes);\r
}\r
catch (InvalidArgsException &e) {}\r
#include "simulator_single_resource.h"
#include "simulator_collection_resource.h"
+#include "RamlParser.h"
namespace RAML
{
SimulatorResourceModel::Attribute buildAttribute(
std::shared_ptr<RAML::Properties> propertyElement);
SimulatorResourceModel buildResourceModel(std::shared_ptr<RAML::Items> item);
+ SimulatorResourceModel buildModelFromResponseBody(
+ RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector<std::string> &interfaceType);
+ RAML::RequestResponseBodyPtr getRAMLResponseBody(
+ std::shared_ptr<RAML::RamlResource> ramlResource, RAML::ActionType type, std::string responseCode);
std::shared_ptr<SimulatorResource> buildResource(
std::shared_ptr<RAML::RamlResource> ramlResource);
m_resModel = resModel;
}
+void SimulatorSingleResourceImpl::setPutErrorResponseModel(const SimulatorResourceModel &resModel)
+{
+ m_putErrorResModel = resModel;
+}
+
+void SimulatorSingleResourceImpl::setPostErrorResponseModel(const SimulatorResourceModel &resModel)
+{
+ m_postErrorResModel = resModel;
+}
+
void SimulatorSingleResourceImpl::notifyApp(SimulatorResourceModel &resModel)
{
if (m_modelCallback)
std::shared_ptr<OC::OCResourceResponse> response;
if ("GET" == request->getRequestType())
{
+ OC::OCRepresentation ocRep = m_resModel.getOCRepresentation();
response = std::make_shared<OC::OCResourceResponse>();
response->setErrorCode(200);
response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(m_resModel.getOCRepresentation());
- std::string resPayload = getPayloadString(m_resModel.getOCRepresentation());
+ response->setResourceRepresentation(ocRep);
+ std::string resPayload = getPayloadString(ocRep);
SIM_LOG(ILogger::INFO, "[" << m_uri <<
"] Sending response for GET request. \n**Payload details**" << resPayload)
}
response = std::make_shared<OC::OCResourceResponse>();
response->setErrorCode(400);
response->setResponseResult(OC_EH_ERROR);
+ if ("PUT" == request->getRequestType())
+ {
+ if (m_putErrorResModel.getOCRepresentation().empty())
+ response->setResourceRepresentation(m_resModel.getOCRepresentation());
+ else
+ response->setResourceRepresentation(m_putErrorResModel.getOCRepresentation());
+ }
+ else
+ {
+ if (m_postErrorResModel.getOCRepresentation().empty())
+ response->setResourceRepresentation(m_resModel.getOCRepresentation());
+ else
+ response->setResourceRepresentation(m_postErrorResModel.getOCRepresentation());
+ }
}
}
else if ("DELETE" == request->getRequestType())
std::vector<int> getAttributeUpdationIds();
void stopUpdation(const int id);
void setResourceModel(const SimulatorResourceModel &resModel);
+ void setPutErrorResponseModel(const SimulatorResourceModel &resModel);
+ void setPostErrorResponseModel(const SimulatorResourceModel &resModel);
void notifyApp();
void notifyApp(SimulatorResourceModel &resModel);
std::recursive_mutex m_objectLock;
std::mutex m_modelLock;
SimulatorResourceModel m_resModel;
+ SimulatorResourceModel m_putErrorResModel;
+ SimulatorResourceModel m_postErrorResModel;
ResourceModelChangedCallback m_modelCallback;
ObserverCallback m_observeCallback;
UpdateAutomationMngr m_updateAutomationMgr;
VALIDATE_INPUT(configPath.empty(), "Empty path!")
std::shared_ptr<SimulatorResource> resource =
- SimulatorResourceFactory::getInstance()->createResource(configPath);
+ SimulatorResourceFactory::getInstance()->createResource(configPath);
if (!resource)
throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
return resource;
VALIDATE_INPUT(!count, "Count is zero!")
std::vector<std::shared_ptr<SimulatorResource>> resources =
- SimulatorResourceFactory::getInstance()->createResource(configPath, count);
+ SimulatorResourceFactory::getInstance()->createResource(configPath, count);
if (!resources.size())
throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
return resources;