Fix for onUpdatedInputResource for android resource container extension
authorMarkus Jung <markus.jung@samsung.com>
Wed, 23 Dec 2015 08:17:12 +0000 (17:17 +0900)
committerUze Choi <uzchoi@samsung.com>
Thu, 31 Dec 2015 05:13:23 +0000 (05:13 +0000)
Several issues had to be fixed to make the automated update
of input data for soft sensors running on Android available.

Fix for concurreny crash issue. Concurrent access on resources is now synchronized.

Renaming. Avoiding the use of Android in APIs, since JNI wrapper could be useable for any type of Java platform.

Added check for null values for JNI class and method references.

Change-Id: Ib120c2a22efca3bc8d4286f51efd9bdc71aaa3f4
Signed-off-by: Markus Jung <markus.jung@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4717
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Uze Choi <uzchoi@samsung.com>
24 files changed:
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleActivator.java [moved from service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/AndroidBundleActivator.java with 88% similarity]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleResource.java [moved from service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/AndroidBundleResource.java with 97% similarity]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/BundleSoftSensorResource.java [moved from service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/AndroidBundleSoftSensorResource.java with 90% similarity]
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainer.java
service/resource-container/android/resource-container/src/main/java/org/iotivity/service/resourcecontainer/RcsResourceContainerBundleAPI.java
service/resource-container/android/resource-container/src/main/jni/AndroidResource.cpp [deleted file]
service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp [new file with mode: 0644]
service/resource-container/android/resource-container/src/main/jni/JniBundleResource.h [moved from service/resource-container/android/resource-container/src/main/jni/AndroidResource.h with 86% similarity]
service/resource-container/android/resource-container/src/main/jni/JniMain.cpp
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceAttributes.cpp
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceContainer.cpp
service/resource-container/android/resource-container/src/main/jni/JniRcsResourceContainer.h
service/resource-container/bundle-api/include/BundleResource.h
service/resource-container/examples/ContainerSampleClient.cpp
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/SampleActivator.java
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/DiscomfortIndexResource.java
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/GyroscopeResource.java [changed mode: 0644->0755]
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/HumidityResource.java
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/LightIntensityResource.java
service/resource-container/examples/android/AndroidBundle/app/src/main/java/org/iotivity/service/sample/androidbundle/resources/TemperatureResource.java
service/resource-container/examples/android/ContainerSampleApp/app/src/main/java/org/iotivity/service/sample/container/ResourceContainer.java
service/resource-container/src/Configuration.cpp
service/resource-container/src/Configuration.h
service/resource-container/src/ResourceContainerImpl.cpp

@@ -22,11 +22,11 @@ package org.iotivity.service.resourcecontainer;
 import android.content.Context;
 import java.util.List;
 
-public abstract class AndroidBundleActivator {
+public abstract class BundleActivator {
     protected RcsResourceContainerBundleAPI bundleAPI;
     protected Context appContext;
     
-    public AndroidBundleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
+    public BundleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
         this.bundleAPI = bundleAPI;
         this.appContext = appContext;
     }
@@ -50,6 +50,6 @@ public abstract class AndroidBundleActivator {
      * Destroys a resource
      * @param resource Instance of a BundleResource
      */
-    public abstract void destroyResource(AndroidBundleResource resource);
+    public abstract void destroyResource(BundleResource resource);
 
 }
\ No newline at end of file
@@ -31,7 +31,7 @@ import android.util.Log;
  * getAttribute method and map the according reads and writes to the technology
  * specific messages.
  */
-public abstract class AndroidBundleResource {
+public abstract class BundleResource {
     protected String                m_name, m_uri, m_resourceType, m_address;
 
     protected RcsResourceAttributes m_attributes = new RcsResourceAttributes();
@@ -42,11 +42,11 @@ public abstract class AndroidBundleResource {
     
     protected native void updateNativeInstance(RcsResourceAttributes update);
 
-    public AndroidBundleResource() {
+    public BundleResource() {
         initAttributes();
     }
 
-    public AndroidBundleResource(Context context) {
+    public BundleResource(Context context) {
         this();
         this.m_context = context;
     }
@@ -28,10 +28,10 @@ import android.content.Context;
 import android.util.Log;
 
 
-public abstract class AndroidBundleSoftSensorResource extends AndroidBundleResource {
+public abstract class BundleSoftSensorResource extends BundleResource {
     protected HashMap<String, RcsValue> m_mapInputData;
     
-    public AndroidBundleSoftSensorResource(Context context) {
+    public BundleSoftSensorResource(Context context) {
         super(context);
     }
     /**
index 53401cf..8ddcd06 100644 (file)
@@ -83,11 +83,11 @@ public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
 
     private native List<String> nativeListBundleResources(String bundleId);
     
-    private native void nativeRegisterAndroidResource(AndroidBundleResource resource,
+    private native void nativeRegisterBundleResource(BundleResource resource,
         String[] attributes, String bundleId, String uri,
         String resourceType, String name);
     
-    private native void nativeUnregisterAndroidResource(AndroidBundleResource resource,
+    private native void nativeUnregisterBundleResource(BundleResource resource,
         String uri);
     
     private native int nativeGetNumberOfConfiguredResources(String bundleId);
@@ -135,7 +135,7 @@ public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
                     Log.d(TAG, "Loading activator: " + className);
                     Class activatorClass = df.loadClass(className, cl);
                     if(activatorClass!= null){
-                        AndroidBundleActivator activator = (AndroidBundleActivator) activatorClass.getConstructor(RcsResourceContainerBundleAPI.class, Context.class).newInstance(this, appContext);
+                        BundleActivator activator = (BundleActivator) activatorClass.getConstructor(RcsResourceContainerBundleAPI.class, Context.class).newInstance(this, appContext);
                         activator.activateBundle();
                     }else{
                         Log.e(TAG, "Activator is null.");
@@ -276,10 +276,10 @@ public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
         return nativeListBundleResources(bundleId);
     }
 
-    public void registerResource(String bundleId, AndroidBundleResource resource){
+    public void registerResource(String bundleId, BundleResource resource){
         Log.d(TAG, "register Resource");
         // bundleResources.add(resource);
-        nativeRegisterAndroidResource(resource, resource.getAttributeKeys(), bundleId,
+        nativeRegisterBundleResource(resource, resource.getAttributeKeys(), bundleId,
                         resource.getURI(), resource.getResourceType(),
                         resource.getName());
     }
@@ -301,9 +301,9 @@ public class RcsResourceContainer implements RcsResourceContainerBundleAPI {
     }
 
     
-    public void unregisterResource(AndroidBundleResource resource){
+    public void unregisterResource(BundleResource resource){
         Log.d(TAG, "unregister Resource");
-        nativeUnregisterAndroidResource(resource, resource.getURI());
+        nativeUnregisterBundleResource(resource, resource.getURI());
     }
 
     public int getNumberOfConfiguredResources(String bundleId){
index 11a5e52..92954aa 100644 (file)
@@ -35,9 +35,9 @@ import java.util.Vector;
  */
 public interface RcsResourceContainerBundleAPI{
 
-    public void registerResource(String bundleId, AndroidBundleResource resource);
+    public void registerResource(String bundleId, BundleResource resource);
 
-    public void unregisterResource(AndroidBundleResource resource);
+    public void unregisterResource(BundleResource resource);
 
     public List<ResourceConfig> getConfiguredBundleResources(String bundleId);
 }
diff --git a/service/resource-container/android/resource-container/src/main/jni/AndroidResource.cpp b/service/resource-container/android/resource-container/src/main/jni/AndroidResource.cpp
deleted file mode 100644 (file)
index 6f0bfa5..0000000
+++ /dev/null
@@ -1,275 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-
-#include "AndroidResource.h"
-#include "JniRcsResourceAttributes.h"
-#include "JavaClasses.h"
-#include "JavaLocalRef.h"
-#include "JNIEnvWrapper.h"
-#include "JniRcsValue.h"
-
-#include <jni.h>
-#include <string.h>
-#include <iostream>
-#include "Log.h"
-
-#define LOG_TAG "JNI-AndroidResource"
-
-using namespace OIC::Service;
-using namespace std;
-
-namespace
-{
-    jclass g_cls_RCSBundleInfo;
-    jfieldID g_field_mNativeHandle;
-}
-
-void initRCSAndroidResource(JNIEnvWrapper *env)
-{
-    auto clsAndroidBundleResource = env->FindClass(PACKAGE_NAME "/AndroidBundleResource");
-
-    g_field_mNativeHandle = env->GetFieldID(clsAndroidBundleResource, "mNativeHandle", "J");
-}
-
-AndroidResource::AndroidResource()
-{
-
-}
-
-void AndroidResource::initAttributes()
-{
-
-}
-
-AndroidResource::AndroidResource(JNIEnv *env, jobject obj, jobject bundleResource,
-                                       string bundleId, jobjectArray attributes)
-{
-    LOGD("Creating android resource, bundleId: %s", bundleId.c_str());
-    (void) obj;
-    m_env = env;
-    int stringCount = m_env->GetArrayLength(attributes);
-    LOGD("string count is %d", stringCount);
-
-    for (int i = 0; i < stringCount; i++)
-    {
-        jstring str = (jstring) m_env->GetObjectArrayElement(attributes, i);
-        const char *rawString = m_env->GetStringUTFChars(str, 0);
-        string s(rawString, strlen(rawString));
-        BundleResource::setAttribute(s, "");
-    }
-
-    m_bundleId = bundleId;
-
-    this->m_bundleResource = m_env->NewGlobalRef(bundleResource);
-
-    m_bundleResourceClass = m_env->GetObjectClass(bundleResource);
-    LOGD("Looking for setter.");
-    m_attributeSetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
-            "handleSetAttributesRequest", "(Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V");
-    LOGD("Looking for getter.");
-    m_attributeGetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
-            "handleGetAttributesRequest", "()Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;");
-    //LOGD("Looking for softSensorResource class.");
-    //jclass androidBundleSoftSensorResourceClass = m_env->FindClass("org/iotivity/service/resourcecontainer/AndroidBundleSoftSensorResource");
-    LOGD("Looking for onUpdatedInputResource.");
-    jclass superclass = m_env->GetSuperclass(m_bundleResourceClass);
-
-    jclass classClass = m_env->FindClass("java/lang/Class");
-
-    // Find the getName() method on the class object
-    jmethodID mid = env->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
-
-    // Call the getName() to get a jstring object back
-    jstring strObj = (jstring)env->CallObjectMethod(superclass, mid);
-
-    // Now get the c string from the java jstring object
-    const char* str = env->GetStringUTFChars(strObj, NULL);
-
-    LOGD("Name of super class is %s", str);
-
-    //check for softsensor resource
-    if(strcmp("org.iotivity.service.resourcecontainer.AndroidBundleSoftSensorResource", str) == 0){
-       m_onUpdatedInputResource = m_env->GetMethodID(m_bundleResourceClass, "onUpdatedInputResource", "(Ljava/lang/String;Ljava/util/Vector;)V");
-       if (env->ExceptionCheck()) {
-           env->ExceptionDescribe();
-       }
-       LOGD("Looking up vector.");
-       m_vectorClazz = m_env->FindClass("java/util/Vector");
-       if (env->ExceptionCheck()) {
-               env->ExceptionDescribe();
-       }
-       LOGD("Looking up vector add method.");
-       m_vectorAddMethod =  m_env->GetMethodID(m_vectorClazz, "add", "(Ljava/lang/Object;)Z");
-       if (env->ExceptionCheck()) {
-              env->ExceptionDescribe();
-       }
-    }
-
-
-    LOGD("Get java vm.");
-    int jvmAccess = m_env->GetJavaVM(&m_jvm);
-    LOGD("JVM: %s", (jvmAccess ? "false" : "true") );
-
-
-}
-
-AndroidResource::~AndroidResource()
-{
-
-}
-
-RCSResourceAttributes::Value AndroidResource::handleGetAttributeRequest(
-        const std::string &attributeName)
-{
-    LOGD("handleGetAttributeRequest called2");
-    LOGD("Attaching thread now");
-    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
-    if(attached>0)
-    {
-        LOGE("Failed to attach thread to JavaVM");
-    }
-    else{
-        jstring attrName = m_env->NewStringUTF(attributeName.c_str());
-        auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
-                m_attributeGetRequestHandler, attrName);
-
-        if (responseObj)
-        {
-            LOGD("parsing attributes");
-            RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
-            LOGD("Received attributes %d", attrs.size());
-        }
-        /*const char *js = m_env->GetStringUTFChars(returnString, NULL);
-        std::string val(js);
-        RCSResourceAttributes::Value newVal = val;
-        m_env->ReleaseStringUTFChars(returnString, js);
-        m_jvm->DetachCurrentThread();*/
-        //BundleResource::setAttribute(attributeName, newVal.toString());
-    }
-    return BundleResource::getAttribute(attributeName);
-}
-
-void AndroidResource::handleSetAttributeRequest(const std::string &attributeName,
-                                      RCSResourceAttributes::Value &&value)
-{
-    jstring attrName = m_env->NewStringUTF(attributeName.c_str());
-    jstring val = m_env->NewStringUTF(value.toString().c_str());
-
-    //LOGD("handleSetAttributeRequest calling object method %d", &m_attributeSetRequestHandler);
-    m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
-    BundleResource::setAttribute(attributeName, std::move(value));
-}
-
-
-void AndroidResource::handleSetAttributesRequest(RCSResourceAttributes &attrs){
-    LOGD("handleSetAttributesRequest called %d", attrs.size());
-
-    //m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
-    //BundleResource::setAttribute(attributeName, std::move(value));
-
-    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
-    if(attached>0)
-    {
-        LOGE("Failed to attach thread to JavaVM");
-    }
-    else{
-        LOGD("Creating resource attributes for JNI.");
-        auto jniRcsAttributes = newAttributesObject(m_env, attrs);
-        LOGD("jobject created. calling");
-        m_env->CallVoidMethod(m_bundleResource,
-                m_attributeSetRequestHandler, jniRcsAttributes);
-        BundleResource::setAttributes(attrs);
-        m_jvm->DetachCurrentThread();
-    }
-}
-
-RCSResourceAttributes & AndroidResource::handleGetAttributesRequest()
-{
-    LOGD("handleGetAttributesRequest");
-    /*std::list<string> attrsNames = getAttributeNames();
-    for(std::list<string>::iterator iterator = attrsNames.begin();
-            iterator != attrsNames.end(); ++iterator )
-    {
-        handleGetAttributeRequest(*iterator);
-    }*/
-    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
-    if(attached>0)
-    {
-        LOGE("Failed to attach thread to JavaVM");
-    }
-    else{
-        auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
-                m_attributeGetRequestHandler);
-
-        if (responseObj)
-        {
-            LOGD("parsing attributes");
-
-            RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
-            LOGD("Received attributes %d", attrs.size());
-            BundleResource::setAttributes(attrs, false);
-        }
-
-        m_jvm->DetachCurrentThread();
-    }
-    LOGD("BundleResource::getAttributes().size() %d", BundleResource::getAttributes().size());
-    return BundleResource::getAttributes();
-}
-
-void AndroidResource::executeLogic(){
-    LOGD("executeLogic");
-
-}
-
-void AndroidResource::onUpdatedInputResource(const std::string attributeName,
-        std::vector<RCSResourceAttributes::Value> values){
-    LOGD("onUpdatedInputResource");
-
-    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
-    jobject valueObj;
-    if(attached>0)
-    {
-        LOGE("Failed to attach thread to JavaVM");
-    }
-    else{
-        jobject obj = m_env->NewObject(m_vectorClazz, m_env->GetMethodID(m_vectorClazz, "<init>", "()V"));
-
-        for (int n=0;n<values.size();n++)
-        {
-           valueObj  = newRCSValueObject(m_env, values[n]);
-           m_env->CallVoidMethod(obj, m_vectorAddMethod, valueObj);
-        }
-        m_env->CallObjectMethod(m_bundleResource,
-                m_onUpdatedInputResource, obj);
-        m_jvm->DetachCurrentThread();
-    }
-    LOGD("BundleResource::getAttributes().size() %d", BundleResource::getAttributes().size());
-}
-
-JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_AndroidBundleResource_updateNativeInstance
-(JNIEnv* env, jobject obj, jobject updates)
-{
-    LOGD("updateNativeInstance");
-    BundleResource* androidResource = reinterpret_cast<BundleResource*>(env->GetLongField(obj, g_field_mNativeHandle));
-    RCSResourceAttributes attrs = toNativeAttributes(env, updates);
-    LOGD("Received attributes %d", attrs.size());
-    androidResource->setAttributes(attrs, true);
-}
diff --git a/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp b/service/resource-container/android/resource-container/src/main/jni/JniBundleResource.cpp
new file mode 100644 (file)
index 0000000..b5f85d5
--- /dev/null
@@ -0,0 +1,361 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+#include "JniBundleResource.h"
+#include "JniRcsResourceAttributes.h"
+#include "JavaClasses.h"
+#include "JavaLocalRef.h"
+#include "JNIEnvWrapper.h"
+#include "JniRcsValue.h"
+
+#include <jni.h>
+#include <string.h>
+#include <iostream>
+#include "Log.h"
+
+#define LOG_TAG "JNI-JniBundleResource"
+
+using namespace OIC::Service;
+using namespace std;
+
+namespace
+{
+    jclass g_cls_RCSBundleInfo;
+    jfieldID g_field_mNativeHandle;
+}
+
+void initRCSJniBundleResource(JNIEnvWrapper *env)
+{
+    auto clsJniBundleResource = env->FindClass(PACKAGE_NAME "/BundleResource");
+
+    g_field_mNativeHandle = env->GetFieldID(clsJniBundleResource, "mNativeHandle", "J");
+}
+
+JniBundleResource::JniBundleResource()
+{
+
+}
+
+void JniBundleResource::initAttributes()
+{
+
+}
+
+JniBundleResource::JniBundleResource(JNIEnv *env, jobject obj, jobject bundleResource,
+                                       string bundleId, jobjectArray attributes)
+{
+    LOGD("Creating android resource, bundleId: %s", bundleId.c_str());
+    (void) obj;
+    m_env = env;
+    int stringCount = m_env->GetArrayLength(attributes);
+    LOGD("string count is %d", stringCount);
+
+    LOGD("Get java vm.");
+    int jvmAccess = m_env->GetJavaVM(&m_jvm);
+
+
+    for (int i = 0; i < stringCount; i++)
+    {
+        jstring str = (jstring) m_env->GetObjectArrayElement(attributes, i);
+        const char *rawString = m_env->GetStringUTFChars(str, 0);
+        string s(rawString, strlen(rawString));
+        JniBundleResource::setAttribute(s, "");
+        m_env->ReleaseStringUTFChars(str, rawString);
+        m_env->DeleteLocalRef(str);
+        LOGD("Deleting and releasing resources - JNI bundle resource");
+    }
+
+    m_bundleId = bundleId;
+
+    this->m_bundleResource = m_env->NewGlobalRef(bundleResource);
+
+    m_bundleResourceClass = (jclass) m_env->NewGlobalRef(m_env->GetObjectClass(bundleResource));
+    LOGD("Looking for setter.");
+    m_attributeSetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
+            "handleSetAttributesRequest",
+            "(Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V");
+    LOGD("Looking for getter.");
+    m_attributeGetRequestHandler = m_env->GetMethodID(m_bundleResourceClass,
+            "handleGetAttributesRequest",
+            "()Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;");
+
+    LOGD("Looking for onUpdatedInputResource.");
+    m_superclass = (jclass) m_env->NewGlobalRef(m_env->GetSuperclass(m_bundleResourceClass));
+
+    m_classClass = (jclass) m_env->NewGlobalRef(m_env->FindClass("java/lang/Class"));
+
+
+    m_vectorClazz = (jclass) m_env->NewGlobalRef(m_env->FindClass("java/util/Vector"));
+    if (m_env->ExceptionCheck()) {
+        m_env->ExceptionDescribe();
+    }
+
+    if (m_env->ExceptionCheck()) {
+       m_env->ExceptionDescribe();
+    }
+
+    if(m_classClass != NULL){
+        // Find the getName() method on the class object
+        jmethodID mid = env->GetMethodID(m_classClass, "getName", "()Ljava/lang/String;");
+
+        // Call the getName() to get a jstring object back
+        if(m_superclass != NULL){
+            jstring strObj = (jstring)env->CallObjectMethod(m_superclass, mid);
+
+            // Now get the c string from the java jstring object
+            const char* str = env->GetStringUTFChars(strObj, NULL);
+
+            LOGD("Name of super class is %s", str);
+
+            //check for softsensor resource
+            if(strcmp("org.iotivity.service.resourcecontainer.BundleSoftSensorResource", str) == 0){
+               m_onUpdatedInputResource = m_env->GetMethodID(m_bundleResourceClass,
+                       "onUpdatedInputResource", "(Ljava/lang/String;Ljava/util/Vector;)V");
+               if (m_env->ExceptionCheck()) {
+                   m_env->ExceptionDescribe();
+               }
+
+               LOGD("Looking up vector add method.");
+               if(m_vectorClazz != NULL){
+                   m_vectorAddMethod =  m_env->GetMethodID(m_vectorClazz, "add", "(Ljava/lang/Object;)Z");
+                   if (m_env->ExceptionCheck()) {
+                       m_env->ExceptionDescribe();
+                   }
+               }
+
+            }
+            LOGD("Deleting and releasing resources - JNIBundleResource 2");
+            m_env->ReleaseStringUTFChars(strObj, str);
+        }
+    }
+}
+
+JniBundleResource::~JniBundleResource()
+{
+
+}
+
+RCSResourceAttributes::Value JniBundleResource::handleGetAttributeRequest(
+        const std::string &attributeName)
+{
+    LOGD("handleGetAttributeRequest called2");
+    LOGD("Attaching thread now");
+    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+    if(attached>0)
+    {
+        LOGE("Failed to attach thread to JavaVM");
+    }
+    else{
+        if(m_attributeGetRequestHandler != NULL){
+            jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+            auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
+                    m_attributeGetRequestHandler, attrName);
+
+            if (responseObj)
+            {
+                LOGD("parsing attributes");
+                RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
+                LOGD("Received attributes %d", attrs.size());
+            }
+        }
+    }
+    return JniBundleResource::getAttribute(attributeName);
+}
+
+void JniBundleResource::handleSetAttributeRequest(const std::string &attributeName,
+                                      RCSResourceAttributes::Value &&value)
+{
+    if(m_attributeSetRequestHandler != NULL){
+        jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+        jstring val = m_env->NewStringUTF(value.toString().c_str());
+
+        //LOGD("handleSetAttributeRequest calling object method %d", &m_attributeSetRequestHandler);
+        m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
+    }
+    JniBundleResource::setAttribute(attributeName, std::move(value));
+}
+
+
+void JniBundleResource::handleSetAttributesRequest(RCSResourceAttributes &attrs){
+    LOGD("handleSetAttributesRequest called %d", attrs.size());
+
+    //m_env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
+    //JniBundleResource::setAttribute(attributeName, std::move(value));
+    if(m_attributeSetRequestHandler != NULL && m_bundleResource != NULL){
+        int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+
+        if(attached>0)
+        {
+            LOGE("Failed to attach thread to JavaVM");
+        }
+        else{
+            LOGD("Creating resource attributes for JNI.");
+
+            m_env->MonitorEnter(m_bundleResource);
+            auto jniRcsAttributes = newAttributesObject(m_env, attrs);
+            LOGD("jobject created. calling");
+            m_env->CallVoidMethod(m_bundleResource,
+                    m_attributeSetRequestHandler, jniRcsAttributes);
+            JniBundleResource::setAttributes(attrs);
+            m_env->MonitorExit(m_bundleResource);
+
+            m_jvm->DetachCurrentThread();
+        }
+    }
+}
+
+RCSResourceAttributes & JniBundleResource::handleGetAttributesRequest()
+{
+    LOGD("handleGetAttributesRequest");
+
+    if(m_attributeGetRequestHandler != NULL && m_bundleResource != NULL){
+        LOGD("attaching thread");
+        int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+        if(attached>0)
+        {
+            LOGE("Failed to attach thread to JavaVM");
+        }
+        else{
+            LOGD("attached, calling get request handler");
+            auto responseObj =  m_env->CallObjectMethod(m_bundleResource,
+                    m_attributeGetRequestHandler);
+
+            if (responseObj)
+            {
+                LOGD("parsing attributes");
+                m_env->MonitorEnter(m_bundleResource);
+                LOGD("to native attributes");
+                RCSResourceAttributes attrs = toNativeAttributes(m_env, responseObj);
+                LOGD("Received attributes %d", attrs.size());
+                JniBundleResource::setAttributes(attrs, false);
+                m_env->MonitorExit(m_bundleResource);
+            }
+
+            m_jvm->DetachCurrentThread();
+        }
+        LOGD("JniBundleResource::getAttributes().size() %d",
+                JniBundleResource::getAttributes().size());
+    }
+    return JniBundleResource::getAttributes();
+}
+
+void JniBundleResource::executeLogic(){
+    // IS CALLED AT JAVA LAYER
+}
+
+void JniBundleResource::onUpdatedInputResource(const std::string attributeName,
+        std::vector<RCSResourceAttributes::Value> values){
+    LOGD("onUpdatedInputResource");
+    if(m_vectorClazz == NULL || m_classClass == NULL){
+        return;
+    }
+    int attached = m_jvm->AttachCurrentThread(&m_env, NULL);
+    jobject valueObj;
+    if(attached>0)
+    {
+        LOGE("Failed to attach thread to JavaVM");
+    }
+    else{
+
+
+        jobject obj = m_env->NewObject(m_vectorClazz,
+                m_env->GetMethodID(m_vectorClazz, "<init>", "()V"));
+
+        LOGD("Looking up vector add method.");
+
+        jmethodID m_vectorAddMethod =  m_env->GetMethodID(m_vectorClazz, "add",
+                "(Ljava/lang/Object;)Z");
+        if (m_env->ExceptionCheck()) {
+            m_env->ExceptionDescribe();
+        }
+
+        if(m_vectorAddMethod == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+
+        for (int n=0;n<values.size();n++)
+        {
+           valueObj  = newRCSValueObject(m_env, values[n]);
+           m_env->CallBooleanMethod(obj, m_vectorAddMethod, valueObj);
+        }
+
+        // Find the getName() method on the class object
+        jmethodID mid = m_env->GetMethodID(m_classClass, "getName",
+                "()Ljava/lang/String;");
+
+        // Call the getName() to get a jstring object back
+        if(m_superclass == NULL || mid == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+
+        jstring strObj = (jstring)m_env->CallObjectMethod(m_superclass, mid);
+
+        // Now get the c string from the java jstring object
+        if(strObj == NULL){
+            m_jvm->DetachCurrentThread();
+            return;
+        }
+        const char* str = m_env->GetStringUTFChars(strObj, NULL);
+
+        LOGD("Name of super class is %s", str);
+
+        jstring attrName = m_env->NewStringUTF(attributeName.c_str());
+
+        //check for softsensor resource
+        if(strcmp("org.iotivity.service.resourcecontainer.BundleSoftSensorResource", str) == 0){
+            jmethodID m_onUpdatedInputResource = m_env->GetMethodID(m_bundleResourceClass,
+                    "onUpdatedInputResource", "(Ljava/lang/String;Ljava/util/Vector;)V");
+            if(m_onUpdatedInputResource != NULL){
+                m_env->MonitorEnter(m_bundleResource);
+                m_env->CallVoidMethod(m_bundleResource,
+                m_onUpdatedInputResource, attrName, obj);
+                m_env->MonitorExit(m_bundleResource);
+                if (m_env->ExceptionCheck()) {
+                    m_env->ExceptionDescribe();
+                }
+            }
+        }
+        LOGD("Deleting and releasing resources - onUpdatedInputResource");
+        m_env->DeleteLocalRef(attrName);
+        m_env->ReleaseStringUTFChars(strObj, str);
+
+        if (m_env->ExceptionCheck()) {
+               m_env->ExceptionDescribe();
+        }
+        m_jvm->DetachCurrentThread();
+    }
+
+    LOGD("JniBundleResource::getAttributes().size() %d", JniBundleResource::getAttributes().size());
+}
+
+JNIEXPORT void
+JNICALL Java_org_iotivity_service_resourcecontainer_BundleResource_updateNativeInstance
+(JNIEnv* env, jobject obj, jobject updates)
+{
+    LOGD("updateNativeInstance");
+    BundleResource* JniBundleResource =
+            reinterpret_cast<BundleResource*>(env->GetLongField(obj, g_field_mNativeHandle));
+    RCSResourceAttributes attrs = toNativeAttributes(env, updates);
+    LOGD("Received attributes %d", attrs.size());
+    JniBundleResource->setAttributes(attrs, true);
+}
@@ -18,8 +18,8 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifndef ANDROIDRESOURCE_H_
-#define ANDROIDRESOURCE_H_
+#ifndef JNI_BUNDLERESOURCE_H_
+#define JNI_BUNDLERESOURCE_H_
 
 #include <map>
 #include <vector>
@@ -33,7 +33,7 @@
 
 class JNIEnvWrapper;
 
-void initRCSAndroidResource(JNIEnvWrapper *);
+void initRCSJniBundleResource(JNIEnvWrapper *);
 
 using namespace std;
 
@@ -41,13 +41,13 @@ namespace OIC
 {
     namespace Service
     {
-        class AndroidResource: public SoftSensorResource
+        class JniBundleResource: public SoftSensorResource
         {
         public:
-            AndroidResource();
-            AndroidResource(JNIEnv *env, jobject obj, jobject bundleResource, string bundleId,
+            JniBundleResource();
+            JniBundleResource(JNIEnv *env, jobject obj, jobject bundleResource, string bundleId,
                     jobjectArray attributes);
-            virtual ~AndroidResource();
+            virtual ~JniBundleResource();
 
             void handleSetAttributeRequest(const std::string& key,
                     RCSResourceAttributes::Value&&);
@@ -93,6 +93,8 @@ namespace OIC
             jclass m_vectorClazz;
             jmethodID m_vectorAddMethod;
             string m_bundleId;
+            jclass m_superclass;
+            jclass m_classClass;
             JNIEnv *m_env;
             JavaVM *m_jvm;
             jfieldID g_field_mNativeHandle;
@@ -104,11 +106,11 @@ namespace OIC
 extern "C" {
 #endif
 /*
- * Class:     org_iotivity_service_resourcecontainer_AndroidBundleResource
+ * Class:     org_iotivity_service_resourcecontainer_JniBundleResource
  * Method:    updateNativeInstance
  * Signature: (Lorg/iotivity/service/resourcecontainer/RcsResourceAttributes;)V
  */
-JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_AndroidBundleResource_updateNativeInstance
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_BundleResource_updateNativeInstance
   (JNIEnv *, jobject, jobject);
 
 #ifdef __cplusplus
index f948535..7052ec2 100644 (file)
@@ -26,7 +26,7 @@
 #include "JniRcsValue.h"
 #include "JavaExceptions.h"
 #include "JniRcsValue.h"
-#include  "AndroidResource.h"
+#include  "JniBundleResource.h"
 
 #define LOG_TAG "JNI-Main"
 
@@ -55,7 +55,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
         initRCSValue(&envWrapper);
         initRCSResourceContainer(&envWrapper);
         initRCSResourceAttributes(&envWrapper);
-        initRCSAndroidResource(&envWrapper);
+        initRCSJniBundleResource(&envWrapper);
     }
     catch (const JavaException &)
     {
index 0e8fb4f..d947e3b 100644 (file)
@@ -127,6 +127,7 @@ RCSResourceAttributes toNativeAttributes(JNIEnvWrapper* env, jobject attrsObj)
         attrs = getNativeHandleAs< RCSResourceAttributes >(env, attrsObj);
     }*/
     LOGD("writeNativeAttributesFromMap");
+
     writeNativeAttributesFromMap(env,
             JavaLocalObject{ env, env->GetObjectField(attrsObj, g_field_mCache) }, attrs);
 
index c207cde..cf84553 100644 (file)
@@ -27,7 +27,7 @@
 #include "Verify.h"
 
 #include "ResourceContainerBundleAPI.h"
-#include "AndroidResource.h"
+#include "JniBundleResource.h"
 #include "RCSResourceContainer.h"
 
 
@@ -100,9 +100,9 @@ void initRCSResourceContainer(JNIEnvWrapper *env)
             AS_SIG(CLS_NAME_STRING)
             ")V");
 
-    auto clsAndroidBundleResource = env->FindClass(PACKAGE_NAME "/AndroidBundleResource");
+    auto clsJniBundleResource = env->FindClass(PACKAGE_NAME "/BundleResource");
 
-    g_field_mNativeHandle = env->GetFieldID(clsAndroidBundleResource, "mNativeHandle", "J");
+    g_field_mNativeHandle = env->GetFieldID(clsJniBundleResource, "mNativeHandle", "J");
 }
 
 void clearRCSResourceContainer(JNIEnvWrapper *env)
@@ -307,12 +307,12 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundl
 
 
 JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterAndroidResource
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterBundleResource
 (JNIEnv *env, jobject obj, jobject bundleResource, jobjectArray attributes, jstring bundleId,
  jstring uri, jstring resourceType, jstring res_name)
 {
     JNIEnvWrapper envWrapper(env);
-    LOGD("nativeRegisterAndroidResource");
+    LOGD("nativeRegisterJniBundleResource");
     auto str_bundle_id = toStdString(&envWrapper, bundleId);
     __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved bundle id: %s.", str_bundle_id.c_str());
     auto str_uri = toStdString(&envWrapper, uri);
@@ -321,9 +321,9 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterA
     __android_log_print(ANDROID_LOG_DEBUG, "JNI-RCSResourceContainer", "retrieved resource type: %s.", str_resourceType.c_str());
     auto str_res_name = toStdString(&envWrapper, res_name);
     LOGD("retrieved res name.");
-    AndroidResource res;
+    JniBundleResource res;
 
-    BundleResource::Ptr androidResource = std::make_shared< AndroidResource >
+    BundleResource::Ptr androidResource = std::make_shared< JniBundleResource >
             (env, obj, bundleResource, str_bundle_id, attributes);
     ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
 
@@ -346,7 +346,7 @@ Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterA
  * Signature: (Lorg/iotivity/resourcecontainer/bundle/api/BundleResource;)V
  */
 JNIEXPORT void JNICALL
-Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterAndroidResource
+Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterBundleResource
 (JNIEnv *env, jobject obj, jobject bundleResource, jstring uri)
 {
     (void)obj;
index 79eaae4..825d276 100644 (file)
@@ -79,10 +79,10 @@ JNIEXPORT jobject JNICALL
 Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeListBundleResources
 (JNIEnv *, jobject, jstring bundleId);
 
-JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterAndroidResource
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeRegisterBundleResource
   (JNIEnv *, jobject, jobject, jobjectArray, jstring, jstring, jstring, jstring);
 
-JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterAndroidResource
+JNIEXPORT void JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeUnregisterBundleResource
   (JNIEnv *, jobject, jobject, jstring);
 
 JNIEXPORT jint JNICALL Java_org_iotivity_service_resourcecontainer_RcsResourceContainer_nativeGetNumberOfConfiguredResources
index 8468fc3..b8bd2d4 100644 (file)
@@ -168,7 +168,7 @@ namespace OIC
                 std::string m_bundleId;
                 std::string m_name, m_uri, m_resourceType, m_address;
                 std::map< std::string,
-                    std::vector< std::map< std::string, std::string > > > m_mapResourceProperty;
+                std::vector< std::map< std::string, std::string > > > m_mapResourceProperty;
 
             private:
                 NotificationReceiver *m_pNotiReceiver;
index 0619a70..0c25b12 100644 (file)
@@ -455,6 +455,85 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
     }
 }
 
+void onGetDiscomfortIndex(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+                      const int eCode)
+{
+    (void)headerOptions;
+    std::cout << "onGetDiscomfortIndex" << std::endl;
+    try
+    {
+        if (eCode == OC_STACK_OK)
+        {
+            std::cout << "GET request was successful" << std::endl;
+
+            std::cout << "Payload: " << rep.getPayload() << std::endl;
+
+            std::cout << "\tdiscomfortIndex: " << rep.getValue<double>("discomfortIndex") << std::endl;
+        }
+        else
+        {
+            std::cout << "onGET Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onPut" << std::endl;
+    }
+}
+
+void onObserveDiscomfort(const HeaderOptions headerOptions, const OCRepresentation &rep,
+               const int &eCode, const int &sequenceNumber)
+{
+    (void)headerOptions;
+    try
+    {
+        if (eCode == OC_STACK_OK)
+        {
+            std::cout << "OBSERVE RESULT:" << std::endl;
+            std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
+            std::cout << "\tdiscomfortIndex: " << rep.getValue<double>("discomfortIndex") << std::endl;
+
+            if (observe_count() > 10)
+            {
+                std::cout << "Cancelling Observe..." << std::endl;
+                OCStackResult result = curResource->cancelObserve();
+
+                std::cout << "Cancel result: " << result << std::endl;
+                sleep(10);
+                std::cout << "DONE" << std::endl;
+                std::exit(0);
+            }
+        }
+        else
+        {
+            std::cout << "onObserve Response error: " << eCode << std::endl;
+        }
+    }
+    catch (std::exception &e)
+    {
+        std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;
+    }
+
+}
+
+// Local function to get representation of light resource
+void getDiscomfortRepresentation(std::shared_ptr<OCResource> resource)
+{
+    if (resource)
+    {
+        std::cout << "Getting Discomfort Representation..." << std::endl;
+        // Invoke resource's get API with the callback parameter
+
+        QueryParamsMap test;
+        std::cout << "Sending request to: " << resource->uri() << std::endl;
+        resource->get(test, &onGetDiscomfortIndex);
+        //resource->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
+    }
+}
+
+
+
+
 // Local function to get representation of light resource
 void getLightIntensityRepresentation(std::shared_ptr<OCResource> resource)
 {
@@ -502,11 +581,12 @@ void foundResource(std::shared_ptr<OCResource> resource)
                     // Call a local function which will internally invoke get API on the resource pointer
                     getLightRepresentation(resource);
                 }*/
-                if (resourceTypes == "oic.r.lightsensor")
+                if (resourceTypes == "oic.r.discomfortindex")
                 {
                     curResource = resource;
+                    std::cout << "\t\tGet discomfort representation " << std::endl;
                     // Call a local function which will internally invoke get API on the resource pointer
-                    getLightIntensityRepresentation(resource);
+                    getDiscomfortRepresentation(resource);
                 }
             }
 
index 5f5cb9f..7af38c5 100755 (executable)
@@ -23,11 +23,12 @@ package org.iotivity.service.sample.androidbundle;
 import android.content.Context;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleActivator;
-import org.iotivity.service.resourcecontainer.AndroidBundleResource;
+import org.iotivity.service.resourcecontainer.BundleActivator;
+import org.iotivity.service.resourcecontainer.BundleResource;
 import org.iotivity.service.resourcecontainer.RcsResourceContainerBundleAPI;
 import org.iotivity.service.resourcecontainer.ResourceConfig;
 import org.iotivity.service.sample.androidbundle.resources.DiscomfortIndexResource;
+import org.iotivity.service.sample.androidbundle.resources.GyroscopeResource;
 import org.iotivity.service.sample.androidbundle.resources.HumidityResource;
 import org.iotivity.service.sample.androidbundle.resources.LightIntensityResource;
 import org.iotivity.service.sample.androidbundle.resources.TemperatureResource;
@@ -35,57 +36,87 @@ import org.iotivity.service.sample.androidbundle.resources.TemperatureResource;
 import java.util.List;
 import java.util.Vector;
 
-public class SampleActivator extends AndroidBundleActivator {
-    private List<AndroidBundleResource> resources = new Vector<AndroidBundleResource>();
+public class SampleActivator extends BundleActivator {
+    private List<BundleResource> resources = new Vector<BundleResource>();
 
     public SampleActivator(RcsResourceContainerBundleAPI bundleAPI, Context appContext){
         super(bundleAPI, appContext);
-        Log.d(SampleActivator.class.getName(), "Created activator instance");
+        Log.d(SampleActivator.class.getName(), "Created activator instance " + bundleAPI
+                + "," + appContext);
     }
 
     @Override
     public void activateBundle() {
         Log.d(SampleActivator.class.getName(), "Activate bundle called");
 
-        List<ResourceConfig> configuredBundleResources = this.bundleAPI.
-                getConfiguredBundleResources("oic.android.sample");
-
-        for(ResourceConfig config : configuredBundleResources){
-            AndroidBundleResource resource = null;
-
-            if("oic.r.lightsensor".equals(config.getResourceType())){
-                resource =
-                        new LightIntensityResource(this.appContext);
-            } else if("oic.r.temperature".equals(config.getResourceType())){
-                resource =
-                        new TemperatureResource(this.appContext);
-            } else if("oic.r.discomfortindex".equals(config.getResourceType())){
-                resource =
-                        new DiscomfortIndexResource(this.appContext);
-            } else if ("oic.r.humidity".equals(config.getResourceType())) {
-                resource =
-                        new HumidityResource(this.appContext);
+        Log.d(SampleActivator.class.getName(), "requesting configured bundle resources");
+
+        Log.d(SampleActivator.class.getName(), "Bundle API: " + this.bundleAPI);
+        if(this.bundleAPI != null)
+        {
+            List<ResourceConfig> configuredBundleResources = this.bundleAPI.
+                    getConfiguredBundleResources("oic.android.sample");
+
+            if(configuredBundleResources !=null) {
+                Log.d(SampleActivator.class.getName(), "configured bundle resources: " +
+                        configuredBundleResources.size());
+
+                for (ResourceConfig config : configuredBundleResources) {
+                    BundleResource resource = null;
+                    Log.d(SampleActivator.class.getName(), "Creating " +
+                        config.getResourceType());
+
+                    if ("oic.r.lightsensor".equals(config.getResourceType())) {
+                        resource =
+                                new LightIntensityResource(this.appContext);
+                    } else if ("oic.r.temperature".equals(config.getResourceType())) {
+                        resource =
+                                new TemperatureResource(this.appContext);
+
+                    } else if ("oic.r.gyroscope".equals(config.getResourceType())) {
+                        resource =
+                                new GyroscopeResource(this.appContext);
+                    } else if ("oic.r.discomfortindex".equals(config.getResourceType())) {
+                        resource =
+                                new DiscomfortIndexResource(this.appContext);
+                    } else if ("oic.r.humidity".equals(config.getResourceType())) {
+                        resource =
+                                new HumidityResource(this.appContext);
+                    }
+
+                    if (resource != null) {
+                        resource.setURI(config.getURI());
+                        resource.setName(config.getName());
+                        bundleAPI.registerResource("oic.android.sample", resource);
+                        resources.add(resource);
+                        Log.d(SampleActivator.class.getName(), "Registering resource " +
+                                config.getURI());
+                    }
+                }
+                Log.d(SampleActivator.class.getName(), "Activate bundle finished");
             }
-
-            if(resource != null) {
-                resource.setURI(config.getURI());
-                resource.setName(config.getName());
-                bundleAPI.registerResource("oic.android.sample", resource);
-                resources.add(resource);
+            else{
+                Log.d(SampleActivator.class.getName(), "configured bundle resources is null");
             }
         }
+        else{
+            Log.d(SampleActivator.class.getName(), "Bundle API is null");
+        }
+
+
     }
 
     @Override
     public void deactivateBundle() {
-        for(AndroidBundleResource resource : resources){
+        Log.d(SampleActivator.class.getName(), "De-activate bundle called.");
+        for(BundleResource resource : resources){
             bundleAPI.unregisterResource(resource);
         }
     }
 
     @Override
     public void createResource(ResourceConfig config) {
-        AndroidBundleResource resource = null;
+        BundleResource resource = null;
 
         if("oic.r.lightsensor".equals(config.getResourceType())){
             resource =
@@ -96,6 +127,9 @@ public class SampleActivator extends AndroidBundleActivator {
         } else if("oic.r.discomfortindex".equals(config.getResourceType())){
             resource =
                     new DiscomfortIndexResource(this.appContext);
+        } else if("oic.r.gyroscope".equals(config.getResourceType())){
+            resource =
+                    new GyroscopeResource(this.appContext);
         } else if ("oic.r.humidity".equals(config.getResourceType())) {
             resource =
                     new HumidityResource(this.appContext);
@@ -110,7 +144,8 @@ public class SampleActivator extends AndroidBundleActivator {
     }
 
     @Override
-    public void destroyResource(AndroidBundleResource androidBundleResource) {
+    public void destroyResource(BundleResource androidBundleResource) {
+        Log.d(SampleActivator.class.getName(), "Destroy resource called.");
         bundleAPI.unregisterResource(androidBundleResource);
     }
 }
index 09bd408..d974a32 100755 (executable)
 
 package org.iotivity.service.sample.androidbundle.resources;
 
+import android.app.Notification;
 import android.content.Context;
+import android.content.Intent;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleSoftSensorResource;
+import org.iotivity.service.resourcecontainer.BundleSoftSensorResource;
 import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
 import org.iotivity.service.resourcecontainer.RcsValue;
 
+import java.util.HashMap;
 import java.util.Vector;
 
-public class DiscomfortIndexResource extends AndroidBundleSoftSensorResource {
+import org.iotivity.service.sample.androidbundle.DummyActivity;
+import org.iotivity.service.sample.androidbundle.R;
+
+public class DiscomfortIndexResource extends BundleSoftSensorResource {
     private static final String LOG_TAG = DiscomfortIndexResource.class.getSimpleName();
 
     public DiscomfortIndexResource(Context context){
         super(context);
         this.setResourceType("oic.r.discomfortindex");
         this.setName("discomfortIndex");
+        m_mapInputData = new HashMap<String, RcsValue>();
     }
 
     @Override
     protected void initAttributes() {
         this.m_attributes.put("discomfortIndex", 0);
         this.m_attributes.put("humidity", 0);
-        this.m_attributes.put("temperature",0);
+        this.m_attributes.put("temperature", 0);
     }
 
     @Override
     protected void onUpdatedInputResource(String attributeName, Vector<RcsValue> values) {
         m_mapInputData.put(attributeName, values.get(0));
+        executeLogic();
     }
 
     @Override
@@ -56,7 +64,6 @@ public class DiscomfortIndexResource extends AndroidBundleSoftSensorResource {
             double dDI = 0.0;
             Vector v = new Vector();
 
-
             int t = m_mapInputData.get("temperature").asInt();
             int h = m_mapInputData.get("humidity").asInt();
             double F = (9.0 * (double) t) / 5.0 + 32.0;
@@ -68,7 +75,14 @@ public class DiscomfortIndexResource extends AndroidBundleSoftSensorResource {
             this.setAttribute("humidity", new RcsValue(h));
             this.setAttribute("discomfortIndex", new RcsValue(dDI));
 
+            setAttribute("discomfortIndex",new RcsValue(dDI), true ); // notify observers
             Log.i(LOG_TAG, "Discomfort Index" + dDI);
+            showNotification(" " + dDI, this.m_context);
+        }
+        else{
+            Log.i(LOG_TAG, "Discomfort Index input data - humidity:  " +
+                    m_mapInputData.get("humidity") + " temp: " +
+                    m_mapInputData.get("temperature") );
         }
     }
 
@@ -82,4 +96,15 @@ public class DiscomfortIndexResource extends AndroidBundleSoftSensorResource {
     public RcsResourceAttributes handleGetAttributesRequest() {
         return this.getAttributes();
     }
+
+    private void showNotification(String eventtext, Context ctx) {
+        // Set the icon, scrolling text and timestamp
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, eventtext);
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+        Log.i(LOG_TAG, "*************************************** ");
+    }
 }
old mode 100644 (file)
new mode 100755 (executable)
index 1dfbeb2..1f167a5
@@ -27,11 +27,12 @@ import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
 import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
 import org.iotivity.service.resourcecontainer.RcsValue;
 
-public class GyroscopeResource extends AndroidBundleResource implements SensorEventListener {
+public class GyroscopeResource extends BundleResource implements SensorEventListener {
     private static final String LOG_TAG = GyroscopeResource.class.getSimpleName();
     private final SensorManager mSensorManager;
     private final Sensor humiditySensor;
@@ -40,7 +41,8 @@ public class GyroscopeResource extends AndroidBundleResource implements SensorEv
         super(context);
         this.setResourceType("oic.r.gyroscope");
         this.setName("gyroscopeSensor");
-        mSensorManager = (SensorManager) context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
         humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
         mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
         Log.d(LOG_TAG, "Created new gyroscope instance");
@@ -65,7 +67,7 @@ public class GyroscopeResource extends AndroidBundleResource implements SensorEv
     public RcsResourceAttributes handleGetAttributesRequest() {
         Log.i(LOG_TAG, "Get Attributes called");
         Log.i(LOG_TAG, "Returning: ");
-        for(String key: m_attributes.keySet()){
+        for(String key:m_attributes.keySet()){
             Log.i(LOG_TAG, " " + key + ": " + m_attributes.get(key));
         }
         return this.m_attributes;
index 36345c9..c40c117 100755 (executable)
@@ -27,11 +27,11 @@ import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
 import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
 import org.iotivity.service.resourcecontainer.RcsValue;
 
-public class HumidityResource extends AndroidBundleResource  implements SensorEventListener {
+public class HumidityResource extends BundleResource implements SensorEventListener {
     private static final String LOG_TAG = HumidityResource.class.getSimpleName();
     private final SensorManager mSensorManager;
     private final Sensor humiditySensor;
@@ -40,8 +40,9 @@ public class HumidityResource extends AndroidBundleResource  implements SensorEv
         super(context);
         this.setResourceType("oic.r.humidity");
         this.setName("humiditySensor");
-        mSensorManager = (SensorManager) context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
-        humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
+        humiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
         mSensorManager.registerListener(this, humiditySensor, SensorManager.SENSOR_DELAY_NORMAL);
     }
 
index 441feaa..0c1017e 100755 (executable)
@@ -27,12 +27,11 @@ import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
 import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
 import org.iotivity.service.resourcecontainer.RcsValue;
 
-
-public class LightIntensityResource extends AndroidBundleResource implements SensorEventListener {
+public class LightIntensityResource extends BundleResource implements SensorEventListener {
     private static final String LOG_TAG = LightIntensityResource.class.getSimpleName();
     private final SensorManager mSensorManager;
     private final Sensor lightSensor;
@@ -41,7 +40,8 @@ public class LightIntensityResource extends AndroidBundleResource implements Sen
         super(context);
         this.setResourceType("oic.r.lightsensor");
         this.setName("lightSensor");
-        mSensorManager = (SensorManager) context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
         lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
         mSensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
     }
index 05d8a34..be88d7a 100755 (executable)
@@ -27,11 +27,11 @@ import android.hardware.SensorEventListener;
 import android.hardware.SensorManager;
 import android.util.Log;
 
-import org.iotivity.service.resourcecontainer.AndroidBundleResource;
+import org.iotivity.service.resourcecontainer.BundleResource;
 import org.iotivity.service.resourcecontainer.RcsResourceAttributes;
 import org.iotivity.service.resourcecontainer.RcsValue;
 
-public class TemperatureResource  extends AndroidBundleResource implements SensorEventListener {
+public class TemperatureResource  extends BundleResource implements SensorEventListener {
     private static final String LOG_TAG = HumidityResource.class.getSimpleName();
     private final SensorManager mSensorManager;
     private final Sensor temperatureSensor;
@@ -40,7 +40,8 @@ public class TemperatureResource  extends AndroidBundleResource implements Senso
         super(context);
         this.setResourceType("oic.r.temperature");
         this.setName("temperatureSensor");
-        mSensorManager = (SensorManager) context.getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
+        mSensorManager = (SensorManager) context.getApplicationContext().
+                getSystemService(Context.SENSOR_SERVICE);
         temperatureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
         mSensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
     }
index 73aa96f..a5cf6e8 100755 (executable)
 
 package org.iotivity.service.sample.container;
 
+import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.os.Message;
 
+import android.os.PowerManager;
 import android.util.Log;
 
 import org.iotivity.service.resourcecontainer.RcsBundleInfo;
@@ -52,17 +54,19 @@ public class ResourceContainer {
     public static boolean                    startBundleFlag;
     private static boolean                   isStarted     = false;
     public static boolean                    isInitialized = false;
+    PowerManager pm = null;
+    PowerManager.WakeLock wl = null;
+
 
-    private FlashLightResource testResource;
 
     // constructor
     public ResourceContainer() {
         resourceContainerActivityInstance = ResourceContainerActivity
                 .getResourceContainerActivityObj();
-        containerInstance = new RcsResourceContainer(resourceContainerActivityInstance.getApplicationContext());
-        testResource = new FlashLightResource(resourceContainerActivityInstance.getApplicationContext());
-        testResource.setURI("/light/1");
-        testResource.setName("light1");
+        containerInstance = new RcsResourceContainer(
+                resourceContainerActivityInstance.getApplicationContext());
+        pm = (PowerManager) resourceContainerActivityInstance.getApplicationContext().
+                getSystemService(Context.POWER_SERVICE);
     }
 
     // Start Container
@@ -72,6 +76,9 @@ public class ResourceContainer {
         Log.i("startContainer : config path : ", configFile);
 
         if (!isStarted) {
+            wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
+                    "ResourceContainer sample");
+            wl.acquire();
             containerInstance.startContainer(configFile);
             isStarted = true;
             logMessage = "Container Started ";
@@ -94,6 +101,7 @@ public class ResourceContainer {
             containerInstance.stopContainer();
             logMessage = "Container stopped";
             isStarted = false;
+            wl.release();
         } else {
             logMessage = "Container not started";
         }
index a4a2a44..830138e 100644 (file)
@@ -168,6 +168,102 @@ namespace OIC
             }
         }
 
+        void Configuration::getResourceConfiguration(std::string bundleId, std::string resourceName,
+                        resourceInfo *resourceInfoOut){
+            rapidxml::xml_node< char > *bundle;
+            rapidxml::xml_node< char > *resource;
+            rapidxml::xml_node< char > *item, *subItem, *subItem2;
+
+            string strBundleId;
+            string strKey, strValue;
+            OC_LOG_V(INFO, CONTAINER_TAG, "Loading resource configuration for %s %s!", bundleId.c_str(), resourceName.c_str());
+
+            if (m_loaded)
+            {
+                try
+                {
+                    // <bundle>
+                    for (bundle = m_xmlDoc.first_node()->first_node(BUNDLE_TAG); bundle; bundle =
+                             bundle->next_sibling())
+                    {
+                        // <id>
+                        strBundleId = bundle->first_node(BUNDLE_ID)->value();
+
+                        OC_LOG_V(INFO, CONTAINER_TAG, "Comparing bundle id %s - %s !", strBundleId.c_str(), bundleId.c_str());
+
+                        if (!strBundleId.compare(bundleId))
+                        {
+                            OC_LOG_V(INFO, CONTAINER_TAG, "Inspecting");
+                            // <resourceInfo>
+                            for (resource = bundle->first_node(OUTPUT_RESOURCES_TAG)->first_node(OUTPUT_RESOURCE_INFO);
+                                 resource; resource = resource->next_sibling())
+                            {
+
+                                for (item = resource->first_node(); item; item =
+                                         item->next_sibling())
+                                {
+                                    strKey = item->name();
+                                    strValue = item->value();
+
+                                    if (!strKey.compare(OUTPUT_RESOURCE_NAME))
+                                        resourceInfoOut->name = trim_both(strValue);
+
+                                    else if (!strKey.compare(OUTPUT_RESOURCE_URI))
+                                        resourceInfoOut->uri = trim_both(strValue);
+
+                                    else if (!strKey.compare(OUTPUT_RESOURCE_ADDR))
+                                        resourceInfoOut->address = trim_both(strValue);
+
+                                    else if (!strKey.compare(OUTPUT_RESOURCE_TYPE))
+                                        resourceInfoOut->resourceType = trim_both(strValue);
+
+                                    else
+                                    {
+                                        for (subItem = item->first_node(); subItem; subItem =
+                                                 subItem->next_sibling())
+                                        {
+                                            map< string, string > propertyMap;
+
+                                            strKey = subItem->name();
+
+                                            if (strKey.compare(INPUT_RESOURCE))
+                                            {
+                                                m_mapisHasInput[strBundleId] = true;
+                                                OC_LOG_V(INFO, CONTAINER_TAG, "Bundle has input (%s)", strBundleId.c_str());
+                                            }
+
+                                            for (subItem2 = subItem->first_node(); subItem2;
+                                                 subItem2 = subItem2->next_sibling())
+                                            {
+                                                string newStrKey = subItem2->name();
+                                                string newStrValue = subItem2->value();
+                                                OC_LOG_V(INFO, CONTAINER_TAG, "key: %s, value %s", newStrKey.c_str(), newStrValue.c_str());
+
+                                                propertyMap[trim_both(newStrKey)] = trim_both(
+                                                                                        newStrValue);
+                                            }
+
+                                            resourceInfoOut->resourceProperty[trim_both(strKey)].push_back(
+                                                propertyMap);
+                                        }
+                                    }
+                                }
+
+                            }
+                        }
+                    }
+                }
+                catch (rapidxml::parse_error &e)
+                {
+                    OC_LOG(ERROR, CONTAINER_TAG, "xml parsing failed !!");
+                    OC_LOG_V(ERROR, CONTAINER_TAG, "Exception (%s)", e.what());
+                }
+            }
+            else{
+                OC_LOG(INFO, CONTAINER_TAG, "config is not loaded yet !!");
+            }
+        }
+
         void Configuration::getResourceConfiguration(std::string bundleId,
                 std::vector< resourceInfo > *configOutput)
         {
@@ -239,6 +335,7 @@ namespace OIC
                                             {
                                                 string newStrKey = subItem2->name();
                                                 string newStrValue = subItem2->value();
+                                                OC_LOG_V(INFO, CONTAINER_TAG, "key: %s, value %s", newStrKey.c_str(), newStrValue.c_str());
 
                                                 propertyMap[trim_both(newStrKey)] = trim_both(
                                                                                         newStrValue);
index 1a39353..ed94470 100644 (file)
@@ -61,6 +61,7 @@ namespace OIC
                 void getConfiguredBundles(configInfo *configOutput);
                 void getBundleConfiguration(string bundleId, configInfo *configOutput);
                 void getResourceConfiguration(string bundleId, vector< resourceInfo > *configOutput);
+                void getResourceConfiguration(string bundleId, string resourceName, resourceInfo *resourceInfoOutput);
 
             private:
                 void getConfigDocument(string pathConfigFile);
index fa09479..66d5a53 100644 (file)
@@ -768,9 +768,14 @@ namespace OIC
 
         void ResourceContainerImpl::discoverInputResource(const std::string &outputResourceUri)
         {
-            OC_LOG_V(DEBUG, CONTAINER_TAG, "Discover input resource%s", outputResourceUri.c_str());
+            OC_LOG_V(DEBUG, CONTAINER_TAG, "Discover input resource %s", outputResourceUri.c_str());
             auto foundOutputResource = m_mapResources.find(outputResourceUri);
-            auto resourceProperty = foundOutputResource->second->m_mapResourceProperty;
+           // auto resourceProperty = foundOutputResource->second->m_mapResourceProperty;
+
+            resourceInfo info;
+            m_config->getResourceConfiguration(foundOutputResource->second->m_bundleId,
+                    foundOutputResource->second->m_name, &info);
+            map< string, vector< map< string, string > > > resourceProperty = info.resourceProperty;
 
             try
             {
@@ -778,6 +783,7 @@ namespace OIC
             }
             catch (std::out_of_range &e)
             {
+                OC_LOG_V(DEBUG, CONTAINER_TAG, "No input resource %s", outputResourceUri.c_str());
                 return;
             }
 
@@ -804,13 +810,17 @@ namespace OIC
                         std::string type = makeValue(INPUT_RESOURCE_TYPE);
                         std::string attributeName = makeValue(INPUT_RESOURCE_ATTRIBUTENAME);
 
+
+                        OC_LOG_V(DEBUG, CONTAINER_TAG, "Start discovery %s, %s, %s", uri.c_str(),
+                                type.c_str(), attributeName.c_str());
                         DiscoverResourceUnit::Ptr newDiscoverUnit = std::make_shared
                                 < DiscoverResourceUnit > (outputResourceUri);
                         newDiscoverUnit->startDiscover(
                             DiscoverResourceUnit::DiscoverResourceInfo(uri, type,
                                     attributeName),
                             std::bind(&SoftSensorResource::onUpdatedInputResource,
-                                      std::static_pointer_cast< SoftSensorResource > (foundOutputResource->second),
+                                      std::static_pointer_cast< SoftSensorResource >
+                        (foundOutputResource->second),
                                       std::placeholders::_1, std::placeholders::_2));
 
                         auto foundDiscoverResource = m_mapDiscoverResourceUnits.find(
@@ -989,7 +999,8 @@ namespace OIC
             {
                 OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
                          std::string( bundleInfoInternal->getID()
-                                      + " bundle activator(" + bundleInfoInternal->getActivatorName()
+                                      + " bundle activator(" +
+                                      bundleInfoInternal->getActivatorName()
                                       + ") not found ").c_str());
                 return;
             }