simulator_env.AppendUnique(CPPPATH = [
'../../resource/include/',
'../../resource/csdk/stack/include',
- '../../resource/csdk/ocrandom/include',
+ '../../resource/c_common/ocrandom/include',
'../../resource/csdk/logger/include',
'../../resource/oc_logger/include',
'./ramlparser/raml',
simulator_env.AppendUnique(CPPPATH = java_headers)
simulator_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
-simulator_env.PrependUnique(LIBS = ['oc', 'RamlParser'])
+simulator_env.PrependUnique(LIBS = ['octbstack', 'oc', 'RamlParser'])
simulator_env.AppendUnique(LIBS = ['pthread'])
simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
std::cout << "9. Set Logger" << std::endl;
std::cout << "10. Set Device Info" << std::endl;
std::cout << "11. Set Platform Info" << std::endl;
- std::cout << "12. Help" << std::endl;
+ std::cout << "12. Add Interface" << std::endl;
+ std::cout << "13. Remove Interface" << std::endl;
+ std::cout << "14. Help" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "######################################" << std::endl;
}
std::cout << "Setting Platform Info is successful" << std::endl;
}
+void addInterface()
+{
+ int index = selectResource();
+ if (-1 == index)
+ return;
+
+ SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+
+ std::vector<std::string> interfaces;
+ interfaces.push_back("oic.if.s");
+ interfaces.push_back("oic.if.a");
+
+ resource->addInterface(interfaces);
+}
+
+void removeInterface()
+{
+ int index = selectResource();
+ if (-1 == index)
+ return;
+
+ SimulatorSingleResourceSP resource = g_singleResources[index - 1];
+
+ std::vector<std::string> interfaces;
+ interfaces.push_back("oic.if.s");
+ interfaces.push_back("oic.if.a");
+
+ resource->removeInterface(interfaces);
+}
+
int main(int argc, char *argv[])
{
printMainMenu();
int choice = -1;
std::cout << "Enter your choice: ";
std::cin >> choice;
- if (choice < 0 || choice > 12)
+ if (choice < 0 || choice > 14)
{
std::cout << "Invaild choice !" << std::endl; continue;
}
case 9 : setLogger(); break;
case 10: setDeviceInfo(); break;
case 11: setPlatformInfo(); break;
- case 12: printMainMenu(); break;
+ case 12: addInterface(); break;
+ case 13: removeInterface(); break;
+ case 14: printMainMenu(); break;
case 0: cont = false;
}
}
*
* NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
*/
- virtual void addInterface(std::string interfaceType) = 0;
+ virtual void addInterface(const std::string &interfaceType) = 0;
+
+ /**
+ * API to add a list of interface types for the resource.
+ *
+ * @param interfaceList - List of interfaces to be added for the resource.
+ *
+ * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+ */
+ virtual void addInterface(const std::vector<std::string> &interfaceList) = 0;
+
+ /**
+ * API to remove interface type for resource.
+ *
+ * @param interfaceType - interface to be removed for resource.
+ *
+ */
+ virtual void removeInterface(const std::string &interfaceType) = 0;
+
+ /**
+ * API to remove a list of interface types for the resource.
+ *
+ * @param interfaceList - List of interfaces to be removed for the resource.
+ *
+ */
+ virtual void removeInterface(const std::vector<std::string> &interfaceList) = 0;
/**
* API to make the resource observable or not.
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry exported="true" kind="lib"
- path="libs/Simulator.jar" />
- <classpathentry kind="con"
- path="org.eclipse.pde.core.requiredPlugins" />
- <classpathentry kind="src" path="src" />
- <classpathentry kind="con"
- path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7" />
- <classpathentry kind="output" path="bin" />
+ <classpathentry exported="true" kind="lib" path="libs/Simulator.jar"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="output" path="bin"/>
</classpath>
import oic.simulator.clientcontroller.Activator;
import oic.simulator.clientcontroller.listener.ILogUIListener;
import oic.simulator.clientcontroller.utils.Constants;
-import oic.simulator.clientcontroller.utils.Utility;
import oic.simulator.logger.LogEntry;
import oic.simulator.logger.LoggerCallback;
import org.eclipse.swt.graphics.Image;
import org.oic.simulator.ILogger;
import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.SimulatorException;
import org.oic.simulator.SimulatorManager;
/**
// Set the logger callback with the native layer
logger = new LoggerCallback();
- try {
- SimulatorManager.setLogger(logger);
- } catch (SimulatorException e) {
- log(Level.ERROR.ordinal(),
- new Date(),
- "Failed to register the logger.\n"
- + Utility.getSimulatorErrorString(e, null));
- }
+ SimulatorManager.setLogger(logger);
}
private static class LogManagerSynchronizerThread implements Runnable {
return;
}
- // Ignore the response if the resource is a device or platform.
+ // Ignore the response if the resource is a device or
+ // platform.
Vector<String> resTypes = resourceN.getResourceTypes();
- if(null != resTypes && resTypes.contains("oic.wk.d") || resTypes.contains("oic.wk.p")) {
+ if (null != resTypes && resTypes.contains("oic.wk.d")
+ || resTypes.contains("oic.wk.p")) {
return;
}
+ "].");
// Send an initial GET request to get the resource
- // attributes.
+ // attributes on an interface supported by the resource.
try {
- resourceN.get(null, getListener);
+ String ifType = null;
+ Vector<String> resInterfaces = resourceN
+ .getResourceInterfaces();
+ if (null != resInterfaces) {
+ ifType = resInterfaces.get(0);
+ }
+ resourceN.get(formQueryParameters(ifType, null),
+ getListener);
} catch (SimulatorException e) {
Activator
.getDefault()
return values;
}
- public void sendGetRequest(RemoteResource resource) {
+ public void sendGetRequest(String ifType, String query,
+ RemoteResource resource) {
if (null == resource) {
return;
}
return;
}
+ Map<String, String> queryParams = formQueryParameters(ifType, query);
try {
- resourceN.get(null, getListener);
+ resourceN.get(queryParams, getListener);
} catch (SimulatorException e) {
Activator
.getDefault()
}
}
- public void sendPutRequest(RemoteResource resource,
+ public void sendPutRequest(String ifType, RemoteResource resource,
SimulatorResourceModel model) {
if (null == resource || null == model) {
return;
if (null == resourceN) {
return;
}
+ Map<String, String> queryParams = formQueryParameters(ifType, null);
try {
- resourceN.put(null, model, putListener);
+ resourceN.put(queryParams, model, putListener);
} catch (Exception e) {
String addlInfo;
addlInfo = "Invalid Attribute Value. Cannot send PUT request.";
}
}
- public void sendPostRequest(RemoteResource resource,
+ public void sendPostRequest(String ifType, RemoteResource resource,
SimulatorResourceModel model) {
if (null == resource || null == model) {
return;
if (null == resourceN) {
return;
}
+ Map<String, String> queryParams = formQueryParameters(ifType, null);
try {
- resourceN.post(null, model, postListener);
+ resourceN.post(queryParams, model, postListener);
} catch (Exception e) {
String addlInfo;
addlInfo = "Invalid Attribute Value. Cannot send POST request.";
return true;
}
+ private Map<String, String> formQueryParameters(String ifType, String query) {
+ Map<String, String> queryParams = new HashMap<String, String>();
+
+ // Including the interface type, if given,
+ if (null != ifType) {
+ ifType = ifType.trim();
+ if (ifType.length() > 0)
+ queryParams.put("if", ifType);
+ }
+
+ // Including other queries, if given.
+ if (null != query) {
+ query = query.trim();
+ if (query.length() > 0) {
+ // Parse the query parameters and fill the map.
+ String queries[] = query.split(";");
+ if (queries.length > 0) {
+ for (String pair : queries) {
+ String tok[] = pair.split("=");
+ if (null != tok && tok.length == 2) {
+ queryParams.put(tok[0].trim(), tok[1].trim());
+ }
+ }
+ }
+ }
+ }
+ return queryParams;
+ }
+
public boolean sendCancelObserveRequest(RemoteResource resource,
boolean removeEntry) {
if (null == resource || !resource.isObserved()) {
autoId = resourceN.startVerification(reqType, verifyListener);
if (autoId != -1) {
if (reqType == VerificationType.GET) {
- // resource.setGetAutomtnInProgress(true);
resource.setGetAutomtnId(autoId);
} else if (reqType == VerificationType.PUT) {
- // resource.setPutAutomtnInProgress(true);
resource.setPutAutomtnId(autoId);
- } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
- // resource.setPostAutomtnInProgress(true);
+ } else {
resource.setPostAutomtnId(autoId);
}
}
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.INFO.ordinal(),
+ new Date(),
+ "[" + reqType.toString()
+ + "] Verification Started for \""
+ + resourceN.getURI() + "\".");
} catch (SimulatorException e) {
Activator
.getDefault()
} else if (reqType == VerificationType.PUT) {
resource.setPutAutomtnInProgress(false);
autoId = resource.getPutAutomtnId();
- } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
+ } else {
resource.setPostAutomtnInProgress(false);
autoId = resource.getPostAutomtnId();
}
package oic.simulator.clientcontroller.view;
+import java.util.Date;
import java.util.Map;
import oic.simulator.clientcontroller.Activator;
import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
import oic.simulator.clientcontroller.utils.Constants;
import oic.simulator.clientcontroller.utils.Utility;
+import oic.simulator.clientcontroller.view.dialogs.GetRequestDialog;
import oic.simulator.clientcontroller.view.dialogs.PostRequestDialog;
import oic.simulator.clientcontroller.view.dialogs.PutRequestDialog;
import oic.simulator.clientcontroller.view.dialogs.VerificationDialog;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.ILogger.Level;
import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.client.SimulatorRemoteResource;
import org.oic.simulator.client.SimulatorRemoteResource.VerificationType;
/**
@Override
public void onVerificationStarted(final RemoteResource resource,
final int autoType) {
- Display.getDefault().asyncExec(new Runnable() {
-
- @Override
- public void run() {
- // changeReqBtnVisibility(autoType, false);
- }
- });
+ // Do Nothing. For Future Use.
}
@Override
public void onVerificationCompleted(final RemoteResource resource,
final int autoType) {
+
+ if (null == resource) {
+ return;
+ }
+
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
- // changeReqBtnVisibility(autoType, true);
+ SimulatorRemoteResource remoteResource = resource
+ .getRemoteResourceRef();
+ if (null == remoteResource) {
+ return;
+ }
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.INFO.ordinal(),
+ new Date(),
+ "["
+ + VerificationType.values()[autoType]
+ .toString()
+ + "] Verification Completed for \""
+ + remoteResource.getURI()
+ + "\".");
}
});
}
@Override
public void onVerificationAborted(final RemoteResource resource,
final int autoType) {
+
+ if (null == resource) {
+ return;
+ }
+
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
- // changeReqBtnVisibility(autoType, true);
+ SimulatorRemoteResource remoteResource = resource
+ .getRemoteResourceRef();
+ if (null == remoteResource) {
+ return;
+ }
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.INFO.ordinal(),
+ new Date(),
+ "["
+ + VerificationType.values()[autoType]
+ .toString()
+ + "] Verification Aborted for \""
+ + remoteResource.getURI()
+ + "\".");
}
});
}
};
}
- private void changeReqBtnVisibility(int reqType, boolean visibility) {
- if (reqType == Constants.GET_AUTOMATION_INDEX) {
- if (!getButton.isDisposed()) {
- getButton.setEnabled(visibility);
- }
- } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
- if (!putButton.isDisposed()) {
- putButton.setEnabled(visibility);
- }
- } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
- if (!postButton.isDisposed()) {
- postButton.setEnabled(visibility);
- }
- }
- }
-
private void updateViewer(RemoteResource resource) {
if (null == attViewer) {
return;
PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
@Override
public void run() {
- resourceManager.sendGetRequest(resourceInSelection);
+ GetRequestDialog getDialog = new GetRequestDialog(
+ Display.getDefault().getActiveShell());
+ if (getDialog.open() == Window.OK) {
+ // Call the native GET method
+ String query = getDialog.getOtherFilters();
+ String ifType = getDialog.getIfType();
+ resourceManager.sendGetRequest(ifType, query,
+ resourceInSelection);
+ }
}
});
}
PutRequestDialog putDialog = new PutRequestDialog(
Display.getDefault().getActiveShell());
if (putDialog.open() == Window.OK) {
- resourceManager.sendPutRequest(resourceInSelection,
- putDialog.getUpdatedRepresentation()
+ // Call the native PUT method
+ String ifType = putDialog.getIfType();
+ resourceManager.sendPutRequest(ifType,
+ resourceInSelection, putDialog
+ .getUpdatedRepresentation()
.getModel());
}
}
PostRequestDialog postDialog = new PostRequestDialog(
Display.getDefault().getActiveShell());
if (postDialog.open() == Window.OK) {
+ // Call the native POST method
+ String ifType = postDialog.getIfType();
ResourceRepresentation representation = postDialog
.getUpdatedRepresentation();
- resourceManager.sendPostRequest(
+ resourceManager.sendPostRequest(ifType,
resourceInSelection,
representation.getSelectedModel());
}
--- /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.view.dialogs;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import oic.simulator.clientcontroller.utils.Utility;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * This dialog is used for generating a PUT request.
+ */
+public class GetRequestDialog extends TitleAreaDialog {
+ private Text queryTxt;
+ private Combo ifTypesCmb;
+
+ private String otherFilters;
+ private String ifType;
+
+ private Map<String, String> ifTypes;
+
+ public GetRequestDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ @Override
+ public void create() {
+ super.create();
+ setTitle("Generate GET Request");
+ setMessage("Dialog which takes query filters and generates a GET request.");
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite compLayout = (Composite) super.createDialogArea(parent);
+
+ Group paramsGrp = new Group(compLayout, SWT.NONE);
+ paramsGrp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ GridLayout layout = new GridLayout(2, false);
+ layout.verticalSpacing = 10;
+ layout.marginTop = 10;
+ paramsGrp.setLayout(layout);
+
+ Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+ ifTypeLbl.setText("Interface Type");
+
+ ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+ GridData gd = new GridData();
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalAlignment = SWT.FILL;
+ ifTypesCmb.setLayoutData(gd);
+ ifTypesCmb.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ ifType = ifTypesCmb.getText();
+ }
+ });
+
+ // Set the interface types.
+ Map<String, String> ifTypes = Utility.getResourceInterfaces();
+ if (null != ifTypes && !ifTypes.isEmpty()) {
+ this.ifTypes = new HashMap<String, String>();
+ String key;
+ for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+ key = entry.getValue() + " (" + entry.getKey() + ")";
+ this.ifTypes.put(key, entry.getKey());
+ ifTypesCmb.add(key);
+ }
+ }
+
+ Label otherFilterLbl = new Label(paramsGrp, SWT.NONE);
+ otherFilterLbl.setText("Other filters");
+
+ queryTxt = new Text(paramsGrp, SWT.BORDER);
+ gd = new GridData();
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalAlignment = SWT.FILL;
+ queryTxt.setLayoutData(gd);
+ queryTxt.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ otherFilters = queryTxt.getText();
+ }
+ });
+
+ return compLayout;
+ }
+
+ @Override
+ protected boolean isResizable() {
+ return true;
+ }
+
+ @Override
+ public boolean isHelpAvailable() {
+ return false;
+ }
+
+ @Override
+ protected Button createButton(Composite parent, int id, String label,
+ boolean defaultButton) {
+ if (id == IDialogConstants.OK_ID) {
+ label = "GET";
+ }
+ return super.createButton(parent, id, label, defaultButton);
+ }
+
+ public String getOtherFilters() {
+ return otherFilters;
+ }
+
+ public String getIfType() {
+ if (ifTypes.containsKey(ifType)) {
+ return ifTypes.get(ifType);
+ }
+ return ifType;
+ }
+
+}
package oic.simulator.clientcontroller.view.dialogs;
+import java.util.HashMap;
+import java.util.Map;
+
import oic.simulator.clientcontroller.Activator;
import oic.simulator.clientcontroller.remoteresource.AttributeElement;
import oic.simulator.clientcontroller.remoteresource.RemoteResource;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
public class PostRequestDialog extends TitleAreaDialog {
private TreeViewer attViewer;
+ private Combo ifTypesCmb;
+
+ private String ifType;
+
+ private Map<String, String> ifTypes;
private AttributeEditingSupport attributeEditor;
protected Control createDialogArea(Composite parent) {
Composite compLayout = (Composite) super.createDialogArea(parent);
+ Group paramsGrp = new Group(compLayout, SWT.NONE);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ paramsGrp.setLayoutData(gd);
+ GridLayout layout = new GridLayout(2, false);
+ layout.verticalSpacing = 10;
+ layout.marginTop = 10;
+ paramsGrp.setLayout(layout);
+
+ Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+ ifTypeLbl.setText("Interface Type");
+
+ ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+ gd = new GridData();
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalAlignment = SWT.FILL;
+ ifTypesCmb.setLayoutData(gd);
+ ifTypesCmb.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ ifType = ifTypesCmb.getText();
+ }
+ });
+
+ // Set the interface types.
+ Map<String, String> ifTypes = Utility.getResourceInterfaces();
+ if (null != ifTypes && !ifTypes.isEmpty()) {
+ this.ifTypes = new HashMap<String, String>();
+ String key;
+ for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+ key = entry.getValue() + " (" + entry.getKey() + ")";
+ this.ifTypes.put(key, entry.getKey());
+ ifTypesCmb.add(key);
+ }
+ }
+
Composite container = new Composite(compLayout, SWT.NONE);
container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- GridLayout layout = new GridLayout(1, false);
+ layout = new GridLayout(1, false);
layout.verticalSpacing = 10;
layout.marginTop = 10;
container.setLayout(layout);
public ResourceRepresentation getUpdatedRepresentation() {
return updatedRepresentation;
}
+
+ public String getIfType() {
+ if (ifTypes.containsKey(ifType)) {
+ return ifTypes.get(ifType);
+ }
+ return ifType;
+ }
}
package oic.simulator.clientcontroller.view.dialogs;
+import java.util.HashMap;
+import java.util.Map;
+
import oic.simulator.clientcontroller.Activator;
import oic.simulator.clientcontroller.remoteresource.AttributeElement;
import oic.simulator.clientcontroller.remoteresource.RemoteResource;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
public class PutRequestDialog extends TitleAreaDialog {
private TreeViewer attViewer;
+ private Combo ifTypesCmb;
+
+ private String ifType;
+
+ private Map<String, String> ifTypes;
private AttributeEditingSupport attributeEditor;
protected Control createDialogArea(Composite parent) {
Composite compLayout = (Composite) super.createDialogArea(parent);
+ Group paramsGrp = new Group(compLayout, SWT.NONE);
+ paramsGrp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ GridLayout layout = new GridLayout(2, false);
+ layout.verticalSpacing = 10;
+ layout.marginTop = 10;
+ paramsGrp.setLayout(layout);
+
+ Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
+ ifTypeLbl.setText("Interface Type");
+
+ ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
+ GridData gd = new GridData();
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalAlignment = SWT.FILL;
+ ifTypesCmb.setLayoutData(gd);
+ ifTypesCmb.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ ifType = ifTypesCmb.getText();
+ }
+ });
+
+ // Set the interface types.
+ Map<String, String> ifTypes = Utility.getResourceInterfaces();
+ if (null != ifTypes && !ifTypes.isEmpty()) {
+ this.ifTypes = new HashMap<String, String>();
+ String key;
+ for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+ key = entry.getValue() + " (" + entry.getKey() + ")";
+ this.ifTypes.put(key, entry.getKey());
+ ifTypesCmb.add(key);
+ }
+ }
+
Composite container = new Composite(compLayout, SWT.NONE);
container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- GridLayout layout = new GridLayout(1, false);
+ layout = new GridLayout(1, false);
layout.verticalSpacing = 10;
layout.marginTop = 10;
container.setLayout(layout);
public ResourceRepresentation getUpdatedRepresentation() {
return updatedRepresentation;
}
+
+ public String getIfType() {
+ if (ifTypes.containsKey(ifType)) {
+ return ifTypes.get(ifType);
+ }
+ return ifType;
+ }
+
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="con"
- path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7" />
- <classpathentry kind="con"
- path="org.eclipse.pde.core.requiredPlugins" />
- <classpathentry kind="src" path="src" />
- <classpathentry kind="lib" path="libs/Simulator.jar" />
- <classpathentry kind="output" path="bin" />
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="lib" path="libs/Simulator.jar"/>
+ <classpathentry kind="output" path="bin"/>
</classpath>
import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.listener.ILogListener;
import oic.simulator.serviceprovider.utils.Constants;
-import oic.simulator.serviceprovider.utils.Utility;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.oic.simulator.ILogger;
import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.SimulatorException;
import org.oic.simulator.SimulatorManager;
/**
// Set the logger callback with the native layer
logger = new LoggerCallback();
- try {
- SimulatorManager.setLogger(logger);
- } catch (SimulatorException e) {
- log(Level.ERROR.ordinal(),
- new Date(),
- "Failed to register the logger.\n"
- + Utility.getSimulatorErrorString(e, null));
- }
+ SimulatorManager.setLogger(logger);
}
private static class LogManagerSynchronizerThread implements Runnable {
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import oic.simulator.serviceprovider.utils.Constants;
import oic.simulator.serviceprovider.utils.Utility;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.oic.simulator.AttributeProperty;
import org.oic.simulator.AttributeProperty.Type;
public ResourceManager() {
data = new Data();
- // Set the default device and platform information
- deviceName = "IoTivity Simulator";
- try {
- SimulatorManager.setDeviceInfo(deviceName);
- } catch (SimulatorException e) {
- Activator
- .getDefault()
- .getLogManager()
- .log(Level.ERROR.ordinal(),
- new Date(),
- "Error while registering the device info.\n"
- + Utility.getSimulatorErrorString(e, null));
- }
-
- platformInfo = new PlatformInfo();
- platformInfo.setPlatformID("Samsung Platform Identifier");
- platformInfo.setManufacturerName("Samsung");
- platformInfo.setManufacturerUrl("www.samsung.com");
- platformInfo.setModelNumber("Samsung Model Num01");
- platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z");
- platformInfo.setPlatformVersion("PlatformVersion01");
- platformInfo.setOperationSystemVersion("OSVersion01");
- platformInfo.setHardwareVersion("HardwareVersion01");
- platformInfo.setFirmwareVersion("FirwareVersion01");
- platformInfo.setSupportUrl("http://www.samsung.com/support");
- platformInfo.setSystemTime("2015-09-10T11:10:30Z");
- try {
- SimulatorManager.setPlatformInfo(platformInfo);
- } catch (SimulatorException e) {
- Activator
- .getDefault()
- .getLogManager()
- .log(Level.ERROR.ordinal(),
- new Date(),
- "Error while registering the platform info.\n"
- + Utility.getSimulatorErrorString(e, null));
- }
-
deviceListener = new DeviceListener() {
@Override
}
};
- // Get the device information to show other details of the device in UI.
- try {
- SimulatorManager.findDevices("", deviceListener);
- } catch (SimulatorException e) {
- Activator
- .getDefault()
- .getLogManager()
- .log(Level.ERROR.ordinal(),
- new Date(),
- "Failed to get the local device information.\n"
- + Utility.getSimulatorErrorString(e, null));
- }
-
resourceModelChangeListener = new ResourceModelChangeListener() {
@Override
threadHandle = new Thread(synchronizerThread);
threadHandle.setName("Simulator service provider event queue");
threadHandle.start();
+
+ // Set the default device name.
+ deviceName = "IoTivity Simulator";
+ try {
+ SimulatorManager.setDeviceInfo(deviceName);
+ } catch (SimulatorException e) {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "Error while registering the device info.\n"
+ + Utility.getSimulatorErrorString(e, null));
+ }
+
+ // Set the default platform information.
+ platformInfo = new PlatformInfo();
+ platformInfo.setPlatformID("Samsung Platform Identifier");
+ platformInfo.setManufacturerName("Samsung");
+ platformInfo.setManufacturerUrl("www.samsung.com");
+ platformInfo.setModelNumber("Samsung Model Num01");
+ platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z");
+ platformInfo.setPlatformVersion("PlatformVersion01");
+ platformInfo.setOperationSystemVersion("OSVersion01");
+ platformInfo.setHardwareVersion("HardwareVersion01");
+ platformInfo.setFirmwareVersion("FirwareVersion01");
+ platformInfo.setSupportUrl("http://www.samsung.com/support");
+ platformInfo.setSystemTime("2015-09-10T11:10:30Z");
+ try {
+ SimulatorManager.setPlatformInfo(platformInfo);
+ } catch (SimulatorException e) {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "Error while registering the platform info.\n"
+ + Utility.getSimulatorErrorString(e, null));
+ }
+
+ // Get the device information to show other details of the device in UI.
+ try {
+ SimulatorManager.findDevices("", deviceListener);
+ } catch (SimulatorException e) {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "Failed to get the local device information.\n"
+ + Utility.getSimulatorErrorString(e, null));
+ }
}
private static class NotificationSynchronizerThread implements Runnable {
jSimulatorSingleResource.start();
resource.setStarted(true);
- // Get the resource interfaces
- resource.setResourceInterfaces(Utility
- .convertVectorToSet(jSimulatorSingleResource.getInterface()));
+ // Add the resource interfaces
+ Set<String> newIfSet = resource.getResourceInterfaces();
+ // Get the default interface(s) if any configured by the platform.
+ // These interfaces will be overwritten by the new interfaces.
+ Set<String> ifSetFromPlatform = Utility
+ .convertVectorToSet(jSimulatorSingleResource.getInterface());
+ resource.setResourceInterfaces(ifSetFromPlatform);
+ updateResourceInterfaces(resource, newIfSet);
} catch (SimulatorException e) {
Activator
.getDefault()
return true;
}
- public int createSingleResourceMultiInstances(String configFile, int count)
+ public Set<SingleResource> createSingleResourceMultiInstances(
+ String configFile, int count, IProgressMonitor progressMonitor)
throws SimulatorException {
- int createCount = 0;
+ Set<SingleResource> resultSet;
try {
+ resultSet = new HashSet<SingleResource>();
Vector<SimulatorResource> jSimulatorResources = SimulatorManager
.createResource(configFile, count);
if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
- return 0;
+ return null;
}
SimulatorSingleResource jResource;
SingleResource resource;
boolean result;
for (SimulatorResource jSimulatorResource : jSimulatorResources) {
+ // If the resource creation progress is canceled, then stop the
+ // creation and stop/delete
+ // the resources created already.
+ if (progressMonitor.isCanceled()) {
+ removeSingleResources(resultSet);
+ return null;
+ }
jResource = (SimulatorSingleResource) jSimulatorResource;
resource = new SingleResource();
resource.setSimulatorResource(jResource);
result = completeSingleResourceCreationByRAML(resource,
jResource.getURI(), jResource.getName(), true);
if (result) {
- createCount++;
+ resultSet.add(resource);
}
} catch (SimulatorException eInner) {
Activator
Utility.getSimulatorErrorString(eInner,
null));
}
- }
- if (createCount > 0) {
- UiListenerHandler.getInstance().resourceCreatedUINotification(
- ResourceType.SINGLE);
+ progressMonitor.worked(1);
}
} catch (SimulatorException eOuter) {
Activator
Utility.getSimulatorErrorString(eOuter, null));
throw eOuter;
}
- return createCount;
+ return resultSet;
}
public List<Resource> getResourceList() {
propValue = resource.getResourceURI();
} else if (propName.equals(Constants.RESOURCE_TYPE)) {
propValue = resource.getResourceType();
+ } else if (propName.equals(Constants.INTERFACE_TYPES)) {
+ Set<String> ifTypes = resource.getResourceInterfaces();
+ if (null != ifTypes && !ifTypes.isEmpty()) {
+ propValue = "";
+ Iterator<String> itr = ifTypes.iterator();
+ while (itr.hasNext()) {
+ propValue += itr.next();
+ if (itr.hasNext()) {
+ propValue += ", ";
+ }
+ }
+ } else {
+ propValue = null;
+ }
} else {
propValue = null;
}
return true;
}
+ public boolean updateResourceInterfaces(Resource resource,
+ Set<String> newIfSet) throws SimulatorException {
+ if (null == resource || null == newIfSet || newIfSet.isEmpty()) {
+ return false;
+ }
+ SimulatorResource jResource = resource.getSimulatorResource();
+ if (null == jResource) {
+ return false;
+ }
+ Set<String> curIfSet = resource.getResourceInterfaces();
+ Iterator<String> itr = curIfSet.iterator();
+ String interfaceType;
+ boolean resourceRestartRequired = false;
+ while (itr.hasNext()) {
+ interfaceType = itr.next();
+ if (newIfSet.contains(interfaceType)) {
+ newIfSet.remove(interfaceType);
+ } else {
+ // Remove this interface support from the resource.
+ try {
+ if (!resourceRestartRequired) {
+ resourceRestartRequired = true;
+ }
+ jResource.removeInterface(interfaceType);
+ itr.remove();
+ } catch (SimulatorException e) {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "There is an error while removing the interface type("
+ + interfaceType
+ + ").\n"
+ + Utility.getSimulatorErrorString(
+ e, null));
+ throw e;
+ }
+ }
+ }
+
+ // Add all remaining interfaces.
+ itr = newIfSet.iterator();
+ while (itr.hasNext()) {
+ interfaceType = itr.next();
+ // Add this interface support to the resource.
+ try {
+ jResource.addInterface(interfaceType);
+ curIfSet.add(interfaceType);
+ } catch (SimulatorException e) {
+ Activator
+ .getDefault()
+ .getLogManager()
+ .log(Level.ERROR.ordinal(),
+ new Date(),
+ "There is an error while adding the interface type("
+ + interfaceType
+ + ").\n"
+ + Utility.getSimulatorErrorString(e,
+ null));
+ throw e;
+ }
+ }
+
+ // As there is no support from native layer for interface removal,
+ // supporting it from the simulator requires restarting the resource if
+ // any existing interfaces are removed.
+ if (resourceRestartRequired) {
+ stopResource(resource);
+ startResource(resource);
+ }
+
+ // Set the resource interfaces.
+ resource.setResourceInterfaces(curIfSet);
+
+ return true;
+ }
+
public boolean attributeValueUpdated(SingleResource resource,
String attributeName, AttributeValue value) {
if (null != resource && null != attributeName && null != value) {
return false;
}
boolean status = false;
- changeResourceLevelAutomationStatus(resource, true);
// Invoke the native automation method
SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
.getSimulatorResource();
Utility.getSimulatorErrorString(e, null));
autoId = -1;
}
- if (-1 == autoId) {
- // Automation request failed and hence status is being
- // rolled back
- changeResourceLevelAutomationStatus(resource, false);
- } else {
+ if (-1 != autoId) {
// Automation request accepted.
+ changeResourceLevelAutomationStatus(resource, true);
+
resource.setAutomationId(autoId);
// Notify the UI listeners in a different thread.
+ "It should not contain # or ? or % or "
+ "consecutive '/' or '/./' or "
+ "'/..'(more than one dot following a slash).";
+
+ public static final String INVALID_RESOURCE_TYPE_MESSAGE = "Resource Type should start with an alphabet.\n"
+ + "It should contain only lowercase alphabets, "
+ + "numbers(0-9), dot(.) and hyphen(-).";
+
public static final int TREE_EXPANSION_LEVEL = 10;
public static final String BASELINE_INTERFACE = "oic.if.baseline";
return true;
}
+ public static boolean isResourceTypeValid(String resType) {
+ if (null == resType || resType.isEmpty()) {
+ return false;
+ }
+
+ char[] ch = resType.toCharArray();
+ for (char c : ch) {
+ if (c != '.' && c != '-' && (c < 'a' || c > 'z')
+ && (c < '0' || c > '9')) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
public static Map<String, String> getResourceInterfaces(
Class<? extends Resource> resourceClass) {
Map<String, String> ifTypes = null;
}
return ifTypes;
}
-
}
\ No newline at end of file
}
// If selected resource is not a single resource, then editor
- // support is not
- // required.
+ // support is not required.
if (!(res instanceof SingleResource)) {
return null;
}
// Stop the automation
resourceManager.stopAutomation((SingleResource) resource, att,
att.getAutoUpdateId());
- MessageDialog.openInformation(Display.getDefault()
- .getActiveShell(), "Automation Status",
- "Automation stopped.");
}
}
}
@Override
public void run() {
- if (null == resource) {
+ if (null == resource || null == attViewer) {
return;
}
Resource resourceInSelection = resourceManager
Tree tree;
tree = attViewer.getTree();
if (!tree.isDisposed()) {
- attViewer.refresh();
-
// Disabling the table to prevent interactions
// during the automation
tree.setEnabled(false);
tree = attViewer.getTree();
if (!tree.isDisposed()) {
tree.setEnabled(true);
- attViewer.refresh();
}
}
});
package oic.simulator.serviceprovider.view;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
import oic.simulator.serviceprovider.manager.UiListenerHandler;
import oic.simulator.serviceprovider.model.MetaProperty;
import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.UpdateResourceInterfaceDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import org.oic.simulator.SimulatorException;
private ResourceManager resourceManagerRef;
+ private Set<String> updatedIfSet;
+
private List<MetaProperty> properties;
private boolean enable_edit;
private Button editBtn;
private Button cancelBtn;
+ private Map<String, String> ifTypes;
+
public MetaPropertiesView() {
resourceManagerRef = Activator.getDefault().getResourceManager();
cancelBtn.setEnabled(true);
editBtn.setText("Save");
setEnableEdit(true);
+
+ Resource resource = resourceManagerRef
+ .getCurrentResourceInSelection();
+ if (null != resource) {
+ updatedIfSet = resource.getResourceInterfaces();
+ }
} else {
boolean result = false;
Resource resourceInSelection = resourceManagerRef
boolean update = false;
boolean uriChange = false;
boolean nameChange = false;
+ boolean interfaceChange = false;
if (resourceManagerRef.isPropValueChanged(
resourceInSelection, properties,
update = true;
uriChange = true;
}
+ // Checking whether any changes made in resource
+ // interfaces by
+ // comparing the current interface set and updated
+ // interface set.
+ if (null != updatedIfSet) {
+ Set<String> curIfSet = resourceInSelection
+ .getResourceInterfaces();
+ if (curIfSet.size() != updatedIfSet.size()) {
+ update = true;
+ interfaceChange = true;
+ } else {
+ Iterator<String> itr = updatedIfSet.iterator();
+ while (itr.hasNext()) {
+ if (!curIfSet.contains(itr.next())) {
+ update = true;
+ interfaceChange = true;
+ break;
+ }
+ }
+ }
+ }
if (update) {
try {
if (uriChange || nameChange)
.getCurrentResourceInSelection(),
properties, uriChange,
nameChange);
+ if (interfaceChange)
+ result = Activator
+ .getDefault()
+ .getResourceManager()
+ .updateResourceInterfaces(
+ resourceInSelection,
+ updatedIfSet);
+
} catch (SimulatorException ex) {
result = false;
}
cancelBtn.setEnabled(false);
editBtn.setText("Edit");
setEnableEdit(false);
+ if (null != updatedIfSet)
+ updatedIfSet.clear();
}
});
+ // Get the supported interfaces.
+ Map<String, String> ifTypesSupported = Utility
+ .getResourceInterfaces(SingleResource.class);
+ if (null != ifTypesSupported && !ifTypesSupported.isEmpty()) {
+ ifTypes = new HashMap<String, String>();
+ String key;
+ for (Map.Entry<String, String> entry : ifTypesSupported.entrySet()) {
+ key = entry.getValue() + " (" + entry.getKey() + ")";
+ ifTypes.put(key, entry.getKey());
+ }
+ }
+
addManagerListeners();
// Check whether there is any resource selected already
}
CellEditor editor = new TextCellEditor(viewer.getTable());
+ if (null != propName && propName.equals(Constants.INTERFACE_TYPES)) {
+ editor.setStyle(SWT.READ_ONLY);
+ final Text txt = (Text) editor.getControl();
+ txt.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ if (null == updatedIfSet) {
+ return;
+ }
+ // Form the result set of interfaces with check-box that
+ // will be shown in the dialog for editing.
+ Map<String, String> curResInterfaces = new HashMap<String, String>();
+ for (Map.Entry<String, String> entry : ifTypes
+ .entrySet()) {
+ if (updatedIfSet.contains(entry.getValue())) {
+ curResInterfaces.put(entry.getKey(),
+ entry.getValue());
+ }
+ }
+
+ // Show the dialog for editing the resource interfaces.
+ UpdateResourceInterfaceDialog ad = new UpdateResourceInterfaceDialog(
+ Display.getDefault().getActiveShell(),
+ curResInterfaces, ifTypes);
+ if (ad.open() == Window.OK) {
+ // Update the local copy of the current resource
+ // interfaces to keep the state for save operation.
+ updatedIfSet.clear();
+ String newPropValue = "";
+ for (Map.Entry<String, String> entry : curResInterfaces
+ .entrySet()) {
+ if (!newPropValue.isEmpty()) {
+ newPropValue += ", ";
+ }
+ String value = ifTypes.get(entry.getKey());
+ newPropValue += value;
+
+ updatedIfSet.add(value);
+ }
+ // Update the model
+ MetaProperty prop = (MetaProperty) element;
+ prop.setPropValue(newPropValue);
+ // Update the viewer in a separate UI thread.
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ viewer.refresh(element, true);
+ }
+ });
+ }
+ }
+ });
+ }
return editor;
}
@Override
public void onResourceCreation(final ResourceType type) {
- Display.getDefault().asyncExec(new Runnable() {
+ Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
resourceManager
.resourceSelectionChanged(null);
-
- MessageDialog.openInformation(
- Display.getDefault()
- .getActiveShell(),
- "Deleted",
- "Resource deleted.");
} catch (SimulatorException e1) {
MessageDialog
.openInformation(Display
"Attribute level automation for this resource is already in progress!!!\nPlease stop all "
+ "running attribute level automations to start resource level automation.");
} else {
-
// Start the automation
// Fetch the settings data
List<AutomationSettingHelper> automationSettings;
boolean status = resourceManager
.startResourceAutomationUIRequest(autoType,
updFreq, selectedResource);
- String statusMsg = status ? "Automation started successfully!!!"
- : "Automation request failed!!!";
- MessageDialog.openInformation(Display.getDefault()
- .getActiveShell(), "Automation Status",
- statusMsg);
+ if (!status) {
+ String statusMsg = "Automation request failed!!!";
+ MessageDialog.openInformation(Display.getDefault()
+ .getActiveShell(), "Automation Status",
+ statusMsg);
+ }
}
}
}
public void widgetSelected(SelectionEvent e) {
boolean status = resourceManager
.stopResourceAutomationUIRequest(selectedResource);
- String statusMsg = status ? "Automation stopped!!!"
- : "Automation stop failed.";
- MessageDialog.openInformation(Display.getDefault()
- .getActiveShell(), "Automation Status", statusMsg);
+ if (!status) {
+ String statusMsg = "Automation stop failed.";
+ MessageDialog.openInformation(Display.getDefault()
+ .getActiveShell(), "Automation Status", statusMsg);
+ }
}
});
int open = wizardDialog.open();
if (open == Window.OK) {
singleResTreeViewer.refresh();
- MessageDialog.openInformation(Display.getDefault()
- .getActiveShell(),
- "Resource Deletion Status", deleteWizard
- .getStatus());
+ if (!deleteWizard.getStatus()) {
+ MessageDialog
+ .openInformation(Display.getDefault()
+ .getActiveShell(),
+ "Resource Deletion Failed",
+ "Failed to delete the resources. Please try again.");
+ }
changeDeleteVisibility();
}
}
--- /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.serviceprovider.view.dialogs;
+
+import java.util.List;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * This class shows a dialog for filtering logs based on severity levels.
+ */
+public class AddInterfaceTypeDialog extends TrayDialog {
+
+ private Combo ifTypesCmb;
+ private String value;
+ private List<String> ifTypes;
+
+ public AddInterfaceTypeDialog(Shell shell, List<String> ifTypes) {
+ super(shell);
+ this.ifTypes = ifTypes;
+ }
+
+ @Override
+ protected void configureShell(Shell shell) {
+ super.configureShell(shell);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+ getShell().setText("Add Interface Type");
+
+ Composite content = new Composite(parent, SWT.NULL);
+ GridLayout gridLayout = new GridLayout();
+ content.setLayout(gridLayout);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ content.setLayoutData(gd);
+
+ Label lbl = new Label(content, SWT.NONE);
+ lbl.setText("Select Interface Type");
+
+ ifTypesCmb = new Combo(content, SWT.NULL);
+ gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ ifTypesCmb.setLayoutData(gd);
+
+ ifTypesCmb.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ value = ifTypesCmb.getText();
+ }
+ });
+
+ initList();
+
+ return composite;
+ }
+
+ private void initList() {
+ if (null != ifTypesCmb && null != ifTypes && !ifTypes.isEmpty()) {
+ ifTypesCmb.setItems(ifTypes.toArray(new String[1]));
+ }
+ }
+
+ @Override
+ public boolean isHelpAvailable() {
+ return false;
+ }
+
+ public String getValue() {
+ return value;
+ }
+}
import java.util.Set;
import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
import oic.simulator.serviceprovider.model.AttributeHelper;
import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
import oic.simulator.serviceprovider.model.SingleResource;
import oic.simulator.serviceprovider.utils.Constants;
import oic.simulator.serviceprovider.utils.Utility;
private Resource createdResource;
+ private IProgressMonitor progressMonitor;
+
public CreateResourceWizard() {
setWindowTitle("Create resources");
IPath path = new Path("/icons/oic_logo_64x64.png");
.getDefault().getResourceManager().isAnyResourceExist()))
|| curPage == simpleResourceAddAttributePage
|| (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage
- .isMultiResourceCreation())) {
+ .isMultiResourceCreation())) {
return true;
}
return false;
});
} catch (InvocationTargetException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
}
} else if (curPage == loadRamlPage) {
new FileInputStream(loadRamlPage.getConfigFilePath());
} catch (Exception e) {
MessageDialog
- .openError(getShell(), "Invalid File",
- "File doesn't exist. Either the file path or file name is invalid.");
+ .openError(getShell(), "Invalid File",
+ "File doesn't exist. Either the file path or file name is invalid.");
// TODO: Instead of MessageDialog, errors may be shown on wizard
// itself.
return false;
if ((loadRamlPage.getResourceCount() + Activator.getDefault()
.getResourceManager().getResourceCount()) > Constants.MAX_RESOURCE_COUNT) {
MessageDialog
- .openInformation(Display.getDefault().getActiveShell(),
- "Resource limit exceeded",
- "Exceeded the limit of resources that can exist in the server.");
+ .openInformation(Display.getDefault().getActiveShell(),
+ "Resource limit exceeded",
+ "Exceeded the limit of resources that can exist in the server.");
return false;
}
+ final int[] resCreatedCount = new int[1];
try {
- getContainer().run(true, false, new IRunnableWithProgress() {
+ getContainer().run(true, true, new IRunnableWithProgress() {
@Override
- public void run(IProgressMonitor monitor)
+ public void run(final IProgressMonitor monitor)
throws InvocationTargetException,
InterruptedException {
+ progressMonitor = monitor;
try {
monitor.beginTask(
"Single Resource Creation(multi-instance) With RAML",
- 3);
- monitor.worked(1);
- createMultiInstanceSingleResourceWithoutRAML();
- monitor.worked(2);
+ loadRamlPage.getResourceCount());
+ resCreatedCount[0] = createMultiInstanceSingleResourceWithoutRAML();
+
} finally {
monitor.done();
}
});
} catch (InvocationTargetException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
}
+ boolean canceled = false;
+ if (null != progressMonitor && progressMonitor.isCanceled()
+ && 0 == resCreatedCount[0]) {
+ canceled = true;
+ }
+ progressMonitor = null;
+ if (canceled) {
+ return false;
+ } else {
+ if (resCreatedCount[0] > 0) {
+ UiListenerHandler.getInstance()
+ .resourceCreatedUINotification(ResourceType.SINGLE);
+ }
+ }
} else if (curPage == updatePropPage) {
// Handling the single instance
String resName = updatePropPage.getResName();
if (Activator.getDefault().getResourceManager()
.isResourceExist(updatePropPage.getResURI())) {
MessageDialog
- .openError(getShell(), "Resource URI in use",
- "Entered resource URI is in use. Please try a different one.");
+ .openError(getShell(), "Resource URI in use",
+ "Entered resource URI is in use. Please try a different one.");
// TODO: Instead of MessageDialog, errors may be shown on wizard
// itself.
return false;
});
} catch (InvocationTargetException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
Activator.getDefault().getLogManager()
- .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+ .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
e.printStackTrace();
}
}
resource.setResourceName(simpleResourceBasicDetailsPage.getResName());
resource.setResourceType(simpleResourceBasicDetailsPage.getResType());
resource.setObservable(simpleResourceBasicDetailsPage.isObservable());
+ resource.setResourceInterfaces(simpleResourceBasicDetailsPage
+ .getInterfaceTypes());
// Resource Attributes
Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
}
}
- private void createMultiInstanceSingleResourceWithoutRAML() {
+ private int createMultiInstanceSingleResourceWithoutRAML() {
+ int toCreateCount = loadRamlPage.getResourceCount();
+ int resCreatedCount = 0;
+ Set<SingleResource> resources;
try {
- int toCreateCount = loadRamlPage.getResourceCount();
- int resCreatedCount = Activator
+ resources = Activator
.getDefault()
.getResourceManager()
.createSingleResourceMultiInstances(
- loadRamlPage.getConfigFilePath(), toCreateCount);
+ loadRamlPage.getConfigFilePath(), toCreateCount,
+ progressMonitor);
+ if (null != progressMonitor && progressMonitor.isCanceled()) {
+ try {
+ Activator.getDefault().getResourceManager()
+ .removeSingleResources(resources);
+ } catch (SimulatorException e) {
+ }
+ return 0;
+ }
+ if (null != resources)
+ resCreatedCount = resources.size();
if (resCreatedCount > 0) {
status = "[" + resCreatedCount + " out of " + toCreateCount
+ "]";
status = "Failed to create resource.\n"
+ Utility.getSimulatorErrorString(e, null);
}
+ return resCreatedCount;
}
}
\ No newline at end of file
private DeleteResourcePage page;
- private String status;
+ private boolean success;
public DeleteResourceWizard() {
setWindowTitle("Delete resources");
}
}
monitor.worked(1);
- status = "Resources deleted.";
+ success = true;
} catch (SimulatorException e) {
- status = "Failed to delete some of the resources. Please try again.";
+ success = false;
} finally {
monitor.done();
}
return true;
}
- public String getStatus() {
- return status;
+ public boolean getStatus() {
+ return success;
}
}
\ No newline at end of file
package oic.simulator.serviceprovider.view.dialogs;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.SingleResource;
import oic.simulator.serviceprovider.utils.Constants;
import oic.simulator.serviceprovider.utils.Utility;
import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
public class SimpleResourceBasicDetailsPage extends WizardPage {
- private Text resNameTxt;
- private Text resUriTxt;
- private Text resTypeTxt;
- private Button observeBtn;
+ private Text resNameTxt;
+ private Text resUriTxt;
+ private Text resTypeTxt;
+
+ private Button observeBtn;
+ private Button addIfTypeBtn;
+ private Button removeIfTypeBtn;
+
+ private List ifTypesList;
- private String resName;
- private String resURI;
- private String resType;
- private boolean observable;
+ private String resName;
+ private String resURI;
+ private String resType;
+ private boolean observable;
+ private Map<String, String> ifTypes;
+ private Set<String> selectedIfTypes;
protected SimpleResourceBasicDetailsPage() {
super("Basic Details");
+ selectedIfTypes = new HashSet<String>();
}
@Override
gd.grabExcessHorizontalSpace = true;
resTypeTxt.setLayoutData(gd);
+ Label ifTypesLbl = new Label(resDetGrp, SWT.NULL);
+ ifTypesLbl.setText(Constants.INTERFACE_TYPES);
+ gd = new GridData();
+ ifTypesLbl.setLayoutData(gd);
+
+ ifTypesList = new List(resDetGrp, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
+ | SWT.H_SCROLL);
+ gd = new GridData();
+ gd.horizontalAlignment = SWT.FILL;
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalSpan = 2;
+ ifTypesList.setLayoutData(gd);
+ ifTypesList.setBackground(Display.getDefault().getSystemColor(
+ SWT.COLOR_WHITE));
+
+ Composite ifTypesOpComp = new Composite(resDetGrp, SWT.NONE);
+ gridLayout = new GridLayout();
+ ifTypesOpComp.setLayout(gridLayout);
+ gd = new GridData();
+ gd.verticalAlignment = SWT.TOP;
+ ifTypesOpComp.setLayoutData(gd);
+
+ addIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+ addIfTypeBtn.setText("Add");
+ gd = new GridData();
+ gd.widthHint = 70;
+ addIfTypeBtn.setLayoutData(gd);
+
+ removeIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+ removeIfTypeBtn.setText("Remove");
+ gd = new GridData();
+ gd.widthHint = 70;
+ removeIfTypeBtn.setLayoutData(gd);
+ removeIfTypeBtn.setEnabled(false);
+
Group otherOptionsGrp = new Group(container, SWT.NONE);
otherOptionsGrp.setText("Other options");
gridLayout = new GridLayout();
addUiListeners();
+ // Set the interface types.
+ Map<String, String> ifTypes = Utility
+ .getResourceInterfaces(SingleResource.class);
+ if (null != ifTypes && !ifTypes.isEmpty()) {
+ this.ifTypes = new HashMap<String, String>();
+ String key;
+ for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+ key = entry.getValue() + " (" + entry.getKey() + ")";
+ this.ifTypes.put(key, entry.getKey());
+ }
+ }
+
setControl(container);
}
observable = observeBtn.getSelection();
}
});
+
+ addIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ boolean addAll = false;
+ int itemsAddedCount = ifTypesList.getItemCount();
+ if (itemsAddedCount < ifTypes.size()) {
+ String key;
+ ArrayList<String> pendingItems = new ArrayList<String>();
+ if (0 == itemsAddedCount) {
+ addAll = true;
+ }
+ for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
+ key = entry.getKey();
+ if (addAll || -1 == ifTypesList.indexOf(key)) {
+ pendingItems.add(key);
+ }
+ }
+
+ AddInterfaceTypeDialog addIfTypeDlg = new AddInterfaceTypeDialog(
+ getShell(), pendingItems);
+ if (Window.CANCEL == addIfTypeDlg.open()) {
+ return;
+ }
+ String ifType = addIfTypeDlg.getValue();
+ ifTypesList.add(ifType);
+ ifTypesList.deselectAll();
+ ifTypesList.select(ifTypesList.getItemCount() - 1);
+ ifTypesList.showSelection();
+ removeIfTypeBtn.setEnabled(true);
+
+ if (itemsAddedCount + 1 == ifTypes.size()) {
+ addIfTypeBtn.setEnabled(false);
+ }
+ }
+ }
+ });
+
+ removeIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int[] selection = ifTypesList.getSelectionIndices();
+ if (null != selection && selection.length > 0) {
+ ifTypesList.remove(selection);
+ }
+
+ removeIfTypeBtn.setEnabled(false);
+ addIfTypeBtn.setEnabled(true);
+ }
+ });
+
+ ifTypesList.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int[] selection = ifTypesList.getSelectionIndices();
+ if (null != selection && selection.length > 0) {
+ removeIfTypeBtn.setEnabled(true);
+ }
+ }
+ });
}
@Override
return null;
}
+ if (!Utility.isResourceTypeValid(resType)) {
+ MessageDialog.openError(Display.getDefault().getActiveShell(),
+ "Invalid Resource Type.",
+ Constants.INVALID_RESOURCE_TYPE_MESSAGE);
+ return null;
+ }
+
// Checking whether the uri is used by any other resource.
if (Activator.getDefault().getResourceManager().isResourceExist(resURI)) {
MessageDialog
return null;
}
+ String[] items = ifTypesList.getItems();
+ if (null == items || items.length == 0) {
+ MessageDialog
+ .openInformation(
+ getShell(),
+ "Default Interface Type Selection",
+ "As no interface types are added, the resource will be "
+ + "configured with the default interface type(oic.if.baseline).");
+ ifTypesList.add("Baseline" + " ("
+ + Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE + ")");
+ }
+ selectedIfTypes.clear();
+ for (String item : ifTypesList.getItems()) {
+ selectedIfTypes.add(ifTypes.get(item));
+ }
+
return ((CreateResourceWizard) getWizard())
.getSimpleResourceAddAttributePage();
}
return resType;
}
+ public Set<String> getInterfaceTypes() {
+ return selectedIfTypes;
+ }
+
public boolean isObservable() {
return observable;
}
import java.util.ArrayList;
import java.util.Map;
-import java.util.Set;
import oic.simulator.serviceprovider.utils.Constants;
import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
/**
* Dialog for starting and stopping the automatic verifications.
*/
public class UpdateResourceInterfaceDialog extends TrayDialog {
- private Map<String, Boolean> resourceIfStatus;
+
+ private Button addIfTypeBtn;
+ private Button removeIfTypeBtn;
+
+ private List ifTypesList;
+
+ private Map<String, String> supportedResInterfaces;
+ private Map<String, String> updatedResInterfaces;
public UpdateResourceInterfaceDialog(Shell shell,
- Map<String, Boolean> resourceIfStatus) {
+ Map<String, String> updatedResInterfaces,
+ Map<String, String> supportedResInterfaces) {
super(shell);
- this.resourceIfStatus = resourceIfStatus;
+ this.updatedResInterfaces = updatedResInterfaces;
+ this.supportedResInterfaces = supportedResInterfaces;
}
@Override
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
- createAutomationGroup(composite);
getShell().setText("Resource Interfaces");
+
+ Composite content = new Composite(parent, SWT.NULL);
+ GridLayout gridLayout = new GridLayout(3, false);
+ content.setLayout(gridLayout);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ content.setLayoutData(gd);
+
+ ifTypesList = new List(content, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
+ | SWT.H_SCROLL);
+ gd = new GridData();
+ gd.horizontalAlignment = SWT.FILL;
+ gd.grabExcessHorizontalSpace = true;
+ gd.verticalAlignment = SWT.FILL;
+ gd.grabExcessHorizontalSpace = true;
+ gd.horizontalSpan = 2;
+ ifTypesList.setLayoutData(gd);
+ ifTypesList.setBackground(Display.getDefault().getSystemColor(
+ SWT.COLOR_WHITE));
+
+ Composite ifTypesOpComp = new Composite(content, SWT.NONE);
+ gridLayout = new GridLayout();
+ ifTypesOpComp.setLayout(gridLayout);
+ gd = new GridData();
+ gd.verticalAlignment = SWT.TOP;
+ ifTypesOpComp.setLayoutData(gd);
+
+ addIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+ addIfTypeBtn.setText("Add");
+ gd = new GridData();
+ gd.widthHint = 70;
+ addIfTypeBtn.setLayoutData(gd);
+ if (null != updatedResInterfaces && null != supportedResInterfaces
+ && updatedResInterfaces.size() == supportedResInterfaces.size()) {
+ addIfTypeBtn.setEnabled(false);
+ }
+
+ removeIfTypeBtn = new Button(ifTypesOpComp, SWT.PUSH);
+ removeIfTypeBtn.setText("Remove");
+ gd = new GridData();
+ gd.widthHint = 70;
+ removeIfTypeBtn.setLayoutData(gd);
+ removeIfTypeBtn.setEnabled(false);
+
+ initInterfaceList();
+
+ addUiListeners();
+
return composite;
}
- /**
- * Dynamically creates a check-box list for changing the resource interface
- * selection.
- */
- private void createAutomationGroup(Composite parent) {
- Group group = new Group(parent, SWT.NONE);
- group.setLayout(new GridLayout());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint = 275;
- group.setLayoutData(gd);
- group.setText("Resource Interfaces");
-
- Set<String> keySet = resourceIfStatus.keySet();
- if (null == keySet) {
- return;
+ private void initInterfaceList() {
+ for (Map.Entry<String, String> entry : updatedResInterfaces.entrySet()) {
+ ifTypesList.add(entry.getKey());
}
- ArrayList<String> list = new ArrayList<String>(keySet);
- for (final String str : list) {
- final Button checkbox = new Button(group, SWT.CHECK);
- checkbox.setText(str);
- checkbox.setSelection(resourceIfStatus.get(str));
-
- // Disabling the check-box for baseline interface.
- if (str.contains(Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE)) {
- checkbox.setEnabled(false);
- }
+ }
- checkbox.addSelectionListener(new SelectionAdapter() {
+ private void addUiListeners() {
+ addIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ boolean addAll = false;
+ int itemsAddedCount = ifTypesList.getItemCount();
+ if (itemsAddedCount < supportedResInterfaces.size()) {
+ String key;
+ ArrayList<String> pendingItems = new ArrayList<String>();
+ if (0 == itemsAddedCount) {
+ addAll = true;
+ }
+ for (Map.Entry<String, String> entry : supportedResInterfaces
+ .entrySet()) {
+ key = entry.getKey();
+ if (addAll || -1 == ifTypesList.indexOf(key)) {
+ pendingItems.add(key);
+ }
+ }
- @Override
- public void widgetSelected(SelectionEvent e) {
- Button btn = (Button) e.getSource();
- if (null == btn) {
+ AddInterfaceTypeDialog addIfTypeDlg = new AddInterfaceTypeDialog(
+ getShell(), pendingItems);
+ if (Window.CANCEL == addIfTypeDlg.open()) {
return;
}
- String btnText = btn.getText();
- resourceIfStatus.put(btnText, btn.getSelection());
+ String ifType = addIfTypeDlg.getValue();
+ ifTypesList.add(ifType);
+ ifTypesList.deselectAll();
+ ifTypesList.select(ifTypesList.getItemCount() - 1);
+ ifTypesList.showSelection();
+ removeIfTypeBtn.setEnabled(true);
+
+ if (itemsAddedCount + 1 == supportedResInterfaces.size()) {
+ addIfTypeBtn.setEnabled(false);
+ }
+ }
+ }
+ });
+
+ removeIfTypeBtn.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int[] selection = ifTypesList.getSelectionIndices();
+ if (null != selection && selection.length > 0) {
+ ifTypesList.remove(selection);
+ }
+
+ ifTypesList.deselectAll();
+ removeIfTypeBtn.setEnabled(false);
+ addIfTypeBtn.setEnabled(true);
+ }
+ });
+
+ ifTypesList.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int[] selection = ifTypesList.getSelectionIndices();
+ if (null != selection && selection.length > 0) {
+ removeIfTypeBtn.setEnabled(true);
}
- });
+ }
+ });
+ }
+
+ @Override
+ protected void okPressed() {
+ String[] items = ifTypesList.getItems();
+ if (null == items || items.length == 0) {
+ MessageDialog
+ .openInformation(
+ getShell(),
+ "Default Interface Type Selection",
+ "As no interface types are added, the resource will be "
+ + "configured with the default interface type(oic.if.baseline).");
+ ifTypesList.add("Baseline" + " ("
+ + Constants.DEFAULT_SINGLE_RESOURCE_INTERFACE + ")");
}
+
+ // Clearing the map to freshly add selected items.
+ updatedResInterfaces.clear();
+ for (String item : ifTypesList.getItems()) {
+ String value = supportedResInterfaces.get(item);
+ updatedResInterfaces.put(item, value);
+ }
+ close();
+ }
+
+ @Override
+ protected Point getInitialSize() {
+ Point actualSize = super.getInitialSize();
+ return new Point(actualSize.x + 100, actualSize.y);
}
@Override
public boolean isHelpAvailable() {
return false;
}
-
- public Map<String, Boolean> getResourceInterfaceStatus() {
- return resourceIfStatus;
- }
}
jstring value = (jstring) m_env->CallObjectMethod(entry, getValueMethodID);
JniString jniKey(m_env, key);
- JniString jniValue(m_env, key);
+ JniString jniValue(m_env, value);
result[jniKey.get()] = jniValue.get();
{
throwInvalidArgsException(env, e.code(), e.what());
}
- catch (SimulatorException &e)
- {
- throwInvalidArgsException(env, e.code(), e.what());
- }
}
JNIEXPORT void JNICALL
}
catch (SimulatorException &e)
{
- throwInvalidArgsException(env, e.code(), e.what());
+ throwSimulatorException(env, e.code(), e.what());
}
}
}
catch (SimulatorException &e)
{
- throwInvalidArgsException(env, e.code(), e.what());
+ throwSimulatorException(env, e.code(), e.what());
}
}
}
catch (SimulatorException &e)
{
+ throwSimulatorException(env, e.code(), e.what());
+ }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_removeInterface
+(JNIEnv *env, jobject object, jstring interfaceType)
+{
+ VALIDATE_INPUT(env, !interfaceType, "Interface type is null!")
+
+ SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+ VALIDATE_OBJECT(env, resource)
+
+ JniString jniInterfaceType(env, interfaceType);
+ resource->removeInterface(jniInterfaceType.get());
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_addInterfaces
+(JNIEnv *env, jobject object, jobject interfaceType)
+{
+ VALIDATE_INPUT(env, !interfaceType, "Interface type is null!")
+
+ SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+ VALIDATE_OBJECT(env, resource)
+
+ std::vector<std::string> interfaceList = JniVector(env).toCpp<std::string>(interfaceType);
+
+ try
+ {
+ resource->addInterface(interfaceList);
+ }
+ catch (InvalidArgsException &e)
+ {
throwInvalidArgsException(env, e.code(), e.what());
}
+ catch (NoSupportException &e)
+ {
+ throwNoSupportException(env, e.what());
+ }
+ catch (SimulatorException &e)
+ {
+ throwSimulatorException(env, e.code(), e.what());
+ }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_removeInterfaces
+(JNIEnv *env, jobject object, jobject interfaceType)
+{
+ VALIDATE_INPUT(env, !interfaceType, "Interface type is null!")
+
+ SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+ VALIDATE_OBJECT(env, resource)
+
+ std::vector<std::string> interfaceList = JniVector(env).toCpp<std::string>(interfaceType);
+
+ resource->removeInterface(interfaceList);
}
JNIEXPORT void JNICALL
}
catch (SimulatorException &e)
{
- throwInvalidArgsException(env, e.code(), e.what());
+ throwSimulatorException(env, e.code(), e.what());
}
}
package org.oic.simulator;
/**
- * This class represents the resource attribute's vaule property.
+ * This class represents the resource attribute's value property.
*/
public class AttributeProperty {
private AttributeProperty mChildProperty = null;
/**
- * Enum to represent propety type.
+ * Enum to represent property type.
*/
public enum Type {
UNKNOWN, RANGE, VALUESET
}
/**
- * Constructs {@AttributeProperty} of type
- * {@AttributeProperty.Type.Range} with min
- * and max values.
+ * Constructs {@link AttributeProperty} of type
+ * {@link AttributeProperty.Type#RANGE} with min and max values.
*
* @param min
- * Minimun value the attribute can have.
+ * Minimum value the attribute can have.
* @param max
* Maximum value the attribute can have.
*/
}
/**
- * Constructs {@AttributeProperty} of type
- * {@AttributeProperty.Type.VALUESET} with
- * array of integer.
+ * Constructs {@link AttributeProperty} of type
+ * {@link AttributeProperty.Type#VALUESET} with array of integer.
*
* @param values
* Array of int type values.
}
/**
- * Constructs {@AttributeProperty} of type
- * {@AttributeProperty.Type.VALUESET} with
- * array of double.
+ * Constructs {@link AttributeProperty} of type
+ * {@link AttributeProperty.Type#VALUESET} with array of double.
*
* @param values
* Array of double type values.
}
/**
- * Constructs {@AttributeProperty} of type
- * {@AttributeProperty.Type.VALUESET} with
- * array of boolean.
+ * Constructs {@link AttributeProperty} of type
+ * {@link AttributeProperty.Type#VALUESET} with array of boolean.
*
* @param values
* Array of boolean type values.
}
/**
- * Constructs {@AttributeProperty} of type
- * {@AttributeProperty.Type.VALUESET} with
- * array of Strings.
+ * Constructs {@link AttributeProperty} of type
+ * {@link AttributeProperty.Type#VALUESET} with array of Strings.
*
* @param values
- * Array of strings.
+ * Array of string type values.
*/
public AttributeProperty(String[] values) {
mType = Type.VALUESET;
/**
* API to get type of property.
*
- * @return {@AttributeProperty.Type}.
+ * @return {@link AttributeProperty.Type}.
*/
public Type type() {
return mType;
/**
* API to get minimum value which was set as property.
+ *
+ * @return Minimum value.
*/
public double min() {
return mMin;
/**
* API to get maximum value which was set as property.
+ *
+ * @return Maximum value.
*/
public double max() {
return mMax;
/**
* API to get array of values which was set as property.
*
- * @return array of {@AttributeValue}.
+ * @return Array of {@link AttributeValue}.
*/
public AttributeValue[] valueSet() {
return mValueSet;
}
/**
- * API to set child attribute propety.
+ * API to set child attribute property.
*
* @param childProperty
- * Child element property this property used if the Attribute
- * value is of array type.
+ * Child element property used if the Attribute value is of array
+ * type.
*/
public void setChildProperty(AttributeProperty childProperty) {
mChildProperty = childProperty;
}
/**
- * API to get child attribute propety.
+ * API to get child attribute property.
*
* @return Child element property.
*/
}
/**
- * Class provides the value type information in detail.
+ * Class which provides the value type information in detail.
*/
public class TypeInfo {
public ValueType mType;
public int mDepth;
/**
- * Constructs {@AttributeValue.TypeInfo} with
- * default values.
+ * Constructs {@link AttributeValue.TypeInfo} with default values.
*/
TypeInfo() {
mType = ValueType.UNKNOWN;
}
/**
- * Constructs {@AttributeValue.TypeInfo} with
- * given {AttributeValue.ValueType}.
+ * Constructs {@link AttributeValue.TypeInfo} with given
+ * {AttributeValue.ValueType}.
*
* @param type
* Value type.
}
/**
- * Constructs {@AttributeValue.TypeInfo} with
- * given {AttributeValue.ValueType}s and depth information.
+ * Constructs {@link AttributeValue.TypeInfo} with given
+ * {AttributeValue.ValueType}s and depth information.
*
* @param type
* Value type.
* @param baseType
- * Value base type. This type is useful when vaule is of
+ * Value base type. This type is useful when value is of
* array type.
* @param depth
- * Depth of array type value. This type is useful when vaule
- * is of array type.
+ * Depth of array type value. This is useful when value is of
+ * array type.
*/
TypeInfo(ValueType type, ValueType baseType, int depth) {
mType = type;
}
/**
- * Constructs {@AttributeValue} with int type value.
+ * Constructs {@link AttributeValue} with int type value.
*
* @param value
* int type value.
}
/**
- * Constructs {@AttributeValue} with double type value.
+ * Constructs {@link AttributeValue} with double type value.
*
* @param value
* double type value.
}
/**
- * Constructs {@AttributeValue} with boolean type value.
+ * Constructs {@link AttributeValue} with boolean type value.
*
* @param value
* boolean type value.
}
/**
- * Constructs {@AttributeValue} with String type value.
+ * Constructs {@link AttributeValue} with string type value.
*
* @param value
* String type value.
}
/**
- * Constructs {@AttributeValue} with SimulatorResourceModel
- * type value.
+ * Constructs {@link AttributeValue} with SimulatorResourceModel type value.
*
* @param value
* SimulatorResourceModel type value.
}
/**
- * Constructs {@AttributeValue} with array of int type
- * values.
+ * Constructs {@link AttributeValue} with array of int type values.
*
* @param values
* Array of int type values.
}
/**
- * Constructs {@AttributeValue} with array of Integer type
- * values.
+ * Constructs {@link AttributeValue} with array of Integer type values.
*
* @param values
* Array of Integer type values.
}
/**
- * Constructs {@AttributeValue} with array of double type
- * values.
+ * Constructs {@link AttributeValue} with array of double type values.
*
* @param values
* Array of double type values.
}
/**
- * Constructs {@AttributeValue} with array of Double type
- * values.
+ * Constructs {@link AttributeValue} with array of Double type values.
*
* @param values
* Array of Double type values.
}
/**
- * Constructs {@AttributeValue} with array of boolean type
- * values.
+ * Constructs {@link AttributeValue} with array of boolean type values.
*
* @param values
* Array of boolean type values.
}
/**
- * Constructs {@AttributeValue} with array of Boolean type
- * values.
+ * Constructs {@link AttributeValue} with array of Boolean type values.
*
* @param values
* Array of Boolean type values.
}
/**
- * Constructs {@AttributeValue} with array of String type
- * values.
+ * Constructs {@link AttributeValue} with array of String type values.
*
* @param values
* Array of String type values.
}
/**
- * Constructs {@AttributeValue} with array of
- * SimulatorResourceModel type values.
+ * Constructs {@link AttributeValue} with array of SimulatorResourceModel
+ * type values.
*
* @param values
* Array of SimulatorResourceModel type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * int type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of int type
+ * values.
*
* @param values
* 2 dimensional array of int type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * Integer type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of Integer
+ * type values.
*
* @param values
* 2 dimensional array of Integer type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * double type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of double type
+ * values.
*
* @param values
* 2 dimensional array of double type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * Double type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of Double type
+ * values.
*
* @param values
* 2 dimensional array of Double type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * boolean type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of boolean
+ * type values.
*
* @param values
* 2 dimensional array of boolean type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * Boolean type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of Boolean
+ * type values.
*
* @param values
* 2 dimensional array of Boolean type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
- * String type values.
+ * Constructs {@link AttributeValue} with 2 dimensional array of String type
+ * values.
*
* @param values
* 2 dimensional array of String type values.
}
/**
- * Constructs {@AttributeValue} with 2 dimensional array of
+ * Constructs {@link AttributeValue} with 2 dimensional array of
* SimulatorResourceModel type values.
*
* @param values
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * int type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of int type
+ * values.
*
* @param values
* 3 dimensional array of int type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * Integer type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of Integer
+ * type values.
*
* @param values
* 3 dimensional array of Integer type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * double type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of double type
+ * values.
*
* @param values
* 3 dimensional array of double type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * Double type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of Double type
+ * values.
*
* @param values
* 3 dimensional array of Double type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * boolean type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of boolean
+ * type values.
*
* @param values
* 3 dimensional array of boolean type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * Boolean type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of Boolean
+ * type values.
*
* @param values
* 3 dimensional array of Boolean type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
- * String type values.
+ * Constructs {@link AttributeValue} with 3 dimensional array of String type
+ * values.
*
* @param values
* 3 dimensional array of String type values.
}
/**
- * Constructs {@AttributeValue} with 3 dimensional array of
+ * Constructs {@link AttributeValue} with 3 dimensional array of
* SimulatorResourceModel type values.
*
* @param values
/**
* API to get value type information.
*
- * @return {@AttributeValue.TypeInfo}.
+ * @return {@link AttributeValue.TypeInfo}.
*/
public TypeInfo typeInfo() {
return createTypeInfo(mValue);
+/*
+ * 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 org.oic.simulator;
+/**
+ * This class holds a set of methods for validating the attribute values of
+ * different types using the given value properties {@link AttributeProperty}.
+ */
public class AttributeValueValidation implements
AttributeValueVisitor.VisitingMethods<Boolean> {
private AttributeProperty mProperty = null;
+ /**
+ * Constructs {@link AttributeValueValidation} with the given attribute
+ * value property.
+ *
+ * @param property
+ * Attribute value property.
+ */
public AttributeValueValidation(AttributeProperty property) {
mProperty = property;
}
+ /**
+ * API to validate the given attribute value. The given value is said to be
+ * valid if it matches with the values given in the value property.
+ *
+ * @param value
+ * {@link AttributeValue} to be validated.
+ * @return True if the given value is valid, otherwise false.
+ */
public boolean validate(AttributeValue value) {
AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
Boolean result = (Boolean) visitor.visit();
return result.booleanValue();
}
+ /**
+ * API to validate an Integer value.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Integer value) {
if (mProperty == null)
return false;
}
+ /**
+ * API to validate a Double value.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Double value) {
if (mProperty == null)
return false;
}
+ /**
+ * API to validate a Boolean value.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Boolean value) {
if (mProperty == null)
return false;
}
+ /**
+ * API to validate a String value.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(String value) {
if (mProperty == null)
return false;
}
+ /**
+ * API to validate a {@link SimulatorResourceModel} value.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(SimulatorResourceModel value) {
return false;
}
+ /**
+ * API to validate an array of integer values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Integer[] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate an array of double values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Double[] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate an array of boolean values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Boolean[] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate an array of string values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(String[] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate an array of {@link SimulatorResourceModel} values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(SimulatorResourceModel[] value) {
return false;
}
+ /**
+ * API to validate a 2D array of integer values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Integer[][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 2D array of double values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Double[][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 2D array of boolean values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Boolean[][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 2D array of string values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(String[][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 2D array of {@link SimulatorResourceModel} values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(SimulatorResourceModel[][] value) {
return false;
}
+ /**
+ * API to validate a 3D array of integer values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Integer[][][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 3D array of double values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Double[][][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 3D array of boolean values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(Boolean[][][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 3D array of string values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(String[][][] values) {
if (mProperty == null)
return true;
}
+ /**
+ * API to validate a 3D array of {@link SimulatorResourceModel} values.
+ *
+ * @return True if the given value is valid, otherwise false.
+ */
@Override
public Boolean visitingValue(SimulatorResourceModel[][][] value) {
return false;
+/*
+ * 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 org.oic.simulator;
+/**
+ * This class visits the given attribute value and invokes the right method
+ * based on the type of the attribute value.
+ */
public class AttributeValueVisitor {
private AttributeValue mValue;
private VisitingMethods mListener;
public T visitingValue(SimulatorResourceModel[][][] value);
}
+ /**
+ * Constructs {@link AttributeValueVisitor} from the given
+ * {@link AttributeValue} and the implementation of the
+ * {@link VisitingMethods} interface.
+ *
+ * @param value
+ * {@link AttributeValue} object.
+ * @param listener
+ * Implementation of {@link VisitingMethods} interface.
+ */
public AttributeValueVisitor(AttributeValue value, VisitingMethods listener) {
mValue = value;
mListener = listener;
}
+ /**
+ * API which processes an {@link AttributeValue} to find its value type and
+ * convert the Object to the appropriate type for invoking the right
+ * visitor(method) in the {@link VisitingMethods} interface.
+ *
+ * @return Object which holds the value returned by the visitor method.
+ */
public Object visit() {
if (null == mValue || null == mListener)
return null;
package org.oic.simulator;
/**
- * Listener for getting device information.
+ * Interface for receiving device information.
*/
public interface DeviceListener {
/**
* Method which provides remote device information.
*
* @param hostUri
- * Holds the address and port information.
+ * Holds the address detail.
* @param devInfo
* {@link DeviceInfo} object holding the device information.
*/
@SuppressWarnings("serial")
public class InvalidArgsException extends SimulatorException {
+ /**
+ * Constructs {@link InvalidArgsException} with the given ordinal
+ * representing the error code and description.
+ *
+ * @param code
+ * Ordinal of an error code.
+ * @param message
+ * Error description.
+ */
public InvalidArgsException(int code, String message) {
super(code, message);
}
+ /**
+ * Constructs {@link InvalidArgsException} with the given error code and
+ * description.
+ *
+ * @param code
+ * {@link SimulatorResult} enum constant representing the error
+ * code.
+ * @param message
+ * Error description.
+ */
public InvalidArgsException(SimulatorResult code, String message) {
super(code, message);
}
+ /**
+ * Constructs {@link InvalidArgsException} with the given error message.
+ *
+ * @param message
+ * Error description.
+ */
public InvalidArgsException(String message) {
super(SimulatorResult.SIMULATOR_INVALID_PARAM, message);
}
@SuppressWarnings("serial")
public class NoSupportException extends SimulatorException {
+ /**
+ * Constructs {@link NoSupportException} with the given error message.
+ *
+ * @param message
+ * Error description.
+ */
public NoSupportException(String message) {
super(SimulatorResult.SIMULATOR_NOT_SUPPORTED, message);
}
+ /**
+ * Constructs {@link NoSupportException} with the given error code and
+ * description.
+ *
+ * @param code
+ * {@link SimulatorResult} enum constant representing the error
+ * code.
+ * @param message
+ * Error description.
+ */
public NoSupportException(SimulatorResult code, String message) {
super(code, message);
}
@SuppressWarnings("serial")
public class OperationInProgressException extends SimulatorException {
+ /**
+ * Constructs {@link OperationInProgressException} with the given error
+ * message.
+ *
+ * @param message
+ * Error description.
+ */
public OperationInProgressException(String message) {
super(SimulatorResult.SIMULATOR_OPERATION_IN_PROGRESS, message);
}
+ /**
+ * Constructs {@link OperationInProgressException} with the given error code
+ * and description.
+ *
+ * @param code
+ * {@link SimulatorResult} enum constant representing the error
+ * code.
+ * @param message
+ * Error description.
+ */
public OperationInProgressException(SimulatorResult code, String message) {
super(code, message);
}
package org.oic.simulator;
/**
- * This class contains remote device platform information and provide APIs
- * access it.
+ * This class contains remote device platform information and provide APIs to
+ * access and update it.
*/
public class PlatformInfo {
private String mPlatformId;
package org.oic.simulator;
/**
- * Listener for getting platform information.
+ * Interface for receiving platform information.
*/
public interface PlatformListener {
/**
* Method which provides remote device platform information.
*
* @param hostUri
- * Holds the address and port information.
+ * Holds the address detail.
* @param platformInfo
* {@link PlatformInfo} object holding the platform information.
*/
private SimulatorResult code;
private String message;
+ /**
+ * Constructs {@link SimulatorException} with the given ordinal representing
+ * the error code and description.
+ *
+ * @param code
+ * Ordinal of an error code.
+ * @param message
+ * Error description.
+ */
public SimulatorException(int code, String message) {
this.code = SimulatorResult.get(code);
this.message = message;
}
+ /**
+ * Constructs {@link SimulatorException} with the given error code and
+ * description.
+ *
+ * @param code
+ * {@link SimulatorResult} enum constant representing the error
+ * code.
+ * @param message
+ * Error description.
+ */
public SimulatorException(SimulatorResult code, String message) {
this.code = code;
this.message = new String(message);
}
+ /**
+ * API to get the error code.
+ *
+ * @return {@link SimulatorResult} enum constant representing the error
+ * code.
+ */
public SimulatorResult code() {
return code;
}
+ /**
+ * API to get the error description.
+ *
+ * @return Error description.
+ */
public String message() {
return message;
}
* @param configPath
* Path to RAML configuration file.
*
- * @return {@link SimulatorResourceServer} - Created resource on success,
+ * @return {@link SimulatorResource} - Created resource on success,
* otherwise null.
*
* @throws InvalidArgsException
* @param count
* Number of resources to be created.
*
- * @return Returns an array of {@link SimulatorResourceServer} objects one
- * for each created resource on success, otherwise null.
+ * @return Returns an array of {@link SimulatorResource} objects one for
+ * each created resource on success, otherwise null.
*
* @throws InvalidArgsException
* Thrown if the input parameters are empty.
/**
* API for creating a resource either single or collection type.
*
- * @param configPath
- * Path to RAML configuration file.
+ * @param type
+ * Indicates whether single or collection type.
+ * @param name
+ * Resource Name.
+ * @param uri
+ * Resource URI.
+ * @param resourceType
+ * Resource Type.
*
- * @return {@link SimulatorResourceServer} - Created resource on success,
+ * @return {@link SimulatorResource} - Created resource on success,
* otherwise null.
*
* @throws InvalidArgsException
* is called when a resource is discovered in the network.
*
* @param resourceType
- * Required resource type
+ * Required resource type.
* @param listener
* Interface to receive the discovered remote resources.
*
*
* @param deviceInfo
* Device information.
+ *
+ * @throws InvalidArgsException
+ * Thrown if the input parameter is empty.
+ * @throws SimulatorException
+ * Thrown for other errors.
*/
public static native void setDeviceInfo(String deviceInfo)
throws InvalidArgsException, SimulatorException;
/**
- * API to search for devices in the network.
+ * API to search for devices on the given host in the network.
*
* @param hostUri
* URI of the host device.
* @param listener
* Listener for receiving the device information.
+ *
+ * @throws InvalidArgsException
+ * Thrown if the input parameter is empty.
+ * @throws SimulatorException
+ * Thrown for other errors.
*/
public static native void findDevices(String hostUri,
DeviceListener listener) throws InvalidArgsException,
*
* @param platformInfo
* {@link PlatformInfo} - Platform information.
+ *
+ * @throws InvalidArgsException
+ * Thrown if the input parameter is empty.
+ * @throws SimulatorException
+ * Thrown for other errors.
*/
public static native void setPlatformInfo(PlatformInfo platformInfo)
throws InvalidArgsException, SimulatorException;
/**
- * API to find all devices' platform information in the network.
+ * API to find the platform information of the given host in the network.
*
* @param hostUri
* URI of the host device.
* @param listener
* Listener for receiving the platform information.
+ *
+ * @throws InvalidArgsException
+ * Thrown if the input parameter is empty.
+ * @throws SimulatorException
+ * Thrown for other errors.
*/
public static native void getPlatformInformation(String hostUri,
PlatformListener listener) throws InvalidArgsException,
* @param logger
* {@link ILogger} to receive the log messages.
*/
- public static native void setLogger(ILogger logger)
- throws SimulatorException;
+ public static native void setLogger(ILogger logger);
private static native Vector<SimulatorResource> createResources(
String configPath, int count);
private AttributeProperty mProperty = null;
/**
- * Constructs {@SimulatorResourceAttribute}
- * with attribute name, value and its property.
+ * Constructs {@link SimulatorResourceAttribute} with the given attribute
+ * name, value and its property.
*
* @param name
* Name of the attribute.
}
/**
- * Constructs {@SimulatorResourceAttribute}
- * with attribute name, value.
+ * Constructs {@link SimulatorResourceAttribute} with the given attribute
+ * name and value.
*
* @param name
* Name of the attribute.
/**
* API to get value of attribute.
*
- * @return Attribute's value {@AttributeValue}.
+ * @return Attribute's value {@link AttributeValue}.
*/
public AttributeValue value() {
return mValue;
/**
* API to get property of attribute's value.
*
- * @return Attribute's value property {@AttributeProperty}.
+ * @return Attribute's value property {@link AttributeProperty
+ * }.
*/
public AttributeProperty property() {
return mProperty;
/**
* API to set the property of attribute.
*
- * @param value
+ * @param property
* Property of the attribute.
*/
public void setProperty(AttributeProperty property) {
import java.util.Map;
/**
- * This class represents the resource model of a resource.
+ * This class represents the resource model of a resource. A resource model
+ * contains a set of attributes and their properties. It represents the complex
+ * value type of an attribute.
*/
public class SimulatorResourceModel {
private Map<String, AttributeProperty> mProperties = null;
/**
- * Constructs new {@SimulatorResourceModel} object.
+ * Constructs new {@link SimulatorResourceModel} object.
*/
public SimulatorResourceModel() {
mValues = new HashMap<>();
* API to add an attribute to resource model.
*
* @param attribute
- * {@link SimulatorResourceAttribute} to be add to resource
+ * {@link SimulatorResourceAttribute} to be added to resource
* model.
*
* @throws InvalidArgsException
}
/**
- * API to check whether resource model has attribute.
+ * API to check whether resource model has an attribute with given name.
*
* @param attrName
* Name of the attribute.
* @param attrName
* Name of the attribute.
*
- * @return Attribute value type information {@AttributeValue.TypeInfo}.
+ * @return Attribute value type information {@link AttributeValue.TypeInfo
+ *
+ * }.
*/
public AttributeValue.TypeInfo getAttributeType(String attrName) {
if (mValues.containsKey(attrName))
* @param attrName
* Name of the attribute.
*
- * @return true if resource model has attribute it is removed, otherwise
- * false.
+ * @return true if resource model has an attribute with the given name,
+ * otherwise false.
*/
public boolean removeAttribute(String attrName) {
if (mValues.containsKey(attrName)) {
/**
* API to update the attribute values from given
* {@link SimulatorResourceModel}.
+ *
+ * @param resourceModel
+ * {@link SimulatorResourceModel} holding the new attribute
+ * values.
*/
public void update(SimulatorResourceModel resourceModel) {
if (null == resourceModel || 0 == resourceModel.size())
}
}
- // Methods used in native code
private SimulatorResourceModel(Map<String, AttributeValue> values,
Map<String, AttributeProperty> properties) {
mValues = values;
SIMULATOR_ERROR;
+ /**
+ * This method returns the {@link SimulatorResult} at the given
+ * position(ordinal).
+ *
+ * @param ordinal
+ * Index of the constant.
+ * @return {@link SimulatorResult} constant at the given index.
+ */
public static SimulatorResult get(int ordinal) {
SimulatorResult result;
package org.oic.simulator.client;
/**
- * Supported connectivity types.
+ * Enum to represent the supported connectivity types.
*/
public enum SimulatorConnectivityType {
SIMULATOR_CT_DEFAULT(0),
}
}
+ /**
+ * Enum to represent the verification types which can be used by the client
+ * to verify the resource model of the remote resource.
+ */
public enum VerificationType {
GET, PUT, POST, DELETE;
}
/**
* API to get the URI for this resource.
*
- * @return Resource URI
+ * @return Resource URI.
*/
public String getURI() {
return mUri;
/**
* API to get the list of resource types.
*
- * @return Array of resource types.
+ * @return Resource types.
*/
public Vector<String> getResourceTypes() {
return mResTypes;
/**
* API to get the list of resource interfaces.
*
- * @return Array of resource interfaces.
+ * @return Resource interfaces.
*/
public Vector<String> getResourceInterfaces() {
return mResInterfaces;
}
/**
- * API to get host address and port information of the resource.
+ * API to get the address detail of the resource.
*
* @return Host address.
*/
}
/**
- * API to get a unique Id of the resource .
+ * API to get a unique Id of the resource.
*
* @return Unique ID.
*/
/**
* API to send GET request to the resource. Response will be notified
- * asynchronously via callback set for {@link IGetListener}.
+ * asynchronously via callback set for {@link GetResponseListener}.
*
* @param queryParams
* Map which can have the query parameter name and value.
/**
* API to send GET request to the resource. Response will be notified
- * asynchronously via callback set for {@link IGetListener}.
+ * asynchronously via callback set for {@link GetResponseListener}.
*
* @param resourceInterface
* Interface type of the resource to operate on.
/**
* API to send PUT request to the resource. Response will be notified
- * asynchronously via callback set for {@link IPutListener}.
+ * asynchronously via callback set for {@link PutResponseListener}.
*
* @param queryParams
* Map which can have the query parameter name and value.
/**
* API to send PUT request to the resource. Response will be notified
- * asynchronously via callback set for {@link IPutListener}.
+ * asynchronously via callback set for {@link PutResponseListener}.
*
* @param resourceInterface
* Interface type of the resource to operate on.
/**
* API to send POST request to the resource. Response will be notified
- * asynchronously via callback set for {@link IPostListener}.
+ * asynchronously via callback set for {@link PostResponseListener}.
*
* @param queryParams
* Map which can have the query parameter name and value.
/**
* API to send POST request to the resource. Response will be notified
- * asynchronously via callback set for {@link IPostListener}.
+ * asynchronously via callback set for {@link PostResponseListener}.
*
* @param resourceInterface
* Interface type of the resource to operate on.
* @param path
* Path to RAML file.
*
- * @return representation {@link SimulatorResourceModel} holding the
+ * @return Representation {@link SimulatorResourceModel} holding the
* representation of the remote resource.
*
* @throws InvalidArgsException
/**
* API to stop sending requests which has been started using
- * {@link setConfigInfo}.
+ * {@link startVerification}.
*
* @param id
* Automation ID.
import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.SimulatorException;
+/**
+ * This class represents a collection type resource which provides a set of APIs
+ * that are specific to collection resource for adding/removing child resources
+ * and obtaining all child resources from the collection.
+ */
public final class SimulatorCollectionResource extends SimulatorResource {
private SimulatorCollectionResource(long nativeHandle) {
import org.oic.simulator.SimulatorException;
import org.oic.simulator.SimulatorResourceModel;
+/**
+ * This class serves as a base class type for all the resources in the
+ * simulator. It provides APIs to get and update the resource details, and
+ * register listeners to get notifications for resource model changes and
+ * observe requests from clients, and APIs to register/ unregister the resource
+ * with the platform.
+ */
public class SimulatorResource {
private native void dispose();
}
}
+ /**
+ * Enum to represent the type of resource.
+ */
public enum Type {
SINGLE, COLLECTION
}
+ /**
+ * Enum to represent the update type of automation.
+ */
public enum AutoUpdateType {
ONE_TIME, REPEAT
}
/**
* API to get the interfaces resource is bound with.
*
- * @return Interface type.
+ * @return Interface types.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
* API to set the name of the resource.
*
* @param name
- * - Name to be set.
+ * Name to be set.
*
* @throws InvalidArgsException
* This exception will be thrown if the resource name is
* API to set the resource URI.
*
* @param uri
- * - URI to be set.
+ * URI to be set.
*
* @throws InvalidArgsException
* This exception will be thrown if the resource URI is invalid.
* @throws SimulatorException
- * This exception will be thrown if the native resource object
- * does not exist or for some general errors.
+ * A resource needs to be stopped by calling the stop() before
+ * calling this API. This exception will be thrown if the native
+ * resource object has not yet been stopped.
*/
public native void setURI(String uri) throws InvalidArgsException,
SimulatorException;
* API to set the resource type.
*
* @param resourceType
- * - resource type string.
+ * Resource type string.
*
* @throws InvalidArgsException
* This exception will be thrown if the resource type is
* API to add interface type for resource.
*
* @param interfaceType
- * - interface to be added for resource.
+ * Interface to be added for resource.
*
* @throws InvalidArgsException
* This exception will be thrown if the interface type is
throws InvalidArgsException, SimulatorException;
/**
+ * API to remove interface type for resource.
+ *
+ * @param interfaceType
+ * Interface to be remove for resource.
+ * @throws InvalidArgsException
+ * This exception will be thrown if the interface type is
+ * invalid.
+ * @throws SimulatorException
+ * This exception will be thrown if the native resource object
+ * does not exist or for some general errors.
+ */
+ public native void removeInterface(String interfaceType)
+ throws InvalidArgsException, SimulatorException;
+
+ /**
+ * API to add a list of interfaces for resource.
+ *
+ * @param interfaceType
+ * List of interfaces to be added to the resource.
+ *
+ * @throws InvalidArgsException
+ * This exception will be thrown if the interface type is
+ * invalid.
+ * @throws SimulatorException
+ * This exception will be thrown if the native resource object
+ * does not exist or for some general errors.
+ */
+ public native void addInterfaces(Vector<String> interfaceType)
+ throws InvalidArgsException, SimulatorException;
+
+ /**
+ * API to remove interface type for resource.
+ *
+ * @param interfaceType
+ * List of interfaces to be removed from the resource.
+ * @throws InvalidArgsException
+ * This exception will be thrown if the interface type is
+ * invalid.
+ * @throws SimulatorException
+ * This exception will be thrown if the native resource object
+ * does not exist or for some general errors.
+ */
+ public native void removeInterfaces(Vector<String> interfaceType)
+ throws InvalidArgsException, SimulatorException;
+
+ /**
* API to make the resource observable or not.
*
* @param state
- * - true make the resource observable, otherwise non-observable.
+ * True makes the resource observable, otherwise non-observable.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
* registered or unregistered with resource.
*
* @param listener
- * - Callback to be set for receiving the notifications.
+ * Callback to be set for receiving the notifications.
*
* @throws InvalidArgsException
* This exception will be thrown if the listener is invalid.
SimulatorException;
/**
- * API to start the resource.
+ * API to start(register) the resource.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
public native void start() throws SimulatorException;
/**
- * API to stop the resource.
+ * API to stop(unregister) the resource.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
public native Vector<Observer> getObservers() throws SimulatorException;
/**
- * API to notify current resource model to specific observer.
+ * API to notify current resource model to a specific observer.
*
* @param observerId
- * - Observer ID to notify.
+ * Observer ID to notify.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
public native void notifyObserver(int observerId) throws SimulatorException;
/**
- * API to notify all registered observers.
+ * API to notify current resource model to all registered observers.
*
* @throws SimulatorException
* This exception will be thrown if the native resource object
*/
public interface ObserverListener {
/**
- * Method will be invoked when a observer is registered with resource.
+ * Method will be invoked when an observer is registered with resource.
*
- * @param uri
+ * @param resourceURI
* URI of the resource.
* @param observer
- * {@link ObserverInfo} object containing the details of
+ * {@link Observer} object containing the details of
* observer.
*/
public void onObserverAdded(String resourceURI, Observer observer);
/**
- * Method will be invoked when a observer is Unregistered with resource.
+ * Method will be invoked when an observer is unregistered from the
+ * resource.
*
* @param resourceURI
* URI of the resource.
* @param observer
- * {@link ObserverInfo} object containing the details of
+ * {@link Observer} object containing the details of
* observer.
*/
public void onObserverRemoved(String resourceURI, Observer observer);
import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.SimulatorException;
import org.oic.simulator.SimulatorResourceAttribute;
-import org.oic.simulator.SimulatorResourceModel;
+/**
+ * This class represents a single type resource(Non-collection resource). It
+ * provides APIs specific to single resource for manipulating the resource model
+ * by adding/removing the attributes, and updating the attribute values manually
+ * and automatically.
+ */
public final class SimulatorSingleResource extends SimulatorResource {
private SimulatorSingleResource(long nativeHandle) {
* Name of the attribute
*
* @return An object of {@link SimulatorResourceAttribute}, or null if
- * resource doest not have attribute of this name.
+ * resource does not have attribute of this name.
*
* @throws InvalidArgsException
* This exception will be thrown if the attribute name is
/**
* API to add an attribute to resource's representation model.
*
- * @param attrName
- * Name of the attribute.
* @param attribute
* Attribute to be added to resource's representation model.
*
* sequentially.
*
* @param type
- * {@link AutomationType} indicating whether the automation is
+ * {@link AutoUpdateType} indicating whether the automation is
* one-time or recursive.
* @param interval
* Interval time in milliseconds.
* @param listener
- * Listener to be notified when value updation ends.
+ * Listener to be notified when automation ends.
*
* @return Automation ID using which the automation can be stopped.
*
* @param attrName
* Name of the attribute to be automated.
* @param type
- * {@link AutomationType} indicating whether the automation is
+ * {@link AutoUpdateType} indicating whether the automation is
* one-time or recursive.
* @param interval
* Interval time in milliseconds.
******************************************************************/\r
\r
#include "IncludeResolver.h"\r
+#include <algorithm>\r
\r
namespace RAML\r
{\r
return "Empty payload";
}
std::ostringstream data;
- std::ostringstream dummy;
+ std::ostringstream valueStr;
std::string payloadType;
OCStringLL *types;
{
if (NULL != types->value && strlen(types->value) > 0)
{
- dummy << types->value;
+ valueStr << types->value;
if (types->next)
- dummy << ", ";
+ valueStr << ", ";
}
types = types->next;
}
- if (!dummy.str().empty())
+ if (!valueStr.str().empty())
{
- data << "Types: " << dummy.str() << std::endl;
- dummy.str("");
+ data << "Types: " << valueStr.str() << std::endl;
+ valueStr.str("");
}
// Interfaces
{
if (NULL != interfaces->value && strlen(interfaces->value) > 0)
{
- dummy << interfaces->value;
+ valueStr << interfaces->value;
if (interfaces->next)
- dummy << ", ";
+ valueStr << ", ";
}
interfaces = interfaces->next;
}
- if (!dummy.str().empty())
+ if (!valueStr.str().empty())
{
- data << "Interfaces: " << dummy.str() << std::endl;
- dummy.str("");
+ data << "Interfaces: " << valueStr.str() << std::endl;
+ valueStr.str("");
}
// Values
values = payload->values;
while (values)
{
- dummy << "\t" << values->name << ":" << rep.getValueToString(values->name) << std::endl;
+ valueStr << "\t" << values->name << ":" << rep.getValueToString(values->name) << std::endl;
values = values->next;
}
- if (!dummy.str().empty())
+ if (!valueStr.str().empty())
{
data << "Values:-" << std::endl;
- data << dummy.str();
- dummy.str("");
+ data << valueStr.str();
+ valueStr.str("");
}
payload = payload->next;
if (payload)
const OC::OCRepresentation &rep)
{
std::ostringstream data;
- std::ostringstream dummy;
+ std::ostringstream queryParamsStr;
if (queryParams.size() > 0)
{
for (auto &qp : queryParams)
- dummy << qp.second << ",";
+ queryParamsStr << qp.first << "=" << qp.second << ";";
}
- if (!dummy.str().empty())
+ if (!queryParamsStr.str().empty())
{
- data << "qp: " << dummy.str() << std::endl;
+ data << "qp: " << queryParamsStr.str() << std::endl;
}
data << getPayloadString(rep);
return data.str();
std::string getRequestString(const std::map<std::string, std::string> &queryParams)
{
std::ostringstream data;
- std::ostringstream dummy;
+ std::ostringstream queryParamsStr;
if (queryParams.size() > 0)
{
for (auto &qp : queryParams)
- dummy << qp.second << ",";
+ queryParamsStr << qp.first << "=" << qp.second << ";";
}
- if (!dummy.str().empty())
+ if (!queryParamsStr.str().empty())
{
- data << "qp: " << dummy.str() << std::endl;
+ data << "qp: " << queryParamsStr.str() << std::endl;
}
data << "Payload: No payload";
return data.str();
namespace OC
{
+ // Read-Only interface
+ const std::string READ_INTERFACE = "oic.if.r";
+
+ // Read-Write Interface
+ const std::string READWRITE_INTERFACE = "oic.if.rw";
+
+ // Actuator Interface
+ const std::string ACTUATOR_INTERFACE = "oic.if.a";
+
+ // Sensor Interface
+ const std::string SENSOR_INTERFACE = "oic.if.s";
+
class OCRepresentation;
}
SimulatorCollectionResourceImpl::SimulatorCollectionResourceImpl()
: m_type(SimulatorResource::Type::COLLECTION_RESOURCE),
- m_interfaces {OC::DEFAULT_INTERFACE, OC::LINK_INTERFACE},
- m_resourceHandle(NULL)
+ m_resourceHandle(NULL),
+ m_interfaces {OC::DEFAULT_INTERFACE, OC::LINK_INTERFACE}
{
m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
void SimulatorCollectionResourceImpl::setInterface(const std::vector<std::string> &interfaces)
{
- m_interfaces = interfaces;
+ if (!interfaces.empty())
+ m_interfaces = interfaces;
}
void SimulatorCollectionResourceImpl::setName(const std::string &name)
{
VALIDATE_INPUT(name.empty(), "Name is empty!")
- std::lock_guard<std::recursive_mutex> lock(m_objectLock);
- if (m_resourceHandle)
- {
- throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
- "Name can not be set when collection is started!");
- }
-
m_name = name;
}
m_resourceType = resourceType;
}
-void SimulatorCollectionResourceImpl::addInterface(std::string interfaceType)
+void SimulatorCollectionResourceImpl::addInterface(const std::string &interfaceType)
{
VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
- if (interfaceType == OC::GROUP_INTERFACE)
+ if (interfaceType == OC::LINK_INTERFACE
+ || interfaceType == OC::BATCH_INTERFACE
+ || interfaceType == OC::DEFAULT_INTERFACE)
+ {
+ if (m_interfaces.end() != std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+ {
+ SIM_LOG(ILogger::ERROR, "Resource already supports " << interfaceType << " interface!");
+ return;
+ }
+
+ std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+ typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+ const std::string &);
+
+ try
+ {
+ invokeocplatform(static_cast<bindInterfaceToResource>(
+ OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+ interfaceType);
+ }
+ catch (SimulatorException &e)
+ {
+ throw;
+ }
+ }
+ else
{
- throw NoSupportException("Collection resource does not support this interface type!");
+ throw NoSupportException("Resource does not support this interface!");
}
- std::lock_guard<std::recursive_mutex> lock(m_objectLock);
- if (m_resourceHandle)
+ m_interfaces.push_back(interfaceType);
+}
+
+void SimulatorCollectionResourceImpl::removeInterface(const std::string &interfaceType)
+{
+ if (m_interfaces.end() == std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
{
- throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
- "Interface type can not be set when resource is started!");
+ SIM_LOG(ILogger::ERROR, "Resource does not support " << interfaceType << " interface currently!");
+ return;
+ }
+
+ m_interfaces.erase(std::remove(m_interfaces.begin(), m_interfaces.end(), interfaceType), m_interfaces.end());
+}
+
+void SimulatorCollectionResourceImpl::addInterface(const std::vector<std::string> &interfaceList)
+{
+ if (!interfaceList.size())
+ {
+ SIM_LOG(ILogger::ERROR, "Interface list is empty!");
+ return;
}
- auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType);
- if (found != m_interfaces.end())
- m_interfaces.push_back(interfaceType);
+ for (auto interfaceType : interfaceList)
+ {
+ addInterface(interfaceType);
+ }
+}
+
+void SimulatorCollectionResourceImpl::removeInterface(const std::vector<std::string> &interfaceList)
+{
+ if (!interfaceList.size())
+ {
+ SIM_LOG(ILogger::ERROR, "Interface list is empty!");
+ return;
+ }
+
+ for (auto interfaceType : interfaceList)
+ {
+ removeInterface(interfaceType);
+ }
}
void SimulatorCollectionResourceImpl::setObservable(bool state)
void setName(const std::string &name);
void setURI(const std::string &uri);
void setResourceType(const std::string &resourceType);
- void addInterface(std::string interfaceType);
+ void addInterface(const std::string &interfaceType);
+ void removeInterface(const std::string &interfaceType);
+ void addInterface(const std::vector<std::string> &interfaceList);
+ void removeInterface(const std::vector<std::string> &interfaceList);
void setObservable(bool state);
void setObserverCallback(ObserverCallback callback);
void setModelChangeCallback(ResourceModelChangedCallback callback);
SimulatorSingleResourceImpl::SimulatorSingleResourceImpl()
: m_type(SimulatorResource::Type::SINGLE_RESOURCE),
- m_interfaces {OC::DEFAULT_INTERFACE},
- m_resourceHandle(NULL)
-{
+ m_resourceHandle(NULL),
+ m_interfaces {OC::DEFAULT_INTERFACE}
+{
+ m_requestTypes[OC::DEFAULT_INTERFACE] = {"GET", "PUT", "POST"};
+ m_requestTypes[OC::READ_INTERFACE] = {"GET"};
+ m_requestTypes[OC::READWRITE_INTERFACE] = {"GET", "PUT", "POST"};
+ m_requestTypes[OC::ACTUATOR_INTERFACE] = {"GET", "PUT", "POST"};
+ m_requestTypes[OC::SENSOR_INTERFACE] = {"GET"};
m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
}
void SimulatorSingleResourceImpl::setInterface(const std::vector<std::string> &interfaces)
{
- m_interfaces = interfaces;
+ // Replace m_interfaces if the list is not empty
+ if (!interfaces.empty())
+ m_interfaces = interfaces;
}
void SimulatorSingleResourceImpl::setName(const std::string &name)
{
VALIDATE_INPUT(name.empty(), "Name is empty!")
- std::lock_guard<std::recursive_mutex> lock(m_objectLock);
- if (m_resourceHandle)
- {
- throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
- "Name can not be set when resource is started!");
- }
-
m_name = name;
}
if (m_resourceHandle)
{
throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
- "Resource type can not be set when resource is started!");
+ "Resource type cannot be set when resource is started!");
}
m_resourceType = resourceType;
}
-void SimulatorSingleResourceImpl::addInterface(std::string interfaceType)
+void SimulatorSingleResourceImpl::addInterface(const std::string &interfaceType)
{
VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
- if (interfaceType == OC::LINK_INTERFACE
- || interfaceType == OC::BATCH_INTERFACE
- || interfaceType == OC::GROUP_INTERFACE)
+ if (interfaceType == OC::READ_INTERFACE
+ || interfaceType == OC::READWRITE_INTERFACE
+ || interfaceType == OC::ACTUATOR_INTERFACE
+ || interfaceType == OC::SENSOR_INTERFACE
+ || interfaceType == OC::DEFAULT_INTERFACE)
+ {
+ if (m_interfaces.end() != std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
+ {
+ SIM_LOG(ILogger::ERROR, "Interface " << interfaceType << " is already supported!");
+ return;
+ }
+
+ std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+ typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &,
+ const std::string &);
+
+ try
+ {
+ invokeocplatform(static_cast<bindInterfaceToResource>(
+ OC::OCPlatform::bindInterfaceToResource), m_resourceHandle,
+ interfaceType);
+ }
+ catch (SimulatorException &e)
+ {
+ throw;
+ }
+ }
+ else
{
- throw NoSupportException("Single type resource does not support this interface!");
+ throw NoSupportException("Interface is not supported!");
}
- std::lock_guard<std::recursive_mutex> lock(m_objectLock);
- if (m_resourceHandle)
+ m_interfaces.push_back(interfaceType);
+}
+
+void SimulatorSingleResourceImpl::removeInterface(const std::string &interfaceType)
+{
+ if (m_interfaces.end() == std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
{
- throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
- "Interface type can not be set when resource is started!");
+ SIM_LOG(ILogger::ERROR, "Interface " << interfaceType << " is not being supported currently!");
+ return;
+ }
+
+ m_interfaces.erase(std::remove(m_interfaces.begin(), m_interfaces.end(), interfaceType), m_interfaces.end());
+}
+
+void SimulatorSingleResourceImpl::addInterface(const std::vector<std::string> &interfaceList)
+{
+ VALIDATE_INPUT(!interfaceList.size(), "Interface list is empty!")
+
+ for (auto interfaceType : interfaceList)
+ {
+ addInterface(interfaceType);
}
+}
- auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType);
- if (found != m_interfaces.end())
- m_interfaces.push_back(interfaceType);
+void SimulatorSingleResourceImpl::removeInterface(const std::vector<std::string> &interfaceList)
+{
+ VALIDATE_INPUT(!interfaceList.size(), "Interface list is empty!")
+
+ for (auto interfaceType : interfaceList)
+ {
+ removeInterface(interfaceType);
+ }
}
void SimulatorSingleResourceImpl::setObservable(bool state)
<< " request received. \n**Payload details**\n" << payload)
}
- // TODO: Handover the request to appropriate interface handler
+ std::string interfaceType(OC::DEFAULT_INTERFACE);
+ OC::QueryParamsMap queryParams = request->getQueryParameters();
+ if (queryParams.end() != queryParams.find("if"))
+ {
+ interfaceType = queryParams["if"];
+ }
std::shared_ptr<OC::OCResourceResponse> response;
- response = requestOnBaseLineInterface(request);
- // Send response if the request handled by resource
- if (response)
+ // Check if the interface type is supported by the resource
+ if (m_interfaces.end() == std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType))
{
- if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
- return OC_EH_ERROR;
+ return sendErrorResponse(request, 403, OC_EH_FORBIDDEN);
+ }
+
+ //Check if requestType is supported by interface.
+ std::map<std::string, std::vector<std::string>>::iterator it = m_requestTypes.find(interfaceType);
+ if (it != m_requestTypes.end())
+ {
+ if (it->second.end() == std::find(it->second.begin(), it->second.end(), request->getRequestType()))
+ {
+ return sendErrorResponse(request, 405, OC_EH_ERROR);
+ }
+ }
+
+ if ("GET" == request->getRequestType())
+ {
+ response = handleReadRequest(request, interfaceType);
}
- else
+ else if ("PUT" == request->getRequestType()
+ || "POST" == request->getRequestType())
+ {
+ response = handleWriteRequest(request, interfaceType);
+ }
+ else if ("DELETE" == request->getRequestType())
{
SIM_LOG(ILogger::ERROR, "[" << m_name << "] " << "Unsupported request received!")
return OC_EH_ERROR;
}
+
+ // Send response if the request handled by resource
+ if (response)
+ {
+ response->setRequestHandle(request->getRequestHandle());
+ response->setResourceHandle(request->getResourceHandle());
+ if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+ return OC_EH_ERROR;
+ }
}
if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
removeObserver(observationInfo);
}
- errCode = OC_EH_OK;
- }
-
- return errCode;
-}
-
-std::shared_ptr<OC::OCResourceResponse> SimulatorSingleResourceImpl::requestOnBaseLineInterface(
- std::shared_ptr<OC::OCResourceRequest> request)
-{
- std::shared_ptr<OC::OCResourceResponse> response;
-
- RAML::ActionType type = getActionType(request->getRequestType());
-
- if (!m_actionTypes.empty())
- {
- if (m_actionTypes.end() == m_actionTypes.find(type))
- return 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(ocRep);
- std::string resPayload = getPayloadString(ocRep);
- SIM_LOG(ILogger::INFO, "[" << m_uri <<
- "] Sending response for GET request. \n**Payload details**" << resPayload)
- }
- else if ("PUT" == request->getRequestType()
- || "POST" == request->getRequestType())
- {
- OC::OCRepresentation requestRep = request->getResourceRepresentation();
- SimulatorResourceModel resModel;
- if (true == updateResourceModel(requestRep, resModel))
- {
- notifyAll(resModel);
- notifyApp(resModel);
-
- response = std::make_shared<OC::OCResourceResponse>();
- response->setErrorCode(200);
- response->setResponseResult(OC_EH_OK);
- response->setResourceRepresentation(resModel.getOCRepresentation());
- std::string resPayload = getPayloadString(resModel.getOCRepresentation());
- SIM_LOG(ILogger::INFO, "[" << m_uri <<
- "] Sending response for " << request->getRequestType() << " request. \n**Payload details**" <<
- resPayload)
- }
- else
- {
- response = std::make_shared<OC::OCResourceResponse>();
- response->setErrorCode(403);
- 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())
- {
- // TODO: Handle this request
}
- if (response)
- {
- response->setRequestHandle(request->getRequestHandle());
- response->setResourceHandle(request->getResourceHandle());
- }
-
- return response;
+ return OC_EH_OK;
}
void SimulatorSingleResourceImpl::addObserver(OC::ObservationInfo ocObserverInfo)
return RAML::ActionType::NONE;
}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::sendErrorResponse
+ (std::shared_ptr<OC::OCResourceRequest> request, const int errCode,
+ OCEntityHandlerResult responseCode)
+{
+ std::shared_ptr<OC::OCResourceResponse> response;
+
+ response = std::make_shared<OC::OCResourceResponse>();
+ response->setErrorCode(errCode);
+ response->setResponseResult(responseCode);
+
+ // Setting error response body as representation in response if available in RAML file
+ if ("PUT" == request->getRequestType())
+ {
+ if (!m_putErrorResModel.getOCRepresentation().empty())
+ response->setResourceRepresentation(m_putErrorResModel.getOCRepresentation());
+ }
+
+ if ("POST" == request->getRequestType())
+ {
+ if (!m_postErrorResModel.getOCRepresentation().empty())
+ response->setResourceRepresentation(m_postErrorResModel.getOCRepresentation());
+ }
+
+ response->setRequestHandle(request->getRequestHandle());
+ response->setResourceHandle(request->getResourceHandle());
+ if (OC_STACK_OK != OC::OCPlatform::sendResponse(response))
+ return OC_EH_ERROR;
+
+ return OC_EH_OK;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorSingleResourceImpl::handleReadRequest
+ (std::shared_ptr<OC::OCResourceRequest> request, const std::string &interfaceType)
+{
+ std::shared_ptr<OC::OCResourceResponse> response;
+ OC::OCRepresentation ocRep;
+
+ response = std::make_shared<OC::OCResourceResponse>();
+ response->setErrorCode(200);
+ response->setResponseResult(OC_EH_OK);
+
+ if (OC::ACTUATOR_INTERFACE == interfaceType ||
+ OC::SENSOR_INTERFACE == interfaceType)
+ {
+ // Only send the representation without the common properties.
+ ocRep = m_resModel.getOCRepresentation();
+ response->setResourceRepresentation(ocRep, interfaceType);
+ }
+ else
+ {
+ // Send the representation along with common properties for the resource.
+ SimulatorResourceModel resModel = m_resModel;
+ setCommonProperties(resModel);
+ ocRep = resModel.getOCRepresentation();
+ response->setResourceRepresentation(ocRep, interfaceType);
+ }
+
+ std::string resPayload = getPayloadString(ocRep);
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] Sending response for GET request. \n**Payload details**" << resPayload)
+
+ return response;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorSingleResourceImpl::handleWriteRequest
+ (std::shared_ptr<OC::OCResourceRequest> request, const std::string &interfaceType)
+{
+ std::shared_ptr<OC::OCResourceResponse> response;
+ OC::OCRepresentation requestRep = request->getResourceRepresentation();
+ SimulatorResourceModel resModel;
+ if (true == updateResourceModel(requestRep, resModel))
+ {
+ notifyAll(resModel);
+ notifyApp(resModel);
+
+ response = std::make_shared<OC::OCResourceResponse>();
+ response->setErrorCode(200);
+ response->setResponseResult(OC_EH_OK);
+ response->setResourceRepresentation(resModel.getOCRepresentation(), interfaceType);
+ std::string resPayload = getPayloadString(resModel.getOCRepresentation());
+ SIM_LOG(ILogger::INFO, "[" << m_uri <<
+ "] Sending response for " << request->getRequestType() << " request. \n**Payload details**" <<
+ resPayload)
+ }
+ else
+ {
+ sendErrorResponse(request, 400, OC_EH_ERROR);
+ }
+
+ return response;
+}
+
+void SimulatorSingleResourceImpl::setCommonProperties(SimulatorResourceModel &resModel)
+{
+ resModel.add("rt", m_resourceType);
+ resModel.add("if", m_interfaces);
+ resModel.add("p", m_property);
+ resModel.add("n", m_name);
+}
\ No newline at end of file
void setName(const std::string &name);
void setURI(const std::string &uri);
void setResourceType(const std::string &resourceType);
- void addInterface(std::string interfaceType);
+ void addInterface(const std::string &interfaceType);
+ void removeInterface(const std::string &interfaceType);
+ void addInterface(const std::vector<std::string> &interfaceList);
+ void removeInterface(const std::vector<std::string> &interfaceList);
void setObservable(bool state);
void setObserverCallback(ObserverCallback callback);
bool isObservable();
private:
SimulatorSingleResourceImpl();
OCEntityHandlerResult handleRequests(std::shared_ptr<OC::OCResourceRequest> request);
- std::shared_ptr<OC::OCResourceResponse> requestOnBaseLineInterface(
- std::shared_ptr<OC::OCResourceRequest> request);
- void resourceModified();
+ std::shared_ptr<OC::OCResourceResponse> handleReadRequest(
+ std::shared_ptr<OC::OCResourceRequest> request, const std::string &interfaceType);
+ std::shared_ptr<OC::OCResourceResponse> handleWriteRequest(
+ std::shared_ptr<OC::OCResourceRequest> request, const std::string &interfaceType);
+ OCEntityHandlerResult sendErrorResponse(std::shared_ptr<OC::OCResourceRequest> request,
+ const int errCode, OCEntityHandlerResult responseCode);
+ void setCommonProperties(SimulatorResourceModel &resModel);
bool updateResourceModel(OC::OCRepresentation &ocRep, SimulatorResourceModel &resModel);
void addObserver(OC::ObservationInfo ocObserverInfo);
void removeObserver(OC::ObservationInfo ocObserverInfo);
std::string m_uri;
std::string m_resourceType;
std::vector<std::string> m_interfaces;
+ std::map<std::string, std::vector<std::string>> m_requestTypes;
std::recursive_mutex m_objectLock;
std::mutex m_modelLock;
{
VALIDATE_INPUT(configPath.empty(), "Empty path!")
- std::shared_ptr<SimulatorResource> resource =
- SimulatorResourceFactory::getInstance()->createResource(configPath);
+ std::shared_ptr<SimulatorResource> resource;
+ try
+ {
+ resource = SimulatorResourceFactory::getInstance()->createResource(configPath);
+ }
+ catch(RAML::RamlException &e)
+ {
+ resource = nullptr;
+ }
if (!resource)
throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
return resource;
VALIDATE_INPUT(configPath.empty(), "Empty path!")
VALIDATE_INPUT(!count, "Count is zero!")
- std::vector<std::shared_ptr<SimulatorResource>> resources =
- SimulatorResourceFactory::getInstance()->createResource(configPath, count);
+ std::vector<std::shared_ptr<SimulatorResource>> resources;
+ try
+ {
+ resources = SimulatorResourceFactory::getInstance()->createResource(configPath, count);
+ }
+ catch(RAML::RamlException &e)
+ {
+ throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
+ }
if (!resources.size())
throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!");
return resources;