[IoTivity Simulator] Handling resource interfaces.
authorG S Senthil Kumar <senthil.gs@samsung.com>
Thu, 28 Jan 2016 15:08:07 +0000 (20:38 +0530)
committerMadan Lanka <lanka.madan@samsung.com>
Mon, 1 Feb 2016 06:26:01 +0000 (06:26 +0000)
1. Added APIs to add and remove resource interfaces from service provider and
   tested the functionality from eclipse plug-ins.
2. Updated client controller UI to get the resource interface type
   as one of the query parameters for sending GET/PUT/POST requests.
3. This code check-in also includes the following:
i)   Validating resource type entered by the user during resource
 creation without RAML from eclipse plug-in.
ii)  Minor bug fixes in native code and eclipse plug-ins.
iii) Updated javadoc comments for Java APIs.
iv)  Minor refactoring and optimization in eclipse plug-ins.
v)  Removal of unused icons from service provider plug-in.
vi)  Removed unnecessary pop-ups for success scenarios.
vii) Included the missing algorithm standard library file in RAML source file
         to avoid build failure.

Change-Id: Ie1c4fda34f06d2763fe7c1b14593191db02cf42e
Signed-off-by: G S Senthil Kumar <senthil.gs@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4849
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Radha Bhavani <radha.p@samsung.com>
Reviewed-by: Madan Lanka <lanka.madan@samsung.com>
56 files changed:
service/simulator/SConscript
service/simulator/examples/server/simulator_server.cpp
service/simulator/inc/simulator_resource.h
service/simulator/java/eclipse-plugin/ClientControllerPlugin/.classpath
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/LogManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeView.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PutRequestDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif [deleted file]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeEditingSupport.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdateResourceInterfaceDialog.java
service/simulator/java/jni/jni_queryparam.cpp
service/simulator/java/jni/simulator_resource_jni.cpp
service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java
service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java
service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java
service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java
service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java
service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java
service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java
service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java
service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java
service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java
service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java
service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java
service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java
service/simulator/ramlparser/raml/IncludeResolver.cpp
service/simulator/src/common/simulator_utils.cpp
service/simulator/src/common/simulator_utils.h
service/simulator/src/server/simulator_collection_resource_impl.cpp
service/simulator/src/server/simulator_collection_resource_impl.h
service/simulator/src/server/simulator_single_resource_impl.cpp
service/simulator/src/server/simulator_single_resource_impl.h
service/simulator/src/simulator_manager.cpp

index 8e77c4e..a155b40 100755 (executable)
@@ -40,7 +40,7 @@ simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client', 'src/server', 'src/co
 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',
@@ -68,7 +68,7 @@ java_headers.append(os.path.join(java_headers[0], 'solaris'))
 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'])
index 11029f2..d95901e 100644 (file)
@@ -376,7 +376,9 @@ void printMainMenu()
     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;
 }
@@ -439,6 +441,36 @@ void setPlatformInfo()
     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();
@@ -448,7 +480,7 @@ int main(int argc, char *argv[])
         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;
         }
@@ -466,7 +498,9 @@ int main(int argc, char *argv[])
             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;
         }
     }
index d5b99ca..9b51d53 100644 (file)
@@ -145,7 +145,32 @@ class SimulatorResource : public UnCopyable
          *
          * 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.
index 607d933..cdbd8da 100644 (file)
@@ -1,11 +1,8 @@
 <?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>
index ffdb442..03700e4 100644 (file)
@@ -24,7 +24,6 @@ import java.util.LinkedList;
 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;
 
@@ -32,7 +31,6 @@ 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;
 
 /**
@@ -57,14 +55,7 @@ public class LogManager {
 
         // 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 {
index 07f57d9..e20e18a 100644 (file)
@@ -114,9 +114,11 @@ public class ResourceManager {
                             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;
                         }
 
@@ -174,9 +176,16 @@ public class ResourceManager {
                                                 + "].");
 
                         // 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()
@@ -1185,7 +1194,8 @@ public class ResourceManager {
         return values;
     }
 
-    public void sendGetRequest(RemoteResource resource) {
+    public void sendGetRequest(String ifType, String query,
+            RemoteResource resource) {
         if (null == resource) {
             return;
         }
@@ -1194,8 +1204,9 @@ public class ResourceManager {
             return;
         }
 
+        Map<String, String> queryParams = formQueryParameters(ifType, query);
         try {
-            resourceN.get(null, getListener);
+            resourceN.get(queryParams, getListener);
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
@@ -1205,7 +1216,7 @@ public class ResourceManager {
         }
     }
 
-    public void sendPutRequest(RemoteResource resource,
+    public void sendPutRequest(String ifType, RemoteResource resource,
             SimulatorResourceModel model) {
         if (null == resource || null == model) {
             return;
@@ -1214,8 +1225,9 @@ public class ResourceManager {
         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.";
@@ -1227,7 +1239,7 @@ public class ResourceManager {
         }
     }
 
-    public void sendPostRequest(RemoteResource resource,
+    public void sendPostRequest(String ifType, RemoteResource resource,
             SimulatorResourceModel model) {
         if (null == resource || null == model) {
             return;
@@ -1236,8 +1248,9 @@ public class ResourceManager {
         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.";
@@ -1274,6 +1287,35 @@ public class ResourceManager {
         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()) {
@@ -1319,16 +1361,21 @@ public class ResourceManager {
             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()
@@ -1354,7 +1401,7 @@ public class ResourceManager {
         } 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();
         }
index 3a0403a..acac4c8 100644 (file)
@@ -16,6 +16,7 @@
 
 package oic.simulator.clientcontroller.view;
 
+import java.util.Date;
 import java.util.Map;
 
 import oic.simulator.clientcontroller.Activator;
@@ -33,6 +34,7 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
 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;
@@ -60,7 +62,9 @@ import org.eclipse.swt.widgets.TreeColumn;
 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;
 
 /**
@@ -224,23 +228,37 @@ public class AttributeView extends ViewPart {
             @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()
+                                                + "\".");
                     }
                 });
             }
@@ -248,11 +266,31 @@ public class AttributeView extends ViewPart {
             @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()
+                                                + "\".");
                     }
                 });
             }
@@ -281,22 +319,6 @@ public class AttributeView extends ViewPart {
         };
     }
 
-    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;
@@ -455,7 +477,15 @@ public class AttributeView extends ViewPart {
                 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);
+                        }
                     }
                 });
             }
@@ -487,8 +517,11 @@ public class AttributeView extends ViewPart {
                         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());
                         }
                     }
@@ -523,9 +556,11 @@ public class AttributeView extends ViewPart {
                         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());
                         }
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/GetRequestDialog.java
new file mode 100644 (file)
index 0000000..b67717a
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * 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;
+    }
+
+}
index edee7a3..6be2b35 100644 (file)
@@ -16,6 +16,9 @@
 
 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;
@@ -33,12 +36,17 @@ import org.eclipse.jface.viewers.TreeViewer;
 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;
@@ -51,6 +59,11 @@ import org.oic.simulator.SimulatorResourceAttribute;
 public class PostRequestDialog extends TitleAreaDialog {
 
     private TreeViewer              attViewer;
+    private Combo                   ifTypesCmb;
+
+    private String                  ifType;
+
+    private Map<String, String>     ifTypes;
 
     private AttributeEditingSupport attributeEditor;
 
@@ -75,9 +88,44 @@ public class PostRequestDialog extends TitleAreaDialog {
     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);
@@ -283,4 +331,11 @@ public class PostRequestDialog extends TitleAreaDialog {
     public ResourceRepresentation getUpdatedRepresentation() {
         return updatedRepresentation;
     }
+
+    public String getIfType() {
+        if (ifTypes.containsKey(ifType)) {
+            return ifTypes.get(ifType);
+        }
+        return ifType;
+    }
 }
index d140caf..435fb44 100644 (file)
@@ -16,6 +16,9 @@
 
 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;
@@ -32,12 +35,17 @@ import org.eclipse.jface.viewers.TreeViewer;
 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;
@@ -50,6 +58,11 @@ import org.oic.simulator.SimulatorResourceAttribute;
 public class PutRequestDialog extends TitleAreaDialog {
 
     private TreeViewer              attViewer;
+    private Combo                   ifTypesCmb;
+
+    private String                  ifType;
+
+    private Map<String, String>     ifTypes;
 
     private AttributeEditingSupport attributeEditor;
 
@@ -73,9 +86,43 @@ public class PutRequestDialog extends TitleAreaDialog {
     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);
@@ -253,4 +300,12 @@ public class PutRequestDialog extends TitleAreaDialog {
     public ResourceRepresentation getUpdatedRepresentation() {
         return updatedRepresentation;
     }
+
+    public String getIfType() {
+        if (ifTypes.containsKey(ifType)) {
+            return ifTypes.get(ifType);
+        }
+        return ifType;
+    }
+
 }
index 61b8c6c..4e3db96 100644 (file)
@@ -1,10 +1,8 @@
 <?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>
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif
deleted file mode 100644 (file)
index 173661c..0000000
Binary files a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif and /dev/null differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif
deleted file mode 100644 (file)
index e3ecc55..0000000
Binary files a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif and /dev/null differ
index 3b8bead..b7510a2 100644 (file)
@@ -26,13 +26,11 @@ import oic.simulator.logger.LoggerCallback;
 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;
 
 /**
@@ -57,14 +55,7 @@ public class LogManager {
 
         // 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 {
index 89df91f..9368c6d 100644 (file)
@@ -19,6 +19,7 @@ package oic.simulator.serviceprovider.manager;
 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;
@@ -35,6 +36,7 @@ import oic.simulator.serviceprovider.model.SingleResource;
 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;
@@ -90,44 +92,6 @@ public class ResourceManager {
     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
@@ -156,19 +120,6 @@ public class ResourceManager {
             }
         };
 
-        // 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
@@ -292,6 +243,58 @@ public class ResourceManager {
         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 {
@@ -576,9 +579,14 @@ public class ResourceManager {
             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()
@@ -729,19 +737,28 @@ public class ResourceManager {
         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);
@@ -749,7 +766,7 @@ public class ResourceManager {
                     result = completeSingleResourceCreationByRAML(resource,
                             jResource.getURI(), jResource.getName(), true);
                     if (result) {
-                        createCount++;
+                        resultSet.add(resource);
                     }
                 } catch (SimulatorException eInner) {
                     Activator
@@ -760,10 +777,7 @@ public class ResourceManager {
                                     Utility.getSimulatorErrorString(eInner,
                                             null));
                 }
-            }
-            if (createCount > 0) {
-                UiListenerHandler.getInstance().resourceCreatedUINotification(
-                        ResourceType.SINGLE);
+                progressMonitor.worked(1);
             }
         } catch (SimulatorException eOuter) {
             Activator
@@ -773,7 +787,7 @@ public class ResourceManager {
                             Utility.getSimulatorErrorString(eOuter, null));
             throw eOuter;
         }
-        return createCount;
+        return resultSet;
     }
 
     public List<Resource> getResourceList() {
@@ -875,6 +889,20 @@ public class ResourceManager {
                     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;
                 }
@@ -1057,6 +1085,84 @@ public class ResourceManager {
         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) {
@@ -1232,7 +1338,6 @@ public class ResourceManager {
             return false;
         }
         boolean status = false;
-        changeResourceLevelAutomationStatus(resource, true);
         // Invoke the native automation method
         SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource
                 .getSimulatorResource();
@@ -1249,12 +1354,10 @@ public class ResourceManager {
                                 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.
index cd4c52a..f8a04bf 100644 (file)
@@ -164,6 +164,11 @@ public class Constants {
                                                                                           + "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";
index 1b3195f..d95b33e 100644 (file)
@@ -522,6 +522,22 @@ public class Utility {
         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;
@@ -535,5 +551,4 @@ public class Utility {
         }
         return ifTypes;
     }
-
 }
\ No newline at end of file
index 4b956cf..98dbfb9 100644 (file)
@@ -178,8 +178,7 @@ public class AttributeEditingSupport {
             }
 
             // If selected resource is not a single resource, then editor
-            // support is not
-            // required.
+            // support is not required.
             if (!(res instanceof SingleResource)) {
                 return null;
             }
@@ -561,9 +560,6 @@ public class AttributeEditingSupport {
                 // Stop the automation
                 resourceManager.stopAutomation((SingleResource) resource, att,
                         att.getAutoUpdateId());
-                MessageDialog.openInformation(Display.getDefault()
-                        .getActiveShell(), "Automation Status",
-                        "Automation stopped.");
             }
         }
     }
index 1d80604..a4bde78 100644 (file)
@@ -162,7 +162,7 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        if (null == resource) {
+                        if (null == resource || null == attViewer) {
                             return;
                         }
                         Resource resourceInSelection = resourceManager
@@ -177,8 +177,6 @@ public class AttributeView extends ViewPart {
                             Tree tree;
                             tree = attViewer.getTree();
                             if (!tree.isDisposed()) {
-                                attViewer.refresh();
-
                                 // Disabling the table to prevent interactions
                                 // during the automation
                                 tree.setEnabled(false);
@@ -216,7 +214,6 @@ public class AttributeView extends ViewPart {
                         tree = attViewer.getTree();
                         if (!tree.isDisposed()) {
                             tree.setEnabled(true);
-                            attViewer.refresh();
                         }
                     }
                 });
index ae70f4c..4ba8c83 100644 (file)
 
 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;
@@ -24,7 +28,10 @@ import oic.simulator.serviceprovider.manager.ResourceManager;
 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;
@@ -36,7 +43,10 @@ import org.eclipse.jface.viewers.TableViewerColumn;
 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;
@@ -45,6 +55,7 @@ import org.eclipse.swt.widgets.Button;
 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;
 
@@ -65,12 +76,16 @@ public class MetaPropertiesView extends ViewPart {
 
     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();
@@ -125,6 +140,12 @@ public class MetaPropertiesView extends ViewPart {
                     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
@@ -155,6 +176,7 @@ public class MetaPropertiesView extends ViewPart {
                         boolean update = false;
                         boolean uriChange = false;
                         boolean nameChange = false;
+                        boolean interfaceChange = false;
 
                         if (resourceManagerRef.isPropValueChanged(
                                 resourceInSelection, properties,
@@ -187,6 +209,27 @@ public class MetaPropertiesView extends ViewPart {
                             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)
@@ -198,6 +241,14 @@ public class MetaPropertiesView extends ViewPart {
                                                             .getCurrentResourceInSelection(),
                                                     properties, uriChange,
                                                     nameChange);
+                                if (interfaceChange)
+                                    result = Activator
+                                            .getDefault()
+                                            .getResourceManager()
+                                            .updateResourceInterfaces(
+                                                    resourceInSelection,
+                                                    updatedIfSet);
+
                             } catch (SimulatorException ex) {
                                 result = false;
                             }
@@ -243,9 +294,23 @@ public class MetaPropertiesView extends ViewPart {
                 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
@@ -387,6 +452,59 @@ public class MetaPropertiesView extends ViewPart {
             }
 
             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;
         }
 
index e3657b8..a14b178 100644 (file)
@@ -96,7 +96,7 @@ public class ResourceManagerView extends ViewPart {
 
             @Override
             public void onResourceCreation(final ResourceType type) {
-                Display.getDefault().asyncExec(new Runnable() {
+                Display.getDefault().syncExec(new Runnable() {
 
                     @Override
                     public void run() {
@@ -301,12 +301,6 @@ public class ResourceManagerView extends ViewPart {
 
                                             resourceManager
                                                     .resourceSelectionChanged(null);
-
-                                            MessageDialog.openInformation(
-                                                    Display.getDefault()
-                                                            .getActiveShell(),
-                                                    "Deleted",
-                                                    "Resource deleted.");
                                         } catch (SimulatorException e1) {
                                             MessageDialog
                                                     .openInformation(Display
@@ -345,7 +339,6 @@ public class ResourceManagerView extends ViewPart {
                                     "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;
@@ -369,11 +362,12 @@ public class ResourceManagerView extends ViewPart {
                         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);
+                        }
                     }
                 }
             }
@@ -386,10 +380,11 @@ public class ResourceManagerView extends ViewPart {
             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);
+                }
             }
         });
 
@@ -476,11 +471,14 @@ public class ResourceManagerView extends ViewPart {
                         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();
                         }
                     }
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddInterfaceTypeDialog.java
new file mode 100644 (file)
index 0000000..912f7d7
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * 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;
+    }
+}
index e7c35b2..20d0523 100644 (file)
@@ -26,8 +26,10 @@ import java.util.Map;
 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;
@@ -67,6 +69,8 @@ public class CreateResourceWizard extends Wizard {
 
     private Resource                       createdResource;
 
+    private IProgressMonitor               progressMonitor;
+
     public CreateResourceWizard() {
         setWindowTitle("Create resources");
         IPath path = new Path("/icons/oic_logo_64x64.png");
@@ -135,7 +139,7 @@ public class CreateResourceWizard extends Wizard {
                 .getDefault().getResourceManager().isAnyResourceExist()))
                 || curPage == simpleResourceAddAttributePage
                 || (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage
-                .isMultiResourceCreation())) {
+                        .isMultiResourceCreation())) {
             return true;
         }
         return false;
@@ -165,11 +169,11 @@ public class CreateResourceWizard extends Wizard {
                 });
             } 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) {
@@ -178,8 +182,8 @@ public class CreateResourceWizard extends Wizard {
                 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;
@@ -189,26 +193,27 @@ public class CreateResourceWizard extends Wizard {
             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();
                         }
@@ -216,13 +221,27 @@ public class CreateResourceWizard extends Wizard {
                 });
             } 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();
@@ -242,8 +261,8 @@ public class CreateResourceWizard extends Wizard {
             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;
@@ -268,11 +287,11 @@ public class CreateResourceWizard extends Wizard {
                 });
             } 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();
             }
         }
@@ -318,6 +337,8 @@ public class CreateResourceWizard extends Wizard {
         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>();
@@ -387,14 +408,27 @@ public class CreateResourceWizard extends Wizard {
         }
     }
 
-    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
                         + "]";
@@ -407,5 +441,6 @@ public class CreateResourceWizard extends Wizard {
             status = "Failed to create resource.\n"
                     + Utility.getSimulatorErrorString(e, null);
         }
+        return resCreatedCount;
     }
 }
\ No newline at end of file
index c75065e..fdeb9cb 100644 (file)
@@ -43,7 +43,7 @@ public class DeleteResourceWizard extends Wizard {
 
     private DeleteResourcePage page;
 
-    private String             status;
+    private boolean            success;
 
     public DeleteResourceWizard() {
         setWindowTitle("Delete resources");
@@ -95,9 +95,9 @@ public class DeleteResourceWizard extends Wizard {
                             }
                         }
                         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();
                     }
@@ -113,7 +113,7 @@ public class DeleteResourceWizard extends Wizard {
         return true;
     }
 
-    public String getStatus() {
-        return status;
+    public boolean getStatus() {
+        return success;
     }
 }
\ No newline at end of file
index f31dbbc..dcd4131 100644 (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;
@@ -35,22 +43,31 @@ import org.eclipse.swt.widgets.Composite;
 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
@@ -105,6 +122,41 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
         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();
@@ -119,6 +171,18 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
 
         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);
     }
 
@@ -158,6 +222,66 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
                 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
@@ -182,6 +306,13 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
             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
@@ -192,6 +323,22 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
             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();
     }
@@ -208,6 +355,10 @@ public class SimpleResourceBasicDetailsPage extends WizardPage {
         return resType;
     }
 
+    public Set<String> getInterfaceTypes() {
+        return selectedIfTypes;
+    }
+
     public boolean isObservable() {
         return observable;
     }
index a0d1b7c..33557d5 100644 (file)
@@ -18,33 +18,45 @@ package oic.simulator.serviceprovider.view.dialogs;
 
 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
@@ -55,51 +67,154 @@ public class UpdateResourceInterfaceDialog extends TrayDialog {
     @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
@@ -115,8 +230,4 @@ public class UpdateResourceInterfaceDialog extends TrayDialog {
     public boolean isHelpAvailable() {
         return false;
     }
-
-    public Map<String, Boolean> getResourceInterfaceStatus() {
-        return resourceIfStatus;
-    }
 }
index fd59abf..af6f142 100644 (file)
@@ -55,7 +55,7 @@ std::map<std::string, std::string> JniQueryParameter::toCpp(jobject jQueryParams
         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();
 
index 334b5b5..6af4cc7 100644 (file)
@@ -235,10 +235,6 @@ Java_org_oic_simulator_server_SimulatorResource_setName
     {
         throwInvalidArgsException(env, e.code(), e.what());
     }
-    catch (SimulatorException &e)
-    {
-        throwInvalidArgsException(env, e.code(), e.what());
-    }
 }
 
 JNIEXPORT void JNICALL
@@ -261,7 +257,7 @@ Java_org_oic_simulator_server_SimulatorResource_setURI
     }
     catch (SimulatorException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        throwSimulatorException(env, e.code(), e.what());
     }
 }
 
@@ -285,7 +281,7 @@ Java_org_oic_simulator_server_SimulatorResource_setResourceType
     }
     catch (SimulatorException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        throwSimulatorException(env, e.code(), e.what());
     }
 }
 
@@ -313,8 +309,64 @@ Java_org_oic_simulator_server_SimulatorResource_addInterface
     }
     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
@@ -330,7 +382,7 @@ Java_org_oic_simulator_server_SimulatorResource_setObservable
     }
     catch (SimulatorException &e)
     {
-        throwInvalidArgsException(env, e.code(), e.what());
+        throwSimulatorException(env, e.code(), e.what());
     }
 }
 
index 32bfafb..5f8d2fb 100644 (file)
@@ -17,7 +17,7 @@
 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 {
 
@@ -28,19 +28,18 @@ 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.
      */
@@ -51,9 +50,8 @@ public class AttributeProperty {
     }
 
     /**
-     * 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.
@@ -66,9 +64,8 @@ public class AttributeProperty {
     }
 
     /**
-     * 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.
@@ -81,9 +78,8 @@ public class AttributeProperty {
     }
 
     /**
-     * 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.
@@ -96,12 +92,11 @@ public class AttributeProperty {
     }
 
     /**
-     * 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;
@@ -113,7 +108,7 @@ public class AttributeProperty {
     /**
      * API to get type of property.
      *
-     * @return {@AttributeProperty.Type}.
+     * @return {@link AttributeProperty.Type}.
      */
     public Type type() {
         return mType;
@@ -121,6 +116,8 @@ public class AttributeProperty {
 
     /**
      * API to get minimum value which was set as property.
+     *
+     * @return Minimum value.
      */
     public double min() {
         return mMin;
@@ -128,6 +125,8 @@ public class AttributeProperty {
 
     /**
      * API to get maximum value which was set as property.
+     *
+     * @return Maximum value.
      */
     public double max() {
         return mMax;
@@ -136,25 +135,25 @@ public class AttributeProperty {
     /**
      * 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.
      */
index 76bc72c..b7f759c 100644 (file)
@@ -31,7 +31,7 @@ public class AttributeValue {
     }
 
     /**
-     * Class provides the value type information in detail.
+     * Class which provides the value type information in detail.
      */
     public class TypeInfo {
         public ValueType mType;
@@ -39,8 +39,7 @@ public class AttributeValue {
         public int       mDepth;
 
         /**
-         * Constructs {@AttributeValue.TypeInfo} with
-         * default values.
+         * Constructs {@link AttributeValue.TypeInfo} with default values.
          */
         TypeInfo() {
             mType = ValueType.UNKNOWN;
@@ -49,8 +48,8 @@ public class AttributeValue {
         }
 
         /**
-         * Constructs {@AttributeValue.TypeInfo} with
-         * given {AttributeValue.ValueType}.
+         * Constructs {@link AttributeValue.TypeInfo} with given
+         * {AttributeValue.ValueType}.
          *
          * @param type
          *            Value type.
@@ -62,17 +61,17 @@ public class AttributeValue {
         }
 
         /**
-         * 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;
@@ -82,7 +81,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with int type value.
+     * Constructs {@link AttributeValue} with int type value.
      *
      * @param value
      *            int type value.
@@ -92,7 +91,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with double type value.
+     * Constructs {@link AttributeValue} with double type value.
      *
      * @param value
      *            double type value.
@@ -102,7 +101,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with boolean type value.
+     * Constructs {@link AttributeValue} with boolean type value.
      *
      * @param value
      *            boolean type value.
@@ -112,7 +111,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with String type value.
+     * Constructs {@link AttributeValue} with string type value.
      *
      * @param value
      *            String type value.
@@ -122,8 +121,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with SimulatorResourceModel
-     * type value.
+     * Constructs {@link AttributeValue} with SimulatorResourceModel type value.
      *
      * @param value
      *            SimulatorResourceModel type value.
@@ -133,8 +131,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of int type
-     * values.
+     * Constructs {@link AttributeValue} with array of int type values.
      *
      * @param values
      *            Array of int type values.
@@ -147,8 +144,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of Integer type
-     * values.
+     * Constructs {@link AttributeValue} with array of Integer type values.
      *
      * @param values
      *            Array of Integer type values.
@@ -158,8 +154,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of double type
-     * values.
+     * Constructs {@link AttributeValue} with array of double type values.
      *
      * @param values
      *            Array of double type values.
@@ -172,8 +167,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of Double type
-     * values.
+     * Constructs {@link AttributeValue} with array of Double type values.
      *
      * @param values
      *            Array of Double type values.
@@ -183,8 +177,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of boolean type
-     * values.
+     * Constructs {@link AttributeValue} with array of boolean type values.
      *
      * @param values
      *            Array of boolean type values.
@@ -197,8 +190,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of Boolean type
-     * values.
+     * Constructs {@link AttributeValue} with array of Boolean type values.
      *
      * @param values
      *            Array of Boolean type values.
@@ -208,8 +200,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of String type
-     * values.
+     * Constructs {@link AttributeValue} with array of String type values.
      *
      * @param values
      *            Array of String type values.
@@ -219,8 +210,8 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with array of
-     * SimulatorResourceModel type values.
+     * Constructs {@link AttributeValue} with array of SimulatorResourceModel
+     * type values.
      *
      * @param values
      *            Array of SimulatorResourceModel type values.
@@ -230,8 +221,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -248,8 +239,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -259,8 +250,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -277,8 +268,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -288,8 +279,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -306,8 +297,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -317,8 +308,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -328,7 +319,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with 2 dimensional array of
+     * Constructs {@link AttributeValue} with 2 dimensional array of
      * SimulatorResourceModel type values.
      *
      * @param values
@@ -339,8 +330,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -360,8 +351,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -371,8 +362,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -392,8 +383,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -403,8 +394,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -424,8 +415,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -435,8 +426,8 @@ public class AttributeValue {
     }
 
     /**
-     * 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.
@@ -446,7 +437,7 @@ public class AttributeValue {
     }
 
     /**
-     * Constructs {@AttributeValue} with 3 dimensional array of
+     * Constructs {@link AttributeValue} with 3 dimensional array of
      * SimulatorResourceModel type values.
      *
      * @param values
@@ -459,7 +450,7 @@ public class AttributeValue {
     /**
      * API to get value type information.
      *
-     * @return {@AttributeValue.TypeInfo}.
+     * @return {@link AttributeValue.TypeInfo}.
      */
     public TypeInfo typeInfo() {
         return createTypeInfo(mValue);
index 30ace70..54bc4e1 100644 (file)
@@ -1,19 +1,59 @@
+/*
+ * 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)
@@ -24,6 +64,11 @@ public class AttributeValueValidation implements
         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)
@@ -34,6 +79,11 @@ public class AttributeValueValidation implements
         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)
@@ -44,6 +94,11 @@ public class AttributeValueValidation implements
         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)
@@ -54,11 +109,21 @@ public class AttributeValueValidation implements
         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)
@@ -79,6 +144,11 @@ public class AttributeValueValidation implements
         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)
@@ -99,6 +169,11 @@ public class AttributeValueValidation implements
         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)
@@ -119,6 +194,11 @@ public class AttributeValueValidation implements
         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)
@@ -139,11 +219,21 @@ public class AttributeValueValidation implements
         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)
@@ -164,6 +254,11 @@ public class AttributeValueValidation implements
         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)
@@ -184,6 +279,11 @@ public class AttributeValueValidation implements
         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)
@@ -204,6 +304,11 @@ public class AttributeValueValidation implements
         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)
@@ -224,11 +329,21 @@ public class AttributeValueValidation implements
         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)
@@ -249,6 +364,11 @@ public class AttributeValueValidation implements
         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)
@@ -269,6 +389,11 @@ public class AttributeValueValidation implements
         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)
@@ -289,6 +414,11 @@ public class AttributeValueValidation implements
         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)
@@ -309,6 +439,11 @@ public class AttributeValueValidation implements
         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;
index 0d2cea5..8a846a6 100644 (file)
@@ -1,5 +1,25 @@
+/*
+ * 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;
@@ -46,11 +66,28 @@ public class AttributeValueVisitor {
         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;
index eda545c..1e24bcd 100644 (file)
 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.
      */
index 256e3eb..ca1ac83 100644 (file)
@@ -22,14 +22,39 @@ package org.oic.simulator;
 @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);
     }
index 7e6348a..60fb7ab 100644 (file)
@@ -22,10 +22,26 @@ package org.oic.simulator;
 @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);
     }
index e0c259c..20086e7 100644 (file)
@@ -23,10 +23,27 @@ package org.oic.simulator;
 @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);
     }
index 8ff3a60..756e565 100644 (file)
@@ -17,8 +17,8 @@
 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;
index bdaf248..900c647 100644 (file)
 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.
      */
index 95e22fa..ffb4e18 100644 (file)
@@ -26,20 +26,50 @@ public class SimulatorException extends Exception {
     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;
     }
index e4d3772..0612ebf 100644 (file)
@@ -36,7 +36,7 @@ public class SimulatorManager {
      * @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
@@ -55,8 +55,8 @@ public class SimulatorManager {
      * @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.
@@ -71,10 +71,16 @@ public class SimulatorManager {
     /**
      * 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
@@ -115,7 +121,7 @@ public class SimulatorManager {
      * 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.
      *
@@ -141,17 +147,27 @@ public class SimulatorManager {
      *
      * @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,
@@ -162,17 +178,27 @@ public class SimulatorManager {
      *
      * @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,
@@ -184,8 +210,7 @@ public class SimulatorManager {
      * @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);
index e8bbb39..272316f 100644 (file)
@@ -27,8 +27,8 @@ public class SimulatorResourceAttribute {
     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.
@@ -45,8 +45,8 @@ public class SimulatorResourceAttribute {
     }
 
     /**
-     * Constructs {@SimulatorResourceAttribute}
-     * with attribute name, value.
+     * Constructs {@link SimulatorResourceAttribute} with the given attribute
+     * name and value.
      *
      * @param name
      *            Name of the attribute.
@@ -71,7 +71,7 @@ public class SimulatorResourceAttribute {
     /**
      * API to get value of attribute.
      *
-     * @return Attribute's value {@AttributeValue}.
+     * @return Attribute's value {@link AttributeValue}.
      */
     public AttributeValue value() {
         return mValue;
@@ -80,7 +80,8 @@ public class SimulatorResourceAttribute {
     /**
      * 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;
@@ -99,7 +100,7 @@ public class SimulatorResourceAttribute {
     /**
      * API to set the property of attribute.
      *
-     * @param value
+     * @param property
      *            Property of the attribute.
      */
     public void setProperty(AttributeProperty property) {
index cac59f8..65623c7 100644 (file)
@@ -20,7 +20,9 @@ import java.util.HashMap;
 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 {
 
@@ -28,7 +30,7 @@ public class SimulatorResourceModel {
     private Map<String, AttributeProperty> mProperties = null;
 
     /**
-     * Constructs new {@SimulatorResourceModel} object.
+     * Constructs new {@link SimulatorResourceModel} object.
      */
     public SimulatorResourceModel() {
         mValues = new HashMap<>();
@@ -61,7 +63,7 @@ public class SimulatorResourceModel {
      * 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
@@ -157,7 +159,7 @@ public class SimulatorResourceModel {
     }
 
     /**
-     * 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.
@@ -177,7 +179,9 @@ public class SimulatorResourceModel {
      * @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))
@@ -191,8 +195,8 @@ public class SimulatorResourceModel {
      * @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)) {
@@ -217,6 +221,10 @@ public class SimulatorResourceModel {
     /**
      * 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())
@@ -240,7 +248,6 @@ public class SimulatorResourceModel {
         }
     }
 
-    // Methods used in native code
     private SimulatorResourceModel(Map<String, AttributeValue> values,
             Map<String, AttributeProperty> properties) {
         mValues = values;
index f40eaca..c1ca1c7 100644 (file)
@@ -34,6 +34,14 @@ public enum SimulatorResult {
 
     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;
index 9812d3d..108ecb2 100644 (file)
@@ -17,7 +17,7 @@
 package org.oic.simulator.client;
 
 /**
- * Supported connectivity types.
+ * Enum to represent the supported connectivity types.
  */
 public enum SimulatorConnectivityType {
     SIMULATOR_CT_DEFAULT(0),
index 3e8f8a1..519b1d7 100644 (file)
@@ -59,6 +59,10 @@ public final class SimulatorRemoteResource {
         }
     }
 
+    /**
+     * 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;
     }
@@ -66,7 +70,7 @@ public final class SimulatorRemoteResource {
     /**
      * API to get the URI for this resource.
      *
-     * @return Resource URI
+     * @return Resource URI.
      */
     public String getURI() {
         return mUri;
@@ -84,7 +88,7 @@ public final class SimulatorRemoteResource {
     /**
      * API to get the list of resource types.
      *
-     * @return Array of resource types.
+     * @return Resource types.
      */
     public Vector<String> getResourceTypes() {
         return mResTypes;
@@ -93,14 +97,14 @@ public final class SimulatorRemoteResource {
     /**
      * 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.
      */
@@ -109,7 +113,7 @@ public final class SimulatorRemoteResource {
     }
 
     /**
-     * API to get a unique Id of the resource .
+     * API to get a unique Id of the resource.
      *
      * @return Unique ID.
      */
@@ -128,7 +132,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -150,7 +154,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -178,7 +182,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -204,7 +208,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -236,7 +240,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -262,7 +266,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * 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.
@@ -332,7 +336,7 @@ public final class SimulatorRemoteResource {
      * @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
@@ -377,7 +381,7 @@ public final class SimulatorRemoteResource {
 
     /**
      * API to stop sending requests which has been started using
-     * {@link setConfigInfo}.
+     * {@link startVerification}.
      *
      * @param id
      *            Automation ID.
index 42c7b79..6abfc41 100644 (file)
@@ -21,6 +21,11 @@ import java.util.Vector;
 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) {
index 5120fd8..78f2d0f 100644 (file)
@@ -22,6 +22,13 @@ import org.oic.simulator.InvalidArgsException;
 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();
@@ -42,10 +49,16 @@ public class SimulatorResource {
         }
     }
 
+    /**
+     * 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
     }
@@ -98,7 +111,7 @@ public class SimulatorResource {
     /**
      * 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
@@ -145,7 +158,7 @@ public class SimulatorResource {
      * 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
@@ -161,13 +174,14 @@ public class SimulatorResource {
      * 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;
@@ -176,7 +190,7 @@ public class SimulatorResource {
      * 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
@@ -192,7 +206,7 @@ public class SimulatorResource {
      * 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
@@ -205,10 +219,56 @@ public class SimulatorResource {
             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
@@ -221,7 +281,7 @@ public class SimulatorResource {
      * 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.
@@ -249,7 +309,7 @@ public class SimulatorResource {
             SimulatorException;
 
     /**
-     * API to start the resource.
+     * API to start(register) the resource.
      *
      * @throws SimulatorException
      *             This exception will be thrown if the native resource object
@@ -258,7 +318,7 @@ public class SimulatorResource {
     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
@@ -278,10 +338,10 @@ public class SimulatorResource {
     public native Vector<Observer> getObservers() throws SimulatorException;
 
     /**
-     * API to notify current resource model to specific observer.
+     * API to notify current resource model to specific observer.
      *
      * @param observerId
-     *            Observer ID to notify.
+     *            Observer ID to notify.
      *
      * @throws SimulatorException
      *             This exception will be thrown if the native resource object
@@ -290,7 +350,7 @@ public class SimulatorResource {
     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
@@ -304,23 +364,24 @@ public class SimulatorResource {
      */
     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);
index 7a1d8ab..ea6e9fb 100644 (file)
@@ -20,8 +20,13 @@ import org.oic.simulator.AttributeValue;
 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) {
@@ -35,7 +40,7 @@ public final class SimulatorSingleResource extends SimulatorResource {
      *            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
@@ -50,8 +55,6 @@ public final class SimulatorSingleResource extends SimulatorResource {
     /**
      * 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.
      *
@@ -99,12 +102,12 @@ public final class SimulatorSingleResource extends SimulatorResource {
      * 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.
      *
@@ -125,7 +128,7 @@ public final class SimulatorSingleResource extends SimulatorResource {
      * @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.
index 0dbf0bb..2de6a19 100755 (executable)
@@ -19,6 +19,7 @@
  ******************************************************************/\r
 \r
 #include "IncludeResolver.h"\r
+#include <algorithm>\r
 \r
 namespace RAML\r
 {\r
index 042f156..e420bf5 100644 (file)
@@ -29,7 +29,7 @@ std::string getPayloadString(const OC::OCRepresentation &rep)
         return "Empty payload";
     }
     std::ostringstream data;
-    std::ostringstream dummy;
+    std::ostringstream valueStr;
 
     std::string payloadType;
     OCStringLL *types;
@@ -54,16 +54,16 @@ std::string getPayloadString(const OC::OCRepresentation &rep)
         {
             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
@@ -72,30 +72,30 @@ std::string getPayloadString(const OC::OCRepresentation &rep)
         {
             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)
@@ -139,15 +139,15 @@ std::string getRequestString(const std::map<std::string, std::string> &queryPara
                              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();
@@ -156,15 +156,15 @@ std::string getRequestString(const std::map<std::string, std::string> &queryPara
 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();
index c6fb66e..231078d 100644 (file)
@@ -58,6 +58,18 @@ invokeocplatform(FnT fn, ArgsT &&...args)
 
 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;
 }
 
index fb7f434..c3b259a 100755 (executable)
@@ -27,8 +27,8 @@
 
 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);
 
@@ -63,20 +63,14 @@ std::vector<std::string> SimulatorCollectionResourceImpl::getInterface() const
 
 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;
 }
 
@@ -108,25 +102,80 @@ void SimulatorCollectionResourceImpl::setResourceType(const std::string &resourc
     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)
index ea31ac6..acda3f5 100755 (executable)
@@ -42,7 +42,10 @@ class SimulatorCollectionResourceImpl : public SimulatorCollectionResource
         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);
index f4f4885..7d31aff 100755 (executable)
 
 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);
 }
 
@@ -60,20 +65,15 @@ std::vector<std::string> SimulatorSingleResourceImpl::getInterface() const
 
 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;
 }
 
@@ -99,33 +99,80 @@ void SimulatorSingleResourceImpl::setResourceType(const std::string &resourceTyp
     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)
@@ -472,22 +519,54 @@ OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests(
                     << " 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())
@@ -510,88 +589,9 @@ OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests(
             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)
@@ -646,3 +646,103 @@ RAML::ActionType SimulatorSingleResourceImpl::getActionType(std::string requestT
 
     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
index 645507e..a5c6c44 100755 (executable)
@@ -40,7 +40,10 @@ class SimulatorSingleResourceImpl : public SimulatorSingleResource
         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();
@@ -83,9 +86,13 @@ class SimulatorSingleResourceImpl : public SimulatorSingleResource
     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);
@@ -96,6 +103,7 @@ class SimulatorSingleResourceImpl : public SimulatorSingleResource
         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;
index 7a45f32..86e80d0 100644 (file)
@@ -48,8 +48,15 @@ std::shared_ptr<SimulatorResource> SimulatorManager::createResource(
 {
     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;
@@ -61,8 +68,15 @@ std::vector<std::shared_ptr<SimulatorResource>> SimulatorManager::createResource
     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;